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

Module-1

The document provides an overview of Object-Oriented Programming (OOP) principles, including encapsulation, inheritance, polymorphism, and abstraction, highlighting their importance in software development. It contrasts OOP with procedural programming, emphasizing the benefits of data security, code reusability, and maintainability in OOP. Additionally, it introduces Java fundamentals, including data types and a simple program example.

Uploaded by

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

Module-1

The document provides an overview of Object-Oriented Programming (OOP) principles, including encapsulation, inheritance, polymorphism, and abstraction, highlighting their importance in software development. It contrasts OOP with procedural programming, emphasizing the benefits of data security, code reusability, and maintainability in OOP. Additionally, it introduces Java fundamentals, including data types and a simple program example.

Uploaded by

Vinay Adari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Object Oriented Programming 22CSE43

MODULE 1
Module Name: Java Fundamentals

SYLLABUS: Object-Oriented Programming Principles: Encapsulation,


Inheritance, and Polymorphism, A first simple program, Control statements,
Data types, Variables, Arrays, Operators, Control Statements, Class
Fundamentals, Declaring objects, Assigning object reference variables,
Introducing methods, Constructors, The this keyword.

1.1 Introduction
What are Object Oriented Programming Languages

Object-oriented programming languages are a powerful tool that allows developers to create
applications modelled on real-world objects. Using objects, classes, and data structures,
developers can create robust, efficient, practical applications. Developers can create reusable
and customizable programs by using best object oriented programming language such as
Java, C++, and Python. By using these languages, developers can create more responsive and
interactive applications, allowing users to have a more enjoyable and productive experience.
Other popular OOP languages are Ruby, C#, and PHP.

Benefits Of Object Oriented Programming

Object Oriented Programming (OOP) has revolutionized the way we write software. From
large-scale enterprise applications to small hobby projects, OOP provides a powerful and
flexible approach to software development. It enables developers to think in terms of objects,
classes, and methods, making code more intuitive and easier to maintain. OOP benefits
developers to create efficient and reusable code, reducing development time and cost.
Furthermore, OOP allows developers to add new features and functionality to existing code,
making it an ideal choice for agile development. With its powerful features and flexibility,
OOP has become an essential tool for modern software development.

FOUR PILLARS OF OOP

Page 1 of 75
Object Oriented Programming 22CSE43

In the world of object-oriented programming (OOP), almost everything is considered an


object. So what is an object in OOP? Objects contain data, referred to as attributes or
properties, and methods. OOP allows objects to interact with each other using four basic
principles: encapsulation, inheritance, polymorphism, and abstraction. These four OOP
principles enable objects to communicate and collaborate to create powerful applications.

1. Encapsulation in object oriented programming

Encapsulation is a principle that seeks to hide the implementation details of objects from the
outside world. It states that all important information is contained within the object; only
selected data is available externally. Each object's inner workings and state are stored
privately within the specified class, whereas other objects do not have access to it or the
ability to make changes. Instead, they can only interact with a few public functions or
methods. This form of data hiding provides program security and control over object state
changes, reduces the risk of errors, and makes the program more understandable.

2. Inheritance in object oriented programming

Inheritance is a principle that enables developers to create new classes based on existing
(parent) classes, with the option of overriding or augmenting their properties and methods.
This is especially useful in programs containing thousands of lines of code, as it simplifies
maintenance and prevents code duplication. By using the logic of the parent class in the child
class, developers can create objects that share code or logic yet are different. This reduces
the complexity of the code and eliminates the need to create a new object for each object
used in the program.

3. Polymorphism in object oriented programming

Polymorphism is a principle that complements inheritance by allowing objects of different


classes to perform actions with the same name using different code. For instance, the "show
information" method can be used to display varied data about objects of the "car", "plane",
or "ship" type. Furthermore, polymorphism helps to create more flexible and modular
programs. Generally, it simplifies the development process as it allows for the creation of
common methods and functions to be used for multiple types of objects.

Page 2 of 75
Object Oriented Programming 22CSE43

4. Abstraction in object oriented programming

Abstraction helps you focus on a system's essential elements and ignore the less important
details that have no effect on its key features. It allows you to construct more understandable
programs. Abstraction can be thought of as an expansion of encapsulation. Take programs
that contain thousands of lines of code as an example. Through the principle of abstraction,
each object only reveals a specific mechanism for usage. Therefore, the code inside becomes
largely independent of other objects. For instance, in a program that stores information about
movies, you can create a class "Movie" that provides access to only the most essential details,
such as title, release year, and genre, while hiding the less important information, like shots
or technical aspects.

SECRETS OF SUCCESSFUL USAGE OF OOP

To successfully develop programs using Object-Oriented Programming (OOP), it is important


to adhere to the following recommendations:

1. Aim for simplicity and efficiency when designing object-oriented code.

2. Adhere to the SOLID principles to prevent problems and keep code flexible,
maintainable, and easy to modify.

3. Identify the classes needed and their relationships to ensure the program functions
efficiently.

4. Avoid over-utilizing imitation and understand when to apply it and when to opt for
object composition instead.

5. Employ abstraction to simplify understanding.

6. Abide by programming standards and conventions to ensure code clarity and


maintainability.

Difference Between Procedural and Object Oriented Programming

Parameter Procedural Programming Object Oriented Programming

Page 3 of 75
Object Oriented Programming 22CSE43

Definition This programming language makes use ofThis programming language uses
a step by step approach for breakingobjects and classes for creating models
down a task into a collection of routinesbased on the real-world environment.
(or subroutines) and variables byThis model makes it very easy for a user
following a sequence of instructions. Itto modify as well as maintain the
carries out each step systematically inexisting code while new objects get
order so that a computer easily gets tocreated by inheriting the characteristics
understand what to do. of the present ones.

Security Procedural Programming does not offerHiding data is possible with Object
any method of hiding data. Thus, it is lessOriented Programming due to the
secure when compared to Object Orientedabstraction. Thus, it is more secure than
Programming. the Procedural Programming.

Method The main program gets divided intoIt involves the concept of classes and
minute parts on the basis of the functions.objects. Hence, it divides the program
It then treats them as separate programsinto minute chunks known as objects.
for smaller programs individually. These are actually instances of classes.

Division of Procedural Programming divides theObject Oriented Programming divides


Program program into small programs and refersthe program into small parts and refers
to them as functions. to them as objects.

Movement Available data is capable of moving freely The objects are capable of moving and
of Data within the system from one function tocommunicating with each other through
another. the member functions.

Approach The Procedural Programming follows aThe Object Oriented Programming


Top-Down approach. follows a Bottom-Up approach.

Page 4 of 75
Object Oriented Programming 22CSE43

Importance This programming model does not giveThis programming model gives
importance to data. It prioritizes theimportance to the data rather than
functions along with the sequence offunctions or procedures. It is because it
actions that needs to follow. works on the basis of the real world.

Orientation It is Structure/Procedure oriented. It is Object Oriented.

Basis The main focus in ProceduralThe main focus in Object Oriented


Programming is on how to do the task,Programming is on data security. Hence,
meaning, on the structure or procedure ofit only permits objects to access the class
the program. entities.

Type of It divides any large program into smallIt divides the entire program into small
Division units called functions. units called objects.

Inheritance It does not provide any inheritance. It achieves inheritance in three modes-
protected, private, and public.

Virtual There is no concept of virtual classes. The concept of virtual functions appears
Classes at the time of inheritance.

Overloading The case of overloading isn’t possible inOverloading is possible in the form of
the case of Procedural Programming. operator overloading and function
overloading in the case of Object
Oriented Programming.

Reusability No feature of reusing codes is present inObject Oriented Programming offers the
of Code Procedural Programming. feature to reuse any existing codes in it
by utilizing a feature known as
inheritance.

Page 5 of 75
Object Oriented Programming 22CSE43

Most Important
It prioritizes function over data. It prioritizes data over function.
Attribute

Modes of The Procedural Programming offers noThe Object Oriented Programming


Access specific accessing mode for accessingoffers three accessing modes- protected,
functions or attributes in a program. private, and public. These, then, serve as
a share to access functions of attributes.

Size of It is not very suitable for solving any bigIt is suitable for solving any big or
Problems or complex problems. complex problems.

Addition of It is not very easy to add new functionsIt is very easy to add new functions and
New and data in the Procedural Programming. data in the Object Oriented
Function and Programming.
Data

Access to In the Procedural Programming, most ofIn the Object Oriented Programming, the
Data the functions use global data for sharing.present data cannot easily move easily
They can access freely from one functionfrom one function to another. One can
to another in any given system. keep it private or even public. Thus, a
user can control the data access.

Data It shares the global data among theIt shares data among the objects through
Sharing functions present in the program. its member functions.

Data Hiding No proper way is available for hiding theIt can hide data in three modes-
data. Thus, the data remains insecure. protected, private, and public. It
increases the overall data security.

Page 6 of 75
Object Oriented Programming 22CSE43

Basis of The Procedural Programming follows anThe Object Oriented programming


World unreal world. follows the real world.

Friend It doesn’t involve any concept of friendAny class or function is capable of


Classes or function. becoming a friend of any other class that
Friend contains the keyword “friend.”
Functions Note – The keyword “friend” only works
for C++.

Examples Some common examples of ProceduralThe examples of Object Oriented


Programming are C, Fortran, VB, andProgramming languages are Java, C++,
Pascal. VB.NET, Python, and C#.NET.

A first simple program:

public class Main

public static void main(String args[]){

System.out.println("Hello World!");

} }

Data types:

Data Types in Java

In programming languages, data types specify the different sizes and values that can be
stored in the variable or constants. Each data type is predefined, which makes Java a statically
and strongly typed language. There are the following two types of data types in Java.

1. Primitive Data Types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
Page 7 of 75
Object Oriented Programming 22CSE43

2. Non-Primitive Data Types: The non-primitive data types include Classes, Interfaces,
String, and Arrays.

Java Primitive Data Types

In Java, primitive data types are the building blocks of data manipulation. These are the basic
data types.

In Java, there are mainly eight primitive data types which are as follows.

1. boolean data type

2. char data type

3. byte data type

4. short data type

5. int data type

6. long data type

7. float data type


Page 8 of 75
Object Oriented Programming 22CSE43

8. double data type

Java is a statically typed programming language. It means all variables must be declared
before their use. That is why we need to declare the variable's type and name. Let's discuss
each data type one by one.

1. Boolean Data Type

In Java, the boolean data type represents a single bit of information with two possible
states: true or false. The size of the Boolean data type is 1 byte (8 bits).

It is used to store the result of logical expressions or conditions. Unlike other primitive data
types like int or double, boolean does not have a specific size or range. It is typically
implemented as a single bit, although the exact implementation may vary across platforms.
freestar

Syntax:

1. boolean flag;

Example

1. Boolean a = false;

2. Boolean b = true;

2. Byte Data Type

The byte data type in Java is a primitive data type that represents an 8-bits signed two's
complement integer. It has a range of values from -128 to 127. Its default value is 0.

The byte data type is commonly used when working with raw binary data or when memory
conservation is a concern, as it occupies less memory than larger integer types like int or
long.

Syntax:

1. byte size;

Example
Page 9 of 75
Object Oriented Programming 22CSE43

1. byte a = 10;

2. byte b = -20;

3. Short Data Type

The short data type in Java is a primitive data type that represents a 16-bits signed two-
complement integer. Its range of values is -32,768 to 32,767.

Similar to the byte data type, short is used when memory conservation is a concern, but more
precision than byte is required. Its default value is 0.

Syntax:
freestar

short var;

Example

1. short a = 10000;

2. short b = -5000;

4. int Data Type

The int data type in Java is a primitive data type that represents a 32-bits signed two's
complement integer. It has a range of values from -2,147,483,648 to 2,147,483,647.

The int data type is one of the most commonly used data types. It is typically used to store
whole numbers without decimal points. Its default value is 0.

Syntax:

1. int myInt = 54;

In Java, int variables are declared using the int keyword. For example, int myInt = 54 ; declares
an int variable named myInt and initializes it with the value 54. int variables can be used in
mathematical expressions, assigned to other int variables, and used in conditional
statements.

Page 10 of 75
Object Oriented Programming 22CSE43

Remember: In Java SE 8 and later versions, we can use the int data type to represent an
unsigned 32-bit integer. It has a value in the range [0, 232-1]. Use the Integer class to use the
int data type as an unsigned integer.

Example

1. int a = 100000;

2. int b = -200000;

5. long Data Type

The long data type in Java is a primitive data type that represents a 64-bits signed two's
complement integer. It has a wider range of values than int, ranging
from 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Its default value is 0.0L or
0.0l.

The long data type is used when the int data type is not large enough to hold the desired
value or when a larger range of integer values is needed.

Syntax:

1. long num = 15000000000L;

2. long num = 9,223,372,036,854,775l

The long data type is commonly used in applications where large integer values are required,
such as in scientific computations, financial applications, and systems programming. It
provides greater precision and a larger range than int, making it suitable for scenarios where
int is insufficient.

Example

1. long a = 5000000L;

2. long b = -6000000L;

Note: In Java SE 8 and later versions, we can use the long data type to represent an unsigned
64-bit long number. It has a minimum value of 0 and a maximum value of 264-1.

Page 11 of 75
Object Oriented Programming 22CSE43

6. float Data Type

The float data type in Java is a primitive data type that represents single-precision 32-
bits IEEE 754 floating-point numbers. It can represent a wide range of decimal values, but it
is not suitable for precise values such as currency. Its default value is 0.0f or 0.0F.

The float data type is useful for applications where a higher range of values is needed and
precision is not critical.

Syntax:

float num = 67;

One of the key characteristics of the float data type is its ability to represent a wide range of
values, both positive and negative, including very small and very large values. However, due
to its limited precision (approximately 6-7 significant decimal digits), it is not suitable for
applications where exact decimal values are required.

Example

float f = 234.5f;

7. double Data Type

The double data type in Java is a primitive data type that represents double-precision 64-bits
IEEE 754 floating-point numbers. Its default value is 0.0. It provides a wider range of values
and greater precision compared to the float data type, which makes it suitable for
applications where accurate representation of decimal values is required.
freestar

Syntax:

1. double num = 75.658d;

One of the key advantages of the double data type is its ability to represent a wider range of
values with greater precision compared to float. It can accurately represent values with up
to approximately 15-16 significant decimal digits, making it suitable for applications that
require high precision, such as financial calculations, scientific computations, and graphics
programming.

Page 12 of 75
Object Oriented Programming 22CSE43

Example

double d = 12.3;

Note: If accuracy is the most important concern, it is suggested not to use float and double data
types; use the BigDecimal class instead.

8. char Data Type

The char data type in Java is a primitive data type that represents a single 16-bits Unicode
character. It can store any character from the Unicode character set, which allows Java to
support the internationalisation and representation of characters from various languages
and writing systems.

Syntax:

char alphabets = 'J';

char a = 60, b = 61, c = 62;

The char data type is commonly used to represent characters, such as letters, digits, and
symbols. It can also be used to perform arithmetic operations, as the Unicode values of
characters can be treated as integers.

Example

char c = 'A';

For example, we can perform addition or subtraction operations on char variables to


manipulate their Unicode values.

Type Default Size Range of Values Example


Values

boolean false 8 bits true, false true, false, 0, 1

byte 0 8 bits -128 to 127 -

char \u0000 16 bits Characters Representation of 'z', '\u0041', '\11',


ASCII values 0 to 255 '\\', '\', '\n'

Page 13 of 75
Object Oriented Programming 22CSE43

short 0 16 bits -32,768 to 32,767 -

int 0 32 bits -2,147,483,648 -5,-1,0,6,8


to
2,147,483,647

long 0 64 bits -9,223,372,036,854,775,808 -7L,-2L,0L,1L,2L


to
9,223,372,036,854,775,807

float 0.0f 32 bits up to 7 decimal digits 3.14f, 89.09F, -9.3F

double 0.0 64 bits up to 16 decimal digits 6.98765e300d , -


567899e-600d , 2e2d

Java Primitive Data Type Example


freestar

Example

public class Main


{
public static void main(String args[])
{
boolean flag = true;
char ch = 'z';
int num = 1234;
byte size = 2;
short srt = 78;
double value = 2.4546778;
float temp = 3.8f;
long val = 1888889;
System.out.println("boolean: " + flag);
System.out.println("char: " + ch);
System.out.println("integer: " + num);
System.out.println("byte: " + size);
System.out.println("short: " + srt);
System.out.println("float: " + value);
System.out.println("double: " + temp);
System.out.println("long: " + val);
}
}
Non-Primitive Data Types in Java

Page 14 of 75
Object Oriented Programming 22CSE43

In Java, non-primitive data types are also known as reference data types. It is used to store
complex objects rather than simple values. Reference data types store references or memory
addresses that point to the location of the object in memory. This distinction is important
because it affects how these data types are stored, passed, and manipulated in Java programs.

1. Class

One common non-primitive data type in Java is the class. Classes are used to create objects,
which are instances of the class. A class defines the properties and behaviours of objects,
including variables (fields) and methods.

For example, you might create a Person class to represent a person, with variables for the
person's name, age, and address, and methods to set and get these values.

Syntax:

class Main

//code

2. Interface

Interfaces are another important non-primitive data type in Java. An interface defines a
contract for what a class implementing the interface must provide without specifying how it
should be implemented. Interfaces are used to achieve abstraction and multiple inheritance
in Java, allowing classes to be more flexible and reusable.

Syntax:
freestar

// interface

interface Shape {

public void draw(); // interface method (does not have a body)

public void color(); // interface method (does not have a body)

3. Arrays

Arrays are a fundamental non-primitive data type in Java that allows you to store multiple
values of the same type in a single variable. Arrays have a fixed size, which is specified when
the array is created and can be accessed using an index. Arrays are commonly used to store
lists of values or to represent matrices and other multi-dimensional data structures.
Page 15 of 75
Object Oriented Programming 22CSE43

Syntax:

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

4. String

In Java, a string is a sequence of characters. In simple words, we can define a string as an


array of characters. The difference between a character array and a string in Java is that the
string is designed to hold a sequence of characters in a single variable, whereas a character
array is a collection of separate char-type entities. Note that, unlike C/C++, Java strings are
not terminated with a null character.

Syntax:

// string without using new operator

String s = "tpointtech";

// String using new operator

String str = new String("Austria");

5. enum

Java also includes other non-primitive data types, such as enums and collections. Enums are
used to define a set of named constants, providing a way to represent a fixed set of values.
Collections are a framework of classes and interfaces that provide dynamic data structures
such as lists, sets, and maps, which can grow or shrink in size as needed.

Syntax:

enum Grade {
FIRST,
SECOND,
THIRD
}
Overall, non-primitive data types in Java are essential for creating complex and flexible
programs. They allow us to create and manipulate objects, define relationships between
objects, and represent complex data structures.

Java Non-Primitive Data Type Example

Example
enum Color {
RED,

Page 16 of 75
Object Oriented Programming 22CSE43

GREEN,
BLUE;
}
public class Main {
public static void main(String[] args) {
String str = "Hello";
int[] arr = { 1, 2, 3, 4, 5 };
Color clr = Color.BLUE;
System.out.println(clr);
System.out.println(str);
for (int member: arr) {
System.out.print(member+", ");
}
}
}
Why char uses 2 bytes in Java, and what is \u0000 ?

It is because Java uses the Unicode system, not the ASCII code system. The \u0000 is the
lowest range of the Unicode system.

Variables:
A variable is a container which holds the value while the Java program is executed. A variable
is assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local,
instance and static.

There are two types of data types in Java: primitive and non-primitive.

Variable

A variable is the name of a reserved area allocated in memory. In other words, it is a name of
the memory location. It is a combination of "vary + able" which means its value can be
changed.

Page 17 of 75
Object Oriented Programming 22CSE43

int data=50;//Here data is variable

Types of Variables

There are three types of variables in Java:

o local variable

o instance variable

o static variable

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that
the variable exists.

A local variable cannot be defined with "static" keyword.

Example of Local Variable

Example

1. //defining a Local Variable

2. int num = 10;

3. System.out.println(" Variable: " + num);

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not shared among
instances.

Example of Instance Variable


Page 18 of 75
Object Oriented Programming 22CSE43

Example

public class InstanceVariableDemo {


//Defining Instance Variables
public String name;
public int age=19;
//Creadting a default Constructor initializing Instance Variable
public InstanceVariableDemo()
{
this.name = "Deepak";
}
}
public class Main{
public static void main(String[] args)
{
// Object Creation
InstanceVariableDemo obj = new InstanceVariableDemo();
System.out.println("Student Name is: " + obj.name);
System.out.println("Age: "+ obj.age);
}
}
3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You can create
a single copy of the static variable and share it among all the instances of the class. Memory
allocation for static variables happens only once when the class is loaded in the memory.

Example Static variable

Example
class Student{
//static variable
static int age;
}
public class Main{
public static void main(String args[]){
Student s1 = new Student();
Student s2 = new Student();
s1.age = 24;
s2.age = 21;
Student.age = 23;
System.out.println("S1\'s age is: " + s1.age);
System.out.println("S2\'s age is: " + s2.age);
}
}
Let’s see some other Java programs for better understanding.

Page 19 of 75
Object Oriented Programming 22CSE43

Java Variable Example: Add Two Numbers

Example

int a=10;
int b=10;
int c=a+b;
System.out.println(c);
Java Variable Example: Widening

Example

int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
Java Variable Example: Narrowing (Typecasting)

Example

float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
System.out.println(f);
Java Variable Example: Overflow

Example
//Overflow
int a=130;
byte b=(byte)a;
System.out.println(a);
System.out.println(b);
Java Variable Example: Adding Lower Type
Example
byte a=10;
byte b=10;
//byte c=a+b;//Compile Time Error: because a+b=20 will be int
byte c=(byte)(a+b);
1. System.out.println(c);

Arrays:
An array is typically a grouping of elements of the same kind that are stored in a single,
contiguous block of memory.

Page 20 of 75
Object Oriented Programming 22CSE43

Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.

In contrast to C/C++, the length member allows us to obtain the array's length. We must
utilise the sizeof operator in C/C++.

An object of a dynamically formed class is called an array in Java. Java arrays implement the
Serializable and Cloneable interfaces and derive from the Object class. In Java, an array can
hold objects or primitive values. Java allows us to create single- or multi-dimensional arrays,
just like C/C++ does.

Additionally, C/C++ does not support the anonymous array functionality that Java does.

Advantages

o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.

o Random access: We can get any data located at an index position.

Disadvantages

o Size Limit: Arrays have a fixed size and do not grow dynamically at runtime.

Types of Array in java

There are two types of array.

Page 21 of 75
Object Oriented Programming 22CSE43

o Single Dimensional Array

o Multidimensional Array

Single-Dimensional Array in Java

A single-dimensional array in Java is a linear collection of elements of the same data type. It
is declared and instantiated using the following syntax:

dataType[] arr; (or)

dataType []arr; (or)

dataType arr[];

Instantiation of an Array in Java

arrayRefVar=new datatype[size];

Example of Java Array

Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.

Example

//Java Program to illustrate how to declare, instantiate, initialize


//and traverse the Java array.
public class Main{
public static void main(String args[]){
//declaration and instantiation of an array
int a[]=new int[5];
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++){//length is the property of array
System.out.println(a[i]);
}
}
}
Declaration, Instantiation and Initialization of Java Array

In Java, you can declare, instantiate, and initialize an array in a single line, as demonstrated
below:

int a[]={33,3,4,5};//declaration, instantiation and initialization

Page 22 of 75
Object Oriented Programming 22CSE43

Let's see the simple example to print this array.

Example

//Java Program to illustrate the use of declaration, instantiation


//and initialization of Java array in a single line
public class Main{
public static void main(String args[]){
//declaration, instantiation and initialization of an array
int a[]={33,3,4,5};
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
For-each Loop for Java Array

We can also print the Java array using for-each loop. The Java for-each loop prints the array
elements one by one. It holds an array element in a variable, then executes the body of the
loop.

The syntax of the for-each loop is given below:

for(data_type variable:array){

//body of the loop

Let's see the example of printing the elements of the Java array using the for-each loop.

Example

//Java Program to print the array elements using for-each loop


public class Main{
public static void main(String args[]){
//declaration and initialization of an array
int arr[]={33,3,4,5};
//traversal of an array using for-each loop
for(int i:arr)
System.out.println(i);
}
}
Passing Array to a Method in Java

We can pass the Java array to the method so that we can reuse the same logic on any array.
When we pass an array to a method in Java, we are essentially passing a reference to the

Page 23 of 75
Object Oriented Programming 22CSE43

array. It means that the method will have access to the same array data as the calling code,
and any modifications made to the array within the method will affect the original array.

Let's see the simple example to get the minimum number of an array using a method.

Example

//Java Program to demonstrate the way of passing an array to method.


public class Main{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];

System.out.println(min);
}

public static void main(String args[]){


int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}
}
Explanation

This Java program demonstrates the concept of passing an array to a method. The min
method takes an integer array arr as a parameter and finds the minimum element in the array
using a simple iterative loop. In the main method, an integer array a is declared and initialized
with values {33, 3, 4, 5}, and then the min method is called with this array as an argument.
The min method iterates through the array to find the minimum element and prints it to the
console.

Anonymous Array in Java

Java's anonymous arrays eliminate the requirement for separate declarations of array
variables by enabling developers to build and initialize arrays directly within method calls or
other expressions. When working with temporary arrays that are just needed for a single job
and don't need a persistent reference within the program, this is quite helpful.

Java supports the feature of an anonymous array, so we do not need to declare the array while
passing an array to the method.

Example

//Java Program to demonstrate the way of passing an anonymous array to method


public class Main{
Page 24 of 75
Object Oriented Programming 22CSE43

//creating a method which receives an array as a parameter


static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
public static void main(String args[]){
printArray(new int[]{10,22,44,66});//passing anonymous array to method
}
}
Explanation

In this example, the printArray method takes an integer array as a parameter and prints each
element of the array. In the main method, an anonymous array {10, 20, 30} is directly passed
as an argument to the printArray method. This concise syntax demonstrates the usage of
anonymous arrays in Java, allowing for more streamlined code without the need for
intermediate variable declarations.

Returning Array from the Method

In Java, methods are not limited to returning simple data types or objects; they can also
return arrays. This feature allows for more flexibility in method design and enables
developers to encapsulate complex logic for generating arrays within methods.

Example

//Java Program to return an array from the method


public class Main{
//creating method which returns an array
static int[] get(){
return new int[]{10,30,50,90,60};
}
public static void main(String args[]){
//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
}
Explanation

The example demonstrates how to return an array from a method in Java and subsequently
use the returned array in the calling code. By encapsulating array creation and initialization
logic within the get method, the code becomes more modular and reusable.

ArrayIndexOutOfBoundsException

Page 25 of 75
Object Oriented Programming 22CSE43

In Java, the ArrayIndexOutOfBoundsException is a runtime exception thrown by the Java


Virtual Machine (JVM) when attempting to access an invalid index of an array. This exception
occurs if the index is negative, equal to the size of the array, or greater than the size of the
array while traversing the array.

TestArrayException.java

//Java Program to demonstrate the case of


//ArrayIndexOutOfBoundsException in a Java Array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
}}
Multidimensional Array in Java

A multidimensional array in Java is an array of arrays where each element can be an array
itself. It is useful for storing data in row and column format.

Syntax to Declare Multidimensional Array in Java

dataType[][] arrayRefVar; (or)

dataType [][]arrayRefVar; (or)

dataType arrayRefVar[][]; (or)

dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java

arr[0][0]=1;

arr[0][1]=2;

arr[0][2]=3;

arr[1][0]=4;

arr[1][1]=5;

arr[1][2]=6;

arr[2][0]=7;

Page 26 of 75
Object Oriented Programming 22CSE43

arr[2][1]=8;

arr[2][2]=9;

Example of Multidimensional Java Array

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.

Example

public class Main {


public static void main(String args[]) {
int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // 3x3 matrix
// Printing the 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Explanation

This Java program initializes and prints a 2D array, representing a 3x3 matrix. Initially, a 2D
array named arr is declared and initialized with values using array initializer syntax. The
array consists of three rows, each containing three columns. The program then iterates
through each row and column of the array using nested loops. Within the loops, it prints the
value of each element, separated by a space. After printing all the elements of a row, a newline
character is printed to move to the next line. This process continues until all elements of the
array are printed. As a result, the program outputs the 3x3 matrix with each element
displayed in its respective row and column.

These examples demonstrate the declaration, instantiation, initialization, and traversal of


both single-dimensional and multidimensional arrays in Java.

Jagged Arrays in Java

In Java, a jagged array is an array of arrays where each row of the array can have a different
number of columns. This contrasts with a regular two-dimensional array, where each row
has the same number of columns.

Declaring and Initializing a Jagged Array

To declare a jagged array in Java, you first declare the array of arrays, and then you initialize
each row separately with its own array of columns.

Page 27 of 75
Object Oriented Programming 22CSE43

int arr[][] = new int[3][];

arr[0] = new int[3];

arr[1] = new int[4];

arr[2] = new int[2];

Example

//Java Program to illustrate the jagged array


public class Main{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;

//printing the data of a jagged array


for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}

Explanation

This Java program demonstrates the concept of a jagged array, where an array of arrays is
created, with each inner array having a different number of columns. Initially, a 2D array
named arr is declared with 3 rows, but with each row having a different number of columns:
the first row has 3 columns, the second row has 4 columns, and the third row has 2 columns.
The program then initializes the jagged array by filling it with sequential values starting from
0. Finally, it iterates through the array and prints out each element, row by row, separated by
a space, with a newline character indicating the end of each row.

What is the class name of a Java array?

Page 28 of 75
Object Oriented Programming 22CSE43

In Java, an array is an object. However, arrays have a special feature in Java where the JVM
generates a proxy class for each array object. This proxy class represents the runtime type of
the array. To obtain the class name of a Java array, you can use the getClass().getName()
method, which is available on all Java objects. This method returns a String representing the
fully qualified name of the class of the object, including any package information.

Example

//Java Program to get the class name of array in Java


public class Main{
public static void main(String args[]){
//declaration and initialization of array
int arr[]={4,4,5};
//getting the class name of Java array
Class c=arr.getClass();
String name=c.getName();
//printing the class name of Java array
System.out.println(name);
}
}
Explanation

This Java program demonstrates how to retrieve the class name of an array in Java using the
getClass().getName() method. It initializes an array arr with integer values, obtains the
runtime class of the array using getClass(), and retrieves the class name using getName().
The obtained class name, typically represented by a single character followed by square
brackets, reflects the dimensionality and type of elements in the array.

Copying a Java Array

Copying an array in Java can be achieved using the arraycopy() method of the System class.
This method allows you to copy elements from a source array to a destination array with a
specified starting position and length.

Syntax of arraycopy method

1. public static void arraycopy(

2. Object src, int srcPos,Object dest, int destPos, int length

3. )

Here, src is the source array, srcPos is the starting position in the source array, dest is the
destination array, destPos is the starting position in the destination array, and length is the
number of elements to be copied.

Example

Page 29 of 75
Object Oriented Programming 22CSE43

//Java Program to copy a source array into a destination array in Java


public class Main {
public static void main(String[] args) {
//declaring a source array
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
//declaring a destination array
char[] copyTo = new char[7];
//copying array using System.arraycopy() method
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
//printing the destination array
System.out.println(String.valueOf(copyTo));
}
}
Explanation

The Java program initializes two character arrays, copyFrom and copyTo, with predefined
values. It then utilizes the System.arraycopy() method to copy a portion of the copyFrom
array into the copyTo array, starting from index 2 and copying 7 elements. Finally, it prints
the contents of the copyTo array, resulting in the output "caffein".

Cloning an Array in Java

In Java, arrays implement the Cloneable interface, allowing us to create clones of arrays. If we
create a clone of a single-dimensional array, it creates a deep copy of the Java array. It means
it will copy the actual value. But, if we create the clone of a multidimensional array, it creates
a shallow copy of the Java array, which means it copies the references.

This distinction is important because modifying elements in a shallow copied


multidimensional array will affect both the original and cloned arrays, while in a deep copied
single-dimensional array, modifications will not impact the original.

TestarrayClone.java

//Java Program to clone the array


class TestarrayClone{
public static void main(String args[]){
int arr[]={33,3,4,5};
System.out.println("Printing original array:");
for(int i:arr)
System.out.println(i);
System.out.println("Printing clone of the array:");
int carr[]=arr.clone();
for(int i:carr)
System.out.println(i);
System.out.println("Are both equal?");

Page 30 of 75
Object Oriented Programming 22CSE43

System.out.println(arr==carr);
}
}
Explanation

An integer array called arr is initialised with the numbers {33, 3, 4, 5} in this Java programme,
and its elements are printed. Then, it uses the clone() method to duplicate arr, assigns the
result to carr, and prints the items of the duplicated array. The last line of the programme
compares arr and carr using the == operator; the result evaluates to false, meaning that arr
and carr are distinct array objects. The elements in both arrays, though, are the same.

Addition of Two Matrices in Java

A fundamental operation in linear algebra and computer science, matrix addition is


frequently utilised in a variety of applications, including scientific computing, computer
graphics, and image processing. To create a new matrix with the same dimensions as the
original, matching elements from each matrix must be added when adding two matrices in
Java. This Java program shows how to add matrices effectively by using stacked loops to do a
basic example of the process.

Let's see a simple example that adds two matrices.

ArrayAddition.java

//Java Program to demonstrate the addition of two matrices in Java


class ArrayAddition{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};

//creating another matrix to store the sum of two matrices


int c[][]=new int[2][3];

//adding and printing addition of 2 matrices


for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}

Page 31 of 75
Object Oriented Programming 22CSE43

}}
Explanation

Multiplication of Two Matrices in Java

Matrix multiplication is a crucial operation in mathematics and computer science, often


utilized in various applications such as graphics rendering, optimization algorithms, and
scientific computing. In Java, multiplying two matrices involves a systematic process where
each element in the resulting matrix is computed by taking the dot product of a row from the
first matrix and a column from the second matrix.

Let's see a simple example to multiply two matrices of 3 rows and 3 columns.

MatrixMultiplicationExample.java

//Java Program to multiply two matrices


public class MatrixMultiplicationExample{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two matrices


int c[][]=new int[3][3]; //3 rows and 3 columns

//multiplying and printing multiplication of 2 matrices


for(int i=0;i<3;i++){

Page 32 of 75
Object Oriented Programming 22CSE43

for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}}

Operators:
Operators are an essential part of any programming language. In Java, operator is a symbol
that is used to perform operations. For example: +, -, *, / etc. These are essential for
performing different types of operations on variables and values. In this section, we will
discuss different types of operators used in Java programming.

There are mainly eight types of operators in Java:

1. Unary Operator

2. Arithmetic Operator

3. Relational Operator

4. Ternary Operator

5. Assignment Operator

6. Bitwise Operator

Page 33 of 75
Object Oriented Programming 22CSE43

7. Logical Operator

8. Shift Operator

Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e. incrementing/decrementing a value by one, negating an expression
and inverting the value of a Boolean. Observe the following table.

Operator Name Description

+ Unary Plus Unary plus operator; indicates positive value (numbers are
positive without this, however)

- Unary Minus The Unary Minus operator can be used to make a positive
value negative.

! Logical The Not operator is used to convert a boolean value. In other


Complement words, it is used to reverse the logical state of an operand.
Operator

++ Increment It is used to increase the value of an operand by one. It can be


done in two possible ways. One is post-increment
(operand++) and other is pre-increment (++operand).
In post-increment, the value of the operand is used first, then
its value is increased by one.
In pre-increment, the value of the operand is incremented
first by one, then the incremented value of the operand is used.

-- Decrement It is used to decrease the value of an operand by one. It can


be done in two possible ways. One is post-decrement
(operand--) and other is pre-decrement (--operand).
In post-decrement, the value of the operand is used first,
then its value is decreased by one.
In pre-increment, the value of the operand is decrement first
by one, then the decremented value of the operand is used.
Java Unary Operator Example: ++ and --

Example

public class Main {


public static void main(String args[]) {
int x=+10;
Page 34 of 75
Object Oriented Programming 22CSE43

System.out.println(x); //10
System.out.println(-x); //-10
}
}
Java Unary Operator Example: Pre-increment and Post-increment

Example

public class Main {


public static void main(String args[]) {
int x=10;
System.out.println(x++); //10 (11)
System.out.println(++x); //12
}
}
Java Unary Operator Example: Pre-decrement and Post-decrement

Example

public class Main {


public static void main(String args[]) {
System.out.println(x--); //10
System.out.println(--x); //8
}
}
Java Unary Operator Example: Logical Complement Operator and Negation

Example

public class Main {


public static void main(String args[]) {
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}
}

Java Arithmetic Operators

Java arithmetic operators are used to perform addition, subtraction, multiplication, division,
and modulo operation. They act as basic mathematical operations.

Page 35 of 75
Object Oriented Programming 22CSE43

Operator Name Description

+ Addition Adds two numbers.

- Subtraction Subtracts one number from another number.

* Multiplication Multiplies two numbers.

/ Division Divides one number by another number.

% Modulus Divides and returns the remainder of two numbers.


Java Arithmetic Operator Example

Example

public class Main {


public static void main(String args[]) {
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}
}
Java Arithmetic Operator Example: Expression

Example

public class Main {


public static void main(String args[]) {
System.out.println(10*10/5+3-1*4/2);
}
}
Java Shift Operators

Java shift operator works on the bits of the data. It shifts the bits of the number from left to
right or right to left. The following table shows the types of shift operator in Java.

Operator Operator Name Description

<< Left Shift Operator All of the bits shift to left by a given number using this
(Signed) operator.

Page 36 of 75
Object Oriented Programming 22CSE43

>> Right Shift Operator All of the bits shift to right by a given number using
(Signed) this operator.

>>> Unsigned Right It is similar to the right shift operator (signed).


Shift Operator However, the vacant leftmost position is occupied
with 0 in place of the signed bit
Java Left Shift Operator

The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.

Java Left Shift Operator Example

Example

public class Main {


public static void main(String args[]) {
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}
}
Java Right Shift Operator

The Java right shift operator >> is used to move the value of the left operand to right by the
number of bits specified by the right operand.

Java Right Shift Operator Example

Example

public class Main {


public static void main(String args[]) {
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}
}
Java Shift Operator Example: >> vs >>> (Unsigned Shift)

Example

public class Main {


public static void main(String args[]) {
// For positive number, >> and >>> works same
System.out.println(20>>2);

Page 37 of 75
Object Oriented Programming 22CSE43

System.out.println(20>>>2);
// For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}
}
Java Relational Operators

Java relational or conditional operators are used to check relationship between two operands
such as less than, less than or equal to, greater than, greater than or equal to, equal to and
not equal to. It is also known as equality operator. These operators return Boolean values
either true or false.

Operator Name Description

< Less Than If the value of the first operand is lesser than the value of
the second operand, the Less Than operator returns true,
otherwise false.

> Greater Than If the value of the first operand is greater than the value of
the second operand, the Greater Than operator returns
true, otherwise false.

<= Less Than or When the value of the first operand is lesser than or equal
Equal to to the value of the second operand, the Less Than or Equal
to operator returns true, otherwise false.

>= Greater Than When the value of the first operand is greater than or equal
or Equal to to the value of the second operand, the Greater Than or
Equal to operator returns true, otherwise false.

== Equal to Equal to operator checks whether the given operands are


equal or not. If they are equal, they return true otherwise
false.

!= Not Equal to Not Equal to operator works just opposite to Equal to


operator. It returns false if the operands are equal in value,
otherwise true.
Java Relational Operator Example

Example

public class Main {


public static void main(String args[]) {
int a=10;
Page 38 of 75
Object Oriented Programming 22CSE43

int b=20;
System.out.println("(a < b) : " + (a<b));
System.out.println("(a > b) : " + (a>b));
System.out.println("(a <= b) : " + (a<=b));
System.out.println("(a >= b) : " + (a>=b));
System.out.println("(a == b) : " + (a==b));
System.out.println("(a != b) : " + (a!=b));
}
}
Java Bitwise Operators

Java bitwise operators are used to perform the manipulation of individual bits of a number
and with any of the integer types. They are used when performing update and query
operations of the Binary indexed trees.

Operator Operator Name Description

| Bitwise OR It is a binary operator which gives OR of the input values


bit by bit.

& Bitwise AND It is a binary operator which gives AND of the input
values bit by bit.

^ Bitwise XOR It is a binary operator which gives XOR of the input


values bit by bit.

~ Bitwise The Bitwise Complement operator is also a unary


Complement operator. It makes every bit 0 to 1, and 1 to 0.
Java Bitwise OR (|) Operator Example

Example

public class Main {


public static void main(String args[]) {
int a = 10; // binary representation 1010
int b = 5; // binary representation 0101
// a | b = 1010 | 0101 = 1111
// the value of 1111 in decimal representation is 15
System.out.println("The value of a | b is: " + (a | b));
}
}
Java Bitwise AND (&) Operator Example

Example

Page 39 of 75
Object Oriented Programming 22CSE43

public class Main {


public static void main(String args[]) {
int a = 11; // binary representation 1011
int b = 5; // binary representation 0101
// a & b = 1011 & 0101 = 0001
// the value of 0001 in decimal representation is 1
System.out.println("The value of a & b is: " + (a & b));
}
1. }

Java Bitwise XOR (^) Operator Example

Example

public class Main {


public static void main(String args[]){
int a = 11; // binary representation 1011
int b = 5; // binary representation 0101
// a ^ b = 1011 ^ 0101 = 1110
// the value of 1110 in decimal representation is 14
System.out.println("The value of a ^ b is: " + (a ^ b));
}
}
Java Bitwise Complement Operator Example

Example

public class Main {


public static void main(String args[]){
int a = 5; // binary representation 0101
// ~a = 1010 which will be represented as 10 in decimal format
// The compiler will give 2's complement of this number which is -6
System.out.println("The value of ~a is: " + (~a));
}
}
Java Logical Operators

Logical operators are used extensively in various programming languages to perform Logical
NOT, OR and AND operations whose functionality is similar to OR gate and AND gate in the
world of digital electronics.

Operator Name Description

&& Conditional The logical && operator does not check the second condition
AND Operator if the first condition is false. It checks the second condition
only if the first one is true.

Page 40 of 75
Object Oriented Programming 22CSE43

|| Conditional OR The logical || operator does not check the second condition
Operator if the first condition is true. It checks the second condition
only if the first one is false.

! Bitwise The NOT operator is used to reverse the value of a Boolean


Complement expression.
Java Logical AND (&&) Operator Example

Example

public class Main {


public static void main(String args[]) {
int a = 10;
int b = 5;
int c = 20;
// (a < b) evaluates to false. Therefore, (a < c) condition will not executed.
// Hence, the value of a will remain 10
if((a < b) && (++a < c))
System.out.println("if block is executed.");
else
System.out.println("else block is executed.");
System.out.println("The value of a is: " + a);
}
}
Java Logical OR (||) Operator Example

Example

public class Main {


public static void main(String args[]) {
int a = 10;
int b = 5;
int c = 20;
// the first condition (a > b) evaluates to true. Therefore, (a++ < c) will not be executed.
// Hence, the value of a will remain 10.
System.out.println(a > b || a++ < c);
System.out.println("The value of a is: " + a);
// the first condition (a < b) evaluates to false. Therefore, (a++ < c) will be executed.
// Hence, the value of a will be 11.
System.out.println(a < b || a++ < c);
System.out.println("The value of a is: " + a);
}
Java Logical NOT or Bitwise Complement (!)Operator Example

Example

Page 41 of 75
Object Oriented Programming 22CSE43

public class Main {


public static void main(String args[]) {
int a = 10;
int b = 5;
// the condition (a > b) evaluates to true. After applying NOT operator, the true value
// changes to false.
System.out.println(!(a > b));
// the condition (a < b) evaluates to false. After applying NOT operator, the false value
// changes to true.
System.out.println(!(a < b));
}
}
Java Ternary Operator

Java Ternary operator is used as one line replacement for if-then-else statement and used a
lot in Java programming. It is the only conditional operator which takes three operands.

Java Ternary Operator Example

The following example checks the maximum between two numbers.

Example

public class Main {


public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Java Assignment Operator

Page 42 of 75
Object Oriented Programming 22CSE43

Java assignment operator is one of the most common operators. It is used to assign the value
on its right to the operand on its left. The left operand has to be a variable and right operand
contains value. Note that the data type of both the operands has to be of the same type. If not,
an error will be raised by the compiler. The associativity of the assignment operators is form
right to left, which means values on the right side of the operator is assigned to the left side.

Types of Assignment Operator

There are two types of assignment operators. They are:

o Simple Assignment operator: The simple assignment operator where only (=) is used.

o Compound Assignment operator: The compound assignment operator is used where


-,+,/,* are used along with (=) operator.

The following table illustrates the working of the different assignment operators.

Types Operator Description

Single = It is the simplest assignment operator that assigns the value


Assignment of the right side to the variable of the left side.
Operator

Compound += It is a compound assignment operator which consists of +


Assignment and =. It first adds the current value of the variable present
Operator on the left side to the value on the right side and then assign
the result to the variable on the left side.

*= It is a compound assignment operator which consists of *


and =. It first multiplies the current value of the variable
present on the left side to the value on the right side and
then assign the result to the variable on the left side.

/= It is a compound assignment operator which consists of /


and =. It first divides the current value of the variable
present on the left side to the value on the right side and
then assign the quotient to the variable on the left side.

%= It is a compound assignment operator which consists of %


and =. It first divides the current value of the variable
present on the left side to the value on the right side and
then assign the remainder to the variable on the left side.
Java Assignment Operator Example

Page 43 of 75
Object Oriented Programming 22CSE43

Example
public class Main {
public static void main(String[] args) {
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
a %= 3; // 9 % 3 = 0
System.out.println(a);
}}
Note: In Java, the compound assignment operator performs implicit typecasting. The following
program illustrates the same.

Java Assignment Operator Example: Adding Short

In this example, we have used the compound operator +=. Similarly, we can do for the other
compound operators.

Example

public class Main {


public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine. It is because implicit typecasting has occurred.
a=a+b; // Compile time error because 10+10=20 now int, and int can't be assigned to a sh
ot without typecast
System.out.println(a);
}}
After Type Cast:

Example
public class Main {
public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
System.out.println(a);
}}
Java Operator Precedence

Page 44 of 75
Object Oriented Programming 22CSE43

Operator Type Precedence

Unary expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic */%

additive +-

Shift << >> >>>

Relational < > <= >= instanceof

equality == !=

Bitwise AND &

Bitwise exclusive OR ^

Bitwise inclusive OR I

Logical AND &&

Logical OR ||

Ternary ?:

Assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Control statements:
Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be
used to control the flow of Java code. Such statements are called control flow statements. It
is one of the fundamental features of Java, which provides a smooth flow of program.

Java provides three types of control flow statements.

Page 45 of 75
Object Oriented Programming 22CSE43

1. Decision Making statements

o if statements

o switch statement

2. Loop statements

o do while loop

o while loop

o for loop

o for-each loop

3. Jump statements

o break statement

o continue statement

1. Decision-Making statements:

As the name suggests, decision-making statements decide which statement to execute and
when. Decision-making statements evaluate the Boolean expression and control the program
flow depending upon the result of the condition provided. There are two types of decision-
making statements in Java, i.e., If statement and switch statement.

If Statement:

In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives a
Boolean value, either true or false. In Java, there are four types of if-statements given
below.

Simple if statement

if-else statement

if-else-if ladder

Nested if-statement
Page 46 of 75
Object Oriented Programming 22CSE43

Let's understand the if-statements one by one.

1) Simple if statement:

It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.

Syntax of if statement is given below.

if(condition) {

statement 1; //executes when condition is true }

Consider the following example in which we have used the if statement in the java code.

Example

public class Main {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}

2) if-else statement

The if-else statement is an extension to the if-statement, which uses another block of
code, i.e., else block. The else block is executed if the condition of the if-block is evaluated
as false.

Syntax:

if(condition) {

statement 1; //executes when condition is true

else{

statement 2; //executes when condition is false

Page 47 of 75
Object Oriented Programming 22CSE43

Consider the following example.

Example
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}

3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if statements.
In other words, we can say that it is the chain of if-else statements that create a decision
tree where the program may enter in the block of code where the condition is true. We
can also define an else statement at the end of the chain.
Syntax of if-else-if statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}

Consider the following example.


Example
public class Main {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");

Page 48 of 75
Object Oriented Programming 22CSE43

}else if (city == "Noida") {


System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}

4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside
another if or else-if statement.

Syntax of Nested if-statement is given below.

if(condition 1) {

statement 1; //executes when condition 1 is true

if(condition 2) {

statement 2; //executes when condition 2 is true

else{

statement 2; //executes when condition 2 is false

Consider the following example.

Example
public class Main {
public static void main(String[] args) {
String address = "Delhi, India";

if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);

Page 49 of 75
Object Oriented Programming 22CSE43

}
}else {
System.out.println("You are not living in India");
}
}
}
Switch Statement:

In Java, Switch statements are similar to if-else-if statements. The switch statement
contains multiple blocks of code called cases and a single case is executed based on the
variable which is being switched. The switch statement is easier to use instead of if-else-
if statements. It also enhances the readability of the program.

Points to be noted about switch statement:

The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java

Cases cannot be duplicate

Default statement is executed when any of the case doesn't match the value of expression.
It is optional.

Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.

While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.

The syntax to use the switch statement is given below.

switch (expression){

case value1:

statement1;

break;

case valueN:

statementN;

break;

default:
Page 50 of 75
Object Oriented Programming 22CSE43

default statement;

Consider the following example to understand the flow of the switch statement.

Example
public class Main {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
2. Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of instructions depends upon a
particular condition.

In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.

1. for loop

2. while loop

3. do-while loop

1. Java for loop

In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code. We use the for loop only when
we exactly know the number of times, we want to execute the block of code.

Page 51 of 75
Object Oriented Programming 22CSE43

1. for(initialization, condition, increment/decrement) {

2. //block of statements

3. }

The flow chart for the for-loop is given below.

public class Main {


public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Java for-each loop

Java provides an enhanced for loop to traverse the data structures like array or collection. In
the for-each loop, we don't need to update the loop variable. The syntax to use the for-each
loop in java is given below.

1. for(data_type var : array_name/collection_name){

2. //statements

3. }

Consider the following example to understand the functioning of the for-each loop in Java.

Example
public class Main {

Page 52 of 75
Object Oriented Programming 22CSE43

public static void main(String[] args) {


String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:");
for(String name:names) {
System.out.println(name);
}
}
}
2. Java while loop

The while loop is also used to iterate over the number of statements multiple times. However,
if we don't know the number of iterations in advance, it is recommended to use a while loop.
Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop
statement in while loop.

It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements
after the loop will be executed.

The syntax of the while loop is given below.

1. while(condition){

2. //looping statements

3. }

The flow chart for the while loop is given in the following image.

Page 53 of 75
Object Oriented Programming 22CSE43

Consider the following example.

Example

public class Main {


public static void main(String[] args) {
int i = 0;
System.out.println("Printing the list of first 10 even numbers");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}
3. Java do-while loop

The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at
least once, we can use do-while loop.

It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.

1. do

2. {

3. //statements

4. } while (condition);

The flow chart of the do-while loop is given in the following image.

Page 54 of 75
Object Oriented Programming 22CSE43

Consider the following example to understand the functioning of the do-while loop in Java.

Example

public class Main {


public static void main(String[] args) {
int i = 0;
System.out.println("Printing the list of first 10 even numbers ");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
3. Jump Statements
Jump statements are used to transfer the control of the program to the specific statements.
In other words, jump statements transfer the execution control to the other part of the
program. There are two types of jump statements in Java, i.e., break and continue.

Java break statement

As the name suggests, the break statement is used to break the current flow of the program
and transfer the control to the next statement outside a loop or switch statement. However,
it breaks only the inner loop in the case of the nested loop.

The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.

The break statement example with for loop

Consider the following example in which we have used the break statement with the for loop.

Example

public class Main {


public static void main(String[] args) {
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
} } } }
break statement example with labeled for loop

Page 55 of 75
Object Oriented Programming 22CSE43

Example

public class Main {


public static void main(String[] args) {
a:
for(int i = 0; i<= 10; i++) {
b:
for(int j = 0; j<=15;j++) {
c:
for (int k = 0; k<=20; k++) {
System.out.println(k);
if(k==5) {
break a;
}
}
}

}
}
}
Java continue statement
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.

Consider the following example to understand the functioning of the continue statement in
Java.

Example
public class Main {
public static void main(String[] args) {
for(int i = 0; i<= 2; i++) {

for (int j = i; j<=5; j++) {

if(j == 4) {
continue;
}
System.out.println(j);
}
}
}
}

Page 56 of 75
Object Oriented Programming 22CSE43

Class Fundamentals:
In object-oriented programming, classes and objects play a vital role in programming. These
are the two main pillars of OOP (Object-Oriented Programming). Without classes and objects,
we cannot create a program in Java.

What is a Class in Java?

A class is a group of objects that 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 Java class contains:

1. Fields

Variables stated inside a class that indicate the status of objects formed from that class are
called fields, sometimes referred to as instance variables. They specify the data that will be
stored in each class object. Different access modifiers, such as public, private, and protected,
can be applied to fields to regulate their visibility and usability.

2. Methods

Methods are functions defined inside a class that include the actions or behaviors that objects
of that class are capable of performing. These techniques allow the outside world to function
and change the object's state (fields). Additionally, methods can be void (that is, they return
nothing) or have different access modifiers. They can also return values.

3. Constructors

Constructors are unique methods that are used to initialize class objects. When an object of
the class is created using the new keyword, they are called with the same name as the class.
Constructors can initialize the fields of an object or carry out any additional setup that's
required when an object is created.
Page 57 of 75
Object Oriented Programming 22CSE43

4. Blocks

Within a class, Java allows two different kinds of blocks: instance blocks, commonly referred
to as initialization blocks and static blocks. Static blocks, which are usually used for static
initialization, are only executed once when the class is loaded into memory. Instance blocks
can be used to initialize instance variables and are executed each time a class object is
generated.

5. Nested Class and Interface

Java permits the nesting of classes and interfaces inside other classes and interfaces. The
members (fields, methods) of the enclosing class are accessible to nested classes, which can
be static or non-static. Nested interfaces can be used to logically group related constants and
methods together because they are implicitly static.

Java Class Syntax

class <class_name>{

field;

method;

What is an object in Java?

An object is a real-world entity that has state and behaviour. In other words, an object is a
tangible thing that can be touch and feel, like a car or chair, etc. The banking system is an
example of an intangible object. Every object has a distinct identity, which is usually
implemented by a unique ID that the JVM uses internally for identification.

Page 58 of 75
Object Oriented Programming 22CSE43

Characteristics of an Object

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

o Behavior: It represents the behavior (functionality) of an object, such as deposit,


withdraw, etc.

o Identity: An object's identity is typically implemented via a unique ID. The ID's value
is not visible to the external user; however, it is internally used by the JVM to identify
each object uniquely.

For Example, a Pen is an object. Its name is Reynolds; its 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 that has state and behavior.

o The object is an instance of a class.

Syntax of an Object

<class_name> variable=new <class_name>();

new keyword in Java

The new keyword is used to allocate memory at runtime. All objects get memory in the Heap
memory area.

In Java, an instance of a class (also referred to as an object) is created using the new keyword.
The new keyword dynamically allocates memory for an object of that class and returns a
reference to it when it is followed by the class name and brackets with optional arguments.

To read more Java new keyword

Class Example: main() Method Within The Class

In Java, the main() method can be declared in a class, which is typically done in
demonstration or basic programs. Having the main() method defined inside a class allows a
program to run immediately without creating a separate class containing it.

Page 59 of 75
Object Oriented Programming 22CSE43

In this example, we have created a Main class that has two data members, id and name. We
are creating the object of the Main class by using the new keyword and printing the object's
value.

Example

//Java Program to illustrate how to define a class and fields


//Defining a Student class.
class Main{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Main s1=new Main();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Explanation

Two fields are defined for the Main class in this Java program: an int type for the id and a
string type for the name. The Main class itself defines the primary method. The new keyword
is used to create an object s1 of the class Main inside the main() method. The fields' default
values, 0 for int and null for String, are printed because they are not explicitly initialized. The
program finally prints the values of the s1 object's name and id fields.

Class Example: main() Method Outside The Class

In real-world development, it is usual practice to organise Java classes into distinct files and
to place the main() method outside of the class it is intended to execute from. This strategy
improves the readability, maintainability, and reusability of the code.

In real-time development, we create classes and use them from another class. It is a better
approach than the previous one. Let's see a simple example, where we have a main() method
in another class.

Page 60 of 75
Object Oriented Programming 22CSE43

We can have multiple classes in different Java files or a single Java file. If you define multiple
classes in a single Java source file, it is a good idea to save the file name with the class name
that has a main() method.

Example
//Creating a Student class
class Student{
//declaring fields or instance variables
int id;
String name;
}
//Creating another class which contains the main() method
class Main{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Explanation

In the above Java program, the main() method is shown in a different class than the Student
class. There are no methods defined for the two fields, name and id, in the Student class. The
main() method then resides in another class called Main, where the default constructor is
used to generate an object s1 of type Student. The field's name and id are written with their
default values, which are null for String and 0 for int, since they are not explicitly initialised.

Initializing an Object in Java

There are the following three ways to initialize an object in Java:

1. By Reference Variable

2. By Method

3. By Constructor

1) Object Initialization through Reference Variable

Initializing an object means storing data in the object. Let's see a simple example where we
are going to initialize the object through a reference variable.

Example

class Student{
int id;
String name;
Page 61 of 75
Object Oriented Programming 22CSE43

}
public class Main{
public static void main(String args[]){
//Creating instance of Student class
Student s1=new Student();
//assigning values through reference variable
s1.id=101;
s1.name="Sonoo";
//printing values of s1 object
System.out.println(s1.id+" "+s1.name);
}
}
Explanation

In the above Java program, there are two classes, Student and Main. In the student class, we
have defined two fields, id and name. The main() method, which is the program's entry point,
is specified in the Main class. The new keyword is used to create an object s1 of type Student
inside the main() method. Next, values 101 and "Sonoo" are initialised in the id and name
fields of s1.

We can also create multiple objects and store information in them through a reference
variable.

Example

class Student{
int id;
String name;
}
public class Main{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
1. }

Page 62 of 75
Object Oriented Programming 22CSE43

Explanation

The above Java program shows how to create and initialise multiple Student class objects in
the Main class. We have created the objects s1 and s2 of the Student class by using the new
keyword. Subsequently, each object's name and id fields are initialized independently. ID is
set to 101, and the name is set to "Sonoo" for S1, and 102 and the name is set to "Amit" and
S2, respectively.

2) Object Initialization through Method

In this example, we are creating the two objects of Student class and initializing the value to
these objects by invoking the insertRecord method.

Here, we are displaying the state (data) of the objects by invoking the displayInformation()
method.

Example

class Student{
int rollno;
String name;
//Creating a method to insert record
void insertRecord(int r, String n){
rollno=r;
name=n;
}
//creating a method to display information
void displayInformation(){System.out.println(rollno+" "+name);}
}
//Creating a Main class to create objects and call methods
public class Main{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Explanation

The provided Java code includes two classes: Student and Main. The Student class includes
rollno and name as fields, along with the methods insertRecord() and displayInformation()
to initialise and print the respective fields' data. Two Student objects are created in the

Page 63 of 75
Object Oriented Programming 22CSE43

main() method of the Main class, and their corresponding insertRecord() methods are called
to set their rollno and name.

As we can see in the above figure, the object gets the memory in the heap memory area. The
reference variable refers to the object allocated in the heap memory area. Here, s1 and s2 are
reference variables that refer to the objects allocated in memory.

3) Object Initialization through a Constructor

The concept of object initialization through a constructor is essential to object-oriented


programming in Java. Special methods inside a class called constructors are called when an
object of that class is created with the new keyword. They initialise the state of objects by
entering initial values in their fields or carrying out any required setup procedures. The
constructor is automatically invoked upon object instantiation, guaranteeing correct
initialization of the object prior to usage.

If you are a beginner, skip this part because we will learn about the constructor later.

Here's an example demonstrating object initialization through a constructor.

Example

class Student {
int id;
String name;
// Constructor with parameters
public Student(int id, String name) {
this.id = id;

Page 64 of 75
Object Oriented Programming 22CSE43

this.name = name;
}
// Method to display student information
public void displayInformation() {
System.out.println("Student ID: " + id);
System.out.println("Student Name: " + name);
}
}
public class Main {
public static void main(String[] args) {
// Creating objects of Student class with constructor
Student student1 = new Student(1, "John Doe");
Student student2 = new Student(2, "Jane Smith");
// Displaying information of the objects
student1.displayInformation();
student2.displayInformation();
}
}
Explanation

In this example, the id and name fields of a Student object are initialised using a constructor
defined by the Student class, which accepts two parameters: id and name. Upon creating
objects student1 and student2 using this constructor, the fields of each are initialised with
the values supplied. This method ensures that objects are created with the correct starting
values, which makes it easier to instantiate and use objects later on in the program.

Object and Class Example: Employee

Let's see an example where we are maintaining records of employees.

Example

class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class Main {

Page 65 of 75
Object Oriented Programming 22CSE43

public static void main(String[] args) {


Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
Object and Class Example: Rectangle

Example

class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
public class Main{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Explanation

This Java code defines a Rectangle class with fields for length and width, along with methods
to insert dimensions and calculate the area. In the Main class's main() method, two Rectangle
objects are instantiated, and their dimensions are set using the insert method.

What are the different ways to create an object in Java?

There are the following ways to create an object in Java.

Page 66 of 75
Object Oriented Programming 22CSE43

1. By new Keyword

The most common way to create an object in Java is using the new keyword followed by a
constructor. For example,

ClassName obj = new ClassName();

It allocates memory for the object and calls its constructor to initialize it.

2. By newInstance() Method

This method is part of the java.lang.Class class and is used to create a new instance of a class
dynamically at runtime. It invokes the no-argument constructor of the class. For example,

1. ClassName obj = (ClassName) Class.forName("ClassName").newInstance();.

3. By clone() Method

The clone() method creates a copy of an existing object by performing a shallow copy. It
returns a new object that is a duplicate of the original object. For example,

ClassName obj2 = (ClassName) obj1.clone();.

4. By Deserialization
freestar

Objects can be created by deserializing them from a stream of bytes. We can achieve it by
using the ObjectInputStream class in Java. The serialized object is read from a file or network,
and then the readObject() method is called to recreate the object.

5. By factory Method

Factory methods are static methods within a class that return instances of the class. They
provide a way to create objects without directly invoking a constructor and can be used to
encapsulate object creation logic. For example,

ClassName obj = ClassName.createInstance().

We will learn these ways to create objects later.

Page 67 of 75
Object Oriented Programming 22CSE43

Anonymous Object

Anonymous simply means nameless. An object that has no reference is known as an


anonymous object. It can be used at the time of object creation only.

If we have to use an object only once, an anonymous object is a good approach. For example:

1. new Calculation();//anonymous object

Calling a method through an anonymous object

Calculation c=new Calculation();

c.fact(5);

Calling method through an anonymous object

new Calculation().fact(5);

Let's see the full example of an anonymous object in Java.

Example

class Main{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){

Page 68 of 75
Object Oriented Programming 22CSE43

new Main().fact(5);//calling method with anonymous object


}
}

Creating Multiple Objects by One Type Only

We can create multiple objects of one type only, as we do in the case of primitives.

Initialization of Primitive Variables

int a=10, b=20;

Initialization of Reference Variables

Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects

Let's see an example.

Example

//Java Program to illustrate the use of the Rectangle class, which


//has length and width data members
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class Main{
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Explanation

The usage of a Main class with length and width as its data members is demonstrated in this
Java program. There are methods in the class to compute the area of a rectangle and insert
dimensions. The main() method of the Main class uses a comma-separated list to generate
two Rectangle objects (r1 and r2) in one line, demonstrating the ability to instantiate

Page 69 of 75
Object Oriented Programming 22CSE43

multiple objects of the same type simultaneously. Each object's dimensions are then specified
by calling the insert method, and each rectangle's area is then calculated and printed by
calling the calculateArea() method.

Example
//Java Program to demonstrate the working of a banking-system
//where we deposit and withdraw amount from our account.
//Creating an Account class which has deposit() and withdraw() methods
class Account{
int acc_no;
String name;
float amount;
//Method to initialize object
void insert(int a,String n,float amt){
acc_no=a;
name=n;
amount=amt;
}
//deposit method
void deposit(float amt){
amount=amount+amt;
System.out.println(amt+" deposited");
}
//withdraw method
void withdraw(float amt){
if(amount<amt){
System.out.println("Insufficient Balance");
}else{
amount=amount-amt;
System.out.println(amt+" withdrawn");
}
}
//method to check the balance of the account
void checkBalance(){System.out.println("Balance is: "+amount);}
//method to display the values of an object
void display(){System.out.println(acc_no+" "+name+" "+amount);}
}
//Creating a test class to deposit and withdraw amount
class Main{
public static void main(String[] args){
Account a1=new Account();
a1.insert(832345,"Ankit",1000);
a1.display();
a1.checkBalance();
a1.deposit(40000);
Page 70 of 75
Object Oriented Programming 22CSE43

a1.checkBalance();
a1.withdraw(15000);
a1.checkBalance();
}}
Explanation

With methods for depositing, withdrawing, checking balance, and showing account details,
the Account class in this Java program emulates a simple banking system. Other
characteristics include account number, name, and amount. The creation, initialization, and
presentation of an Account object a1 with account information take place in the main()
method of the Main class. Next, the account is used for deposits and withdrawals, and after
each transaction, the balance is checked.

Difference Between Class and Object in Java

Feature Class Object

Definition A class is a blueprint or template It is an instance of a class.


for creating objects.

Type It is a logical entity. It is a real-world entity.

Memory Class definition does not occupy It occupies memory when an object is
Allocation memory. created.

Keyword It is created by using the class It is created by using the new keyword
keyword. and a class constructor.

Contains It contains properties and It is used to access the properties and


behaviors that an object will have. behaviors defined in the class.

Existence Exists only in source code. Exists in runtime (in memory).

Usage Defines the structure and behavior Represents an entity with actual
of objects. values.

Syntax class ClassName{ } ClassName objectName = new


ClassName();

Life It exists until the program runs. It exists as long as the object is
referenced in the program.

Page 71 of 75
Object Oriented Programming 22CSE43

Inheritance The classes can be extended using It cannot be inherited because objects
inheritance. are specific instances.

Questions:
1. A class is an instance of an object.
2. An object is a blueprint for a class.
3. A class is a blueprint for an object, and an object is an instance of a class.
4. An object and a class are identical in Java.
5. Justify the following:
1. Java arrays can dynamically change their size.
2. Java arrays can store elements of different data types.
3. Java arrays are always initialized with default values.
4. Java arrays do not allow duplicate elements.
6. List and explain Java buzzwords. Which factors are making Java famous
language(features of java)
7. Explain java tokens3.Explain java command line arguments4.What are the different
primitive data types in java? Give their sizes in bits5.Explain the importance of static
variable and method6.Give the brief note on operators in java.
8. Explain Precedence and Associativity of Operators8.How to use break and continue
statements in java?
9. Explain control statements
10. Explain looping statements with an example
11. Write any six significant differences between Procedure Oriented Programming and
Object Oriented Programming.
12. Define class and object in java. What is the importance of constructor? Write a java
program to perform constructor overloading
13. Illustrate the usage of this keyword
14. Explain about methods? Explain Method overloading?
15. explain about access modifiers?
16. Explain nested classes

Page 72 of 75
Object Oriented Programming 22CSE43

17. What is a Constructor? What is the main purpose of Constructors? How to invoke a
constructor in JAVA?
18. What is Java?
19. Why is Java a platform independent language?
20. What are the differences between C++ and Java?
21. Why is Java not a pure object oriented language?
22. List the features of the Java Programming language?
23. What do you get in the Java download file?
24. Explain JVM, JRE, and JDK.
25. What is a ClassLoader?
26. What are the Memory Allocations available in JavaJava?
27. What are the differences between Heap and Stack Memory in Java?
28. Explain the concept of Object-Oriented Programming (OOP) and its key principles
(Encapsulation, Inheritance, Polymorphism, Abstraction) with illustrative examples.
29. What is the difference between a class and an object in Java? Provide a code example
to demonstrate the creation and usage of objects.
30. Describe the purpose of constructors in Java. How do they differ from methods?
Explain constructor overloading with an example.
31. Explain the concept of inheritance in Java. How is it implemented using
the extends keyword? Give an example of a simple inheritance hierarchy.
32. What is polymorphism in Java? Explain different types of polymorphism (compile-
time and runtime) with examples.
33. Explain the concept of abstraction in Java. How can you achieve abstraction using
abstract classes and interfaces? Provide examples.
34. What are access modifiers in Java? Explain the purpose of public, private, protected,
and default access modifiers with examples.
35. Explain the difference between == and .equals() when comparing objects in Java.
Provide examples to illustrate the difference.
36. What is the purpose of this keyword in Java? Explain its usage with examples.
37. What is the purpose of the super keyword in Java? Explain its usage with examples.

Page 73 of 75
Object Oriented Programming 22CSE43

38. What is the difference between an abstract class and an interface in Java? When
should you use one over the other?
39. Explain the concept of method overloading and method overriding in Java. Provide
examples of both.
40. What are nested classes in Java? Explain the difference between inner classes and
static nested classes.
41. Explain the concept of encapsulation in Java. How can you achieve encapsulation
using access modifiers and getter/setter methods?
42. Explain the difference between primitive data types and objects in Java. Provide
examples of each.
43. What are the different types of operators in Java? Explain the purpose of each type
with examples.
44. Explain the concept of arrays in Java. How do you declare, initialize, and access
elements of an array?
45. What are the different control flow statements in Java? Explain the usage
of if, else, switch, for, while, and do-while statements with examples.
46. Explain the concept of exception handling in Java. What are try, catch, finally,
and throw keywords used for?
47. What is the difference between String, StringBuffer, and StringBuilder classes in Java?
When should you use each of them?
48. What is the purpose of the static keyword in Java? Explain its usage with examples.
49. What is the purpose of the final keyword in Java? Explain its usage with examples.
50. Explain the concept of packages and imports in Java. How do they help in organizing
code?
51. What is the purpose of the main method in Java? Why is it declared as static?
52. Explain the difference between && and & operators in Java. Provide examples to
illustrate the difference.
53. Explain the difference between break and continue statements in Java. Provide
examples to illustrate the difference.

Page 74 of 75
Object Oriented Programming 22CSE43

54. Write a Java program to calculate the area and perimeter of a rectangle. The program
should take the length and width as input from the user and display the calculated
area and perimeter.
55. Create a Java class named Rectangle with the following features:

Attributes: length and width (both should be private).


Constructor: To initialize the length and width.
Methods:
calculateArea(): Returns the area of the rectangle.
calculatePerimeter(): Returns the perimeter of the rectangle.
displayDimensions(): Displays the length and width of the rectangle.

Page 75 of 75

You might also like