Module-1
Module-1
MODULE 1
Module Name: Java Fundamentals
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.
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.
Page 1 of 75
Object Oriented Programming 22CSE43
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.
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.
Page 2 of 75
Object Oriented Programming 22CSE43
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.
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.
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.
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.
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.
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
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
System.out.println("Hello World!");
} }
Data types:
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.
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.
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.
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;
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;
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;
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:
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;
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:
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
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:
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;
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:
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.
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:
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';
Page 13 of 75
Object Oriented Programming 22CSE43
Example
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 {
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
Syntax:
String s = "tpointtech";
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.
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
Types of Variables
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.
Example
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
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
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
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.
Disadvantages
o Size Limit: Arrays have a fixed size and do not grow dynamically at runtime.
Page 21 of 75
Object Oriented Programming 22CSE43
o Multidimensional Array
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[];
arrayRefVar=new datatype[size];
Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.
Example
In Java, you can declare, instantiate, and initialize an array in a single line, as demonstrated
below:
Page 22 of 75
Object Oriented Programming 22CSE43
Example
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.
for(data_type variable:array){
Let's see the example of printing the elements of the Java array using the for-each loop.
Example
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
System.out.println(min);
}
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.
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
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.
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
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
TestArrayException.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.
dataType []arrayRefVar[];
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;
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.
Example
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.
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.
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
Example
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.
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
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 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.
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
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".
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.
TestarrayClone.java
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.
ArrayAddition.java
Page 31 of 75
Object Oriented Programming 22CSE43
}}
Explanation
Let's see a simple example to multiply two matrices of 3 rows and 3 columns.
MatrixMultiplicationExample.java
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.
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
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.
+ 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.
Example
System.out.println(x); //10
System.out.println(-x); //-10
}
}
Java Unary Operator Example: Pre-increment and Post-increment
Example
Example
Example
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
Example
Example
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.
<< 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.
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.
Example
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.
Example
Example
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.
< 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.
Example
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.
& Bitwise AND It is a binary operator which gives AND of the input
values bit by bit.
Example
Example
Page 39 of 75
Object Oriented Programming 22CSE43
Example
Example
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.
&& 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.
Example
Example
Example
Page 41 of 75
Object Oriented Programming 22CSE43
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.
Example
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.
o Simple Assignment operator: The simple assignment operator where only (=) is used.
The following table illustrates the working of the different assignment operators.
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.
In this example, we have used the compound operator +=. Similarly, we can do for the other
compound operators.
Example
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
Arithmetic */%
additive +-
equality == !=
Bitwise exclusive OR ^
Bitwise inclusive OR I
Logical OR ||
Ternary ?:
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.
Page 45 of 75
Object Oriented Programming 22CSE43
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
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.
if(condition) {
Consider the following example in which we have used the if statement in the java code.
Example
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) {
else{
Page 47 of 75
Object Oriented Programming 22CSE43
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
}
Page 48 of 75
Object Oriented Programming 22CSE43
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.
if(condition 1) {
if(condition 2) {
else{
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.
The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
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.
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
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
2. //block of statements
3. }
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.
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
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.
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
Example
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
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.
Consider the following example in which we have used the break statement with the for loop.
Example
Page 55 of 75
Object Oriented Programming 22CSE43
Example
}
}
}
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++) {
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.
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.
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.
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.
class <class_name>{
field;
method;
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 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
Syntax of an Object
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.
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
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.
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.
1. By Reference Variable
2. By Method
3. By Constructor
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.
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.
If you are a beginner, skip this part because we will learn about the constructor later.
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.
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
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.
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,
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,
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,
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,
Page 67 of 75
Object Oriented Programming 22CSE43
Anonymous Object
If we have to use an object only once, an anonymous object is a good approach. For example:
c.fact(5);
new Calculation().fact(5);
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
We can create multiple objects of one type only, as we do in the case of primitives.
Example
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.
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.
Usage Defines the structure and behavior Represents an entity with actual
of objects. values.
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:
Page 75 of 75