CORE JAVA TUTORIAL
📘 Module 1: Introduction to Programming
🔹 1. What is Programming?
Definition:
Programming is the process of writing instructions for a computer to follow. These instructions
tell the computer what tasks to perform and how to perform them.
Analogy:
Like writing a recipe that a robot can follow to cook food.
Examples of what programs can do:
● Open a browser
● Display a webpage
● Store customer details
● Calculate bank interest
🔹 2. Why Learn Programming?
Reason How it helps
Automation Automate boring, repetitive tasks
Problem Solving Learn structured thinking and logic
App Development Create your own websites, mobile apps
Career Growth High demand for software developers
Freelancing Build and sell tools, apps, automations
🔹 3. Types of Programming Languages
Programming languages are broadly classified based on how close they are to machine
hardware and how easily humans can understand and write them.
Type Example Languages Use Case
Low-Level Assembly, Machine Code Hardware-level control (rarely used today)
High-Level Java, Python, C, C++ Business logic, apps, enterprise software
Scripting JavaScript, Bash, PHP Automation scripts, webpage interactivity
🔸 1. Low-Level Languages
🧠 What It Means:
● Very close to binary (0s and 1s).
● Difficult for humans to write/read.
● Used when direct control over hardware is needed.
🛠 Examples:
● Machine Code: Actual binary instructions executed by the CPU.
● Assembly Language: One step above machine code; uses symbolic code like MOV,
ADD.
📦 Use Case:
● Writing programs for microcontrollers, embedded devices, firmware.
● Example: Writing code for a washing machine chip or aerospace navigation system.
⚠ Why Not Common Today:
● Very complex and hardware-specific.
● Most modern programming is done using high-level languages for productivity.
🔸2. High-Level Languages
🧠 What It Means:
● Easy to read, write, and understand for humans.
● Uses English-like syntax.
● One program can work on multiple platforms (with a compiler/interpreter).
🛠 Examples:
● Java – Enterprise applications, Android apps.
● Python – AI, automation, scripting, web dev.
● C, C++ – System-level programs, gaming engines.
📦 Use Case:
● Building full applications: websites, mobile apps, enterprise software, games.
● Example: You build an online banking portal or an e-commerce app.
🔸 3. Scripting Languages
🧠 What It Means:
● Special type of high-level language focused on automating repetitive tasks or adding
dynamic behavior to programs/webpages.
● Generally interpreted line-by-line rather than compiled.
🛠 Examples:
● JavaScript – Makes webpages interactive (e.g., buttons, animations).
● Bash – Automates tasks on Linux like backups, file moves.
● PHP – Backend scripting for dynamic websites like Facebook (early days).
📦 Use Case:
● Writing scripts for:
○ System maintenance
○ Automating tasks like sending emails or renaming files
○ Making web pages dynamic and user-friendly
🎯 Key Differences Summary
Feature Low-Level High-Level Scripting
Ease of Writing Very hard Easy to write and read Very easy and quick
Speed Fastest Moderate Slightly slower
Used by Hardware engineers Application developers Web devs, sysadmins
Tools Needed Assembler Compiler Interpreter
💡 Real-Life Analogy
Language Type Analogy Example
Low-Level Talking in binary to a robot (e.g., “1001 0010”)
High-Level Giving clear English instructions to a worker
Scripting Writing a quick checklist note for reminders
🔹 4. What is an Algorithm?
Algorithm: A step-by-step procedure to solve a problem.
Example: Making Tea (Algorithm)
1. Boil water
2. Add tea leaves
3. Add milk and sugar
4. Strain and serve
Flowchart:
A diagrammatic representation of an algorithm using symbols.
Symbol Meaning
○ Start/End
▭ Process step
◇ Decision (Yes/No)
5. Basic Programming Terms
Term Description
Variable A container to store data
Instruction A line of code that tells the computer what to do
Syntax The grammar rules of programming languages
Compiler A tool that translates code into machine-readable form
Bug A mistake/error in the program
Debugging Fixing errors in the code
📘 Module 2: Introduction to Java
🔹 1. What is Java?
Java is a general-purpose, high-level, object-oriented programming language that is known
for its platform independence and robust architecture.
Feature Explanation
High-Level Java code is written in human-readable syntax, making it easier
to write and understand.
Object-Oriented Java is built around objects—similar to how we think in real life.
For example, a Car object may have speed (data) and drive()
(behavior).
Platform-Independent Java code is compiled into bytecode, which runs on any machine
that has the Java Virtual Machine (JVM). This makes Java
portable across different operating systems.
General-Purpose Java can be used to build a variety of software: websites, mobile
apps, desktop applications, enterprise tools, and even games.
🔹 2. History and Evolution of Java
Year Event
1991 Java project started by James Gosling at Sun Microsystems (originally called Oak)
1995 Official release of Java as a programming language
2006 Sun open-sourced Java under GPL
2010 Oracle Corporation acquires Sun Microsystems and takes ownership of Java
Today Java remains one of the most popular languages for Android, backend, enterprise
systems, and more.
📌 Did you know?
The name "Java" comes from Java coffee beans – a favorite of the developers.
🔹 3. Why Learn Java?
Benefit Description
Robust Java has strong memory management, exception handling, and
automatic garbage collection to avoid crashes.
Secure Runs inside a sandbox environment and has built-in security features –
ideal for sensitive apps like banking.
Widely Used Over 3 billion devices run Java – including Android phones, ATMs,
POS systems, and web servers.
Huge There's a massive support network: forums, tutorials, courses, and
Community open-source libraries. Great for beginners!
🔹 4. Applications of Java
Java is used everywhere. Here are the most common application areas:
Application Type Examples
Web Applications Online banking portals, e-commerce platforms, HR management
systems (e.g., OrangeHRM)
Mobile Applications Android apps (Java is the primary language for native Android
development)
Desktop IDEs like NetBeans, IntelliJ IDEA, and business tools
Applications
Enterprise CRMs, ERPs, internal company systems—especially in banking,
Applications insurance, and healthcare
Cloud Computing Java runs in all major cloud platforms like AWS, Google Cloud,
Microsoft Azure
💡 Real-Life Analogy: Why Java?
Imagine you are designing a universal remote. You want it to work on any TV brand.
That’s how Java works—it runs on any platform (Windows, Linux, Mac), thanks to the
JVM.
🧠 Quick Review
Question Answer
What makes Java The Java Virtual Machine (JVM) executes bytecode
platform-independent? on any OS.
What is Java mainly used for Android apps, enterprise systems, and backend
today? development.
Who maintains Java today? Oracle Corporation
📘 Module 3: Java Ecosystem and Architecture
🔹 1. JDK – Java Development Kit
● The JDK is the toolkit for Java developers.
● It contains everything you need to write, compile, and debug Java code.
Tool Purpose
javac Java compiler – converts .java to
.class
java Launches JVM to run code
Debuggers, Help in testing and monitoring apps
tools
JRE Included inside JDK
You must install JDK to start writing Java programs.
🔹 2. JRE – Java Runtime Environment
● The JRE is used to run Java programs.
● It contains:
○ The JVM (Java Virtual Machine)
○ Java class libraries (built-in tools like System.out.println)
If you're only running Java apps (not writing them), you only need the JRE.
🔹 3. JVM – Java Virtual Machine
The JVM is the heart of Java. It:
● Executes compiled .class files (bytecode)
● Provides:
○ Memory management
○ Automatic garbage collection
○ Security checks
Feature Purpose
Platform-specific There is a JVM for Windows, Mac, Linux—but your code stays the
same.
Sandboxing Prevents malicious code from harming the system
Bytecode Converts .class bytecode into machine-specific instructions
Interpreter
JVM makes Java write once, run anywhere possible.
🔹 4. How Java Code Runs (Step-by-Step)
Step Action
1 Developer writes Java code → HelloWorld.java
2 Code is compiled with javac → HelloWorld.class
(bytecode)
3 JVM reads and executes the .class file
4 Output is displayed on screen
🔹 5. Diagram: Java Code Execution Flow
┌────────────────────┐
│ HelloWorld.java │ ← Source Code (written by you)
└────────────────────┘
↓ (javac compiler)
┌────────────────────┐
│ HelloWorld.class │ ← Bytecode
└────────────────────┘
↓ (JVM)
┌────────────────────┐
│ Output on screen │ ← Runs on any OS!
└────────────────────┘
💡 Think of it like this:
● .java → Your recipe
● .class → Ready-to-cook ingredients
● JVM → The chef who cooks it, no matter the kitchen (Windows, Mac, Linux)
✅ Quick Review
Question Answer
What’s the difference between JDK and JDK = Develop + Run; JRE = Only Run
JRE?
What does JVM do? It runs the bytecode and manages memory and
security
Can Java code run on Mac and Yes, thanks to platform-specific JVMs
Windows?
📘 Module 4: Java Program Structure
🔹 1. Basic Structure of a Java Program
A simple Java program always includes:
Part Purpose
class Defines the blueprint of the program
main() Entry point – Java starts running from here
method
Statements Instructions you want the program to do
; Each Java statement ends with a
semicolon
{ } Curly braces group code blocks together
🧠 Template of a Basic Java Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
System.out.println(“Hi Kalpesh”);
}
}
Output: Hello, world!
Hi Kalpesh
Line Explanation
public class HelloWorld Declares the class (like a container for code)
public static void Main method – Java starts execution from
main(String[] args) here
System.out.println(...) Prints text to screen
{ and } Groups code blocks
🔹 2. First Java Program: HelloWorld
📄 Step 1: Write this in a file named HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Welcome to Java Programming!");
}
}
📦 Step 2: Save it as HelloWorld.java
🔹 3. Compiling and Running a Java Program
There are two ways to run a Java program: via Terminal or via IDE (like IntelliJ/Eclipse/VS
Code).
🖥️ A. Using Terminal or Command Prompt
✅ Make sure JDK is installed and PATH is set.
# Step 1: Compile the program
javac HelloWorld.java
# Step 2: Run the compiled program
java HelloWorld
📌 Output:
Welcome to Java Programming!
💡 What Happens Internally?
Command What it Does
javac Compiles .java into .class (bytecode)
java JVM runs the .class file
🧑💻 B. Using an IDE (like IntelliJ or Eclipse)
1. Open IDE
2. Create a new project
3. Add a Java class with name HelloWorld
▶️
4. Paste the code
5. Click Run
💡 IDEs help with:
● Auto-complete
● Error checking
● Easy running/debugging
🧠 Recap Table
Part Example What it Does
Class public class Declares a program
HelloWorld
Main method public static void Entry point of execution
main(...)
Print System.out.println(... Displays output
)
Compile javac HelloWorld.java Converts to bytecode
Run java HelloWorld Runs the code via JVM
📘 Module 5 : Installing Java & Eclipse IDE
.
🧰 Part 1: Install Java (JDK – Java Development Kit)
✅ Step 1: Check if Java is already installed
Open Command Prompt / Terminal and type:
java -version
If it says "Java not recognized", you need to install it.
🪟 For Windows
🔽 Download JDK:
1. Go to: https://www.oracle.com/java/technologies/javase-downloads.html
2. Click on Java SE (Standard Edition)
3. Choose the latest version and click on Windows x64 Installer
4. Download and run the installer
✅ Setup Environment Variables:
1. After installation, open:
○ Control Panel → System → Advanced system settings →
Environment Variables
2. Under "System Variables", find Path, and click Edit
Click New, and paste the path where Java is installed (usually):
C:\Program Files\Java\jdk-XX\bin
3. Click OK and Apply
🔁 Verify:
Open Command Prompt and type:
java -version
javac -version
💻 Part 2: Install Eclipse IDE
💡 What is Eclipse?
Eclipse is a free and beginner-friendly IDE for writing and running Java code.
✅ Step 1: Download Eclipse
Go to: https://www.eclipse.org/downloads/
1. Click on "Download 64-bit" under Eclipse IDE for Java Developers
2. Download the installer and run it
✅ Step 2: Install Eclipse
1. Choose Eclipse IDE for Java Developers
2. Select JDK path (auto-selected if already installed)
3. Choose install location (default is fine)
4. Click Install
✅ Step 3: Launch Eclipse
1. Open Eclipse
2. It will ask for a workspace location – keep the default
3. Click Launch
🧪 Step 4: Create First Java Project in Eclipse
1. Go to File → New → Java Project
2. Name it: FirstProject → Click Finish
3. Right-click src folder → New → Class → Name it: HelloWorld
4. Check the box for public static void main
5. Paste the code:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Java setup successful!");
}
}
6. Click Run ▶️
🎉 Output will appear in the console:
Java setup successful!
✅ Summary Table
Tool Purpose Download
JDK Compiles & runs Java Oracle JDK
Eclipse Code editor + runner Eclipse IDE
Additional Concepts:
1. 💡 What Is an IDE?
Explain:
● IDE = Integrated Development Environment
● Makes coding easier with:
○ Code suggestions
○ Error highlighting
○ Debugging tools
○ One-click Run/Compile
2. 📂 What Is a Workspace in Eclipse?
● A Workspace is a folder where all your projects are stored
● You can switch between multiple workspaces
3. 🧠 Common Beginner Mistakes (and Fixes)
Mistake Why it happens How to fix
Missing main Forget to add entry point Use public static void
method main(String[] args)
Wrong file/class Class name doesn’t match Filename must be same as class name
name filename
Compilation error Forget ; or {} IDE will show red underline – follow the
suggestion
JDK not set in No Java detected Go to Preferences > Installed
Eclipse JREs and set correct path
4. ⚙️ Eclipse UI Overview (with Diagram)
Include a labeled screenshot or diagram (or Figma wireframe) showing:
● Project Explorer
● Editor Window
● Console Output
● Run button
● Error tab
📘 Variables in Java
🔹 1. What are Variables?
A variable in Java is a symbolic name associated with a memory location that holds a
value during program execution.
At runtime, variables are mapped to specific locations in memory (stack or heap),
depending on the context and type.
🔹 2. Why Are Variables Important?
● Store temporary data to be used later
● Pass values between methods
● Enable program flexibility and reusability
● Allow abstraction in data handling (e.g., user inputs, DB results)
🔹 3. Variable Declaration Syntax
type variableName = value; // Initialization
type variableName; // Declaration only
✅ Examples:
int age = 30;
String name = "Anas";
double price;
boolean isActive = true;
🔹 4. Rules for Naming Variables
Rule Description
✅ Start with a letter (a-z, A-Z), _, or $
❌ Cannot start
with
numbers or symbols like @, #, %
🆗 Allowed camelCase (recommended), snake_case,
PascalCase
❌ Not allowed Java reserved keywords (e.g., class, int)
🧠 Best Practice Use meaningful names: userAge,
productCount
🔹 5. Types of Variables in Java
Type Declared Where? Lifetime Stored In
Local Inside a method/block Until block ends Stack
Instanc Inside class, outside As long as object Heap
e method exists
Static Inside class, marked Until JVM stops Method
static Area
✅ Examples:
class Product {
int price; // instance variable
static int taxRate = 18; // static variable
void showPrice() {
int discount = 10; // local variable
System.out.println(price - discount);
🔹 6. Variable Storage – What Happens in Memory?
Variable Type JVM Memory Area
Local Stack Frame
Instance Heap
Static Method Area (shared across all
objects)
Example:
Product p1 = new Product();
Product p2 = new Product();
● p1.price and p2.price stored separately in Heap
● Product.taxRate stored once in Method Area, shared
🔹 7. Final Variables
Use final keyword to make variable constant after assignment:
final int MAX_RETRY = 5;
● Must be initialized exactly once
● Helps enforce immutability
🔹 8. Common Mistakes
Mistake Issue
Using before initializing Compiler Error
Confusing static vs Unexpected behavior in shared
instance data
Shadowing without Debugging difficulty
realizing
✅ Summary Table
Concept Description
Variable Symbolic reference to memory data
Syntax type name = value;
Types Local, Instance, Static
Memory Stack, Heap, Method Area
Final Used for constants
Shadowing Overriding higher scope variable
📘 Data Types in Java
🔹 1. What are Data Types?
A data type defines:
● The kind of data a variable can hold (number, text, boolean, etc.)
● The amount of memory it consumes
● The operations that can be performed on it
Java is statically typed → every variable’s data type must be declared at compile-time.
🔹 2. Categories of Data Types
Java data types are broadly classified into:
Type Subcategories
✅ Primitive byte, short, int, long, float, double, char, boolean
✅ Non-Primitive String, Arrays, Objects, Classes, Interfaces,
Enums
🔹 3. Primitive Data Types
Type Size Default Range Example Use Case
byte 1 byte 0 -128 to 127 byte b = 100; Memory-efficient
counters
short 2 bytes 0 -32,768 to 32,767 short s = Small numeric
1000; data
int 4 bytes 0 -2^31 to 2^31-1 int i = Default for
100000; whole numbers
long 8 bytes 0L Very large long l = High-precision
9999999L; counting
float 4 bytes 0.0f ~6–7 decimal float f = Approximate
digits 5.5f; decimal values
doubl 8 bytes 0.0d ~15 decimal double d = Precise
e digits 99.99; scientific
calculations
char 2 bytes '\u0000' Unicode (0 to char c = 'A'; Single character
65535) storage
boole 1 bit false true / false boolean b = Conditions, flags
an true;
🧠 Note: float and double are approximate; use BigDecimal for exact currency/math.
🔹 4. Behind the Scenes – Memory Allocation
● Primitive types are stored directly in memory (stack or heap depending on context).
● Each type has a fixed size, helping JVM with optimization.
● Default values are auto-assigned for class-level variables but not for local variables
🔹 5. Type Casting (Conversion)
✅ Implicit (Widening)
Java automatically converts smaller types to larger compatible types:
int a = 10;
long b = a; // OK
float c = b; // OK
❌ Explicit (Narrowing)
Manual casting is required for larger → smaller types:
double d = 9.87;
int i = (int) d; // i becomes 9
💡 Risk: Data loss or truncation!
🔹 6. Non-Primitive Data Types
Type Description
String Sequence of characters, backed by char[]
Array Fixed-size sequence of elements (same
type)
Class Blueprint of user-defined objects
Object Superclass of all non-primitives in Java
Enum Set of constant values
Interfa Contract for classes to implement
ce
🧠 Non-primitives are always stored as references → actual data is in Heap, reference on
Stack.
🔹 7. Wrapper Classes
Java provides object versions of all primitives – useful in Collections, generics, etc.
Primitive Wrapper
int Integer
char Charact
er
double Double
boolean Boolean
... ...
Integer i = Integer.valueOf(5);
Use with ArrayList<Integer> etc.
🔹 8. Autoboxing & Unboxing
Java automatically converts between primitives and wrapper objects:
List<Integer> list = new ArrayList<>();
list.add(10); // Autoboxing: int → Integer
int x = list.get(0); // Unboxing: Integer → int
✅ Summary Table
Category Types / Examples Stored In
Primitive int, float, char, boolean... Stack
Non-Primitive String, Array, Object, Interface... Heap
Default Values Class vars get 0, false, null N/A
Conversion Widening (safe), Narrowing (unsafe) JVM handles
Wrapper Integer, Boolean, etc. for collections Heap
Classes
📘 Operators in Java
🔹 1. What are Operators?
Operators are special symbols in Java used to perform operations on variables and values.
They are classified based on type of operation and number of operands.
🔹 2. Categories of Java Operators
Type Description Examples
Arithmetic Operators Basic math operations +, -, *, /, %
Relational / Compare values ==, !=, >, <, >=, <=
Comparison
Logical Operators Combine boolean expressions &&, ||
Assignment Operators Assign values to variables =
Unary Operators Operate on a single operand ++, --
Bitwise Operators Operate on bits &, |
Ternary Operator Conditional expressions (if-else condition ? trueVal :
short) falseVal
🔹 3. Arithmetic Operators
Operator Use Example Result
+ Addition 5 + 2 7
- Subtraction 5 - 2 3
* Multiplication 5 * 2 10
/ Division 5 / 2 2 (int div)
% Modulo 5 % 2 1
🧠 Backend: / between integers truncates decimal → use float or double for precision.
🔹 4. Relational (Comparison) Operators
Operator Description Example Output
== Equal to 5 == 5 true
!= Not equal to 5 != 4 true
> Greater than 5 > 2 true
< Less than 5 < 2 false
>= Greater than or 5 >= 5 true
equal
<= Less than or equal 5 <= 4 false
🔍 Can be used in conditions like if (a > b) {...}.
🔹 5. Logical Operators
Used to combine boolean expressions.
Operator Description Example Output
&& Logical AND true && false false
|| Logical OR True || False true
! Logical NOT !true false
🧠 Short-circuiting:
● &&: If left is false, right is not evaluated
● ||: If left is true, right is not evaluated
🔹 6. Assignment Operators
Operator Description Example Equivalent
= Assign value x = 5 -
+= Add and assign x += 5 x = x + 5
-= Subtract and x -= 3 x = x - 3
assign
*= Multiply and assign x *= 2 x = x * 2
/= Divide and assign x /= 2 x = x / 2
%= Modulo and assign x %= 2 x = x % 2
🔹 7. Unary Operators
Operate on a single operand.
Operator Description Example Result
+ Positive value (no-op) +5 5
- Negation -5 -5
++ Increment ++x / Adds 1
x++
-- Decrement --x / Subtracts
x-- 1
! Logical NOT !true false
🧠 ++x (pre-increment) increments before usage, x++ (post-increment) increments after
usage.
int x = 5;
System.out.println(++x); // 6
System.out.println(x++); // 6 (then x becomes 7)
🔹 8. Bitwise Operators
Operate at bit-level (low-level optimization, flags, compression).
Operator Name Description Example
& AND 1 & 1 → 1, 1 & 0 → 0 5 & 3→1
` ` OR 1
^ XOR 1^1 → 0, 1^0 → 1 5 ^ 3→6
~ NOT Inverts bits ~5 → -6
<< Left Shift Multiply by 2^n 5 << 1 → 10
>> Right Shift Divide by 2^n 5 >> 1 → 2
🧠 Used in embedded systems, low-level IO, or performance-heavy apps.
🔹 9. Ternary Operator
Shorthand for if-else condition.
int a = 10, b = 20;
int max = (a > b) ? a : b;
✅ If a > b, max = a, else max = b.
🔹 10. instanceof Operator
Used to check if an object is an instance of a specific class or interface.
String s = "Java";
System.out.println(s instanceof String); // true
✅ Prevents ClassCastException.
🔹 11. Type Cast Operator
Used to convert one type to another manually.
double d = 9.99;
int i = (int) d; // i = 9 (fractional part lost)
🧠 Casting can lead to:
● Truncation (double to int)
● Overflow (int to byte)
🧠 Bonus: Operator Precedence & Associativity
Operator Type Associativity
Postfix x++ Left to Right
Unary ++x, !x Right to Left
Multiplicative * Left to Right
Additive +, - Left to Right
Relational Left to Right
Logical Left to Right
Assignment Right to Left
Example:
int a = 5 + 2 * 3; // 2*3=6 → 5+6=11
✅ Summary
Operator Type Examples Use Case
Arithmetic +, -, *, /, % Basic math
Relational ==, >, <, etc. Conditions
Logical &&, `
Assignment =, +=, *= etc. Assign & update values
Unary ++, --, !, ~ Single operand manipulation
Bitwise &, ` , ^, <<` etc.
Ternary ? : Inline if-else
instanceof Type checking Safe casting
Type Cast (type) Manual conversion
value
📘 Conditional Statements in Java
🔹 What are Conditional Statements?
Conditional statements control the flow of execution in a program. They allow the program to
make decisions based on certain conditions and execute different code paths accordingly.
🔹 Why Use Conditional Statements?
Purpose Explanation
Decision-Making Enables dynamic program behavior based on runtime input or
logic.
Control Flow Helps avoid hardcoding all scenarios linearly.
Cleaner Code Reduces repetition by handling conditions in structured blocks.
🔹 Types of Conditional Statements
1. if Statement
✅ Syntax:
if (condition) {
// block executes if condition is true
}
✅ Example:
int age = 20;
if (age >= 18) {
System.out.println("Eligible to vote.");
}
💡 Behind the scenes:
● JVM evaluates the condition.
● If condition returns true, block enters the "True" branch.
● Uses conditional jump bytecode like if_icmpg
2. if-else Statement
✅ Syntax:
if (condition) {
// true block
} else {
// false block
}
✅ Example:
int marks = 45;
if (marks >= 50) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
3. if-else-if Ladder
✅ Syntax:
if (condition1) {
// block 1
} else if (condition2) {
// block 2
} else {
// default block
}
✅ Example:
int score = 85;
if (score >= 90) {
System.out.println("Grade A");
} else if (score >= 75) {
System.out.println("Grade B");
} else {
System.out.println("Grade C");
}
4. switch Statement
● Used when a single variable needs to be checked against multiple exact values.
● Introduced for int, char, String (since Java 7), enum, and now switch
expressions in Java 14+.
✅ Syntax (Java 8 and below):
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// default code
}
✅ Syntax (Java 14+ – Switch Expressions)
String grade = switch(score) {
case 90 -> "Grade A";
case 80 -> "Grade B";
default -> "Grade C";
};
✅ Example:
char ch = 'B';
switch (ch) {
case 'A':
System.out.println("Apple");
break;
case 'B':
System.out.println("Ball");
break;
default:
System.out.println("Unknown");
}
🔹 Rules and Best Practices
Rule/Tip Explanation
Always use break in switch cases Prevents fall-through unless intentionally
used
Use {} even for single-line if blocks Improves readability and reduces logical bugs
Avoid deeply nested if-else Refactor to method calls or use switch
Prefer switch for exact-value Especially useful for enums and menu logic
checking
🔹 Common Mistakes
● Using = instead of == in if conditions
● Forgetting break in switch (unless fall-through is intended)
● Comparing incompatible types (e.g., string vs char)
📘 Loops in Java
🔹 What are Loops?
Loops are control structures that allow repeated execution of a block of code until a condition
is met or fails. They help in:
● Avoiding redundancy
● Processing data structures
● Automating repetition
🔹 Why Use Loops?
Purpose Explanation
Automate repetition Run same logic multiple times (e.g., print 1 to 100)
Work with collections Iterate through arrays, lists, etc.
Improve code clarity Reduces need for copy-paste logic
🔹 Types of Loops in Java
🔁 1. for Loop
Used when the number of iterations is known.
✅ Syntax:
for (initialization; condition; update) {
// code block
}
✅ Example:
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
Output:-
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
🔬 Behind the scenes (Memory/Bytecode):
● Initialization executed once.
● Condition checked before every iteration.
● If true, block executes and then update step runs.
🔁 2. while Loop
Used when condition-driven loop is needed (uncertain iteration count).
✅ Syntax:
while (condition) {
// code block
}
✅ Example:
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
💡 Notes:
● Initialization must be done before the loop.
● Infinite loop risk if condition never fails.
🔁 3. do-while Loop
Guaranteed single execution of loop block even if condition fails on first check.
✅ Syntax:
do {
// code block
} while (condition);
✅ Example:
int i = 1;
do {
System.out.println("Count: " + i);
i++;
} while (i <= 5);
🔁 4. Enhanced for Loop (a.k.a. for-each)
Used to iterate collections/arrays without needing index control.
✅ Syntax:
for (type element : arrayOrCollection) {
// block
}
✅ Example:
int[] numbers = {1, 2, 3, 4};
for (int num : numbers) {
System.out.println(num);
}
💡 JVM Detail:
● Internally uses iterator when dealing with objects like List, Set.
● Doesn’t allow modification during traversal (ConcurrentModificationException if altered
mid-loop).
🔹 Jump Statements in Loops
Keyword Meaning
break Exits the loop immediately
continu Skips current iteration and goes to next
e one
✅ Example – break:
for (int i = 1; i <= 10; i++) {
if (i == 5) break;
System.out.println(i);
}
✅ Example – continue:
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
System.out.println(i);
}
🔹 Loop Comparison Table
Feature for while do-while enhanced
for
Use case Known count Unknown count At least once Arrays/Lists
Initialization Inside loop Before loop Before loop Implicit
Post check Yes Yes No (runs first) No
Index control Yes Yes Yes No
🔬 What Happens in Memory (Deep Dive)
● Loop variables are stored on the stack (method frame).
● Bytecode includes jump instructions (like goto, if_icmpge) to manage control flow.
● Loop unrolling optimization may happen during JIT compilation if loop bounds are
predictable.
● For-each with objects like List uses Iterator under the hood (calls hasNext() and
next()).
🧠 Best Practices
Tip Why it matters
Prefer for-each when index isn’t Cleaner and avoids errors
needed
Avoid infinite loops unless intentional Can crash app or hog
CPU
Avoid modifying collection in for-each Use iterator explicitly
Minimize logic inside loop body Improves performance
🔁 Nested Loops in Java
🔹 What Are Nested Loops?
A nested loop means a loop inside another loop.
● The outer loop runs once → inner loop runs completely.
● Used in matrix operations, pattern printing, data processing, etc.
🔁 Syntax:
for (initialization1; condition1; update1) {
for (initialization2; condition2; update2) {
// Inner loop block
}
// Outer loop block
}
✅ Simple Example:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.println("i = " + i + ", j = " + j);
}
}
🧠 Output:
i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 2
🔸 Real-World Example: 2D Array Traversal
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
🔸 Pattern Printing Example (Star Pyramid)
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
🧠 Output:
*
* *
* * *
* * * *
* * * * *
🧠 Behind the Scenes (How Nested Loops Work in Memory)
● Each loop frame exists on the stack.
● JVM evaluates each iteration of the inner loop completely before moving to next
iteration of the outer loop.
● The total number of iterations = outer loop count × inner loop count.
Outer: i = 3
Inner: j = 4
Total Iterations = 3 × 4 = 12
🚨 Nested Loop Performance Consideration
Nested Loop Time Complexity
Depth
1 level O(n)
2 levels O(n²)
3 levels O(n³)
More… 🚨 Inefficient!
Too many nested loops can cause performance issues (especially on large datasets). Use
algorithmic optimization or dynamic programming when necessary.
🔸 Nested while and do-while Examples
int i = 1;
while (i <= 3) {
int j = 1;
while (j <= 2) {
System.out.println("i = " + i + ", j = " + j);
j++;
}
i++;
}
🔄 Nested Loops Best Practices
Tip Why
Limit depth to 2–3 max More becomes hard to read and
inefficient
Comment inner logic Improve readability
Consider breaking into functions Clean, reusable code
Analyze time complexity Avoid O(n²)+ loops unless truly required
📚 Use Cases
● Pattern printing (like triangles, pyramids)
● Matrix multiplication
● Grid-based algorithms (e.g., games, simulations)
● Comparing elements in 2 datasets (e.g., brute-force search)
📦 Arrays in Java
🔹 What is an Array?
An Array is a collection of elements (same data type) stored in contiguous memory
locations.
Think of it like a train with compartments — each compartment stores a value and
has a fixed position (index).
🔹 Why Use Arrays?
Need How Array Helps
Store multiple values Instead of 10 variables, use 1 array
Index-based fast access Constant time O(1) access
Efficient memory allocation Elements are stored in contiguous
memory
Ideal for iteration & search Use loops easily with arrays
🔹 Array Syntax
🛠 Declaration: 2 ways
Syntax1:- datatype[] arrayname;
Example:- int[] numbers; // preferred
Syntax2: datatype arrayname[];
Example:- int numbers[]; // also valid
🧪 Initialization:
Syntax: arrayname = new datatype[size of array]
Example:- numbers = new int[5]; // Creates array of size 5
(default values = 0)
📦 Declaration + Initialization:
Syntax:- datatype[] arrayname = new datatype[size of array]
Examples:- int[] numbers = new int[5];
🚀 Shortcut Initialization: preferred when you know all array elements.
Syntax:- datatype[] arrayname = {val1, val2, val3,....,valn}
Example:- int[] primes = {2, 3, 5, 7, 11};
🔹 Accessing Elements (Index-based)
System.out.println(numbers[0]); // First element
numbers[2] = 100; // Set value at index 2
● Indexing starts from 0
● Last index = length - 1
🔍 Important: Memory & Backend
● Arrays are stored in heap memory
● Reference is stored in the stack
● Default values:
○ int → 0
○ boolean → false
○ Object → null
int[] arr = new int[3];
🔧 JVM allocates a block of 3 integers (12 bytes) in heap and stores the memory reference in
the stack.
🔍 Array Traversal with Loops
Using for loop:
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
Using enhanced for-each loop:
for (int num : arr) {
System.out.println(num);
}
How the enhanced for loop works here
for (int i : number2) {
...
}
● This is value-based iteration, not index-based.
● So in the first iteration, i = number2[0] = 0
in the second iteration, i = number2[1] = 0
… and so on, for all 12 elements.
● Since all values are 0, i is always 0.
🔸 Types of Arrays
Type Description Example
1D Array Linear data structure int[] a = {1, 2, 3};
2D Array Matrix-like (rows × columns) int[][] m = new
int[2][3];
Multi-D Array Higher dimensional arrays int[][][] tensor =
...;
🔹 2D Arrays (Two-Dimensional Arrays)
✅ Definition:
A 2D array is an array of arrays, used to represent matrices, grids, or tables. Each element is
accessed via two indices: row and column.
📌 Syntax:
// Declaration
int[][] matrix;
// Initialization
matrix = new int[3][4]; // 3 rows, 4 columns
// Declaration + Initialization
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
🧠 Behind the Scenes (Memory):
● 2D arrays in Java are arrays of references to arrays
● Rows may or may not be of the same size (i.e., jagged arrays allowed)
matrix
↓
[ref] → [1][2][3]
[ref] → [4][5][6]
Each row is a separate 1D array in memory.
🔁 Traversal:
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
Or with for-each:
for (int[] row : matrix) {
for (int col : row) {
System.out.print(col + " ");
}
System.out.println();
}
🧪 Example:
int[][] matrix = {
{10, 20, 30},
{40, 50, 60}
};
System.out.println(matrix[1][2]); // Output: 60
🔸 Comparison Table
Feature 1D Array 2D Array
Shape Linear Tabular / Matrix
Indexing Single index (arr[i]) Double index (arr[i][j])
Memory Contiguous Array of references to
arrays
Use Cases List of numbers, marks, IDs Game board, matrices,
tables
Default All elements default to 0, false, or null depending
values on type
⚠️ Common Errors
Mistake Description
ArrayIndexOutOfBoundsExc Accessing beyond declared range
eption
NullPointerException Using an array reference before initialization
Jagged access Uneven rows: be careful with
matrix[i].length
📚 Use Cases
1D:
● Marks, scores, names
● Stacks, queues
● Frequency counters
2D:
● Matrices for math problems
● Game boards (tic-tac-toe)
● Storing table data (Excel-like)
🧠 Interview Tips
● Know how memory is managed (stack vs heap)
● Always mention .length is per-dimension:
○ arrayname.length = no. of rows
○ arrayname[i].length = no. of cols in row i
● You can have jagged arrays: int[][] jagged = new int[3][];
🛠 Practice Tasks
1. Declare and fill a 5-element int array.
2. Create a 3x3 matrix and print the diagonal.
3. Implement matrix addition.
4. Reverse a 1D array in place.
📘 Strings in Java – Deep Dive
🔹 What is a String in Java?
● A String is a sequence of characters.
● In Java, String is a class in java.lang package, not a primitive type.
● Immutable: Once created, cannot be changed.
String s = "hello";
Internally:
char[] value = {'h','e','l','l','o'};
🔹 Why Strings are Immutable?
1. Security: For classes like URL, ClassLoader, etc.
2. Caching: String pool benefits.
3. Thread Safety: Can share safely between threads.
4. Hashing: Hashcode remains constant.
🔹 String Memory Structure (JVM Internals)
Created using... Stored in... Memory
String s = "abc"; String Constant Heap (interned)
Pool
String s = new Heap (outside SCP) Heap
String("abc"); (non-interned)
String a = "hello"; // 1 object in SCP
String b = new String("hello"); // 2 objects: one in SCP, one in heap
🔹 Ways to Create Strings
String s1 = "Java"; // String Literal (pooled)
String s2 = new String("Java"); // Object (non-pooled)
char[] arr = {'J','a','v','a'};
String s3 = new String(arr); // From char array
🔹 Commonly Used String Methods
Method Purpose
length() Returns length
charAt(index) Returns char at index
substring(start, end) Extract substring
toLowerCase() / Case conversion
toUpperCase()
trim() Removes leading/trailing spaces
equals() / Compare content
equalsIgnoreCase()
compareTo() Lexicographic comparison
indexOf() / Search character/substring
lastIndexOf()
contains() Checks presence of substring
split() Splits string using regex
replace() Replaces characters/words
isEmpty() / isBlank() Checks if empty or whitespace only
🔹 String Pool vs Heap
String s1 = "Java";
String s2 = "Java";
System.out.println(s1 == s2); // true → same reference in pool
String s3 = new String("Java");
System.out.println(s1 == s3); // false → s3 in heap
To force intern:
String s4 = new String("Java").intern();
System.out.println(s1 == s4); // true
🔹 String Concatenation & Performance
String s = "a" + "b" + "c"; // compile-time optimization
String s = "";
for (int i = 0; i < 1000; i++) {
s += i; // BAD: creates many objects
}
✅ Use StringBuilder or StringBuffer:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i);
}
String result = sb.toString()
🔹 Comparison Methods
Method Use case
== Compares references, not values
equals() Compares content
compareTo Lexicographical comparison
() (-1/0/1)
🔹 Mutable Alternatives
Class Thread Safe Use Case
StringBuil ❌ Single-threade
d
der
StringBuff ✅ Multi-threaded
er
🔸 Memory and GC Behavior
● String literals are interned and never GC'ed until class unloading.
● StringBuilder doesn’t go to pool; used for performance tuning.
● Be careful with substrings pre–Java 7: used to share large char[].
🧠 Interview Tricky Questions
Question Answer
What’s the difference between == and Reference vs content
equals()?
Why Strings are immutable? Security, caching,
thread-safety
How does String Pool work? Interns string literals
Is String final? Can we extend it? No, it's final
What’s better for loops: + or StringBuilder? StringBuilder for
performance
🔧 Practice Examples
✅ Check Palindrome
public static boolean isPalindrome(String str) {
String rev = new StringBuilder(str).reverse().toString();
return str.equals(rev);
}
✅ Reverse Words:
String str = "Java is fun";
String[] parts = str.split(" ");
Collections.reverse(Arrays.asList(parts));
System.out.println(String.join(" ", parts)); // fun is Java
✅ Remove duplicates:
String input = "aabbcc";
StringBuilder output = new StringBuilder();
for (char ch : input.toCharArray()) {
if (output.indexOf(String.valueOf(ch)) == -1)
output.append(ch);
}
✅ Summary
Topic Details
Data Type Reference type
Class java.lang.String
Immutability Yes
Memory Area Heap (with String Pool for literals)
Performance Tip Use StringBuilder for heavy
modifications
Use Case IDs, names, messages, file paths, configs
✅ Final Comparison Table
Feature String StringBuilder StringBuffer
Mutable ❌ No ✅ Yes ✅ Yes
Thread-Safe ✅ Yes ❌ No ✅ Yes
Performance ❌ Slow ✅ Fast ⚠️ Moderate
Use In Constants, Loops, internal ops Multi-threaded ops
keys
Memory Efficient ❌ No ✅ Yes ⚠️ Less Efficient
🧠 Interview Insights
● String is immutable and stored in the String Pool.
● StringBuilder is best for performance in most cases.
● StringBuffer is rarely used now; better to use StringBuilder with explicit
synchronization when needed.
● == checks reference equality, .equals() checks value equality for Strings.
📘 Object Oriented Programming –
Classes
🔹 What is a Class?
● A class is a collection of variables (attributes) and methods (behaviors).
Example:
Class → Animal (Logical Entity)
|
├── Dog
├── Elephant
└── Cat (Physical Entities)
● All these objects share similar attributes/behaviors, hence they fall under the same
class.
🔹 Class vs Object
● Class → Logical entity (blueprint).
● Object → Physical entity (real-world instance).
👉 A class is logical because it does not occupy memory until objects are created.
👉 An object contains attributes and behaviors.
● Attribute → Variables
● Behavior → Methods
🔹 Key Points
1. A class can only extend one other class (single inheritance).
2. A class can implement multiple interfaces.
Class members (variables & methods) are accessed using:
objectName.variableName
objectName.methodName()
3. Any number of objects can be created from a class.
4. Each object has its own copy of instance variables but shares the class definition.
🔹 Example: Employee Class
Employee (Class)
-----------------
Variables:
- Id
- Name
- Salary
- Dept
Method:
- Bonus()
Objects:
Obj1:
Id = 01
Name = David
Salary = 1000
Dept = INS
Bonus()
Obj2:
Id = 04
Name = Brandi
Salary = 5000
Dept = Trends
Bonus()
Obj3:
Id = 09
Name = Joseph
Salary = 7000
Dept = Xell
Bonus()
👉 All objects are stored in different memory locations.
👉 They are not related to each other except that they belong to the same class.
Example Class: Employee
class Employee {
int eid; // Employee ID
String ename; // Employee Name
double sal; // Salary
String job; // Job Title
// Method to display details
void display() {
System.out.println(eid);
System.out.println(ename);
System.out.println(sal);
System.out.println(job);
// Method to calculate and print bonus
void bonus() {
System.out.println(sal * 10 / 100); // 10% bonus
🔹 Creating Objects & Assigning Values
Object 1
Employee emp1 = new Employee(); // Creating object
emp1.eid = 100; // Assign values
emp1.ename = "John";
emp1.sal = 80000;
emp1.job = "Manager";
emp1.display(); // Call method
Object 2
Employee emp2 = new Employee();
emp2.eid = 101;
emp2.ename = "David";
emp2.sal = 50000;
emp2.job = "Tech Assistant";
emp2.display();
👉 Here values are assigned to variables through reference variable (object name).
🔹 Important Points
● A class contains:
○ Variables → define the state of objects.
○ Methods → define behavior.
● An object is created using new.
● Methods are invoked using object reference.
● Each object has its own copy of variables.
🔹 Possibility Examples
interface I1 {}
interface I2 {}
class A {}
class B {}
Valid & Invalid Combinations
Example Possibility
class Test1 extends A {} ✅ Possible
class Test2 extends A, B ❌ Not Possible (Multiple Inheritance not allowed)
{}
class Test3 implements I1 ✅ Possible
{}
class Test4 extends I2 {} ❌ Not Possible (cannot extend interface)
class Test5 implements I1, ✅ Possible
I2 {}
class Test7 implements I1, ❌ Not Possible (wrong order: extends must come
I2 extends A {} before implements)
Objects
● An object is an instance of a class.
● A class can have any number of objects.
● Objects of the same class share the same attributes & behaviour i.e., variables and
methods.
● Object for a class can be defined as:
○ Objects are created in the main method, normally.
Syntax:
ClassName objectName = new ClassName();
● Accessing variables through objects:
objectName.variableName;
● Calling methods through an object:
objectName.methodName();
Example:
Car c = new Car(); // c → reference, new Car() → object, Car → class
Methods
● Methods are a block of code which contains logic.
● A class can have any number of methods.
Syntax:
datatype methodName() {
// code
}
Notes
1. main() method can be placed in the same class.
2. Such a class cannot be shared with others because it has the main() code, which is
very specific to one project/package.
3. If main() is not present in a class, variables and methods can be shared.
4. main() method can be present in a separate class.
○ For this, both classes should be inside the same project and same package.
5. Such a class (without main()) can be shared with others because it does not contain
main(), which is project-specific.
Class Variables
We can assign values to variables in 3 ways:
1. By using Reference Variables
Reference variables are created during object creation.
objectName.variableName = value;
2. By Using Methods
(i) Create a method in the class
void getValue(int id, String name, char g) {
sid = id;
sname = name;
grade = g;
}
(ii) Call the above method in main class with certain values
objectName.getValue(101, "Anas", 'A');
3. By Using Constructor
● Constructor is also a method, but a special type.
● It is used only for initializing class variables (not for logic).
● Constructor name must be same as the class name.
● A constructor does not return any value (not even void).
● Constructor does not need to be explicitly called—it is automatically invoked at the
time of object creation.
Example:
className(int id, String name, char g) {
sid = id;
sname = name;
grade = g;
}
Methods in Java
● Method: When defined inside a class.
👉
● Function: Commonly used term in the main program.
In Java, methods and functions are almost the same.
● In the main class, when creating an object, we must pass values if required.
● If we try to assign values using a constructor incorrectly, it will throw an error.
Example:
ClassName objectName = new ClassName(101, "Anas", 23);
Java Methods
● A Java method is a block of code that is referred to by a name and can be called
(invoked) at any point in the program by using its name.
● A method is like a sub-program that acts on data and may return a value.
● Each method has its own name.
Types of Methods (Based on Parameters & Return Value)
Case Parameters Return Value
Case ✗ ✗
1
Case ✗ ✓
2
Case ✓ ✗
3
Case ✓ ✓
4
Methods in a Class
● A class can have any number of methods.
Syntax:
Case 1: Method without parameters and without return value
void methodName() {
// code
}
Case 2: Method without parameters but with return value
int methodName() {
// code
return value;
}
Case 3: Method with parameters and without return value
void methodName(param1, param2, ... )
{
// code
}
Case 4: Method with parameters and with return value
int methodName(param1, param2, ... )
{
// code
return value;
}
Types of Constructor
1. Default Constructor
● Syntax: In class, create a default constructor.
ConstructorName()
{
// variable initialization
}
● Usage in main class: To invoke the default constructor, create an object of the class.
ClassName objectName = new ClassName();
Parameterized Constructor
A Parameterized Constructor contains parameters.
● To create a constructor with parameters:
ClassName(Type param1, Type param2) {
variable1 = param1;
variable2 = param2;
}
● In the main class, while creating an object, pass values to the constructor:
ClassName obj = new ClassName(value1, value2);
Method vs Constructor
Method Constructor
1. Method name can be anything. 1. Constructor must have the same name as the
class.
2. Method can return a value. 2. Constructor cannot return a value.
3. Needs to be called explicitly. 3. Automatically invoked at the time of object
creation.
4. We can write logic inside 4. Constructor is only used for variable initialization.
methods.
5. Constructor is also a method.
Overloading (Method & Constructor)
(Also called Compile-Time Polymorphism)
Definition
Overloading is an approach through which we can achieve polymorphism.
Types of Overloading
1. Method Overloading
2. Constructor Overloading
Explanation
Overloading is the process of creating multiple methods/constructors having the same name
but different sets of parameters (different number or types of parameters).
Advantages of Overloading
1. Saves Memory
○ Since methods/constructors have the same name, they are stored in the same
memory location.
○ Based on the input parameters, the correct method gets executed.
2. Saves Time
○ We don’t need to create multiple different methods/constructors with different
names.
○ Instead, we just reuse the same method name with different parameters.
Rules for Creating Method/Constructor Overloading
1. Method/constructor must differ in types or number of parameters.
2. The number of parameters and/or their datatypes must be different.
Example: Method Overloading
package packagename;
class MethodOverloading {
void add(int a, int b) {
System.out.println(a + b); // Version 1
}
void add(int a, double b) {
System.out.println(a + b); // Version 2
}
void add(double a, double b) {
System.out.println(a + b); // Version 3
}
void add(int a, int b, int c) {
System.out.println(a + b + c); // Version 4
}
public static void main(String[] args) {
MethodOverloading mo = new MethodOverloading();
mo.add(5, 6); // Calls version 1
mo.add(8, 20.30); // Calls version 2
mo.add(60.30, 30); // Calls version 3
mo.add(4, 5, 7); // Calls version 4
}
}
Example 2: Constructor Overloading
package packagename;
public class ConstructorOverloading {
// Constructor 1
ConstructorOverloading(int a, int b) {
System.out.println(a + b);
}
// Constructor 2
ConstructorOverloading(int a, double b) {
System.out.println(a + b);
}
// Constructor 3
ConstructorOverloading(double a, int b) {
System.out.println(a + b);
}
// Constructor 4
ConstructorOverloading(int a, int b, int c) {
System.out.println(a + b + c);
}
public static void main(String args[]) {
ConstructorOverloading co1 = new ConstructorOverloading(10,
20);
ConstructorOverloading co2 = new ConstructorOverloading(10,
20.30);
ConstructorOverloading co3 = new ConstructorOverloading(10.20,
30);
ConstructorOverloading co4 = new ConstructorOverloading(10,
20, 30);
}
}
✨ This is a Java program demonstrating constructor overloading — same class name, but
constructors with different parameter lists (number & types).
Example 3: Overloading Main Method in Java
● We can create any number of main methods, but we must change their signature.
● We cannot create a main method with the same signature (public static void
main(String args[])) more than once, because:
○ It is the default entry point of the program.
○ JVM will always start execution from this method only.
Code Example
package packagename;
public class OverloadMain {
// 1. Overloaded main method with single int parameter
public void main(int a) {
System.out.println(a);
}
// 2. Overloaded main method with two int parameters
public void main(int a, int b) {
System.out.println(a + b);
}
// 3. Standard main method (entry point)
public static void main(String args[]) {
OverloadMain om = new OverloadMain();
om.main(5); // Calls method 1
om.main(10, 20); // Calls method 2
}
}
✅ Explanation:
1. The public static void main(String args[]) is the default method that JVM
calls.
2. Other main methods are overloaded methods — they do not serve as entry points but
can be called from inside the main method.
3. In the example:
○ om.main(5) → calls public void main(int a)
○ om.main(10, 20) → calls public void main(int a, int b)
this Keyword in Java
The this keyword can be used in method and constructor resolution.
Example 1: Without Using this Keyword
Code:
package packagename;
public class ThisKeyword {
int a, b; // Instance (class) variables
void getValue(int a, int b) {
a = a;
b = b;
}
void display() {
System.out.println(a);
System.out.println(b);
}
public static void main(String args[]) {
ThisKeyword th = new ThisKeyword();
th.getValue(10, 20);
th.display();
}
}
Output:
0
0
✅
Not the expected output.
Expected output was:
10
20
Explanation:
1. The program is syntactically correct but logically wrong.
2. Inside the method getValue(int a, int b), the method parameters (a, b)
shadow (hide) the instance variables (a, b).
○ The assignment a = a; assigns the local variable to itself, not the instance
variable.
○ Similarly for b = b;.
3. As a result, the instance variables are never updated and retain their default values (0
for int).
4. Hence, the output is 0 0 instead of 10 20.
👉 The solution is to use the this keyword (e.g., this.a = a; this.b = b;) so that the
compiler knows we are assigning the value to the instance variables, not to the method
parameters.
Example 2: Using this Keyword
Code:
package packagename;
public class ThisKeyword {
int a, b; // Instance (class) variables
void getValue(int a, int b) {
this.a = a; // 'this.a' refers to instance variable
this.b = b; // 'this.b' refers to instance variable
}
void display() {
System.out.println(a);
System.out.println(b);
}
public static void main(String args[]) {
ThisKeyword th = new ThisKeyword();
th.getValue(10, 20);
th.display();
}
}
Output:
10
20
✅ Expected output achieved.
Explanation:
1. Using this keyword solves the drawback seen in the previous example.
2. this keyword tells the method that the variable being referred to is the instance
variable of the class, not the local (method parameter) variable.
○ this.a = a; → assigns the method parameter a to the instance variable a.
○ this.b = b; → assigns the method parameter b to the instance variable b.
3. Thus, the instance variables actually get updated with the values 10 and 20.
4. Output becomes 10 and 20 as expected.
👉 Now you have both cases side by side:
● Without this → wrong result (0 0)
● With this → correct result (10 20)
Static Variables & Static Methods
● static is a keyword in Java which is applicable for both variables and methods
Static Variables
Example 1: Without Using static Keyword
class Employee {
int empno;
String ename;
int deptno;
void bonus() {
// some logic
}
}
Objects Created:
● emp1 → empno = 101, ename = "John", deptno = 10
● emp2 → empno = 102, ename = "Ravi", deptno = 10
● emp3 → empno = 103, ename = "Ritu", deptno = 10
● emp4 → empno = 104, ename = "Preeti", deptno = 10
(Each object has its own copy of empno, ename, deptno, and bonus() method)
Notes:
1. Every object occupies its own space in memory.
2. Objects are independent.
○ Modifying a variable in one object does not affect the same variable in another
object.
Problem in the Above Approach:
1. Since deptno = 10 is assigned to all employee objects, this is:
○ Time-consuming.
○ Wastes extra memory (same value stored repeatedly).
2. If we want to change deptno for all employees (e.g., from 10 → 12),
✅
○ We must update it in every single object, which is inefficient.
3. To overcome such drawbacks, we can use the static keyword
Example 2: Using static Keyword
Code:
class Employee {
int empno;
String ename;
static int deptno = 10; // static variable shared by all objects
void bonus() {
// some logic
}
}
Objects Created:
● emp1 → empno = 101, ename = "Jack", deptno = 10 (shared)
● emp2 → empno = 102, ename = "David", deptno = 10 (shared)
● emp3 → empno = 103, ename = "Scott", deptno = 10 (shared)
● emp4 → empno = 104, ename = "Rock", deptno = 10 (shared)
(Only one copy of deptno is created and shared among all objects)
Explanation:
1. With this approach, the static variable is common to all objects.
○ So, if the static variable is modified, the change is reflected in all objects.
2. This saves both memory and time cost, since only one copy of the variable is stored.
3. deptno can be changed in the class just like a normal variable.
4. If we don’t want to update it through the class, we can modify it through any object, and
the change will still be reflected everywhere.
✅ Key Benefit of static keyword:
● Instead of wasting memory by duplicating the same variable in every object, static
allows sharing one common copy across all objects.
Static Methods in Java
Rules of Static Methods:
1. Static methods can access only static stuff (variables/methods) without using an
object.
○ Non-static variables and methods can be accessed only after object creation.
2. If the main method is specified in some other class, then:
○ We must mention the class name along with the variable & method (if they are
static).
Example:
System.out.println(ClassName.staticVariable);
ClassName.methodName();
3. If main is in the same class, then we don’t need to mention the class name for
accessing static variables/methods.
Important Points:
● Static methods can also access non-static stuff, but only through objects.
● Non-static methods can access both static and non-static stuff directly.
Example:
package packagename;
public class StaticExample {
static int a = 10; // static variable
int b = 20; // non-static variable
static void m1() { // static method
StaticExample se = new StaticExample(); // create object for
non-static access
System.out.println(se.b); // accessing non-static
var through object
System.out.println("This is m1 -- Static method");
}
void m2() { // non-static method
System.out.println("This is m2 -- Non-static method");
}
}
✅ Explanation:
● Inside m1() (a static method), to access non-static variable b, we must create an object.
● Inside m2() (a non-static method), we can directly access both a and b.
System Class in Java
● System is a predefined class in Java.
● out is a variable of type PrintStream.
● print() → prints message in same line.
● println() → prints message in new line.
Example Code
public class StaticExample {
static int a = 10; // static variable
int b = 20; // non-static variable
static void m1() {
System.out.println("This is m1 -- Static method");
}
void m2() {
System.out.println("This is m2 -- Non-Static method");
}
void m3() { // Non-static method
System.out.println("This is m3 -- Non-Static method");
System.out.println(a); // Accessing static variable directly
System.out.println(b); // Accessing non-static variable
directly
m1(); // Calling static method directly
m2(); // Calling non-static method directly
}
public static void main(String[] args) {
// Accessing static variable & method directly
System.out.println(a);
m1();
// Creating object to access non-static members
StaticExample se = new StaticExample();
System.out.println(se.b);
se.m2();
// Calling m3() using object
se.m3();
}
}
Key Points:
● Non-static method can access both static and non-static members directly.
● Static method (main) can access only static members directly.
○ To access non-static members, it must create an object
Comparison Table:
Method Type Static Static Non-Static Non-Static
Variable Method Variable Method
Static Method ✔ (direct) ✔ (direct) ✘ (only via object) ✘ (only via
object)
Non-Static ✔ (direct) ✔ (direct) ✔ (direct) ✔ (direct)
Method
✔ = Direct Access
✘ = Through Objects