Unit – 1:
1. operators programs
ans: See brief about different types of operators and examples.
https://www.geeksforgeeks.org/operators-in-java/
2. conditional statements
if,if-else,elif ladder,nested if else ( define and write a small
program/example)
https://www.geeksforgeeks.org/conditional-statements-in-
programming/
loop statements
while,do-while,for loop
Flow controls If Statement in Java
The if-else statement shall be applied to decide whether to use a given
condition. If this condition is true, it will evaluate the boolean expression
and execute a code block inside an if statement. If this condition is
false, a block of code in the other statement optional is executed. The
following is an example:
int age = 18;
if (age >= 18) {
System.out.println(“You are eligible to vote!”);
} else {
System.out.println(“You are not eligible to vote yet.”);
}
If-Else Statement in Java
If the statement does tell us that if a condition is true, an order of
statements must be executed in case it is false. What if we’re going to do
something else when the condition isn’t true? That’s the other
statement we got here. You can use the else statement with the if
statement to execute a code block when the condition is false.
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
If-Else-If ladder in Java
The IfElseIf ladder is a control flow in Java that allows programs to
perform an evaluation of several conditions, executing different blocks
of code on the basis of those conditions. It allows for forming a series of
if-else statements in an orderly fashion.
The IfelseElseIf ladder consists of multiple ifelseElseIf statements,
where each ifelseElseIf condition is evaluated only if the preceding
conditions are false. The ladder structure helps to organize and prioritize
the conditions that need to be checked.
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else if (condition3) {
// Code to be executed if condition3 is true
} else {
// Code to be executed if none of the conditions are true
}
Loops in Java
Programming constructs that make it possible to repeat the execution of
blocks of code are called loops in Java. They’re providing a way to extend
instructions until one of the conditions has been fulfilled. Java gives you
three main types of loops: for loop, while loop, and do while loop.
For Loop
If the number of iterations is known in advance, then a “for loop” will be
applied. It comprises three parts: initialization, condition, and
increment/decrement. The loop initializes a variable, checks the
condition, and executes code blocks for as long as this condition
remains false. Here is an example:
for (int i = 0; i < 5; i++) {
System.out.println(“Iteration: ” + i);
}
While Loop
If it is unknown in advance what number of iterations are used, the while
loop will be applied. Once the specified condition is met, it will
constantly execute a code block. Before each increment, the condition
shall be verified. Here is an example:
int count = 0;
while (count < 5) {
System.out.println(“Count: ” + count);
count++;
}
Do While Loop
The do-while loop is similar to the while loop, but the only difference is it
checks the condition after each iteration. It ensures that the code block
will be implemented at least once, regardless of whether this condition
was initially incorrect. Let’s take an example:
int num = 1;
do {
System.out.println(“Number: ” + num);
num++;
} while (num <= 5);
For Each Loop
In Java programming, the for-each loop, also known as the enhanced
for loop, is a convenient iteration construct that simplifies the process
of iterating over arrays or collections. It does not require explicit indexing
or manual iteration and makes it easy for users to access and apply
each sequence element.
Syntax:
for (elementType element : arrayOrCollection) {
// Code to be executed for each element
}
Continue Statement in Java
In Java, the continue statement is a control flow statement used within
loops to skip the remaining code in the current iteration and proceed to
the next iteration. On the basis of certain special conditions, it is
common to use selective bypass for some parts of the loop body.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the remaining code for i = 3
}
System.out.println(“Iteration: ” + i);
}
Break Statement in Java
The break statement controls the flow of loop and switch statements to
allow you to leave these blocks earlier than is necessary when some
conditions are met. It provides an efficient tool to control the operation
of a program and achieve desired behavior by means of specific criteria.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // Exit the loop when i is equal to 3
}
System.out.println(“Iteration: ” + i);
}
Return Keywords in Java
The Return keyword is used in Java to finish the execution of a method
and return value, where applicable. When a method is called, it will
perform a series of operations, which may lead to a result. We can
specify a value for which the caller of this method must send it back in
our return statement.
When the method is declared with a return type other than null, it
indicates that methods are expected to return a value for this specific
type. For example, if you declare a method by the return type int, it will
return an integer value. In these cases, the return keyword is used for
sending the value back to the caller.
If a method is declared with an unreturnable type, it will indicate that it
returned no value. In such cases, the return keyword is used to exit the
method without returning a value. Under certain conditions or to reach
the end of a method, it can be useful to terminate that method’s
implementation.
------------------------------------------------------------------------------------------
Unit-2
1.types of constructors and explanation
Constructors are special methods used to initialize objects in object-
orientated programming. When an object of a class is created, a
constructor is explicitly called by the compiler. A constructor's name is
always the same as the class name, and it has no return type, not even
void.
1. Default constructor
A default constructor is automatically provided by Java if no other
constructor is explicitly defined in the class. It takes no arguments and
initializes the object with default values (e.g., null for reference types, 0
for numeric types, false for boolean).
2. Parameterized constructor
A parameterized constructor is used when you have a class with
multiple instance variables, and you want to initialize them with specific
values at the time of object creation.
public class NumberHolder {
private int number;
// Default constructor initializes number to a default value
public NumberHolder() {
this.number = 10;
// Parameterized constructor initializes number to the provided value
public NumberHolder(int number) {
this.number = number;
// Getter method for number
public int getNumber() {
return number;
public static void main(String[] args) {
NumberHolder holder1 = new NumberHolder(); // Calls default constructor
NumberHolder holder2 = new NumberHolder(20); // Calls parameterized constructor
System.out.println("Value of holder1's number: " + holder1.getNumber());
System.out.println("Value of holder2's number: " + holder2.getNumber());
}
Method Overloading in Java
Method Overloading is a Compile time polymorphism. In method overloading, more than one
method shares the same method name with a different signature in the class. In method overloading,
the return type can or can not be the same, but we have to change the parameter because, in java, we
can not achieve method overloading by changing only the return type of the method.
// Java Program to Implement
// Method Overloading
import java.io.*;
class MethodOverloadingEx {
static int add(int a, int b)
return a + b;
static int add(int a, int b, int c)
return a + b + c;
public static void main(String args[])
System.out.println("add() with 2 parameters");
// Calling function with 2 parameters
System.out.println(add(4, 6));
System.out.println("add() with 3 parameters");
// Calling function with 3 Parameters
System.out.println(add(4, 6, 7));
Output:
add() with 2 parameters
10
add() with 3 parameters
17
Method Overriding in Java
Method Overriding is a type of runtime polymorphism. In method overriding, a method in a derived
class has the same name, return type, and parameters as a method in its parent class. The derived
class provides a specific implementation for the method that is already defined in the parent class.
Example of Method Overriding:
import java.io.*;
// Base Class
class Animal {
void eat() {
System.out.println("eat() method of base class");
System.out.println("Animal is eating.");
// Derived Class
class Dog extends Animal {
@Override
void eat() {
System.out.println("eat() method of derived class");
System.out.println("Dog is eating.");
// Method to call the base class method
void eatAsAnimal() {
super.eat();
// Driver Class
class MethodOverridingEx {
// Main Function
public static void main(String args[]) {
Dog d1 = new Dog();
Animal a1 = new Animal();
// Calls the eat() method of Dog class
d1.eat();
// Calls the eat() method of Animal class
a1.eat();
// Polymorphism: Animal reference pointing to Dog object
Animal animal = new Dog();
// Calls the eat() method of Dog class
animal.eat();
// To call the base class method, you need to use a Dog reference
((Dog) animal).eatAsAnimal();
Output:
Output
eat() method of derived class
Dog is eating.
eat() method of base class
Animal is eating.
eat() method of derived class
Dog is eating.
eat() method of base class
Animal is eating.
Final:
The final keyword in Java is used to restrict the behavior of variables, methods, and classes. Here's
how it works:
Uses of final Keyword
1. Final Variable:
o Once assigned, its value cannot be changed.
o If it's a reference variable, the object it refers to cannot be changed, but its fields can be
modified.
final int number = 10;
number = 20; // Error: cannot assign a value to final variable 'number'
2. Final Method:
o Prevents the method from being overridden by subclasses.
o It ensures the method's functionality remains the same.
class Parent {
final void display() {
System.out.println("This is a final method.");
class Child extends Parent {
// void display() {} // Error: Cannot override the final method from Parent
3. Final Class:
o Prevents the class from being inherited.
o Ensures the class remains immutable or its behavior unaltered.
final class FinalClass {
void show() {
System.out.println("This is a final class.");
class SubClass extends FinalClass { // Error: Cannot inherit from final class
class FinalKeywordDemo {
// Final variable
final int speedLimit = 90;
final void displayLimit() {
System.out.println("Speed Limit: " + speedLimit);
public static void main(String[] args) {
// Demonstrate final variable
FinalKeywordDemo obj = new FinalKeywordDemo();
obj.displayLimit();
// Uncommenting the next line will cause an error
// obj.speedLimit = 100; // Cannot modify a final variable
// Demonstrate final class
FinalClass finalClassObj = new FinalClass();
finalClassObj.show();
final class FinalClass {
void show() {
System.out.println("Final Class Method.");
Output
mathematica
Speed Limit: 90
Final Class Method.
Static :: refer java oops mid pdf
Array in Java
An array in Java is a collection of elements of the same data type, stored in a contiguous memory
location. Arrays are fixed in size and can store primitive data types (e.g., int, float) or objects.
Syntax for Array Declaration and Initialization
// Declaration
dataType[] arrayName;
// Declaration and Initialization
dataType[] arrayName = new dataType[size];
// Shortcut Initialization
dataType[] arrayName = {value1, value2, ..., valueN};
Types of Arrays in Java
1. Single-Dimensional Array:
A simple list-like structure where elements are accessed using a single index.
Example:
public class SingleDimArray {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
System.out.println("Accessing single-dimensional array:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
2. Two-Dimensional Array:
A table-like structure (matrix) where elements are accessed using two indices: rows and
columns.
Syntax:
dataType[][] arrayName = new dataType[rows][columns];
Example:
public class TwoDimArray {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("Accessing two-dimensional array:");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
System.out.println(); // New line after each row
Inheritance in Java (IMP)
Inheritance is a key concept in Object-Oriented Programming (OOP) that allows one class (child or
subclass) to acquire the properties (fields) and behaviors (methods) of another class (parent or
superclass). This promotes code reusability and hierarchical classification.
Syntax of Inheritance in Java
class Parent {
// Parent class properties and methods
class Child extends Parent {
// Child class properties and methods
• The keyword extends is used for inheritance.
• The child class inherits all non-private fields and methods from the parent class.
Types of Inheritance in Java (draw diagram for these types)
1. Single Inheritance:
A child class inherits from one parent class.
Example:
class Parent {
void show() {
System.out.println("This is a parent class.");
}
class Child extends Parent {
void display() {
System.out.println("This is a child class.");
public class SingleInheritance {
public static void main(String[] args) {
Child obj = new Child();
obj.show(); // Access parent class method
obj.display(); // Access child class method
Output:
This is a parent class.
This is a child class.
2. Multilevel Inheritance: (***imp )
A class inherits from a child class, forming a chain.
Example:
java
Copy code
class Grandparent {
void grandparentMethod() {
System.out.println("This is the grandparent class.");
class Parent extends Grandparent {
void parentMethod() {
System.out.println("This is the parent class.");
}
class Child extends Parent {
void childMethod() {
System.out.println("This is the child class.");
public class MultilevelInheritance {
public static void main(String[] args) {
Child obj = new Child();
obj.grandparentMethod(); // Access grandparent method
obj.parentMethod(); // Access parent method
obj.childMethod(); // Access child method
Output:
This is the grandparent class.
This is the parent class.
This is the child class.
3. Hierarchical Inheritance:
Multiple child classes inherit from a single parent class.
Example:
class Parent {
void parentMethod() {
System.out.println("This is the parent class.");
class Child1 extends Parent {
void child1Method() {
System.out.println("This is child 1.");
}
class Child2 extends Parent {
void child2Method() {
System.out.println("This is child 2.");
public class HierarchicalInheritance {
public static void main(String[] args) {
Child1 obj1 = new Child1();
obj1.parentMethod();
obj1.child1Method();
Child2 obj2 = new Child2();
obj2.parentMethod();
obj2.child2Method();
Output:
This is the parent class.
This is child 1.
This is the parent class.
This is child 2.
4. Multiple Inheritance (Not Supported in Java with Classes):
Java does not support multiple inheritance with classes to avoid ambiguity. However, multiple
inheritance can be achieved using interfaces.
Example:
interface A {
void methodA();
interface B {
void methodB();
}
class C implements A, B {
public void methodA() {
System.out.println("This is method A.");
public void methodB() {
System.out.println("This is method B.");
public class MultipleInheritanceWithInterface {
public static void main(String[] args) {
C obj = new C();
obj.methodA();
obj.methodB();
Output:
This is method A.
This is method B.
Interface in Java
An interface in Java is a reference type, similar to a class, that can contain only abstract methods
(methods without a body) and static final variables. Interfaces are used to define abstract
behaviors that can be implemented by any class, irrespective of where they sit in the class hierarchy.
The primary purpose of an interface is to define a contract that other classes must follow, providing a
way to achieve abstraction and multiple inheritance.
Syntax of an Interface
1. Defining an Interface:
interface InterfaceName {
// abstract method (implicitly public and abstract)
returnType methodName();
}
2. Implementing an Interface:
class ClassName implements InterfaceName {
// Providing concrete implementation of interface methods
public returnType methodName() {
// method body
Example program:
// Defining an interface
interface Animal {
// Abstract methods (no body)
void sound(); // Method to define sound of an animal
void sleep(); // Method to define sleep behavior
// Implementing the interface
class Dog implements Animal {
// Providing concrete implementation of the methods
public void sound() {
System.out.println("Dog barks.");
public void sleep() {
System.out.println("Dog sleeps in its kennel.");
class Cat implements Animal {
// Providing concrete implementation of the methods
public void sound() {
System.out.println("Cat meows.");
}
public void sleep() {
System.out.println("Cat sleeps on a mat.");
// Main class
public class InterfaceExample {
public static void main(String[] args) {
// Creating objects of classes that implement the interface
Animal dog = new Dog(); // Dog class implementing Animal interface
Animal cat = new Cat(); // Cat class implementing Animal interface
// Calling methods via interface reference
dog.sound();
dog.sleep();
System.out.println(); // Line break for clarity
cat.sound();
cat.sleep();
Abstract Class in Java
An abstract class in Java is a class that cannot be instantiated on its own and is meant to be
subclassed by other classes. It can contain both abstract methods (methods without a body) and
concrete methods (methods with a body). Abstract classes are used when you want to provide some
common functionality while forcing the subclasses to implement other methods.
Syntax of Abstract Class
abstract class ClassName {
abstract void abstractMethod();
void concreteMethod() {
System.out.println("This is a concrete method.");
}
abstract class Animal {
// Abstract method (does not have a body)
abstract void sound();
// Concrete method
void eat() {
System.out.println("This animal is eating.");
class Dog extends Animal {
void sound() {
System.out.println("Dog barks.");
class Cat extends Animal {
// Implementing the abstract method
void sound() {
System.out.println("Cat meows.");
public class AbstractClassExample {
public static void main(String[] args) {
// Animal obj = new Animal(); // This would give an error because Animal is abstract
Dog dog = new Dog();
dog.sound(); // Dog's implementation of sound
dog.eat(); // Inherited method from Animal
Cat cat = new Cat();
cat.sound(); // Cat's implementation of sound
cat.eat(); // Inherited method from Animal
}
OUTPUT:
Dog barks.
This animal is eating.
Cat meows.
This animal is eating.
Dynamic Method Dispatch in Java
Dynamic Method Dispatch is a mechanism in Java that allows Java to determine which method to
call at runtime rather than at compile time. It is one of the key features of polymorphism in Java,
specifically for overriding methods in inheritance hierarchies.
When a subclass overrides a method in the parent class, the runtime type of the object determines
which version of the method to invoke. This mechanism allows you to call the overridden method of
the subclass, even when using a reference of the superclass type.
// Parent class
class Animal {
// Overridden method
void sound() {
System.out.println("Animal makes a sound");
// Child class 1
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
// Child class 2
class Cat extends Animal {
@Override
void sound() {
System.out.println("Cat meows");
}
public class DynamicMethodDispatch {
public static void main(String[] args) {
// Parent reference and child objects
Animal animal1 = new Dog();
Animal animal2 = new Cat();
// Dynamic method dispatch happens here
animal1.sound(); // Calls Dog's sound()
animal2.sound(); // Calls Cat's sound()
OUTPUT:
Dog barks
Cat meows
Key Features of Dynamic Method Dispatch:
• Polymorphism: The main feature here is runtime polymorphism, where the method that gets
invoked depends on the object's actual type at runtime, not the reference type.
• Overriding vs Overloading: Dynamic dispatch is applicable when methods are overridden in
subclasses, not when they are overloaded.
• Flexibility: It allows for more flexible and reusable code, where you can write code that works
with the superclass type, but the correct subclass method will be called at runtime.