0% found this document useful (0 votes)
13 views

OOPs unit-1 Notes

oops notes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

OOPs unit-1 Notes

oops notes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

OBJECT ORIENTED PROGRAMMING

UNIT -1

Object-oriented programming:

Object-oriented programming (OOP) is a fundamental programming


paradigm based on the concept of “objects”. These objects can contain
data in the form of fields (often known as attributes or properties) and code
in the form of procedures (often known as methods).
The core concept of the object-oriented approach is to break complex
problems into smaller objects.

What is an object in Java:

An entity that has state and behavior is known as an object e.g., chair, bike,
marker, pen, table, car, etc. It can be physical or logical (tangible and
intangible). The example of an intangible object is the banking system.

An object has three characteristics:

o State: represents the data (value) of an object.


o Behavior: represents the behavior (functionality) of an object such as
deposit, withdraw, etc.
o Identity: An object identity is typically implemented via a unique ID.
The value of the ID is not visible to the external user. However, it is
used internally by the JVM to identify each object uniquely.

For Example, Pen is an object. Its name is Reynolds; color is white, known as
its state. It is used to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from


which objects are created. So, an object is the instance(result) of a class.

Object Definitions:
o An object is a real-world entity.
o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

Create an Object

In Java, an object is created from a class. We have already created the class
named Main, so now we can use this to create objects.

To create an object of Main, specify the class name, followed by the object
name, and use the keyword new:

Example:

Create an object called "myObject" and print the value of x:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObject = new Main();

System.out.println(myObject.x);

}
Multiple Objects

Create two objects of Main:

Example:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj1 = new Main(); // Object 1

Main myObj2 = new Main(); // Object 2

System.out.println(myObj1.x);

System.out.println(myObj2.x);

Ways to Create an Object of a Class

There are four ways to create objects in Java. Strictly speaking, there is
only one way(by using a new keyword), and the rest internally use
a new keyword.

1. Using new keyword


It is the most common and general way to create an object in Java.
Example:
// creating object of class Test
Test t = new Test();
2. Using Class.forName(String className) method

There is a pre-defined class in java.lang package with name Class. The


forName(String className) method returns the Class object associated
with the class with the given string name. We have to give a fully qualified
name for a class. On calling the new Instance() method on this Class object
returns a new instance of the class with the given string name.

// creating object of public class Test


// consider class Test present in com.p1 package
Test obj = (Test)Class.forName("com.p1.Test").newInstance();

3. Using clone() method

clone() method is present in the Object class. It creates and returns a copy
of the object.
// creating object of class Test
Test t1 = new Test();
// creating clone of above object
Test t2 = (Test)t1.clone();

4. Deserialization

De-serialization is a technique of reading an object from the saved state in


a file. Refer to Serialization/De-Serialization in Java
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
Object obj = in.readObject();
Creating multiple objects by one type only (A good practice)

In real-time, we need different objects of a class in different methods.


Creating a number of references for storing them is not a good
practice and therefore we declare a static reference variable and use it
whenever required. In this case, the wastage of memory is less. The
objects that are not referenced anymore will be destroyed by the Garbage
Collector of Java.

Example:
Test test = new Test();
test = new Test();
In the inheritance system, we use a parent class reference variable to store
a sub-class object. In this case, we can switch into different subclass
objects using the same referenced variable.

Example:
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
public class Test
{
// using Dog object
Animal obj = new Dog();
// using Cat object
obj = new Cat();
}

Anonymous Objects in Java


Anonymous objects are objects that are instantiated but are not stored in
a reference variable.
 They are used for immediate method calls.
 They will be destroyed after method calling.
 They are widely used in different libraries. For example, in AWT libraries,
they are used to perform some action on capturing an event(eg a key
press).
 In the example below, when a key button(referred to by the btn) is
pressed, we are simply creating an anonymous object of EventHandler
class for just calling the handle method.

btn.setOnAction(new EventHandler()
{
public void handle(ActionEvent event)
{
System.out.println("Hello World!");
}
});

3 Ways to initialize object

There are 3 ways to initialize object in Java.

1. By reference variable
2. By method
3. By constructor

Java Classes

A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created. It is a logical entity. It
can't be physical.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:

1. class <class_name>{
2. field;
3. method;
4. }

Instance variable in Java


A variable which is created inside the class but outside the method is
known as an instance variable. Instance variable doesn't get memory at
compile time. It gets memory at runtime when an object or instance is
created. That is why it is known as an instance variable.

Method in Java

In Java, a method is like a function which is used to expose the behavior of


an object.

Advantage of Method
o Code Reusability AND Code Optimization
o new keyword in Java
o The new keyword is used to allocate memory at runtime. All objects
get memory in Heap memory area.

Abstraction
Abstract class in Java

A class which is declared with the abstract keyword is known as an abstract


class in Java. It can have abstract and non-abstract methods (method with
the body).

Before learning the Java abstract class, let's understand the abstraction in
Java first.

Abstraction is a process of hiding the implementation details and showing


only functionality to the user.

Another way, it shows only essential things to the user and hides the
internal details, for example, sending SMS where you type the text and
send the message. You don't know the internal processing about the
message delivery.

Abstraction lets you focus on what the object does instead of how it does
it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can


have abstract and non-abstract methods. It needs to be extended and its
method implemented. It cannot be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change
the body of the method.

Example of abstract class

1. abstract class A{}

Abstract Method in Java

A method which is declared as abstract and does not have implementation


is known as an abstract method.

Example of abstract method

1. abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract
method run. Its implementation is provided by the Honda class.

1. abstract class Bike{


2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }
In this example, Shape is the abstract class, and its implementation is
provided by the Rectangle and Circle classes.

Mostly, we don't know about the implementation class (which is hidden to


the end user), and an object of the implementation class is provided by
the factory method.

A factory method is a method that returns the instance of the class. We


will learn about the factory method later.

In this example, if you create the instance of Rectangle class, draw() method
of Rectangle class will be invoked.

File: TestAbstraction1.java

1. abstract class Shape{


2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown by en
d user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle1 extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11. //In real scenario, method is called by programmer or user
12. class TestAbstraction1{
13. public static void main(String args[]){
14. Shape s=new Circle1();//In a real scenario, object is provided through
method, e.g., getShape() method
15. s.draw();
16. }
17. }

Real scenario of abstract class


The abstract class can also be used to provide some implementation of
the interface. In such case, the end user may not be forced to override all
the methods of the interface.

1. interface A{
2. void a();
3. void b();
4. void c();
5. void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){System.out.println("I am c");}
10. }
11.
12. class M extends B{
13. public void a(){System.out.println("I am a");}
14. public void b(){System.out.println("I am b");}
15. public void d(){System.out.println("I am d");}
16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}

Output:I am a
I am b
I am c
I am d
Encapsulation

Encapsulation in Java is a process of wrapping code and data together into


a single unit, for example, a capsule which is mixed of several medicines.

We can create a fully encapsulated class in Java by making all the data
members of the class private. Now we can use setter and getter methods to
set and get the data in it.

The Java Bean class is the example of a fully encapsulated class

The meaning of Encapsulation, is to make sure that "sensitive" data is


hidden from users. To achieve this, you must:

 declare class variables/attributes as private


 provide public get and set methods to access and update the value
of a private variable

Get and Set

You learned from the previous chapter that private variables can only be
accessed within the same class (an outside class has no access to it).
However, it is possible to access them if we provide
public get and set methods.
The get method returns the variable value, and the set method sets the
value.

Syntax for both is that they start with either get or set, followed by the
name of the variable, with the first letter in upper case:

Example

public class Person {

private String name; // private = restricted access

// Getter

public String getName() {

return name;

// Setter

public void setName(String newName) {

this.name = newName;

}
Example explained

The get method returns the value of the variable name.

The set method takes a parameter (newName) and assigns it to


the name variable. The this keyword is used to refer to the current object.

However, as the name variable is declared as private, we cannot access it


from outside this class:

Example

public class Main {

public static void main(String[] args) {

Person myObj = new Person();

myObj.name = "John"; // error

System.out.println(myObj.name); // error

If the variable was declared as public, we would expect the following


output:

John
Inheritance

Inheritance in Java is a mechanism in which one object acquires all the


properties and behaviors of a parent object. It is an important part
of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that
are built upon existing classes. When you inherit from an existing class, you
can reuse methods and fields of the parent class. Moreover, you can add
new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as


a parent-child relationship.

Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).


o For Code Reusability.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It


is a template or blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other
class. It is also called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a
subclass inherits the features. It is also called a base class or a parent
class.
o Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class
when you create a new class. You can use the same fields and
methods already defined in the previous class.
The syntax of Java Inheritance

1. class Subclass-name extends Superclass-name


2. {
3. //methods and fields
4. }

The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase the
functionality.

In the terminology of Java, a class which is inherited is called a parent or


superclass, and the new class is called child or subclass.

Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee


is the superclass. The relationship between the two classes is Programmer
IS-A Employee. It means that Programmer is a type of Employee.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through


interface only. We will learn about interfaces later.
When one class inherits multiple classes, it is known as multiple inheritance.
For Example:
Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the


example given below, Dog class inherits the Animal class, so there is the
single inheritance.

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}

Output:
barking...
eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As


you can see in the example given below, BabyDog class inherits the Dog
class which again inherits the Animal class, so there is a multilevel
inheritance.

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical


inheritance. In the example given below, Dog and Cat classes inherits the
Animal class, so there is hierarchical inheritance.

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}

Output:
meowing...
eating...

Polymorphism in Java

Polymorphism in Java is a concept by which we can perform a single


action in different ways. Polymorphism is derived from 2 Greek words: poly
and morphs. The word "poly" means many and "morphs" means forms. So
polymorphism means many forms.

There are two types of polymorphism in Java: compile-time polymorphism


and runtime polymorphism. We can perform polymorphism in java by
method overloading and method overriding.

If you overload a static method in Java, it is the example of compile time


polymorphism. Here, we will focus on runtime polymorphism in java.

Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in


which a call to an overridden method is resolved at runtime rather than
compile-time.

In this process, an overridden method is called through the reference


variable of a superclass. The determination of the method to be called is
based on the object being referred to by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting
If the reference variable of Parent class refers to the object of Child class, it
is known as upcasting. For example:

1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting

For upcasting, we can use the reference variable of class type or an


interface type. For Example:

1. interface I{}
2. class A{}
3. class B extends A implements I{}

Here, the relationship of B class would be:

B IS-A A
B IS-A I
B IS-A Object

Since Object is the root class of all classes in Java, so we can write B IS-A
Object.

Example of Java Runtime Polymorphism


In this example, we are creating two classes Bike and Splendor. Splendor
class extends Bike class and overrides its run() method. We are calling the
run method by the reference variable of Parent class. Since it refers to the
subclass object and subclass method overrides the Parent class method, the
subclass method is invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is


known as runtime polymorphism.

1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splendor extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splendor();//upcasting
9. b.run();
10. } }
Compile-Time Polymorphism in Java
It is also known as static polymorphism. This type of polymorphism is
achieved by function overloading or operator overloading.
Note: But Java doesn’t support the Operator Overloading.
Method Overloading
When there are multiple functions with the same name but different
parameters then these functions are said to be overloaded. Functions can
be overloaded by changes in the number of arguments or/and a change in
the type of arguments.
Example 1:
 Java

// Java Program for Method overloading

// By using Different Types of Arguments

// Class 1
// Helper class

class Helper {

// Method with 2 integer parameters

static int Multiply(int a, int b)

// Returns product of integer numbers

return a * b;

// Method 2

// With same name but with 2 double parameters

static double Multiply(double a, double b)

// Returns product of double numbers

return a * b;

// Class 2

// Main class
class GFG {

// Main driver method

public static void main(String[] args)

// Calling method by passing

// input as in arguments

System.out.println(Helper.Multiply(2, 4));

System.out.println(Helper.Multiply(5.5, 6.3));

Output

8
34.65

Subtype of Run-time Polymorphism


i. Virtual functions
It allows an object of a derived class to behave as if it were an object of
the base class. The derived class can override the virtual function of the
base class to provide its own implementation. The function call is resolved
at runtime, depending on the actual type of the object.
Diagram –

Polymorphism in Java is a concept that allows objects of different classes


to be treated as objects of a common class. It enables objects to behave
differently based on their specific class type.
Advantages of Polymorphism in Java
1. Increases code reusability by allowing objects of different classes
to be treated as objects of a common class.
2. Improves readability and maintainability of code by reducing the
amount of code that needs to be written and maintained.
3. Supports dynamic binding, enabling the correct method to be
called at runtime, based on the actual class of the object.
4. Enables objects to be treated as a single type, making it easier to
write generic code that can handle objects of different types.
Disadvantages of Polymorphism in Java
1. Can make it more difficult to understand the behavior of an
object, especially if the code is complex.
2. This may lead to performance issues, as polymorphic behavior
may require additional computations at runtime.
Features of Java

The primary objective of Java programming language creation was to make


it portable, simple and secure programming language. Apart from this,
there are also some excellent features which play an important role in the
popularity of this language. The features of Java are also known as Java
buzzwords.

A list of the most important features of the Java language is given below.

Simple

Java is very easy to learn, and its syntax is simple, clean and easy to
understand. According to Sun Microsystem, Java language is a simple
programming language because:

o Java syntax is based on C++ (so easier for programmers to learn it


after C++).
o Java has removed many complicated and rarely-used features, for
example, explicit pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an
Automatic Garbage Collection in Java.

Object-oriented

Java is an object-oriented programming language. Everything in Java is an


object. Object-oriented means we organize our software as a combination
of different types of objects that incorporate both data and behavior.

Platform Independent
ava is platform independent because it is different from other languages
like C, C++, etc. which are compiled into platform specific machines while
Java is a write once, run anywhere language. A platform is the hardware or
software environment in which a program runs.

There are two types of platforms software-based and hardware-based. Java


provides a software-based platform.

The Java platform differs from most other platforms in the sense that it is a
software-based platform that runs on top of other hardware-based
platforms. It has two components:

1. Runtime Environment
2. API(Application Programming Interface)

Java code can be executed on multiple platforms, for example, Windows,


Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and
converted into bytecode. This bytecode is a platform-independent code
because it can be run on multiple platforms, i.e., Write Once and Run
Anywhere (WORA).
Secured

Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime
Environment (JRE) which is used to load Java classes into the Java
Virtual Machine dynamically. It adds security by separating the
package for the classes of the local file system from those that are
imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that
can violate access rights to objects.
o Security Manager: It determines what resources a class can access
such as reading and writing to the local disk.

Robust

The English mining of Robust is strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java
Virtual Machine to get rid of objects which are not being used by a
Java application anymore.
o There are exception handling and the type checking mechanism in
Java. All these points make Java robust.

o Architecture-neutral
o Java is architecture neutral because there are no implementation
dependent features, for example, the size of primitive types is fixed.
o In C programming, int data type occupies 2 bytes of memory for 32-
bit architecture and 4 bytes of memory for 64-bit architecture.
However, it occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.

Portable

Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.

High-performance

Java is faster than other traditional interpreted programming languages


because Java bytecode is "close" to native code. It is still a little bit slower
than a compiled language (e.g., C++). Java is an interpreted language that
is why it is slower than compiled languages, e.g., C, C++, etc.

Distributed

Java is distributed because it facilitates users to create distributed


applications in Java. RMI and EJB are used for creating distributed
applications. This feature of Java makes us able to access files by calling the
methods from any machine on the internet.

Multi-threaded

A thread is like a separate program, executing concurrently. We can write


Java programs that deal with many tasks at once by defining multiple
threads. The main advantage of multi-threading is that it doesn't occupy
memory for each thread. It shares a common memory area. Threads are
important for multi-media, Web applications, etc.

Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It
means classes are loaded on demand. It also supports functions from its
native languages, i.e., C and C++.

What is JRE?

Java Run-time Environment (JRE) is the part of the Java Development Kit
(JDK). It is a freely available software distribution which has Java Class
Library, specific tools, and a stand-alone JVM. It is the most common
environment available on devices to run java programs. The source Java
code gets compiled and converted to Java bytecode. If you wish to run this
bytecode on any platform, you require JRE. The JRE loads classes, verify
access to memory, and retrieves the system resources. JRE acts as a layer on
the top of the operating system.

It also includes:

o Technologies which get used for deployment such as Java Web Start.
o Toolkits for user interface like Java 2D.
o Integration libraries like Java Database Connectivity
(JDBC) and Java Naming and Directory Interface (JNDI).
o Libraries such as Lang and util.
o Other base libraries like Java Management Extensions (JMX), Java
Native Interface (JNI) and Java for XML Processing (JAX-WS).

What does JRE consist of?

JRE consists of the following components:


o Deployment technologies such as deployment, Java plug-in, and
Java Web Start.
o User interface toolkits, including Abstract Window Toolkit (AWT),
Swing, Java 2D, Accessibility, Image I/O, Print Service, Sound, drag,
and drop (DnD) and input methods.
o Integration libraries including Interface Definition Language (IDL),
Java Database Connectivity (JDBC), Java Naming and Directory
Interface (JNDI), Remote Method Invocation (RMI), Remote Method
Invocation Over Internet Inter-Orb Protocol (RMI-IIOP) and scripting.
o Other base libraries, including international support, input/output
(I/O), extension mechanism, Beans, Java Management Extensions
(JMX), Java Native Interface (JNI), Math, Networking, Override
Mechanism, Security, Serialization and Java for XML Processing (XML
JAXP).
o Lang and util base libraries, including lang and util, zip, Java Archive
(JAR), instrument, reflection, Collections, Concurrency Utilities,
management, versioning, Logging, Preferences API, Ref Objects and
Regular Expressions.
o Java Virtual Machine (JVM), which comprise of Server Virtual
Machine and Java HotSpot Client.
How does JRE work with JVM?

JRE has an instance of JVM with it, library classes and development tools. To
understand the working of JRE let us see an example of a simple "Hello
World" program.

1. import java.util.*
2. public static void main(String[] args){
3. System.out.println(?Hello world?);
4. }

Once you write this program, you have to save it with .java extension.
Compile your program. The output of the Java compiler is a byte-code
which is platform independent. After compiling, the compiler generates a
.class file which has the bytecode. The bytecode is platform independent
and runs on any device having the JRE. From here, the work of JRE begins.
To run any Java program, you need JRE. The flow of the bytecode to run is
as follows:
The following steps take place at runtime:

o Class Loader
At this step, the class loader loads various classes which are essential
for running the program. The class loader dynamically loads the
classes in the Java Virtual Machine.
When the JVM is started, three class loaders are used:
1. Bootstrap class loader
2. Extensions class loader
3. System class loader
o Byte code verifier
Byte code verifier can be considered as a gatekeeper. It verifies the
bytecode so that the code doesn't make any sort of disturbance for
the interpreter. The code is allowed to be interpreted only when it
passes the tests of the Bytecode verifier which checks the format and
checks for illegal code.
o Interpreter
Once the classes get loaded and the code gets verified, then
interpreter reads the assembly code line by line and does the
following two functions:
o Execute the Byte Code
o Make appropriate calls to the underlying hardware

In this way, the program runs in JRE.

How to set up Java JRE with PATH Environment Variables?

To develop or run Java applications, you need to download and install the
Java SE Development Kit.

Step 1.) Download the Java SE latest release from the official site of the
oracle.

Step 2.) After downloading the file, you will have an executable file
downloaded. Run that file and keep everything as default and keep clicking
next and then install.

Step 3.) After completing the installation, your JDK and JRE would be
downloaded in the program files folder.

Step 4.) After complete installation, you need to set up the environment
variables.

Step 5.) Go to control panel -> System and Security -> System ->
Advanced System Settings. The following dialog box will appear.

Step 6.) Click on Environment Variables, go to system variables, and double


click on Path.

Step 7.) Now add the path of your bin file present in the JRE file to the Path
variable.
Difference between JVM, JDK, and JRE
o JVM - Java Virtual Machine is a virtual machine which runs programs
which are compiled to bytecodes. The JVM is detailed by a
specification that formally describes what is required in a JVM
implementation. Having a specification ensures interoperability of
Java programs across different implementations so that program
authors using the Java Development Kit (JDK) need not worry about
traits of the underlying hardware platform.
o JDK- JDK is a wrapper around the JRE and additionally contains the
compiler, interpreter, debugger and other tools. It provides users with
features to run as well as develop Java programs.
o JRE- JRE is made up of class libraries, JVM and supporting files

Java Source File Structure


Java source file structure describes that the Java source code file must
follow a schema or structure. In this article, we will see some of the
important guidelines that a Java program must follow.
A Java program has the following structure:
1. package statements: A package in Java is a mechanism to encapsulate
a group of classes, sub-packages, and interfaces.
2. import statements: The import statement is used to import a package,
class, or interface.
3. class definition: A class is a user-defined blueprint or prototype from
which objects are created, and it is a passive entity.
Example:
Compilation and Execution of a Java Program


Java, being a platform-independent programming language, doesn’t work
on the one-step compilation. Instead, it involves a two-step execution, first
through an OS-independent compiler; and second, in a virtual machine
(JVM) which is custom-built for every operating system.
The two principal stages are explained below:

Principle 1: Compilation

First, the source ‘.java’ file is passed through the compiler, which then
encodes the source code into a machine-independent encoding, known as
Bytecode. The content of each class contained in the source file is stored in
a separate ‘.class’ file. While converting the source code into the bytecode,
the compiler follows the following steps:
Step 1: Parse: Reads a set of *.java source files and maps the resulting
token sequence into AST (Abstract Syntax Tree)-Nodes.

Step 2: Enter: Enters symbols for the definitions into the symbol table.
Step 3: Process annotations: If Requested, processes annotations found
in the specified compilation units.
Step 4: Attribute: Attributes the Syntax trees. This step includes name
resolution, type checking and constant folding.
Step 5: Flow: Performs dataflow analysis on the trees from the previous
step. This includes checks for assignments and reachability.
Step 6: Desugar: Rewrites the AST and translates away some syntactic
sugar.
Step 7: Generate: Generates ‘.Class’ files.

The class files generated by the compiler are independent of the machine
or the OS, which allows them to be run on any system. To run, the main
class file (the class that contains the method main) is passed to the JVM
and then goes through three main stages before the final machine code is
executed. These stages are:
These states do include:
1. ClassLoader
2. Bytecode Verifier
3. Just-In-Time Compiler
Let us discuss all 3 stages.
Stage 1: Class Loader
The main class is loaded into the memory bypassing its ‘.class’ file to the
JVM, through invoking the latter. All the other classes referenced in the
program are loaded through the class loader.
A class loader, itself an object, creates a flat namespace of class bodies
that are referenced by a string name. The method definition is provided
below illustration as follows:
Illustration:
// loadClass function prototype

Class r = loadClass(String className, boolean resolveIt);

// className: name of the class to be loaded


// resolveIt: flag to decide whether any referenced class should be loaded
or not.
There are two types of class loaders
 primordial
 non-primordial
The primordial class loader is embedded into all the JVMs and is the
default class loader. A non-primordial class loader is a user-defined class
loader, which can be coded in order to customize the class-loading
process. Non-primordial class loader, if defined, is preferred over the
default one, to load classes.
Stage 2: Bytecode Verifier
After the bytecode of a class is loaded by the class loader, it has to be
inspected by the bytecode verifier, whose job is to check that the
instructions don’t perform damaging actions. The following are some of
the checks carried out:
 Variables are initialized before they are used.
 Method calls match the types of object references.
 Rules for accessing private data and methods are not violated.
 Local variable accesses fall within the runtime stack.
 The run-time stack does not overflow.
 If any of the above checks fail, the verifier doesn’t allow the class
to be loaded.
Stage 3: Just-In-Time Compiler
This is the final stage encountered by the java program, and its job is to
convert the loaded bytecode into machine code. When using a JIT
compiler, the hardware can execute the native code, as opposed to having
the JVM interpret the same sequence of bytecode repeatedly and
incurring the penalty of a relatively lengthy translation process. This can
lead to performance gains in the execution speed unless methods are
executed less frequently.
The process can be well-illustrated by the following diagram given above
as follows from which we landed up to the conclusion.
Conclusion: Due to the two-step execution process described above, a java
program is independent of the target operating system. However, because of
the same, the execution time is way more than a similar program written in
a compiled platform-dependent program.

Fundamental Programming Structures in Java


Variables: Variables are used to store data values. In Java, you need to
declare the data type of a variable before using it.

int age = 25;

double salary = 50000.50;

String name = "John";

Operators: Operators are used to perform operations on variables and


values.

int sum = 5 + 3; // Addition

int difference = 10 - 5; // Subtraction

double product = 3.5 * 2.0; // Multiplication

double quotient = 10.0 / 2.5; // Division

Control Structures:

Conditional Statements (if-else): Used for decision making.

int x = 10;

if (x > 0) {

System.out.println("Positive");

} else {
System.out.println("Negative or zero");

Loops:

for loop: Executes a block of code a fixed number of times. for (int i = 0; i <
5; i++) {

System.out.println("Iteration: " + i);

while loop: Executes a block of code as long as a specified condition is


true.

int i = 0;

while (i < 5) {

System.out.println("Iteration: " + i);

i++;

do-while loop: Similar to the while loop but executes the block of code at
least once before checking the condition.
int i = 0;

do {

System.out.println("Iteration: " + i);

i++;

} while (i < 5);

Arrays: Arrays are used to store multiple values in a single variable.

int[] numbers = {1, 2, 3, 4, 5};

Methods: Methods are blocks of code that perform a specific task and are
reusable.

public static int add(int a, int b) {

return a + b;

Classes and Objects: In Java, everything is encapsulated within classes.


Objects are instances of classes.

class Person {

String name;

int age;

}
Packages: Packages are used to organize classes and interfaces into
namespaces.

package com.example.myproject;

Classes and Objects

 Classes: Blueprints for creating objects, defining properties


(attributes) and behaviors (methods).
 Objects: Instances of classes, encapsulating data (state) and
functionality.

class Car {

String color; // Attribute

int speed; // Attribute

public void accelerate() { // Method (behavior)

speed++;

Constructors

 Special methods invoked when an object is created to initialize its


state.
 Same name as the class, no return type.
class Car {

String color;

int speed;

public Car(String color) { // Constructor

this.color = color; // 'this' keyword refers to current object

speed = 0;

Car myCar = new Car("Red"); // Constructor call

Methods

 Functions defined within a class to perform operations on object data.


 Can have parameters (arguments) to receive input and return values.

class Car {

String color;

int speed;

public void accelerate(int amount) { // Method with parameter


speed += amount;

public int getSpeed() { // Method returning speed

return speed;

myCar.accelerate(20);

int currentSpeed = myCar.getSpeed();

Access Specifiers

 Control access to class members (attributes and methods):


o public: Accessible from anywhere.
o private: Accessible only within the class.
o protected: Accessible within the class and subclasses.
o default (package-private): Accessible within the same package.

Static Members

 Belong to the class itself, not to individual objects.


 Accessed using the class name, not object references.
class MathUtil {

public static int add(int a, int b) {

return a + b;

int sum = MathUtil.add(5, 3); // Accessing static method

Comments

 Enhance code readability by explaining logic or functionality.


 Single-line (//) or multi-line (/* */) comments.

// Single-line comment

/*

Multi-line comment

*/

Data Types

 Specify variable types to hold different kinds of data:


o Primitive: Basic data types (byte, short, int, long, float, double,
char, boolean).
o Non-primitive (Reference): Objects (String, arrays, classes).
Data types in Java are fundamental building blocks that define the type of
value a variable can hold and the operations that can be performed on it.
There are two main categories of data types in Java:

1. Primitive Data Types

These are predefined data types provided by Java itself. They are simple,
efficient, and represent basic values. Here's a breakdown of the primitive
data types:

Data Size
Description Range
Type (bits)
Represents small whole
byte 8 -128 to 127
numbers
Represents whole numbers
short 16 -32,768 to 32,767
(slightly larger than byte)
Represents whole numbers -2,147,483,648 to
int 32
(most commonly used) 2,147,483,647
Represents large whole
long 64 -2^63 to (2^63) - 1
numbers
Represents single-precision Larger range of decimal
float 32
floating-point numbers numbers (approximate)
Represents double-
Even larger range of decimal
double precision floating-point 64
numbers (more precise)
numbers
Represents a single '\u0000' to '\uffff' (includes
char 16
character (uses Unicode) symbols)
Represents logical values
boolean 1 true or false
(true or false)

2. Non-Primitive Data Types (Reference Types)


These are user-defined data types that refer to objects in memory. Objects
can hold various data types and methods to operate on that data. Examples
include:

 String: Represents a sequence of characters (immutable in Java).


 Arrays: Ordered collections of elements of the same data type.
 Classes: Blueprints for creating objects, defining attributes
(properties) and methods (behaviors).
 Interfaces: Define contracts (what methods a class must implement)
to promote code reusability.

Example:

byte age = 25; // Stores a whole number between -128 and 127

double pi = 3.14159; // Stores a floating-point number (approximate)

String name = "Alice"; // Stores a sequence of characters

Choosing the Right Data Type

 Consider the range of values you need to store (e.g., use byte for
small numbers, int for most whole numbers).
 Think about memory efficiency if dealing with large datasets (byte
and short use less memory than int).
 For decimal numbers, choose between float (less precise but uses less
memory) and double (more precise but uses more memory).
 Use boolean for true/false decisions.

Variables

 Named containers to store data values of specific types.


 Declaration: type variableName;
 Initialization: variableName = value;

int age = 25;

String name = "Alice";

Operators

 Perform operations on data:


o Arithmetic (+, -, *, /, %)
o Assignment (=, +=, -=, *=, /=, %=, etc.)
o Comparison (==, !=, <, >, <=, >=)
o Logical (&&, ||, !)
o Bitwise (&, |, ^, <<, >>, >>>)

Control Flow

 Control program execution flow using statements:


o if statements for conditional execution.
o switch statements for multiple-choice selection.
o for, while, and do-while loops for repetition.
o break and continue statements for loop control.

int x = 10;

if (x > 5) {

System.out.println("x is greater than 5");

} else {

System.out.println("x is less than or equal to 5");


}

Arrays

 Collections of elements of the same data type.


 Declared: type[] arrayName = new type[size];
 Accessed using indices: arrayName[index].

int[] numbers = new int[5];

numbers[0] = 1;

numbers[1] = 2;

// ...

int firstElement = numbers[0];

Types of Arrays

 Single-dimensional Arrays: Collections with a single index.


 Multi-dimensional Arrays: Arrays of arrays (e.g., matrices).

You might also like