Java Notes(Part 2)
What are Functions
- Function = block of reusable code
- Performs a specific task
- Called when needed
Example
void greet(){
System.out.println("Hello");
}Why We Need Functions
- Code reusability
- Reduce code duplication
- Improves readability
- Easier debugging
Example
Instead of repeating code many times, call function once.
Types of Functions
Without Parameter & Without Return
void show(){
System.out.println("Hello");
}With Parameter & Without Return
void add(int a, int b){
System.out.println(a + b);
}With Parameter & With Return
int add(int a, int b){
return a + b;
}Without Parameter & With Return
int getNumber(){
return 10;
}How to Define a Function
Syntax
returnType functionName(parameters){
// code
}Example
int multiply(int a, int b){
return a * b;
}Understanding the Main Method
Main method is entry point of Java program
Syntax
public static void main(String[] args)Meaning
public → accessible everywhere
static → no object needed
void → returns nothing
main → JVM starting method
String[] args → command line argumentsExample
public static void main(String[] args){
System.out.println("Hello Java");
}Function Overloading
- Same function name
- Different parameters
- Happens at compile time
Example
int add(int a, int b){
return a + b;
}int add(int a, int b, int c){
return a + b + c;
}Function Chaining
- One function calls another function
Example
void start(){
step1();
}void step1(){
step2();
}void step2(){
System.out.println("Done");
}
Execution flow
start → step1 → step2Recursion
- Function calling itself
- Used for repeated problems
Example (Factorial)
int factorial(int n){if(n == 1)
return 1; return n * factorial(n-1);
}
Example
factorial(4)4 × factorial(3)
3 × factorial(2)
2 × factorial(1)Result
24Traditional Programming vs Object-Oriented Programming
Procedural Programming
- Program divided into functions
- Focus on procedures and logic
- Data and functions separate
Example languages
CObject-Oriented Programming (OOP)
- Program divided into objects
- Combines data + behavior
- Models real-world entities
Example languages
Java, C++, PythonProblems with Procedural Approach
- Difficult to manage large programs
- Data security issues
- Hard to reuse code
- Difficult maintenance
Representing Real World in Code
OOP represents real-world things as objects
Example
Car
Student
BankAccount
MobileEach object has
Properties (data)
Behaviors (actions)Example
Car
Properties → color, speed
Behavior → start(), stop()What are Classes
- Class = blueprint of object
- Defines properties and methods
- Used to create objects
Example
class Student{int id;
String name;}
User-Defined Data Types
Classes create custom data types
Example
Student s1;Here Student becomes a new data type
Creating Objects
Object = instance of class
Syntax
ClassName objectName = new ClassName();Example
Student s1 = new Student();Compile-Time vs Runtime Concepts
Compile-Time
- Code checked by compiler
- Syntax errors detected
Example
Missing semicolon
Wrong datatypeRuntime
- Code executes in JVM
- Logical errors appear
Example
Divide by zeroCharacteristics of Objects
Every object has
State
Behavior
IdentityExample
Object → CarState → color, speed
Behavior → drive(), brake()
Identity → unique objectNaming Conventions in Java
Class name
PascalCase
Example: StudentDataVariable name
camelCase
Example: studentNameMethod name
camelCase
Example: calculateTotal()Representing Behaviors
Behaviors represented using methods
Example
class Car{void start(){
System.out.println("Car started");
}}
Non-Physical Objects
Objects do not have to be physical.
Examples
BankAccount
Transaction
Order
StudentThey represent concepts in software
Writing Your First Class & Object
Example
class Student{int id;
String name;}public class Main{ public static void main(String[] args){ Student s1 = new Student(); s1.id = 1;
s1.name = "Rahul"; System.out.println(s1.name);
}
}
Role of the Main Class
- Contains main() method
- JVM starts execution from main()
- Entry point of program
Example
public static void main(String[] args)What are Constructors
- Constructor = special method used to initialize objects
- Called automatically when object is created
- Same name as class name
- No return type
Example
class Student{Student(){
System.out.println("Object created");
}}
Object creation
Student s1 = new Student();Rules of Constructor in Java
- Constructor name must match class name
- No return type (not even void)
- Called automatically during object creation
- Can be overloaded
Example
class Car{Car(){
System.out.println("Constructor called");
}}
Default Constructor
- Constructor with no parameters
- If programmer does not write constructor → compiler creates one
Example
class Test{}Compiler internally creates
Test(){
}Parameterized Constructor
- Constructor with parameters
- Used to initialize object with values
Example
class Student{int id;
String name; Student(int i, String n){
id = i;
name = n;
}}
Object creation
Student s1 = new Student(1,"Rahul");Constructor Overloading
- Multiple constructors with different parameters
Example
class Student{Student(){
System.out.println("Default");
} Student(int id){
System.out.println("ID constructor");
}}
Writing Constructor Example
class Car{String brand; Car(String b){
brand = b;
}}
Object
Car c1 = new Car("Toyota");this Keyword
- Refers to current object
- Used to remove variable ambiguity
Example
class Student{int id; Student(int id){
this.id = id;
}}
Explanation
this.id → instance variable
id → parameterConstructor Chaining
- One constructor calls another constructor
- Done using this()
Example
class Demo{Demo(){
this(10);
System.out.println("Default");
} Demo(int x){
System.out.println(x);
}}
Execution
Demo() → Demo(10)Can Constructors Be Called Manually
- Constructors cannot be called like normal methods
Wrong
Student();Correct
Student s = new Student();Constructor called through new keyword
What an Object Contains Internally
An object contains:
Instance Variables (data)
Methods (behavior)
Object Identity (memory reference)Example
class Student{int id;
String name;}
Object
Student s1 = new Student();Memory idea
s1 → referenceHeap
[id, name]Object Size in Java
Object size depends on:
- Instance variables
- Data type size
- Object header (JVM metadata)
Example
class Test{
int a;
double b;
}Size roughly
int → 4 bytes
double → 8 bytes
+ object headerObject stored in Heap memory.
Call by Value vs Call by Reference
Call by Value
- Copy of variable passed
- Original value does not change
Example
void change(int x){
x = 20;
}Call
int a = 10;
change(a);Result
a = 10Original value unchanged.
Call by Reference
- Reference of variable passed
- Original value can change
Example concept
method receives memory referenceIs Java Call by Value or Reference
Important rule
Java is always CALL BY VALUEBut for objects:
value of reference is passedExample
class Test { int x;}void modify(Test t){
t.x = 50;
}
Call
Test obj = new Test();
obj.x = 10;modify(obj);Result
obj.x = 50Because reference value points to same object.
Parameter Passing Example
Example
class Demo{void update(int x){
x = x + 10;
}}
Call
int a = 5;
update(a);Result
a remains 5Primitive values do not change.
Object Parameter Example
class Student{int id;}
Method
void change(Student s){
s.id = 100;
}Call
Student s1 = new Student();
s1.id = 10;change(s1);Result
s1.id = 100Object state changed.
Shallow Copy
- Copies object reference
- Both variables point to same object
Example
Student s1 = new Student();
Student s2 = s1;Memory
s1 → object
s2 → same objectChanges affect both references.
Deep Copy
- Creates new object
- Copies values separately
Example
Student s1 = new Student();
Student s2 = new Student();s2.id = s1.id;Memory
s1 → object1
s2 → object2Objects independent
static Keyword in Java
staticmeans belongs to class, not object- Shared by all objects of the class
- Memory created only once
Example
class Student{
static String college = "ABC College";
}All objects share same college value.
Static Variables
- Declared using static keyword
- Same value shared among all objects
- Stored in class area
Example
class Student{int id;
static String college = "ABC";}
Object example
Student s1 = new Student();
Student s2 = new Student();Both objects share
college = ABCStatic Methods
- Belong to class
- Can be called without creating object
- Can access only static members
Example
class Demo{
static void show(){
System.out.println("Hello");
}
}Call
Demo.show();Rules of Static Members
- Static members belong to class
- Static methods cannot access non-static variables directly
- Static methods can call other static methods
- Access using ClassName.variable
Example
ClassName.staticVariableStatic Block
- Used for static initialization
- Executes once when class loads
Example
class Test{static{
System.out.println("Static block executed");
}}
Execution order
Static block → main methodfinal Keyword
final means cannot be changed
Used with:
Variables
Methods
ClassesExample
final int MAX = 100;Value cannot change
final Method
- Method cannot be overridden
Example
final void show(){
System.out.println("Hello");
}final Class
- Class cannot be inherited
Example
final class Demo{
}Example in Java
String classWhy main() Method Must be Static
Main method is program entry point
JVM calls it without creating object
So it must be static
Example
public static void main(String[] args)static final Variables
- Used to create constants
- Value cannot change
- Shared by all objects
Example
static final double PI = 3.14;Used like
System.out.println(Math.PI);String[] args Parameter
- Used to receive command line arguments
- Arguments passed during program execution
Example
Run program
java Test Hello JavaCode
public static void main(String[] args){System.out.println(args[0]);
System.out.println(args[1]);}
Output
Hello
JavaWhat is Encapsulation
- Encapsulation = wrapping data and methods together
- Data is hidden from outside access
- Achieved using private variables + public methods
Example
class Student{private int id; public void setId(int id){
this.id = id;
} public int getId(){
return id;
}
}
Getters and Setters
Used to access and update private variables
Get Deepaksingh’s stories in your inbox
Join Medium for free to get updates from this writer.
Getter → read value
public int getId(){
return id;
}Setter → modify value
public void setId(int id){
this.id = id;
}Usage
Student s = new Student();s.setId(10);
System.out.println(s.getId());Benefits of Encapsulation
- Data hiding
- Better security
- Controlled data access
- Easier maintenance
- Improves code organization
What is Inheritance
- Inheritance = one class acquiring properties of another class
- Helps in code reuse
Keyword used
extendsParent and Child Classes
Parent class → Super class
Child class → Sub class
Example
class Animal{void eat(){
System.out.println("Animal eats");
}}class Dog extends Animal{ void bark(){
System.out.println("Dog barks");
}}
Usage
Dog d = new Dog();d.eat();
d.bark();Code Reusability
Child class can reuse parent class methods
Example
Dog inherits eat() from AnimalNo need to rewrite code.
Types of Inheritance in Java
Single Inheritance
A → BMultilevel Inheritance
A → B → CHierarchical Inheritance
A
/ \
B CMultiple Inheritance
Not supported with classes in JavaSupported using interfaces
Real Code Example
class Vehicle{void start(){
System.out.println("Vehicle starts");
}}class Car extends Vehicle{ void drive(){
System.out.println("Car driving");
}}
Main class
public class Main{public static void main(String[] args){ Car c = new Car(); c.start();
c.drive();
}
}
Output
Vehicle starts
Car drivingWhat is Abstraction
- Abstraction = hiding implementation details
- Shows only important features
- Achieved using:
- Abstract classes
- Interfaces
Example
ATM Machine
User sees → withdraw(), deposit()
Hidden → internal banking logicTypes of Abstraction
Partial Abstraction
- Achieved using abstract class
- Class can have abstract + normal methods
Full Abstraction
- Achieved using interface
- Methods are abstract by default
Low Level vs High Level Abstraction
Low Level Abstraction
Focus on implementation
Example → loops, algorithmsHigh Level Abstraction
Focus on functionality
Example → login(), startCar()Abstract Classes
- Declared using abstract keyword
- Cannot create object directly
Can contain:
- abstract methods
- normal methods
- variables
Example
abstract class Animal{abstract void sound();}
Child class
class Dog extends Animal{
@Override
void sound(){
System.out.println("Dog barks");
}
}Interfaces in Java
- Interface defines method blueprint
- Methods are public and abstract by default
- Supports multiple inheritance
Example
interface Vehicle{void start();}
Implementation
class Car implements Vehicle{@Override
public void start(){
System.out.println("Car starts");
}}
Abstract Class vs Interface
Abstract Class ____________________Interface
Can have abstract + normal methods — — — — — — Methods abstract by default
Uses extends — — — — — — — — — — — — — — — — Uses implements
Supports constructors — — — — — — — — — — — — -No constructors
Single inheritance — — — — — — — — — -Multiple interfaces allowed
Abstraction vs Encapsulation
Abstraction
Hides implementation
Focus on functionality
Example → abstract class / interfaceEncapsulation
Hides data
Uses private variables
Example → getters and settersWhat is Polymorphism
- Polymorphism = one name, many forms
- Same method behaves differently
Types
1. Static Polymorphism
2. Dynamic PolymorphismStatic Polymorphism (Method Overloading)
- Same method name
- Different parameters
- Happens at compile time
Example
class MathUtils{int add(int a, int b){
return a + b;
} int add(int a, int b, int c){
return a + b + c;
}}
Dynamic Polymorphism (Method Overriding)
- Child class overrides parent method
- Happens at runtime
Example
class Animal{
void sound(){
System.out.println("Animal sound");
}
}Child class
class Dog extends Animal{@Override
void sound(){
System.out.println("Dog barks");
}}
Static & Final Methods in Polymorphism
Static Methods
Cannot be overridden
Belong to classExample
class Demo{
static void show(){
System.out.println("Static method");
}
}Final Methods
Cannot be overridden
Prevents method modificationExample
class Parent{final void display(){
System.out.println("Final method");
}}
Why Java Allows Only One Public Class per File
- Java file name must match public class name
- Ensures clear structure and easy compilation
Example
public class Test{
}File name must be
Test.javaReason
JVM easily finds the main public classWhat are Wrapper Classes
- Wrapper classes convert primitive data types into objects
- Located in java.lang package
Examples
PrimitiveWrapperintIntegerdoubleDoublecharCharacterbooleanBoolean
Example
int a = 10;
Integer b = Integer.valueOf(a);Autoboxing
- Automatic conversion of primitive → wrapper object
Example
int a = 10;
Integer b = a;Java internally does
Integer b = Integer.valueOf(a);Unboxing
- Automatic conversion of wrapper → primitive
Example
Integer a = 20;
int b = a;Internally
int b = a.intValue();When Java Performs Autoboxing / Unboxing
Occurs during
Assignment
Method parameters
Collections (ArrayList, HashMap)
Arithmetic operationsExample
ArrayList<Integer> list = new ArrayList<>();list.add(10);Here 10 is autoboxed into Integer object.
NullPointerException During Unboxing
Occurs when wrapper object is null
Example
Integer a = null;int b = a;Error
NullPointerExceptionReason
Java tries to call a.intValue()
but object is nullDifference Between == and .equals()
==
Compares memory references.equals()
Compares object valuesExample
Integer a = 100;
Integer b = 100;System.out.println(a == b);
System.out.println(a.equals(b));Internal Working of Integer Class
Integer class contains
private final int value;Example structure
class Integer{private final int value;}
Once created
value cannot change (immutable)Integer Caching in JVM
JVM caches integers between
-128 to 127Example
Integer a = 100;
Integer b = 100;System.out.println(a == b);Output
trueBecause both refer to same cached object.
Example
Integer a = 200;
Integer b = 200;Output
falseNew objects created.
Important Abstract Class Interview Points
- Abstract class cannot be instantiated
- Can contain abstract and concrete methods
- Can have constructors
- Can have instance variables
Example
abstract class Shape{abstract void draw();}
What are POJO Classes
POJO = Plain Old Java Object
Simple Java class used to store data
Characteristics
Private variables
Public getters/setters
No business logicExample
class Student{
private int id;
private String name; public int getId(){
return id;
} public void setId(int id){
this.id = id;
}}
Why Frameworks Use POJO
Frameworks like
Spring
HibernateUse POJO because
Easy to manage data
Simple structure
ReusableTypes of Nested Classes
Nested classes are classes inside another class.
Types
1. Static Nested Class
2. Inner Class
3. Local Class
4. Anonymous ClassWhy Classes are Nested
- Improve code organization
- Increase encapsulation
- Logical grouping of related classes
- Used when class is only needed by outer class
Example
Car → EngineEngine is used only inside Car class.
Static Nested Class
- Declared using static keyword
- Does not require outer class object
- Can access only static members of outer class
Example
class Outer{static class Inner{ void display(){
System.out.println("Static Nested Class");
} }}
Object creation
Outer.Inner obj = new Outer.Inner();
obj.display();Real World Use Cases of Static Nested Classes
Used when class is logically related but independent
Examples
Map.Entry
Builder pattern
Configuration classesExample
class Database{static class Config{ String url; }}
Inner Classes
- Non-static nested class
- Requires outer class object
- Can access all members of outer class
Example
class Outer{int x = 10; class Inner{ void show(){
System.out.println(x);
} }}
Object creation
Outer o = new Outer();
Outer.Inner i = o.new Inner();
i.show();Memory Representation of Inner Class Objects
Memory structure
Outer object
↓
Inner object contains reference to outer objectMeaning
Inner class always linked to outer objectWhy Static Members Were Restricted in Inner Classes (Older Java)
Earlier Java versions did not allow
static variables
static methodsinside inner classes because:
Inner class belongs to object, not class
Static members belong to classNewer Java allows static final constants.
Example
static final int MAX = 100;Local Classes
Class defined inside a method
Example
class Test{void display(){ class Local{
void show(){
System.out.println("Local class");
}
} Local l = new Local();
l.show();
}}
Scope
Accessible only inside that methodEffective Final Rule
Local variables used inside local classes must be final or effectively final
Example
void show(){int x = 10; class Local{
void display(){
System.out.println(x);
}
}}
Here x is effectively final because value does not change.
Anonymous Classes
- Class without name
- Used when class needed only once
Example
interface Animal{
void sound();
}Anonymous class
Animal a = new Animal(){public void sound(){
System.out.println("Dog barks");
}};a.sound();
When Each Nested Class is Used
Static Nested Class
Used when class does not need outer object
Example → Builder classesInner Class
Used when inner class depends on outer class
Example → UI componentsLocal Class
Used for small helper logic inside methodsAnonymous Class
Used for quick one-time implementations
Example → event handlingHow System.out.println() Works
System.out.println() prints text to the console.
Internal flow
System → out → println()Explanation
System → class
out → static PrintStream object
println() → method of PrintStreamExample
System.out.println("Hello");Internally similar to
PrintStream ps = System.out;
ps.println("Hello");Role of System Class
Systemis a final class in java.lang package- Provides access to system resources
Important members
System.out → standard output
System.err → error output
System.in → input streamWhat System.err is Used For
- Used to print error messages
Example
System.err.println("Error occurred");Difference
System.out → normal output
System.err → error messagesHow Java Reads Input from Keyboard
Keyboard input is read using
System.inSystem.in is an object of
InputStreamExample
int data = System.in.read();Reads one byte from input.
What Streams of Data Are
A stream = flow of data
Example
Keyboard → Program → ScreenTypes
Input Stream → data enters program
Output Stream → data leaves programInputStream / OutputStream Hierarchy
InputStream hierarchy
InputStream
|
|-- FileInputStream
|-- BufferedInputStream
|-- ByteArrayInputStreamOutputStream hierarchy
OutputStream
|
|-- FileOutputStream
|-- BufferedOutputStream
|-- ByteArrayOutputStreamHow System.in.read() Works
Example
int ch = System.in.read();Process
1. User types a character
2. Character stored as ASCII
3. System.in.read() reads one byte
4. Returns integer valueExample
Input
AOutput
65Difference Between Reader and InputStream
InputStreamReaderWorks with bytesWorks with charactersUsed for binary dataUsed for text data
Example
InputStream → images, files
Reader → text filesHow BufferedReader Improves Performance
- Reads large chunks of data at once
- Reduces number of I/O operations
Example
BufferedReader br =
new BufferedReader(
new InputStreamReader(System.in)
);Reading input
String s = br.readLine();Role of InputStreamReader
- Converts byte stream → character stream
Flow
Keyboard → System.in (bytes)
↓
InputStreamReader
↓
BufferedReader (characters)Example
InputStreamReader isr =
new InputStreamReader(System.in);Limitations of BufferedReader
Cannot parse primitive types directly
Need manual conversion
More complex codeExample
int n = Integer.parseInt(br.readLine());Why Scanner Exists
Scanner simplifies input handling.
Advantages
Easy to use
Directly reads int, double, string
Less codeExample
Scanner sc = new Scanner(System.in);int n = sc.nextInt();
String name = sc.next();Scanner vs BufferedReader
Scanner — — — — — — — — — — — — — — -Buffered
Easy to use — — — — — — — — — -Faster
Parses data types automatically — — — — — Needs manual parsing
Slower for large input — — — — — — — -Better performance







