Java OOPS Concepts Notes
Java OOPS Concepts Notes
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
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
test.m1(number); //110
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)
}
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
}
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
} 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.
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 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.
Objective:
1) Re-usability
2) Avoid duplication
Common classes – 5
extends
Predefined
Parent Class
Child class
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
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).
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.
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
System.out.println(mi.x);
System.out.println(mi.y);
}
}
I1 I1 C1 C2 Parent
11
C Child
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
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 {
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
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
Rule2: Assignment is valid or not : 'C' must be either same or child of 'A'.
Animal an=new Dog();
Cat ct=(Cat) 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
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];
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).
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)
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.
Removing element
myset.remove(10.5); // 10.5 is value (not an index)
System.out.println("After removing:"+myset);
//[null, A, 100, welcome, true]
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())