Java Complete Notes
Java Complete Notes
What is Java?
Java is a high-level, class-based, object-oriented programming language developed by James Gosling
at Sun Microsystems in 1995. It follows the principle: Write Once, Run Anywhere (WORA).
Features of Java
• Simple — Easy to learn; syntax similar to C/C++ but without complex features like pointers
• Object-Oriented — Everything is modelled as objects and classes
• Platform Independent — Bytecode runs on any OS with a JVM
• Robust — Strong memory management, exception handling, type checking
• Secure — No explicit pointer access; security manager controls resource access
• Multithreaded — Built-in support for concurrent execution
• Portable — Same bytecode runs across platforms
• High Performance — JIT (Just In Time) compiler optimises bytecode at runtime
Keyword/Part Meaning
public Access modifier — visible to all
class Declares a class named HelloWorld
static Method belongs to class, not an object; called
without creating object
void Method returns no value
main Entry point — JVM starts execution here
String[] args Array to receive command-line arguments
[Link] Prints text to console and moves to next line
2. Java Tokens
Tokens are the smallest individual units in a Java program — the building blocks the compiler reads.
Identifier Rules
• Can contain letters (a-z, A-Z), digits (0-9), underscore (_), dollar sign ($)
• Must NOT start with a digit
• Cannot be a keyword
• Case-sensitive (age, Age, AGE are three different identifiers)
• No length limit (but keep it meaningful)
Literals in Detail
Literal Type Example Notes
Integer 42, 0xFF (hex), 0b1010 (binary), Default type is int; add L for
0755 (octal) long: 100L
Floating Point 3.14, 2.5f, 1.0e10 Default is double; add f for float
Character 'A', '\n', '\t', '\\', '\'' Single quotes; uses Unicode
String "Hello", "Line1\nLine2" Double quotes; objects of String
class
Boolean true, false Only these two values;
lowercase
Null null Represents no object reference
3. Variables and Data Types
What is a Variable?
A variable is a named memory location that stores a value. The value can change during program
execution. Every variable has a type, a name, and a value.
Types of Variables
Type Where Declared Scope Default Value
Local Variable Inside a method or Only inside that No default — must
block method/block initialise
Instance Variable Inside class, outside Throughout the object's int→0, double→0.0,
method life boolean→false,
Object→null
Static Variable Inside class with static Shared across all Same defaults as
keyword objects (class-level) instance variables
void display() {
int localVar = 5; // local variable
[Link](localVar + instanceVar + staticVar);
}
}
Type Casting
Converting one data type to another.
// Widening (automatic)
int i = 100;
long l = i; // int → long (no cast needed)
double d = l; // long → double
// Narrowing (explicit)
double pi = 3.99;
int truncated = (int) pi; // truncated = 3 (decimal part lost)
// char ↔ int
char ch = 'A';
int ascii = ch; // ascii = 65
char back = (char) 66; // back = 'B'
4. Operators
An operator is a symbol that tells the compiler to perform a specific mathematical, relational, or logical
operation.
Arithmetic Operators
Operator Name Example Result
+ Addition 10 + 3 13
- Subtraction 10 - 3 7
* Multiplication 10 * 3 30
/ Division 10 / 3 3 (integer division)
% Modulus (Remainder) 10 % 3 1
Logical Operators
Operator Name Usage Returns true when
&& Logical AND a && b Both a AND b are true
|| Logical OR a || b At least one of a OR b
is true
! Logical NOT !a a is false (inverts
result)
✅ Key Point: && and || use short-circuit evaluation. For &&, if the first operand is false, the second
is NOT evaluated. For ||, if first is true, second is NOT evaluated.
Assignment Operators
Operator Equivalent To Example After execution
= — x = 10 x = 10
+= x = x + val x += 5 x = 15
Operator Equivalent To Example After execution
-= x = x - val x -= 3 x = 12
*= x = x * val x *= 2 x = 24
/= x = x / val x /= 4 x=6
%= x = x % val x %= 4 x=2
Bitwise Operators
Operator Name Example (a=5=0101, Result
b=3=0011)
& Bitwise AND a&b 0001 = 1
| Bitwise OR a|b 0111 = 7
^ Bitwise XOR a^b 0110 = 6
~ Bitwise NOT ~a ...11111010 = -6
<< Left Shift a << 1 1010 = 10 (multiply by
2)
>> Right Shift a >> 1 0010 = 2 (divide by 2)
>>> Unsigned Right Shift a >>> 1 0010 = 2 (no sign
extension)
Ternary Operator
The only operator with three operands. It is a shorthand for if-else.
// Syntax: condition ? valueIfTrue : valueIfFalse
int a = 10, b = 20;
int max = (a > b) ? a : b; // max = 20
1. Simple if Statement
// Executes block only if condition is true
int marks = 75;
if (marks >= 40) {
[Link]("Pass");
}
2. if-else Statement
int age = 16;
if (age >= 18) {
[Link]("Can vote");
} else {
[Link]("Cannot vote");
}
3. if-else-if Ladder
Used to test multiple conditions in sequence. Once a condition is true, the rest are skipped.
int marks = 82;
if (marks >= 90) {
[Link]("Grade A");
} else if (marks >= 75) {
[Link]("Grade B");
} else if (marks >= 60) {
[Link]("Grade C");
} else if (marks >= 40) {
[Link]("Grade D");
} else {
[Link]("Fail");
}
4. Nested if
int age = 25;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
[Link]("Can drive");
} else {
[Link]("Need a license");
}
} else {
[Link]("Too young to drive");
}
5. switch Statement
Efficiently handles multiple fixed values of a single variable. Works with int, char, String, enum (not
float/double).
int day = 3;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Other day");
}
📌 Note: Without break, execution 'falls through' to the next case. This can be intentional (to handle
multiple cases with same logic) or a bug.
1. for Loop
Best when the number of iterations is known in advance.
// Syntax: for (initialization; condition; update)
for (int i = 1; i <= 5; i++) {
[Link]("Count: " + i);
}
2. while Loop
Best when the number of iterations is NOT known, and the condition is checked BEFORE each
iteration.
// Count down from 5
int n = 5;
while (n > 0) {
[Link](n);
n--;
}
3. do-while Loop
The body executes AT LEAST ONCE because condition is checked AFTER the first iteration.
int i = 1;
do {
[Link]("Iteration: " + i);
i++;
} while (i <= 5);
Nested Loops
A loop inside another loop. The inner loop completes fully for every single iteration of the outer loop.
// Multiplication table
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
[Link](i * j + "\t");
}
[Link]();
}
// Output:
// 1 2 3
// 2 4 6
// 3 6 9
Comparison of Loops
Loop Condition Check Min Executions Best Used When
for Before each iteration 0 Number of iterations is
known
while Before each iteration 0 Iteration count is
unknown; pre-check
needed
do-while After each iteration 1 (always) Body must run at least
once
for-each Before each element 0 Iterating arrays or
collections
7. Jumping Statements
1. break Statement
Immediately exits the nearest enclosing loop or switch block. Execution continues at the statement after
the loop.
// Stop searching when found
int[] arr = {3, 7, 2, 9, 5};
int target = 9;
for (int i = 0; i < [Link]; i++) {
if (arr[i] == target) {
[Link]("Found at index: " + i);
break; // exit loop immediately
}
}
2. continue Statement
Skips the rest of the current loop iteration and jumps to the next iteration. Does NOT exit the loop.
// Print only odd numbers
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; // skip even numbers
[Link](i);
}
// Output: 1 3 5 7 9
// Labeled continue
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) continue outer; // skip to next i
[Link](i + "," + j);
}
}
3. return Statement
Exits the current method and optionally returns a value to the caller.
// Return a value
int add(int a, int b) {
return a + b; // exits method and returns sum
}
Method Syntax
accessModifier returnType methodName(parameter1, parameter2, ...) {
// method body
return value; // only if returnType is not void
}
Types of Methods
Type Returns? Has Parameters? Example
No param, no return No (void) No void greet() { ... }
With param, no return No (void) Yes void printName(String
n) { ... }
No param, with return Yes No int getMax() { return
100; }
With param and return Yes Yes int add(int a, int b)
{ return a+b; }
Method Overloading
Same method name, different parameter lists (different type, number, or order). Resolved at compile
time (static polymorphism).
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
// Fibonacci
int fib(int n) {
if (n <= 1) return n;
return fib(n-1) + fib(n-2);
}
sum(1, 2); // 3
sum(1, 2, 3, 4, 5); // 15
int a = 10;
change(a);
[Link](a); // Still 10! Original unchanged
Static Variables
class Counter {
static int count = 0; // shared by all objects
String name;
Counter(String n) {
name = n;
count++;
}
}
Static Methods
class MathUtil {
static int square(int n) { // static method
return n * n;
}
}
Static Block
Executed once when the class is first loaded, before any constructor runs. Used for static initialization.
class Config {
static String dbUrl;
static {
dbUrl = "jdbc:mysql://localhost/mydb";
[Link]("Config loaded!");
}
}
4 Pillars of OOP
Pillar Definition Java Mechanism
Encapsulation Bundling data and methods; private fields + public
hiding internal state getters/setters
Inheritance A class acquires properties of extends keyword
another class
Polymorphism Same name, different behaviour Method overloading & overriding
depending on context
Abstraction Hiding complexity; showing only abstract class, interface
what is needed
// Behaviour (methods)
void accelerate() {
speed += 10;
[Link](brand + " now at " + speed + " kmph");
}
}
Constructors
Type Description Example
Default Provided by Java if no Car() { }
constructor defined. Sets all
Type Description Example
fields to defaults.
No-arg User-defined constructor with no Car() { brand="Unknown"; }
parameters.
Parameterised Accepts arguments to initialise Car(String b, int s) { ... }
fields.
Copy Creates a new object as a copy Car(Car c) { [Link]=[Link];
of another object. }
11. Encapsulation
What is Encapsulation?
Encapsulation means bundling the data (fields) and the methods that operate on that data together in a
single unit (class), and restricting direct access to the data from outside the class. This is achieved by
making fields private and providing public getter and setter methods.
Why Encapsulation?
• Data hiding — internal representation is hidden from misuse
• Control — can validate data before setting values
• Flexibility — can change internal implementation without affecting external code
• Read-only or write-only fields — by providing only getter or only setter
// Usage
BankAccount acc = new BankAccount("Ravi", 5000);
[Link](1000);
// [Link] = -9999; // ERROR — private field
[Link]([Link]()); // 6000.0
Access Modifiers
Modifier Same Class Same Package Subclass (diff Other Classes
pkg)
private ✅ Yes ❌ No ❌ No ❌ No
(default / ✅ Yes ✅ Yes ❌ No ❌ No
package)
protected ✅ Yes ✅ Yes ✅ Yes ❌ No
public ✅ Yes ✅ Yes ✅ Yes ✅ Yes
📌 Note: Use private for all fields (data). Use public for methods that form the class's interface. Use
protected when subclasses need access. Avoid default unless intentional.
12. Has-A Relationship
What is Has-A Relationship?
A Has-A relationship means one class contains a reference to another class as a member variable.
This is also called Composition or Aggregation. It models 'whole-part' relationships.
class House {
private Room livingRoom; // Composition — House owns Room
private Room bedroom;
House() {
livingRoom = new Room("Living Room"); // created inside House
bedroom = new Room("Bedroom");
}
// When House object dies, Room objects die too
}
class Department {
String deptName;
Professor prof; // Aggregation — Professor passed from outside
Types of Inheritance
Type Description Java Support
Single One child inherits from one ✅ Supported
parent
Multilevel A → B → C (chain of ✅ Supported
inheritance)
Hierarchical Multiple children share one ✅ Supported
parent
Multiple One child inherits from two ❌ NOT supported with classes
parents (only via interfaces)
Hybrid Combination of above types ✅ Partial (via interfaces)
Multilevel Inheritance
class Vehicle {
void start() { [Link]("Vehicle starting"); }
}
super Keyword
super refers to the immediate parent class. Used to: (1) call parent constructor, (2) call parent method,
(3) access parent field.
class Animal {
String name;
Animal(String name) { [Link] = name; }
void describe() { [Link]("Animal: " + name); }
}
void describe() {
[Link](); // calls Animal's describe()
[Link]("Colour: " + colour);
}
}
Method Overriding
When a subclass provides its own implementation of a method that is already defined in the parent
class. The method signature must be identical.
class Shape {
double area() { return 0; }
}
@Override
double area() { return w * h; }
}
Overriding Rules
• Method name and parameter list must be exactly the same
• Return type must be same or a covariant (subtype) return type
• Access modifier cannot be more restrictive than the parent method
• static, final, and private methods CANNOT be overridden
• Constructors are NOT inherited and cannot be overridden
final Keyword
Usage Effect
final variable Value cannot be changed after assignment
(constant)
final method Cannot be overridden in any subclass
final class Cannot be extended (inherited from)
14. Polymorphism
What is Polymorphism?
Polymorphism means 'many forms'. In Java, it allows one interface to be used for many types. The
same method name behaves differently based on the object it is called on.
Abstract Class
A class declared with abstract keyword. Cannot be instantiated (cannot create objects directly). Can
have both abstract methods (no body) and concrete methods (with body).
abstract class Shape {
String colour;
@Override
double area() { return [Link] * radius * radius; }
@Override
double perimeter() { return 2 * [Link] * radius; }
}
Interface
A completely abstract type (before Java 8) — all methods are implicitly abstract and public. A class
implements an interface and must provide implementations for all its methods. A class can implement
multiple interfaces.
interface Flyable {
// All fields are public static final (constants) by default
double MAX_ALTITUDE = 10000;
interface Swimmable {
void swim();
}
@Override
public void land() { [Link]("Duck landing"); }
@Override
public void swim() { [Link]("Duck is swimming"); }
}
Upcasting (Implicit)
Converting a child class reference to a parent class reference. Done automatically. Safe — no data
loss. The child object still exists, but only parent methods are visible via the reference.
class Animal {
void eat() { [Link]("Animal eating"); }
}
Downcasting (Explicit)
Converting a parent class reference back to a child class reference. MUST be done explicitly. Can
cause ClassCastException at runtime if the actual object is not of the target type.
Animal a = new Dog(); // Upcast — a points to a Dog object
Dog d = (Dog) a; // Downcast — we know it's a Dog, so it's safe
[Link](); // Works!
// DANGEROUS DOWNCAST
Animal a2 = new Animal(); // actual object is Animal
Dog d2 = (Dog) a2; // ClassCastException at RUNTIME!
instanceof Operator
Tests whether an object is an instance of a specific class or interface. Always use this before
downcasting to avoid ClassCastException.
Animal a = new Cat();
[Link](a instanceof Animal); // true
[Link](a instanceof Cat); // true
[Link](a instanceof Dog); // false
Overriding toString()
class Student {
String name;
int rollNo;
@Override
public String toString() {
return "Student[name=" + name + ", roll=" + rollNo + "]";
}
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Point)) return false;
Point other = (Point) obj;
return this.x == other.x && this.y == other.y;
}
@Override
public int hashCode() {
return 31 * x + y; // must be consistent with equals
}
}
Creating Strings
// Method 1: String Literal — uses String Pool
String s1 = "Hello";
String s2 = "Hello"; // s2 points to same object as s1 in pool
// Comparing
[Link](s1 == s2); // true (same pool reference)
[Link](s1 == s3); // false (different heap object)
[Link]([Link](s3)); // true (same content)
📌 Note: Always use .equals() to compare String content, never == (which compares references).
// String to int
int num = [Link]("42");
// int to String
String s = [Link](42);
String s2 = [Link](42);
String s3 = "" + 42; // implicit conversion
// Better:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
[Link](i); // Only one object mutated
}
String result2 = [Link]();
String Formatting
// [Link]() — like printf
String name = "Ravi";
int age = 21;
double gpa = 8.75;
String msg = [Link]("Name: %s, Age: %d, GPA: %.2f", name, age, gpa);
[Link](msg);
// Name: Ravi, Age: 21, GPA: 8.75
// Format specifiers:
// %s = String %d = integer
// %f = float/double %.2f = 2 decimal places
// %c = char %b = boolean
// %n = newline %10s = right-align in 10 chars
Quick Reference Summary