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

Java OOPS Concepts Notes

The document provides an overview of Object-Oriented Programming (OOP) concepts, including classes, objects, methods, constructors, and the four pillars of OOP: encapsulation, inheritance, polymorphism, and abstraction. It explains how to define classes and create objects, as well as the differences between method overloading and overriding. Additionally, it covers the use of the 'this' keyword, static variables, and the importance of encapsulation in data security and maintainability.

Uploaded by

bandarbhai571
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java OOPS Concepts Notes

The document provides an overview of Object-Oriented Programming (OOP) concepts, including classes, objects, methods, constructors, and the four pillars of OOP: encapsulation, inheritance, polymorphism, and abstraction. It explains how to define classes and create objects, as well as the differences between method overloading and overriding. Additionally, it covers the use of the 'this' keyword, static variables, and the importance of encapsulation in data security and maintainability.

Uploaded by

bandarbhai571
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Object Oriented Programming : OOPs concept is based on the concept of objects, which

contain data (fields/attributes) and behavior (methods/functions).


Class : Defines the structure, attributes, and behaviors. It is like a blueprint.
Object : A real instance of the class, holding actual data. It is a physical entity.
Class Object
class ClassName ClassName ObjectName=new ClassName();
{
variables
methods
}
// Defining the class (Blueprint) // Main class to create an object
public class Car { public class Main {
public static void main(String[] args) {
// Fields (attributes)
String make; // Creating an object of the Car class
char model; Car myCar = new Car();
int year;
// Assigning data using object reference
// Method to display car details myCar.make=Toyota;
void displayDetails() myCar.model=C; Input
{ myCar.year=2020;
System.out.println("Car Make: " + make);
System.out.println("Car Model: " + model); // Calling the method of the object
System.out.println("Car Year: " + year); myCar.displayDetails();
OR Output :
System.out.prntln(make+" "+model+" "+year); Car Make: Toyota
} Car Model: C
Output : Toyota C 2020 Car Year: 2020
// User defined method (to directly assign //Assigning data using user defined method
data in main class) myCar.setCarData(“Toyota”, ‘C’,2020);
void setCarData(String cMake, char cModel,
int cYear) //Calling the method of the object Input
{ myCar.displayDetails();
make=cMake;
model=cModel;
year=cYear;
}
// Constructor to initialize the object (this) //Creating object & Assigning data using
Car(String make, char model, int year) constructor
{ Car myCar = new Car("Toyota", "Corolla", 2020);
this.make = make;
this.model = model;
this.year = year;
}
How many ways we can store data into variable ?
1) By using object reference variable
2) By using method
3) By using constructor

Methods :
Block or group of statements which will perform certain task.
We must call the method through object.
1) No parameters → No return value
2) No parameters → Returns value
3) Takes parameters → No return value
4) Takes parameters → Returns value
Class (without main method) Class (with main method)
public class Greetings { public class GreetingsMain {
public static void main(String[] args)
{
Greetings gr=new Greetings(); //Object

1) No parameters →No return value


void m1()
{ gr.m1();
System.out.println("Hello..");
}
2) No parameters → Returns value String s=gr.m2();
String m2()
System.out.println(s);
{
OR
return("Hello how are you?");
System.out.println(gr.m2());
}
3) Takes parameters → No return value
void m3(String name)
{ gr.m3("John");
System.out.println("Hello "+ name);
}
4) Takes parameters → Returns value String s=gr.m4("David");
String m4(String name)
System.out.println(s);
{
OR
return("Hello "+name);
System.out.println(gr.m4("David"));
}
Constructor: A constructor in Java is a special type of method used to initialize
objects. Constructors are automatically called when an object is created using the
new keyword.
Default Constructor Parameterized Constructor
public class ConstructorDemo { public class ConstructorDemo {
int x,y; int x,y;
ConstructorDemo() ConstructorDemo(int a, int b)
{ {
x=10; x=a;
y=20; y=b;
} }
void sum() void sum()
{ {
System.out.println(x+y); System.out.println(x+y);
} }

public static void main(String[] args) { public static void main(String[] args) {
ConstructorDemo cd=new ConstructorDemo(); ConstructorDemo cd=new ConstructorDemo(100,200);
cd.sum(); cd.sum();

//30 //300

Method Constructor
Method name can be anything Constructor name should be same as class name
Constructor will never return a value (not even
Method may or may not return a value
void)
If method is not returning any value, then We don't specify the void
specify void
Method can take parameters/arguments Constructor can take parameters/arguments
We have to invoke/call methods explicitly Constructor automatically invoked at the time of
through object object creation
Used for specifying logic Used for initializing the values of the variables

What are the four pillars of OOP?


1. Encapsulation – Hiding implementation details and exposing only necessary features.
2. Inheritance – Acquiring properties of a parent class in a child class.
3. Polymorphism – Same method, different behavior (Overloading & Overriding).
4. Abstraction – Hiding implementation details using abstract classes or interfaces.
Call by Value: When you pass a primitive type (like int, float, etc.) to a method, a copy of the
value is passed. Any changes made to the parameter inside the method do not affect the original
variable outside the method.
//passing copy of the variable
public class Test { public class CallByValue {
public static void main(String[] args) {
void m1(int number)
{ Test test=new Test();
number=number+10;
Syso("Value in the method:"+ number); int number=100;
} Syso("Before method:"+number); //100

test.m1(number); //110

Syso("After method:"+number); //100


//Original number doesn’t impact
}
Call By Reference:
Instead of value, passing the object reference.
By taking the reference of the object(test), we call the reference.
public class Test { class CallByReference {
public static void main(String[] args) {
int number;
// Create a Test object
// Method to modify the number field of the Test test = new Test();
Test object test.number = 100; // Initializing the number
void m2(Test t) { field

t.number = t.number + 10; // Print value before method call


// Modify the number field of the passed object Syso("Value before method: " + test.number);

Syso("Value in the method: " + t.number); // Call the m2 method and pass the test object
// Print the modified value test.m2(test);
}
} // Print the value of number after the method
call
Syso("Value after method: " + test.number);
This shows that the number field of the Test }
object is modified inside the m2() method }
because Java passes the reference (not the
actual object) to the method. //100
The change is reflected in the main method as //110
well. //110
Polymorphism: One thing can have many forms. (One method can have many forms
i.e. different parameters (int, double etc)
Shape - rectangle, triangle, circle etc...
Water - vapor, ice Burge
In Java, polymorphism can be achieved in two primary ways:
1. Compile-time Polymorphism (Method Overloading) : Occurs when multiple
methods in the same class have the same name but differ in the number or type of
parameters.
class X
{
void add()
void add(int x, int y)
}

2. Runtime Polymorphism (Method Overriding) : Occurs when a subclass provides a


specific implementation of a method that is already defined in its superclass. The method
that gets executed is determined at runtime based on the actual object type.
e.g. A subclass provides a new implementation for an inherited method.
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}

// Child class (Overriding the method)


class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
}
}
Method Overloading: Defining multiple methods in the same class with the same name but
different parameters.

Normal Class, Method creation Main Class, Object creation, Method Call
class Calculator { public static void main(String[] args) {

// Declare the variables outside the method Calculator calc = new Calculator();
int a = 10; // Instance variable a
int b = 20; // Instance variable b // Calls the method that prints the result
directly inside it
// Overloaded method with void return type calc.add();
void add() // add() method uses instance variables a
{ and b
int sum = a + b;
// Use the instance variables a and b //Sum of 10 and 20: 30
Syso("Sum of " +a+ " and " +b+ ": " +sum);
// Prints the sum directly inside the method
}

// Overloaded method to add three integers Syso(calc.add(2, 3, 4));


int add(int a, int b, int c) // Calls add(int, int, int) and prints the result
{
return a + b + c; //9
}

// Overloaded method to add two double Syso(calc.add(2.5, 3.5));


values // Calls add(double, double) and prints the
double add(double a, double b) result
{ }
return a + b; }
}
} //6.0
Constructor Overloading: Defining multiple constructors in the same class with the same
name but different parameters.
public class Box { public class BoxMain {

double width, height, depth; public static void main(String[] args)


Box() //1st Constructor {
{ Box b=new Box(); //1
width=0;
height=0; Box b=new Box(5.0,5.5,5.7); //2
depth=0;
OR Box b=new Box(10.5); //3
width=height=depth=0; //Created 3 objects to call 3 constructors
}
Syso(b.volume());
Box(double w, double h, double d) //2nd //Calling normal method for output
{ }
width=w; }
height=h;
depth=d;
}

Box(double len) //3rd


{
width=height=depth=len;
}

double volume()
//normal method for calculation/output
{
return (width*height*depth);
}
}
//w, h, d, len are variables
Day12 1:25
Can we pass parameters to main method? Yes
Can we overload main method? Yes
public static void main(String args[])
{
}
this Keyword:
When a constructor or method parameter has the same name as an instance variable, this is used
to differentiate between them.
OR
If using same name to class variables and local variables, then this keyword is used to
differentiate between them. (this keyword always refers to the class)
public class ThisKeyword { public static void main(String[] args)
{
int x, y;
// class variables/ instance variables

Example for method: //Object creation, methods to assign values and print
void setData(int x, int y) ThisKeyword th=new ThisKeyword();
//a,b are the local variables(if taken instead x ,y) th.setData(10,20);
{ th.display();
this.x=x;
this.y=y;
}
OR OR
Example for constructor: ThisKeyword th=new ThisKeyword(10,20);
ThisKeyword(int x, int y) th.display();
{
this.x=x;
}
this.y=y;
}
void display()
{
System.out.println(x+" "+y);
}

Types of variables:
• Class variables/Instance variables
• Local variables
Encapsulation: Data hiding by wrapping variables & methods in a single unit (class).
Use: If you want to provide some kind of security to the class variables
1) All variables should be private
2) For every variable there should be 2 methods (get & set)
3) Variables can be operated only through methods

public class Account { public class AccountMain {

private int accno; public static void main(String[] args) {


private String name;
private double amount; Account acc=new Account();

public int getAccno() {


return accno;
}
public void setAccno(int accno) { acc.setAccno(10101);
this.accno = accno;
}
public String getName() {
return name;
}
public void setName(String name) { acc.setName("John");
this.name = name;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) { acc.setAmount(12552.535);
this.amount = amount;
}

} System.out.println(acc.getAccno());
System.out.println(acc.getName());
NOTE: Every getter should return the value System.out.println(acc.getAmount())
instead of only printing }
}
Generate Setters and Getters :
NOTE: Instead of creating it manually -
Go to Source > Generate getters and setters > Select variable to generate getters and setters > Generate
Key Features of Encapsulation:
1. Data Hiding: Internal details of a class are hidden from the outside world. Access to them is
controlled using access modifiers.

o Private (private): Accessible only within the class.


o Protected (protected): Accessible within the class and its subclasses.
o Public (public): Accessible from anywhere.
2. Getter and Setter Methods: Instead of directly accessing class variables, encapsulation promotes
using getter and setter methods to read and modify data safely.

3. Improves Maintainability and Flexibility: Since data is accessed through methods, logic can be
modified without affecting external code.

4. Enhances Security: Prevents unauthorized access and accidental modification of critical data.

System.out.println() What it is ?
System.out.println("welcome") System : Predefined class

class Test out : PrintStream type static variable


{
static String s="welcome"; PrintSteam : Predefined Class
}
Test.s.lenght() print and println : Methods belongs to PrintStream class

class System
{
static PrintStream out;
}

System.out.print()
System.out.println()
static Keyword:
Make variable static only if we have a common data across multiple objects (eg. dept numbers are same). Then it
will be common across multiple object else variables are independent.

Advantage: Saves memory and updating it is easy.


1) static methods can access static stuff directly (without object). NOTE: Bcz public static void main(String[] args) {
2) static methods can access non-static stuff through object.
3) non-static methods can access everything directly.
Class with Main method Main class
(call static & non-static methods from same class) (call static & non-static methods from another class)
public class StaticDemo { public class StaticMain {
public static void main(String[] args) {
//Use reference class name – belongs to which class
static int a=10; // static variable System.out.println(StaticDemo.a);
int b=20; // non-static variable

static void m1() // static method StaticDemo.m1();


{
System.out.println("this is m1 static method...");
} // Create an object to call non static method/variable

void m2() // non-static StaticDemo sd=new StaticDemo();


{ System.out.println(sd.b);
System.out.println("this is m2 non-static method..."); sd.m2();
}

void m() // non-static sd.m();


{
System.out.println(a); }
System.out.println(b); }
m1();
m2(); NOTE:
} We can call static and non-static method from another
class using reference class name.
public static void main(String[] args) i.e. StaticDemo
{
System.out.println(a); m() is a non – static method
m1(); It has static and non-static methods in it 20`, and we
System.out.println(b); called m() method through the object sd.
//cannot access directly bcoz variable b is non-static
m2();
// we cannot access directly bcoz method m2 is non-static

// Create an object to call non static method/variable

StaticDemo sd=new StaticDemo();


System.out.println(sd.b);
sd.m2();
sd.m();
}
}
Inheritance:
Acquiring all the properties (Variables) & behaviors (methods) from one class to another class is called
inheritance. Creating a new class based on an existing class to promote code reuse.

Objective:
1) Re-usability
2) Avoid duplication
Common classes – 5

Home Loan Personal Loan


Total classes earlier – 10 20 Total classes earlier – 10

Different classes - 5 15 Different classes - 5

Class Parent Parent class Base class Super class

extends

Class Child Child class Derived class Sub class

Types: class Child extends Parent


NOTE: We cannot implement multiple inheritance using class concept (bcz we cannot extend
multiple class at a time) but with Interface concept (Interface A, B, C instead of parent class A, B, C)
Why cannot we do multiple inheritance?
Even though you have not created any duplicate methods in Parent class A and B (i.e. m1 and m2) still those classes are
having duplicate methods (i.e. m) coming from Object class (i.e. default parent class in java). By default, whenever you create
a class, it acquires everything from Predefined class i.e. object class in java (e.g. method m).

Predefined

Parent Class

Child class

class A public class InheritanceTypes {


{ public static void main(String[] args)
int a; {
void display() B bobj=new B();
{ bobj.a=10;
System.out.println(a); bobj.b=20;
}
} bobj.display();
bobj.show();
class B extends A
{
int b;
void show() C cobj=new C();
{ cobj.a=100;
System.out.println(b); cobj.b=200;
} cobj.c=300;
}
class C extends B
{ cobj.display();
int c; cobj.show();
void print() cobj.print();
{
System.out.println(c); }
} }
}
class Parent public class HierarchyInheritance {
{ public static void main(String[] args) {
void display(int a)
{ System.out.println(a); } Child1 c1=new Child1();
} c1.display(100);
c1.show(200);
class Child1 extends Parent{
void show(int b) Child2 c2=new Child2();
c2.display(10);
class Child2 extends Parent c2.print(20);
void print(int c) }
What is ??
public static void main(String args[])
{
}
public - Access modifier (can accessible everywhere in the project)
static - Directly called by JVM (without object) (static keyword must be the before method name)
void - No returned value
String args[] - String type array (It can accept any type of data using “ i.e. “10.5” “A” “Arshad” , that’s why it is string type array)

public static void main(String a[]) Valid


public static void main(String []a) Valid
void main(String args[]) public static Invalid
public static void main(int a[]) Invalid
static public void main(String args[]) Valid
static void public main(String args[]) Invalid

Explain the difference between == and .equals() in Java?


== (Reference Comparison) – Compares memory addresses.
.equals() (Content Comparison) – Compares actual values of objects.
e.g. String a = new String("Java");
String b = new String("Java");

System.out.println(a == b); // false (Different memory locations)


System.out.println(a.equals(b)); // true (Same content)
Method Overloading:
1. Possible only in single and multiple classes (inheritance)
2. We should change the signature (Parent) of the method
3. Method names are same
4. Belongs to polymorphism

Method Overriding:
1. Possible only in multiple classes (inheritance)
2. We should not change the signature (Parent) of the method but body(Child) we should change
3. Method names are same
4. Belongs to inheritance

Method Overloading vs. Method Overriding in Java:


Feature Method Overloading Method Overriding
Defining multiple methods in the same Defining a method in a subclass that has the same
Definition class with the same name but signature as a method in the superclass, but with a
different parameters. different implementation.
Same class (multiple methods with
Subclass & Superclass relationship (subclass
Where It Occurs the same name but different provides its own version of a method).
parameters).
Must be different (either in the
Parameters number, type, or order of parameters).
Must be exactly the same as the superclass method.

Return Type Can be different. Must be same (or a covariant return type).
Access Cannot have a more restrictive access level than the
Can have different access levels.
Modifiers overridden method in the superclass.
Cannot be overridden (but can be hidden if redefined
static Methods Can be overloaded. in the subclass).
final Methods Can be overloaded. Cannot be overridden.
Can be overloaded (multiple
Constructors constructors in the same class).
Cannot be overridden (constructors are not inherited).

Polymorphism Compile-time Polymorphism Runtime Polymorphism (decision is made at


Type (decision is made at compile-time). runtime).

@Override Required (Recommended) to ensure proper


Not required.
Annotation overriding.
class Bank
extends

class ICICI
extends

class SBI
In above, class Bank is immediate parent class of class ICICI and class ICICI is immediate parent class of class SBI.
super Keyword:
1. super keyword is used to invoke the immediate parent class variable (else latest variable invokes)
2. super keyword is used to invoke the immediate parent class method
3. super keyword is used to invoke the immediate parent class constructor
Overriding: Defining a method in a subclass that has the same signature as a method in the
superclass, but with a different implementation.

class Bank class ABC


{ {
double roi() void m1(int a)
{ {
return 0; System.out.println(a);
} }
} void m2(int b)
class ICICI extends Bank {
{ System.out.println(b);
double roi() }
{ }
return 10.5;
} class XYZ extends ABC
} {
class SBI extends Bank void m1(int a) // overriding
{ {
double roi() System.out.println(a*a);
{ }
return 11.5; void m2(int b) //overriding
} {
} System.out.println(b*b);
}
public class OverridingDemo { void m2(int a, int b) //overloading
{
public static void main(String[] args) { System.out.println(a+b);
}
ICICI ic=new ICICI(); }
System.out.println(ic.roi()); //10.5 public class OverloadingVsOverriding {

SBI sb=new SBI(); public static void main(String[] args) {


System.out.println(sb.roi()); //11.5
XYZ xyzobj=new XYZ();
} xyzobj.m1(10);
} xyzobj.m2(5);
xyzobj.m2(10,20);
}
}
Example of Method overriding, Constructor overloading:

public class Animal { public class TestSuper {

String color="white"; public static void main(String[] args)


{
void eat() Dog d=new Dog();
{
System.out.println("eating...."); d.displayColor();
} d.eat();
Animal() //constructor
{ or
System.out.println("This is Animal..");
} Dog d=new Dog("Elephant");
Animal(String name) //constructor }
{
System.out.println(name); }
}
NOTE:
class Dog extends Animal ✓ No need to use super keyword to invoke constructor
from parent class.
{ ✓ As the constructor invokes at the time of object
creation, it will 1st invoke from parent class then
String color="black"; child class.
✓ Constructor name should be same as class name
void displayColor() that is why constructor overriding is not possible
{
System.out.println(super.color); E.g. Why constructor overriding not possible..?
} public class Animal {
void eat()
{ Animal() //constructor
//System.out.println("eating bread"); {
super.eat(); System.out.println("This is Animal..");
} }
Dog() //constructor
{ class Dog extends Animal
super(); //Optional: invoke parent class
constructor Animal() //constructor
//System.out.println("this is Dog.."); {
} System.out.println("This is Animal..");
}
Dog(String name) //constructor
// Constructor name should be same as class name
{
super(name);
}
}
final Keyword:
If applied final keyword on:
Variables - We cannot change the value of the variable (constant)
Methods - We cannot override those methods in Child classes
Class - We cannot extend the class

class Test final class Arshad


{ {
final int x=100; final void m1()
} {
System.out.println("m1 from Test1");
public class FinalKeyword { }
}
public static void main(String[] args) {
class Mujawar extends Arshad
Test t=new Test(); // we cannot extend the class (Arshad is final class)
t.x=200; {
// we cannot change the value of x. x is final variable. void m1()
System.out.println(t.x); // we cannot override final methods (m1 is final method)
} {
System.out.println("m1 from Test2");
} }
}
public class FinalKeyword2 {
public static void main(String[] args) {
}
}

Difference between final, finally, and finalize in Java ?

Keyword Description Usage


final variable: Cannot be reassigned.
Used for constants, prevents
final final method: Cannot be overridden.
modification.
final class: Cannot be inherited.
Used in exception handling, Always executes after try-catch block, even if an
finally
always executes. exception occurs.
A method used for garbage Called by the Garbage Collector before an object
finalize
collection. is destroyed.
Data abstraction:
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.

Interface
1) An interface is a blueprint of class.
2) Interface contains final & Static variables.
3) Interface contains abstract methods. (also allowed default methods & Static methods from
java8 onwards)
4) An abstract method is a method contains signature but not body (Un-implemented method).
5) Methods in interface are public.
6) Interface supports the functionality of multiple inheritance.
7) We can define interface with interface keyword.
8) A class extends another class; an interface extends another interface, but a class
implements an interface.
9) We can create Object reference for Interface, but we cannot instantiate interface.

Access modifiers:
public - directly access all variables & methods everywhere
protected - accessible outside of package (sub classes) through inheritance
default – accessible only within the same package
private - access only within the same class
continue

interface Shape public static void main(String[] args) {


{
int length=10; // final and static //Scenario 1
int width=20; // final and static
InterfaceDemo idobj=new InterfaceDemo();
void circle(); // abstract method idobj.circle(); // abstract
idobj.square(); // default
default void square() Shape.rectangle(); // static
{ ( static method directly accessed through interface name )
System.out.println("this is square -
default method...."); System.out.println(Shape.length+Shape.width);//30
} //System.out.println(idobj.length+idobj.width);
static void rectangle()
{ idobj.triangle(); // access
System.out.println("this is
rectangle- static method...");
} //Scenario 2
}
public class InterfaceDemo implements Shape sh=new InterfaceDemo();
//use implemented class name at the time of obj creation
Shape
{
sh.circle(); // abstract method
public void circle()
sh.square(); // default method
{
//sh.rectangle(); // cannot access
System.out.println(" this is circle –
Shape.rectangle(); // static method
abstract method...");
//sh.triangle() ; // cannot access
}
//Whenever you are implementing any method from the
interface into the class need to specify public access }
modifier – implementation of abstract method }
void triangle()
{
System.out.println("this is
triangle..");
}

Why interface is needed, where we are going to use.? (Development)


Initially developers aware of requirements but they don’t to know how to implement them,
they will start creating requirement in the form of interfaces they keep all abstract method, once they understand
how to implement then they can start creating classes.
We are going to use existing interface (Selenium WebDriver)(Testing)
Initially they have created WebDriver which contains so many types of methods later on they have created multiple
classes to implement this webdriver.
e.g. ChromBrower class, EdgeBroweser class
Multiple Inheritance:
public interface I1 { public interface I2 {

int x=100; int y=200;


void m1(); void m2();
}
}
public class MultipleInheritance implements I1,I2
{

public void m1()


{
System.out.println(" this is m1...");
}

public void m2()


{
System.out.println("this is m2...");
}

public static void main(String[] args) {

MultipleInheritance mi=new MultipleInheritance();


mi.m1();
mi.m2();

System.out.println(mi.x);
System.out.println(mi.y);
}
}

Interface Interface Class Class

I1 I1 C1 C2 Parent
11

C Child

C extends C1 implements I1, I2 //Possible


C extends C1,C2 implements I1, I2 //Not Possible (only one class is allowed as parent)

Multiple Inheritance using Interface concept


Wrapper Classes – Data Conversion
In Java, a wrapper refers to a class that encapsulates a primitive data type, allowing it to be
treated as an object. Java provides wrapper classes for all primitive data types in the java.lang
package.
• For every primitive data type there is corresponding wrapper class is available.
• Wrapper classes convert primitive to object type and vice versa.
• Collection in java allows only object type of data.

List of Wrapper Classes:


Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

Why Use Wrapper Classes?


1. Collection Framework Compatibility – Collections (e.g., ArrayList, HashMap) only work with
objects, not primitives.
2. Utility Methods – Wrapper classes provide useful methods for conversions, parsing, etc.
3. Autoboxing & Unboxing – Automatic conversion between primitive types and their wrapper
objects.
Auto boxing (Primitive Object)
Un-boxing (Object Primitive)
Key Features:
• Autoboxing: Automatically converts primitives to wrapper objects.
• Unboxing: Automatically converts wrapper objects to primitives.
• Immutable: Wrapper objects are immutable (cannot be changed after creation).
• Parsing & Conversion: Methods like parseInt(), toString(), and valueOf() help in conversions.

Example:
int x=100;
double d=10.5;
Integer x=100;
Double d=10.5
String s="welcome";
String s1="welcome"; // cannot convert to number
String s1="150"; // can convert to number
String s2="160"; // can convert to number

Scenario 1: int, double, bool, char → String (Possible)


Scenario 2: String → int, double, bool, char (Not possible)
public class WrapperExample { public class DataConvertions {
public static void main(String[] args) { 1. Implicit (Widening) Conversion
int → double
int no = 10; int num = 100;
double d = num; // int to double (automatic conversion)
// Autoboxing: Converting primitive to Wrapper Object
Integer num = no; // Object System.out.println("Integer value: " + num);
Or System.out.println("Converted to double: " + d);
Integer num = 10; // Equivalent to Integer.valueOf(10)
Double price = 99.99; 2. Explicit (Narrowing) Conversion
Character letter = ‘A’; double → int
Boolean bool = true; double d = 99.99;
int num = (int) d; // Explicit conversion (double to int)
// Unboxing: Converting Wrapper Object to primitive // type casting
int n = num; // Equivalent to num.intValue() System.out.println("Double value: " + d);
double p = price; System.out.println("Converted to int: " + num);
char l = letter; // 99 (decimal part lost)
boolean b = bool; 3. Type Conversion using Wrapper Classes
int num = 50;
// Wrapper class methods
String str = Integer.toString(100); Integer obj = Integer.valueOf(num); // Boxing (primitive to object)
// Convert int to String int value = obj.intValue(); // Unboxing (object to primitive)
int parsedValue = Integer.parseInt("50");
// Convert String to int System.out.println("Boxed Integer: " + obj);
System.out.println("Unboxed int: " + value);
System.out.println("Autoboxed Integer: " + num);
System.out.println("Unboxed int: " + n); 4. String Conversion
System.out.println("Converted String: " + str); Primitive to String: int, double, bool, char → String
System.out.println("Parsed int: " + parsedValue); Use String.valueOf() or toString()
} int num = 100;
} String str = String.valueOf(num);
or
Conversion Type Method Integer.toString(num)
Widening (auto) int → long → float → double System.out.println("Converted String: " + str);
Narrowing (manual) (type) value
Primitive → Object Integer.valueOf(int) boolean bool=true;
String str=String.valueOf(bool);
Object → Primitive obj.intValue()
System.out.println("Converted String: " + str);
Primitive → String String.valueOf(int)
String → Primitive Integer.parseInt(str) String to Primitive: String → int, double, bool, char (not possible)
Use wrapper class methods like parseInt(), parseDouble()
String str = "123";
int num = Integer.parseInt(str);
System.out.println("Converted int: " + num);

String str ="10.5";


double dou = Double.parseDouble(str);
System.out.println("Converted double: " + dou);

String str = “true”;


boolean bool = Boolean.parseBoolean(str);
System.out.println("Converted boolean: " + bool);
NOTE:
String s="welcome"; // cannot convert to number
String → char // cannot covert - not possible
Packages:
built-in packages - java.util, java.io, etc.
user-defined packages - Custom packages created using package keyword.
sub packages - A package inside another package.

Access modifiers:
public - directly access all variables & methods everywhere
protected - accessible outside of package (sub classes) through inheritance
default – accessible only within the same package
private - access only within the same class

package mainPack.subPack2;
import mainPack.subPack1.ClassTest1; // if accessing outside the package
public class ClassTest2 {

public class ClassTest2 extends ClassTest1{ // Protected example

Type Casting in Java - Type casting refers to converting one data type into another.
1. Implicit (Widening) Casting – byte → short → int → long → float → double
Performed automatically when converting a smaller type to a larger type.
2. Explicit (Narrowing) Casting – double → float → long → int → short → byte
Requires manual (type) conversion when converting a larger type to a smaller type.
int i=100; double d=10.5;
double d=i; // up casting int i=(int)d; // down casting
System.out.println(d); //100.0 System.out.println(i); //10

Ex1:
Object o=new String("welcome");
StringBuffer sb=(StringBuffer) o; Rule1 Rule2 Rule3
Ex2:
String s=new String("welcome");
StringBuffer sb=(StringBuffer) s; Rule1
Ex3:
Object o=new String("welcome");
StringBuffer sb=(String) o; Rule1 Rule2
Ex4:
String s=new String("welcome");
StringBuffer sb=(String) s; Rule1 Rule2
Ex5:
Object o=new String("welcome");
String s=(String) o; Rule1 Rules2 Rule3

System.out.println(s);
A B C D
Cat ct = (Cat) an;
class Animal{}
class Dog extends Animal{} Converting an to Cat
class Cat extends Animal{} reference variable for cat obj animal type of object/variable

class Animal

public class TypeCastingObjects { class Dog class Cat


public static void main(String[] args) {

Rule 1: Conversion is valid or not: The type of 'D' and 'C' must have some relationship (either parent to child or child to
parent or same type).
Animal an=new Dog(); //Animal reference (an) is being converted into a Dog reference. A Dog object is created, but it is stored in Animal ref.
Cat ct=(Cat) an; // Rule 1

Dog dg=new Dog();


Cat ct=(Cat) dg; // Rule1

Rule2: Assignment is valid or not : 'C' must be either same or child of 'A'.
Animal an=new Dog();
Cat ct=(Cat) an; // Rule2

Animal an=new Dog();


Cat ct=(Dog) an; // Rule2

Rule3: The underlying object type of 'D' must be either same or child of 'C'.
Animal an=new Dog();
Cat ct=(Cat) an; // Rule 3

Animal an=new Dog(); // Upcasting (Dog → Animal)


Dog dg=(Dog) an; // Down casting (Animal → Dog) // Rule1 – Rule2 – Rule3

Step-by-Step Breakdown:
Animal an = new Dog(); → Upcasting
• A Dog object is created, but it is stored in an Animal reference.
• This is safe and happens implicitly because Dog is-a Animal (inheritance).
Dog dg = (Dog) an; → Downcasting
• an actually holds a Dog object, so downcasting is valid.
• The explicit cast (Dog) an tells Java to treat an as a Dog object.
• Now, dg can access both Animal and Dog methods.
Exception handling:
Exception is an event which will cause program termination.
Types of Errors:
1. Syntax Errors – Issues in code structure, caught during compilation.
2. Logical Errors – Code runs but produces incorrect results.
Types of Exceptions:
1. Checked Exceptions (Compile-time Exceptions)
• Exceptions identified by the Java compiler.
• Must be handled using try-catch or declared with throws.
• Examples:
o InterruptedException
o FileNotFoundException
o IOException
2. Unchecked Exceptions (Runtime Exceptions)
• Exceptions not checked at compile time, occurring during execution.
• Usually caused by programming mistakes.
• Examples:
o ArithmeticException (e.g., division by zero)
o NullPointerException (accessing an object reference that is null)
o ArrayIndexOutOfBoundsException (accessing an invalid array index)

import java.util.Scanner;
System.out.println("program is started.........");
Scanner sc=new Scanner(System.in);

Example1 Example2
System.out.println("Enter a number:"); int a[]=new int[5];

int num=sc.nextInt(); System.out.println("Enter the position(0-4):");


int pos=sc.nextInt();
System.out.println(100/num);
// ArithmeticException System.out.println("Enter the value:");
int value=sc.nextInt();
a[pos]=value;
//ArrayIndexOutOfBoundsException

System.out.println(a[pos]);
Example3 Example4
String s="welcome"; String s=null;
int num=Integer.parseInt(s); System.out.println(s.length());
//NumberFormatException //NullPointerException
System.out.println(num);

System.out.println("program is completed........");
Exception Handling using try-catch-finally
try
{
}
catch(“Exception name here and reference variable”)
{
}
finally
{
}

✓ try Block: The try block contains the code that might throw an exception. If an exception occurs, execution
jumps to the catch block.
✓ catch Block: The catch block handles the exception. It catches specific exceptions and prevents program
termination. You can also use multiple catch blocks to handle different exceptions
✓ finally Block: The finally block executes always, whether an exception occurs or not. It is typically used for
resource cleanup (e.g., closing files or database connections).

Example Demonstrating finally


public class ExceptionHandlingExample {
public static void main(String[] args) {
try
{
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // This will throw ArrayIndexOutOfBoundsException
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index is out of bounds: " + e.getMessage());
}
finally
{
System.out.println("This will always execute.");
}
}
Output:
Array index is out of bounds: Index 5 out of bounds for length 3
This will always execute.

Understanding the finally Block


The finally block always executes, regardless of whether an exception occurs or not.

Case Exception Occurred? Catch Block Executed? Finally Block Executed?


Case 1 Yes Handled Yes
Case 2 Yes Not Handled Yes
Case 3 No Ignored Yes
Handling Unknown Exceptions (2. Unchecked - Runtime)
If you're unsure what type of exception might occur, you have two solutions:
1. Multiple catch Blocks
You can use multiple catch blocks to handle different types of exceptions separately.
try
{
int num = Integer.parseInt("ABC"); // This will throw NumberFormatException
}
catch (ArithmeticException e)
{
System.out.println("Arithmetic Exception: " + e.getMessage());
}
catch (NumberFormatException e)
{
System.out.println("Number Format Exception: " + e.getMessage());
}
catch (Exception e) // Catches any other exception
{
System.out.println("Some other exception occurred: " + e.getMessage());
}
2. Using the Exception Class
If you don’t know what exception might occur, you can catch all exceptions using the generic Exception class.
try
{
int x = 10 / 0; // This will throw ArithmeticException
}
catch (Exception e) // Catches all exception
{
System.out.println("Exception occurred: " + e.getMessage());
}
Note: Catching Exception is useful but should be used cautiously, as it hides specific exceptions.
Handling Unknown Exceptions (1. Checked – Compile time)
Checked exception can be handled using throws and try-catch
public class CheckedExceptions {
public static void main(String[] args) throws IOException {

System.out.println("Program is started..");
System.out.println("Program is progress..");
//
try
try-catch {
FileInputStream file=new FileInputStream("C:\\file.txt");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
//
FileInputStream file=new FileInputStream("C:\\file.txt");
throws
System.out.println(file.read());
System.out.println("Program is completed..");
Collections:
The Collections Framework in Java provides a set of interfaces and classes to store and manage objects efficiently.
Collection (Interface)

List (I) Set (I) Map (I)


Ordered, allows duplicates Unordered, no duplicates stored in the form of key, value pairs

ArrayList (C)→ Dynamic array, fast access HashSet (C) → Uses HashMap internally, no order HashMap (C)
LinkedList (C)→ Doubly linked list, fast insert/delete Unordered, allows one null key, fast lookup

ArrayList:
ArrayList is a class in Java that implements the List interface, which is part of the java.util package.
An ArrayList in Java is a resizable array that is part of the java.util package. Unlike a normal array, which has a fixed
size, an ArrayList can grow and shrink dynamically.
Key Features:
• Heterogeneous data - allowed
• Insertion order- preserved (Index)
• Duplicate elements - allowed
• Multiple nulls - allowed
Important Methods:
• add(), add(index, element), get(), set(), remove(), contains(), size(), isEmpty(), clear()
• Iterating using for-loop, foreach-loop, Iterator

HashSet:
HashSet is a class in Java that implements the Set interface, which is part of the java.util package.
Key Features:
• Heterogeneous data - allowed
• Insertion order - Not preserved (Index not supported)
• Duplicate elements - Not Allowed
• Multiple nulls - Not allowed / only single null is allowed

HashMap:
HashMap is a class in Java that implements the Map interface and is used to store key-value pairs.
Key Features:
• Heterogeneous data - allowed
• Data can be stored in the form of key, value pairs.
• Key is unique. But we can have duplicate values.
• Insertion order not preserved (Index not followed)
• Allows one null key but multiple null values
ArrayList Example :
import java.util.ArrayList; 11. Iterating through the ArrayList (3 methods)
import java.util.Iterator;
public class ArrayListExample { (i) Using for-loop
public static void main(String[] args) { System.out.println("\nIterating using for-loop:");
for (int i = 0; i < myList.size(); i++)
1. Creating an ArrayList of Strings {
ArrayList<String> myList = new ArrayList<String>(); System.out.println(myList.get(i));
}
2. Adding elements (directly as Strings)
myList.add("Alice"); // String (ii) Using enhanced for-each loop
myList.add("25"); // Integer as String System.out.println("\nIterating using for-each loop:");
myList.add("3.14"); // Double as String for (Object x : myList)
myList.add("true"); // Boolean as String {
myList.add("A"); // Character as String System.out.println(x);
myList.add(null); // Null value }
myList.add("25"); // Duplicate value
myList.add("Alice"); // Duplicate String (iii) Using Iterator
System.out.println("\nIterating using Iterator:");
System.out.println("ArrayList after adding elements: " + Iterator<String> it = myList.iterator();
myList); while (it.hasNext())
{
3. Inserting element at a specific index System.out.println(it.next());
myList.add(2, "Inserted Element"); }
System.out.println("\nAfter inserting at index 2: " +
myList); 12. Clearing the ArrayList
myList.clear();
4. Accessing elements using get(index) System.out.println("\nAfter clearing, is the list empty? " +
System.out.println("Element at index 3: " + myList.get(3)); myList.isEmpty());
}
5. Updating an element using set(index, value) }
//(modify/replace/change)
Output:
myList.set(1, "99"); // Changing "25" to "99"
System.out.println("After updating index 1: " + myList);
2 → ArrayList after adding elements: [Alice, 25, 3.14, true, A, null,
25, Alice]
6. Removing an element by index 3 → After inserting at index 2: [Alice, 25, Inserted Element, 3.14,
myList.remove(4); true, A, null, 25, Alice]
System.out.println("After removing element at index 4: " + 4 → Element at index 3: 3.14
myList); 5 → After updating index 1: [Alice, 99, Inserted Element, 3.14, true,
A, null, 25, Alice]
7. Removing an element by value 6 → After removing element at index 4: [Alice, 99, Inserted
myList.remove("Alice"); // Removes the first occurrence Element, 3.14, A, null, 25, Alice]
of "Alice" 7 → After removing 'Alice': [99, Inserted Element, 3.14, A, null, 25,
System.out.println("After removing 'Alice': " + myList);
Alice]
8 → Contains '3.14'? true
8. Checking if an element exists
9 → Size of ArrayList: 7
System.out.println("Contains '3.14'? " +
10 → Is the list empty? false
myList.contains("3.14"));
11 → Iterating using (i) for-loop, (ii) for-each loop, (iii) iterator
99
9. Getting the size of the ArrayList Inserted Element
System.out.println("Size of ArrayList: " + myList.size()); 3.14
A
10. Checking if the ArrayList is empty null
System.out.println("Is the list empty? " + 25
myList.isEmpty()); Alice
12 → After clearing, is the list empty? true
HashSet Example :
import java.util.ArrayList; import java.util.HashSet; No Duplicates Allowed → If you add 100 twice, only one
import java.util.Iterator; import java.util.Set; instance remains.
public class HashSetDemo { Unordered Collection → Elements are stored in random
public static void main(String[] args) { order.
Declaration Fast Operations → add(), remove(), contains() are very
HashSet myset=new HashSet(); fast due to hashing.
//Set myset=new HashSet(); Allows null Value → Only one null is allowed.
//HashSet <String>myset=new HashSet<String>();
No Indexing → You cannot retrieve elements using an
Use above for homogeneous data
index directly.

adding elements into HashSet


myset.add(100);
Basic Operations:
myset.add(10.5);
• add(element) → Adds an element to the HashSet
myset.add("welcome");
(duplicates are not allowed).
myset.add(true);
• remove(element) → Removes the specified element from
myset.add('A');
the HashSet.
myset.add(100);
• contains(element) → Returns true if the HashSet contains
myset.add(null);
the specified element.
myset.add(null);
Size and Checking:
• size() → Returns the number of elements in the HashSet.
Printing HashSet
• isEmpty() → Returns true if the HashSet is empty.
System.out.println(myset);
• clear() → Removes all elements from the HashSet.
//[null, A, 100, 10.5, welcome, true]
Iterating Over HashSet:
• Using for-each loop → Iterates through all elements.
Size of HashSet
• Using Iterator → Iterates using an Iterator.
System.out.println("Size of hashset:"+ myset.size()); //6

Removing element
myset.remove(10.5); // 10.5 is value (not an index)
System.out.println("After removing:"+myset);
//[null, A, 100, welcome, true]

inserting elements at a specific position


Direct access via index is NOT possible in HashSet

Convert `HashSet` to `ArrayList` for indexed access


ArrayList al=new ArrayList(myset);
System.out.println(al); //[null, A, 100, welcome, true]
System.out.println(al.get(2)); //100

Read all the elements → using for..each


for(Object x:myset)
{
System.out.println(x);
}
→ Using iterator
Iterator <Object> it=myset.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
clearing all the elements in HashSet
myset.clear();
System.out.println(myset.isEmpty()); //true
}
HashMap Example:
import java.util.Map; → using Iterator
import java.util.Map.Entry; System.out.println("\nUsing Iterator:");
import java.util.HashMap; Iterator<Entry<Integer, String>> it = hm.entrySet().iterator();
import java.util.Iterator;
while (it.hasNext())
public class HashMapDemo { {
public static void main(String[] args) { Entry<Integer, String> entry = it.next();
System.out.println(entry.getKey() + " " + entry.getValue());
Declaration of HashMap (Key = Integer, Value = String) }
HashMap hm=new HashMap(); Clearing all elements from HashMap
or hm.clear();
Map hm=new HashMap(); System.out.println("Is HashMap empty? " + hm.isEmpty());
or Output: true
HashMap<Integer, String> hm = new HashMap<>(); }
}
Adding key-value pairs HashMap with Integer keys and String values (Both
hm.put(101, "John"); Homogeneous)
hm.put(102, "Scott"); HashMap<Integer, String> hm = new HashMap<>();
hm.put(103, "Mary"); Using Object to store different data types (Heterogeneous)
hm.put(104, "Scott"); HashMap<Integer, Object> hm = new HashMap<>();
hm.put(102, "David"); // Overwrites "Scott" with "David"
The Iterator interface allows sequential access to
Printing HashMap (Unordered, No duplicate keys) elements in a HashMap.
System.out.println(hm);
• put(key, value) → Adds or updates a key-value pair in the
Size of HashMap HashMap.
System.out.println("Size of HashMap: " + hm.size()); • putIfAbsent(key, value) → Adds the key-value pair only if
Output: 4 the key does not already exist.
• get(key) →Retrieves the value associated with the given key.
Removing a key-value pair • getOrDefault(key, defaultValue) → Returns the value for a
hm.remove(103); // Removes key 103 and its associated key if it exists; otherwise, returns the provided default value.
value • remove(key) → Removes a key-value pair using the key.
System.out.println("After removing key 103: " + hm); • remove(key, value) → Removes the key-value pair only if it
Output: {101=John, 102=David, 104=Scott} matches the given value.
Checking Elements:
Accessing a value using its key • containsKey(key) → Returns true if the key exists in the
System.out.println(hm.get(102)); HashMap.
Output: David • containsValue(value) → Returns true if the specified value
exists in the HashMap.
Getting all keys, values, and key-value pairs Retrieving Keys, Values, and Entries:
System.out.println("Keys: " + hm.keySet()); • keySet() → Returns a Set of all keys in the HashMap.
Output: [101, 102, 104] • values() → Returns a Collection of all values in the
System.out.println("Values: " + hm.values()); HashMap.
Output: [John, David, Scott] • entrySet() → Returns a Set of all key-value pairs
System.out.println("Entries: " + hm.entrySet()); (Map.Entry<K, V>).
Output: [101=John, 102=David, 104=Scott] Size and Clearing:
• size() → Returns the number of key-value pairs in the
Read all the elements → using for-each loop HashMap.
• isEmpty() → Returns true if the HashMap is empty.
System.out.println("Using for-each loop:"); • clear() → Removes all key-value pairs from the HashMap.
Iterating Over HashMap:
for (int k : hm.keySet()) • Using for-each with keySet() → Iterates through all keys.
{ • Using for-each with entrySet() → Iterates through all key-
System.out.println(k + " " + hm.get(k)); value pairs.
} • Using Iterator on entrySet() → Iterates using an Iterator.
Difference between ArrayList, HashSet, and HashMap:
Feature ArrayList HashSet HashMap
Implements List interface Set interface Map interface
Data Structure Dynamic array Hash table Key-Value pairs stored in Hash table
Duplicates Allowed Not Allowed Keys: Not Allowed
Values: Allowed
Insertion Order Preserved (Index-based) Not Preserved Not Preserved (Unordered)
Heterogeneous Allowed (if using Allowed (if using Allowed (if using
Data ArrayList<Object>) HashSet<Object>) HashMap<Object, Object>)
Indexing Allowed (Can access via Not Allowed Not Allowed (Uses keys instead)
index)
Access Time O(1) for get(index) O(1) for add/remove O(1) for put/get
Complexity O(n) for contains(value) O(1) for contains(value) O(n) for containsValue(value)
Iteration for-loop, foreach, Iterator foreach, Iterator foreach, Iterator, Map.Entry
Methods
Null Values Multiple Nulls Allowed One Null Allowed One Null Key & Multiple Null
Values Allowed
Usage When ordered collection is When unique elements are When key-value mapping is required
needed needed (won’t show duplicate)
Important add(), add(index, element), add(), remove(), contains(), put(), putIfAbsent(), get(), remove(),
Methods get(), set(), remove(), size(), isEmpty(), clear(), containsKey(), containsValue(), size(),
contains(), size(), isEmpty(), addAll(), removeAll(), isEmpty(), clear(), keySet(), values(),
clear() retainAll() entrySet()

contains(value) in HashSet → O(1)


containsKey(key) in HashMap → O(1)
containsValue(value) in HashMap → O(n) (Slowest) Iterating through all elements is always O(n)
O(1) in ArrayList ?
Accessing an element by index:
ArrayList contains() is O(n) because it must search linearly.

O(1) in HashSet ?
Checking if an element exists (contains())

O(1) in HashMap ?
Getting a value by key (get())
Checking if a key exists (containsKey())
Inserting a key-value pair (put())

You might also like