Oops With Java Unit 1-1
Oops With Java Unit 1-1
INTRODUCTION:
• Java is a general –Purpose Programming Language.
• It is High Level Language.
• Java was originally developed by James Gosling at Sun Microsystems in 1995.
• Java is a Language that is Platform independent.
• A Platform is the hardware and Software environment in which a Programs run.
• Java has irs own Runtime Environment(JRE) and API.
• Java code is once compiled; it can run on any platform without recompiling or any
kind of modification.
• “write Once Run anywhere”
• Java is supported by Java Virtual Machine(JVM).
It is mostly used for building desktop applications, web applications, Android apps and
enterprise systems.
Features of Java:
• Object-Oriented Programming (OOP): Java supports OOP concepts to create modular
and reusable code.
• Platform Independence: Java programs can run on any operating system with a JVM.
• Robust and Secure: Java ensures reliability and security through strong memory
management and exception handling.
• Multithreading and Concurrency: Java allows concurrent execution of multiple tasks for
efficiency.
• Rich API and Standard Libraries: Java provides extensive built-in libraries for various
programming needs.
• Frameworks for Enterprise and Web Development: Java supports frameworks that
simplify enterprise and web application development.
• Open-Source Libraries: Java has a wide range of libraries to extend functionality and
speed up development.
• Maintainability and Scalability: Java’s structured design allows easy maintenance and
growth of applications.
When we learn any programming language, the first step is writing a simple program to
display "Hello World". So, here is a simple Java program that displays "Hello World" on
the screen.
// A Java program to print Hello World!
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello World!");
}
}
Output
Hello World!
Explanation:
Single-line comment
// This is a comment
Multi-line comment
/*
This is a multi-line comment.
This is useful for explaining larger sections of code.
*/
Famous Applications Built Using Java
• Android Apps: Most of the Android mobile apps are built using Java.
• Netflix: This uses Java for content delivery and backend services.
• Amazon: Java language is used for its backend systems.
• LinkedIn: This uses Java for handling high traffic and scalability.
• Minecraft: This is one of the world’s most popular games that is built in Java.
• Spotify: This uses Java in parts of its server-side infrastructure.
• Uber: Java is used for backend services like trip management.
• NASA WorldWind: This is a virtual globe software built using Java.
The following applications get structured around objects using OOP systems.
Client-Server Systems
IT infrastructure is made up of object-oriented client-server systems, which are used to make Object-
Oriented Client-Server Internet (OCSI) applications.
Object-Oriented Database
The object-oriented database stores objects, such as integers and real numbers,
1. Class:
A class is a user-defined data type. It consists of data members and member functions, which
can be accessed and used by creating an instance of that class. It represents the set of properties
or methods that are common to all objects of one type. A class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and
brands but all of them will share some common properties like all of them will have 4 wheels,
Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed limits, mileage are
their properties.
2. Object:
It is a basic unit of Object-Oriented Programming and represents the real-life entities. An Object
is an instance of a Class. When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated. An object has an identity, state, and
behavior. Each object contains data and code to manipulate the data. Objects can interact without
having to know details of each other’s data or code, it is sufficient to know the type of message
accepted and type of response returned by the objects.
For example “Dog” is a real-life Object, which has some characteristics like color, Breed, Bark,
Sleep, and Eats.
3. Data Abstraction:
• Data abstraction is one of the most essential and important features of object-oriented
programming.
• Data abstraction refers to providing only essential information about the data to the
outside world, hiding the background details or implementation.
• Consider a real-life example of a man driving a car. The man only knows that pressing
the accelerators will increase the speed of the car or applying brakes will stop the car, but
he does not know about how on pressing the accelerator the speed is increasing, he does
not know about the inner mechanism of the car or the implementation of the accelerator,
brakes, etc in the car. This is what abstraction is.
4. Encapsulation:
• Encapsulation is defined as the wrapping up of data under a single unit.
• It is the mechanism that binds together code and the data it manipulates.
• In Encapsulation, the variables or data of a class are hidden from any other class and can
be accessed only through any member function of their class in which they are declared.
• As in encapsulation, the data in a class is hidden from other classes, so it is also known
as data-hiding.
Consider a real-life example of encapsulation, in a company, there are different sections like the
accounts section, finance section, sales section, etc.
The finance section handles all the financial transactions and keeps records of all the data related
to finance.
Similarly, the sales section handles all the sales-related activities and keeps records of all the
sales.
Now there may arise a situation when for some reason an official from the finance section needs
all the data about sales in a particular month.
In this case, he is not allowed to directly access the data of the sales section. He will first have
to contact some other officer in the sales section and then request him to give the particular data.
This is what encapsulation is. Here the data of the sales section and the employees that can
manipulate them are wrapped under a single name “sales section”.
5. Inheritance:
Inheritance is an important pillar of OOP(Object-Oriented Programming).
The capability of a class to derive properties and characteristics from another class is called
Inheritance. When we write a class, we inherit properties from other classes. So when we create
a class, we do not need to write all the properties and functions again and again, as these can be
inherited from another class that possesses it. Inheritance allows the user to reuse the code
whenever possible and reduce its redundancy.
6. Polymorphism:
The word polymorphism means having many forms.
In simple words, we can define polymorphism as the ability of a message to be displayed in more
than one form.
For example, A person at the same time can have different characteristics. Like a man at the
same time is a father, a husband, an employee. So the same person posses different behavior in
different situations. This is called polymorphism.
7. Dynamic Binding: In dynamic binding, the code to be executed in response to the function
call is decided at runtime. Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at run time. Dynamic Method Binding One
of the main advantages of inheritance is that some derived class D has all the members of its
base class B. Once D is not hiding any of the public members of B, then an object of D can
represent B in any context where a B could be used. This feature is known as subtype
polymorphism.
8. Message Passing: It is a form of communication used in object-oriented programming as well
as parallel programming. Objects communicate with one another by sending and receiving
information to each other. A message for an object is a request for execution of a procedure and
therefore will invoke a function in the receiving object that generates the desired results. Message
passing involves specifying the name of the object, the name of the function, and the information
to be sent.
Why do we need object-oriented programming
• To make the development and maintenance of projects more effortless.
• To provide the feature of data hiding that is good for security concerns.
• We can solve real-world problems if we are using object-oriented programming.
• It ensures code reusability.
• It lets us write generic code: which will work with a range of data, so we don't have to write
basic stuff over and over again.
OOP vs Real Life (Simple Mapping)
OOP Concept Real Life Example
Class Blueprint of a house
Object Actual house
Encapsulation ATM machine
Inheritance Child inherits traits
Polymorphism Same phone button, different functions
Benefits/Advantages of JAVA :
• Straightforward Java - It is anything but difficult to program, compose, gather,
investigate, and learn than elective programming dialects. Java might be a more modest
sum convoluted than C++; therefore, Java utilizes programmed memory portion and trash
assortment.
• Item Oriented - It grants you to make standard projects and reusable code.
• Stage Independent Java code - It runs on any machine that needn't bother with any unique
programming to be introduced, however, the JVM should be available on the machine.
• Java is a disseminated language - Java is a dispersed language as it gives an instrument
for dividing information and projects between numerous PCs that improve the presentation
and proficiency of the framework. The RMI(Remote Method Invocation) is something that
bolsters the dispersed handling in Java.
• Secure Java - It has no unequivocal pointer. Besides this, it is a security administrator that
characterizes the entrance of classes.
• Memory distribution - In Java, memory is part into two sections one is stored and another
is stack. At whatever point we pronounce a variable JVM gives memory from one or the
other stack or pile space. It assists with remaining the information and reestablish it without
any problem.
• Multithreaded - It is the potential for a program to perform numerous assignments
simultaneously. at long last time showed up to become familiar with the ideas of
Multithreading in Java.
• Java gives Automatic Garbage Collection - There is programmed memory for the
executives in Java that is overseen by the Java Virtual Machine(JVM). At whatever point
the articles are not utilized by programs any longer and they don't allude to anything.
Disadvantages of JAVA :
• Execution Java language - It is a more slow language when contrasted with different
dialects as it is a memory burning-through language.
• Java requires huge memory space - Java requires a critical or significant measure of
memory space when contrasted with different dialects like C and C++. During the
execution of trash assortment, the memory productivity and the exhibition of the framework
might be unfavorably influenced.
• Verbose and Complex codes - Java codes are verbose, implying that there are numerous
words in them and there are numerous long and complex sentences that are hard to peruse
and comprehend. This can decrease the meaningfulness of the code.
• Slow Startup Time - Java applications can have slower startup times because of the need
to initialize the JVM and load necessary classes.
• Limited Real-Time Capabilities - Java's garbage collection process can introduce pauses
that make it less suitable for real-time systems where consistent response times are crucial.
In this chapter, we will first learn what are JDK, JRE, and JVM, and how they are different
from each other.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn't physically exist. It is a specification that provides a runtime environment in
which Java bytecode can be executed. It can also run those programs that are written in other
languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from that of others.
However, Java is platform independent. There are three notions of the
JVM: specification, implementation, and instance.
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
To read more JVM Architecture
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools that are used for developing Java applications.
It is used to provide the runtime environment. It is the implementation of JVM. It physically
exists. It contains a set of libraries + other files that the JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun
Microsystems.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment that is used to develop Java applications and applets. It physically
exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
1. A specification specifying the workings of the Java Virtual Machine. However, the
implementation provider is independent of choosing the algorithm. Oracle and other
companies have provided its implementation.
2. An implementation Its implementation is known as JRE (Java Runtime
Environment).
3. Runtime Instance Whenever we write a java command on the command prompt to
run the Java class, an instance of JVM is created.
Functions of JVM
The JVM performs following operations:
• Verifies code: It checks the bytecode for security and correctness to ensure it does not violate Java’s
safety rules.
• Executes code: The JVM converts bytecode into machine-level instructions and executes them using
the interpreter or JIT compiler.
• Provides a runtime environment: It manages memory, threads, and system resources required to
run Java applications efficiently.
• Memory areas: The JVM defines memory regions such as heap, stack, method area, and PC register
for program execution.
• Class file format: It specifies a standard structure for .class files so they can be understood by any
JVM.
• Register set: The JVM uses registers like the program counter to track instruction execution.
• Garbage-collected heap: It automatically manages memory by removing unused objects through
garbage collection.
• Fatal error reporting and more: The JVM handles serious runtime errors and provides diagnostic
information for debugging.
JVM Architecture
JVM (Java Virtual Machine) architecture defines how Java programs are loaded, executed,
and managed in memory that ensures platform independence and efficient performance. The
main components of JVM architecture:
1) Classloader:
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the
Java program, it is loaded first by the classloader. There are three built-in classloaders in
Java.
1. Runtime Constant Pool: The runtime constant pool is part of the Class(Method) Area
and consists of constant pool entries. These are used to store symbolic references,
literals, and other constant values required by the class. These include class and
interface names, method and field names, string literals, and numeric literals.
2. Field Data: The Class(Method) Area also stores information about the fields declared
within a class, including their names, types, and access modifiers. This data is used by
the JVM to access and manipulate object fields at runtime.
3. Method Data: Along with field data, the Class(Method) Area contains information
about the methods declared within a class, including their names, return types,
parameter types, and bytecode instructions. This information is used by the JVM to
invoke methods and execute bytecode instructions during program execution.
3) Heap:
The Heap is the runtime data area in which objects are allocated.
1. Object Allocation: The Heap is responsible for allocating memory for objects
dynamically created during program execution. When an object is instantiated using
the new keyword or by invoking a constructor, memory is allocated on the Heap to
store the object's data.
2. Garbage Collection: The Heap is managed by the JVM's garbage collector, which
periodically scans the Heap for objects that are no longer in use or reachable by the
application. Garbage collection involves reclaiming memory occupied by these unused
objects, freeing up space for new allocations.
3. Heap Structure: The Heap is typically divided into two main areas: The Young
Generation and the Old Generation (also known as the Tenured Generation). The
Young Generation is further divided into the Eden Space and Survivor Spaces, while
the Old Generation contains long-lived objects that have survived multiple garbage
collection cycles.
4) Stack:
Java Stack stores frames. It holds local variables and partial results, and plays a part in method
invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method
invocation completes.
1. Frame Structure: Each frame contains local variables, operand stacks, and a
reference to the runtime constant pool of the method being executed. Local variables
store method parameters and local variables, while the operand stack is used for
intermediate results and operand manipulation during method execution.
2. Method Invocation: The Stack plays a crucial role in method invocation and return.
When a method is invoked, a new frame is created and pushed onto the stack. Upon
method completion, the frame is popped off the stack, and control returns to the
invoking method.
The Program Counter (PC) register is a special register within the JVM that contains the
memory address of the currently executing instruction.
The Native Method Stack is a memory area within the JVM used for executing native
methods, which are methods written in languages other than Java, such as C or C++.
Additional information about the Native Method Stack includes:
Native Method Invocation: When a Java application invokes a native method, the execution
flow transitions to the Native Method Stack, where the native method's code is executed.
7) Execution Engine
It contains:
1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) Compiler: It is used to improve the performance. JIT compiles
parts of the byte code that have similar functionality at the same time, and hence
reduces the amount of time needed for compilation. Here, the term "compiler" refers
to a translator from the instruction set of a Java virtual machine (JVM) to the
instruction set of a specific CPU.
OR
Example:
class Test {
public static void main(String[] args) {
[Link]("Hello JVM");
}
}
The Class Loader Subsystem loads the .class file into JVM memory.
Hello JVM
4-Piller of object oriented programming are the core Concepts based on which
oop is based.
Encapsulation
Definition: Encapsulation means wrapping data and methods into a single unit (class) and
hiding data from outside access.
How it is achieved:
class Student {
private int age;
public void setAge(int age) {
[Link] = age;
}
Real-life example:
Car – You drive using steering, brake, accelerator; internal engine details are hidden.
3️) Inheritance:
Definition: Inheritance allows one class to acquire properties and behaviour of another
class.
Keyword used:
• Extends
Example (Java):
class Animal {
void eat() {
[Link]("Eating");
}
}
class MathOp {
int add(int a, int b) {
return a + b;
}