Java Notes
1. Introduction to Java
• Java is a high-level, object-oriented, platform-independent
programming language.
• Developed by Sun Microsystems (now owned by Oracle).
• Known for its slogan: “Write Once, Run Anywhere (WORA)” →
due to JVM.
• Used for:
o Desktop Applications
o Web Applications
o Mobile Apps (Android)
o Enterprise Solutions
o Cloud & Big Data
• 2. History of Java
• 1991 → Project started by James Gosling & team (called "Green
Project").
• Initially named Oak (after an oak tree outside Gosling’s office).
• Later renamed to Java (inspired by Java coffee ).
• 1995 → Officially released by Sun Microsystems.
• 2009 → Oracle Corporation acquired Sun Microsystems → Java
ownership transferred to Oracle.
3. Features of Java (with reasons)
Feature Explanation Reason
Syntax similar to
C/C++ but no
Simple Easy to learn.
complexity like
pointers.
Everything is in the Promotes
Object-
form of classes & reusability &
Oriented
objects. modularity.
Code is compiled into
Platform- Same program runs
bytecode which runs
Independent on any OS.
on JVM.
Prevents
No explicit pointers,
Secure unauthorized
built-in security APIs.
access.
Strong memory
Reduces crashes &
Robust management,
errors.
exception handling.
Can execute multiple Better performance
Multithreaded
tasks simultaneously. in concurrent apps.
Run anywhere
Bytecode is platform-
Portable without
independent.
modification.
Faster execution
High Uses JIT (Just-In-
compared to pure
Performance Time) compiler.
interpretation.
Feature Explanation Reason
Supports RMI, EJB for Enables building
Distributed distributed network-based
computing. apps.
Can load classes
More flexible
Dynamic dynamically at
programs.
runtime.
4. What is Package in Java?
• Definition: A package is a group of related classes, interfaces,
and sub-packages.
• Purpose:
o Avoid name conflicts
o Reuse code
o Better organization
• Types:
1. Built-in Packages → e.g. [Link], [Link], [Link]
2. User-defined Packages → created by programmers.
5. Classes in Java
• Definition: A class is a blueprint/template from which objects
are created.
• Contains fields (variables) and methods.
6. Main Method in Java vs C
Aspect Java C
public static void main(String[]
Syntax int main()
args)
Return void (does not return value to int (returns status code
Type OS) to OS)
OS starts execution
Entry Point JVM looks for main method
from main
String[] args → command line
Arguments int argc, char *argv[]
arguments
Modifiers public static are mandatory No such modifiers
7. Compiler vs Interpreter
Aspect Compiler Interpreter
Translates entire code
Translates line by line
Definition into machine code at
during execution.
once.
Slower (executes line by
Speed Faster (once compiled).
line).
Aspect Compiler Interpreter
Errors shown
All errors shown after
Errors immediately (line by
compilation.
line).
Example C, C++ Python, JavaScript
Java uses both →
Compiler (javac)
Java
converts code into
Special
bytecode, then JVM’s
Case
Interpreter + JIT
Compiler executes it.
1. Arithmetic Operators in Java
• Definition: Operators that perform basic mathematical
operations.
• Operators:
o + → Addition
o - → Subtraction
o * → Multiplication
o / → Division
o % → Modulus (remainder)
Example Program:
public class ArithmeticDemo {
public static void main(String[] args) {
int a = 20, b = 6;
[Link]("a + b = " + (a + b)); // Addition
[Link]("a - b = " + (a - b)); // Subtraction
[Link]("a * b = " + (a * b)); // Multiplication
[Link]("a / b = " + (a / b)); // Division
[Link]("a % b = " + (a % b)); // Modulus
}
}
Output:
a + b = 26
a - b = 14
a * b = 120
a/b=3
a%b=2
Concept:
• / gives quotient.
• % gives remainder.
• Works on int, float, double etc.
2. Data Types in Java
Java has two categories of data types:
(A) Primitive Data Types (8 types)
• Predefined by Java, store simple values (not objects).
• Examples:
Type Size Example Real-life Analogy
1 byte (–128 to Small container (like
byte byte age = 25;
127) pen drive of 1GB)
short 2 bytes short year = 2025; Year value
int 4 bytes int salary = 50000; Employee salary
long phone =
long 8 bytes Mobile number
9876543210L;
4 bytes (decimal
float float pi = 3.14f; Approximate values
up to 7 digits)
8 bytes (decimal double area =
double Scientific calculations
up to 15 digits) 12345.6789;
char 2 bytes (Unicode) char grade = 'A'; Grades, letters
Boolean is Java
boolean 1 bit Yes/No situations
Fun = true;
(B) Non-Primitive Data Types
• Created by programmers or derived from classes.
• Examples: String, Arrays, Classes, Interfaces
• Real-Life Example:
o String → like a sentence ("Hello World")
o Array → basket holding multiple fruits
o Class → blueprint of a Car
o Object → actual Car made from the blueprint
EXAMPLE
public class DataTypeDemo {
public static void main(String[] args) {
// Primitive
byte age = 25;
double price = 99.99;
boolean isJavaFun = true;
// Non-Primitive
String name = "Ajay";
int[] marks = {90, 85, 80};
[Link]("Age: " + age);
[Link]("Price: " + price);
[Link]("Is Java Fun? " + isJavaFun);
[Link]("Name: " + name);
[Link]("First Mark: " + marks[0]);
}
}
3. What is a Variable in Java?
• Definition: A variable is a name given to a memory location to
store data.
• Syntax:
• dataType variableName = value;
• Types of Variables in Java:
1. Local Variable → declared inside a method (lives during
method execution).
2. Instance Variable → declared inside class but outside
method (belongs to object).
3. Static Variable → declared with static keyword (shared by
all objects).
OOPs vs Procedure-Oriented Programming
OOP (Object-
POP (Procedure-
Aspect Oriented
Oriented Programming)
Programming)
Focuses on objects Focuses on
Approach
(data + methods). functions/procedures.
Example
Java, C++, Python C, Pascal
Languages
Data is encapsulated
Data Data is global → less
→ protected by
Security secure.
classes.
Supports Inheritance
Code reuse via functions
Reusability & Polymorphism →
only.
high reusability.
Divides program into Divides program into
Structure
objects. functions.
Real-life Blueprint (class) → Step-by-step recipe
analogy House (object). (procedures).
Compiler vs Interpreter (and how they work together in
Java)
Aspect Compiler Interpreter
Translates entire source
Translates line by
Definition code into machine code at
line at runtime.
once.
Faster execution after
Speed Slower (line-by-line).
compilation.
Error Shows all errors at once Stops immediately
Detection after compilation. when error occurs.
Example C, C++ Python, JavaScript
In Java → Both are used together:
1. Compiler (javac) → Converts .java file → .class file (bytecode).
2. JVM (Java Virtual Machine) → Uses Interpreter + JIT (Just-In-
Time Compiler) to convert bytecode → machine code.
This is why Java is platform-independent.
Data Types in Java (Flow Chart)
Syntax to Create an Object in Java
ClassName objectName = new ClassName();
Common Methods in Java
(A) String Methods
• length() → returns length of string
• toUpperCase(), toLowerCase()
• charAt(int index)
• substring(int begin, int end)
• equals(), equalsIgnoreCase()
String str = "Java";
[Link]([Link]()); // 4
[Link]([Link]()); // JAVA
(B) Wrapper Class Methods
• [Link]("123") → converts String → int
• [Link](123) → converts int → String
(C) Math Class Methods
• [Link](25) → 5.0
• [Link](2,3) → 8.0
• [Link](10,20) → 20
• [Link]() → random double [0.0 – 1.0)
(D) Object Class Methods (superclass of all classes)
• toString() → returns string representation
• equals(Object obj) → compares objects
• hashCode() → returns hash code
Java Environment Components
1. JVM (Java Virtual Machine)
• Definition: JVM is an abstract machine that runs Java
bytecode (.class files).
• Key Functions:
1. Loads code → Class Loader loads .class files into
memory.
2. Verifies code → Bytecode verifier ensures no illegal
code (security).
3. Executes code → Interpreter + JIT (Just-In-Time)
Compiler convert bytecode → machine code.
4. Manages Memory → Uses Heap (for objects),
Stack (for methods), and Garbage Collector (to
clean unused objects).
JVM Architecture (Simplified)
2. JRE (Java Runtime Environment)
• Definition: Software package that provides environment
to run Java applications.
• Includes:
o JVM
o Core Libraries (like [Link], [Link], [Link])
• Does Not Include: Compiler (javac) → cannot develop
Java programs.
Use JRE when you just want to run a Java program.
Example:
If you download a Java game or desktop app → you only
need JRE.
3. JDK (Java Development Kit)
• Definition: Full software package for developing +
running Java programs.
• Includes:
o JRE (JVM + libraries)
o Development Tools:
▪ javac → Java Compiler (compiles .java →
.class)
▪ java → Launcher (runs program)
▪ javadoc → Generates documentation
▪ jdb → Debugger
Use JDK when you want to write, compile, and run Java
programs.
4. Relationship Between JDK, JRE, JVM
JDK = JRE + Development Tools
JRE = JVM + Libraries
JVM = Executes Bytecode
Or visually:
JDK
└── JRE
└── JVM
5. Example (Step-by-step Execution in Java)
1. Write program → [Link]
class Hello {
public static void main(String[] args) {
[Link]("Hello World");
}
}
2. Compile using JDK Compiler:
javac [Link]
→ Produces [Link] (bytecode).
3. Run using JRE (java command → JVM executes):
java Hello
→ Output:
Hello World
6. Key Interview Points
• JVM: Machine-dependent (different JVMs for Windows,
Linux, Mac).
• Bytecode: Machine-independent (same .class runs
everywhere).
• JRE: Only runs programs, cannot compile.
• JDK: Contains everything → used by developers.
• HotSpot JVM: Default JVM used by Oracle.
• JIT Compiler: Improves performance by compiling
repeated bytecode into native code.
Decision-Making Statements in Java
• Used to control program flow based on conditions.
Looping Statements in Java
Definition:
A loop is used to execute a block of code repeatedly until a
condition is true.
1. for loop
• Used when the number of iterations is known.
• Syntax:
Output:
2. while loop
• Used when the number of iterations is not fixed.
• Syntax:
•
3. do-while loop
• Similar to while, but executes at least once (condition
checked later).
• Syntax:
4. for-each loop (Enhanced for loop)
• Used to iterate over arrays or collections.
• Syntax:
Key Points
• for → fixed iterations.
• while → condition-based (unknown iterations).
• do-while → runs at least once.
• for-each → best for arrays/collections.
Difference Between Loops in Java
Loop Condition Executes At Example
When to Use
Type Checking Least Once? Use Case
When number No (may
Printing 1 to
for of iterations is Checked before not run if
10
loop known in each iteration. condition
numbers.
advance. false initially).
When number No (may Read data
while of iterations is Checked before not run if until user
loop unknown, each iteration. condition presses
condition-based. false initially). "exit".
Menu-
When code
do- driven
must execute at Checked after Yes (runs
while program
least once, then execution. at least once).
loop (ATM,
check condition.
game).
for- When iterating Automatically No Printing
each through arrays checks till end of (depends on elements of
loop or collections. collection. elements). array.
Summary:
• for → fixed count.
• while → uncertain count, condition-based.
• do-while → ensures one-time execution.
• for-each → best for arrays/collections.