JAVA History Explination:
1991 – The Birth of "Oak"
• At Sun Microsystems, James Gosling and his team started a project called "Green
Project".
• They wanted a programming language for consumer electronic devices (like TVs, remote
controls).
• The language was originally named Oak (after an oak tree outside Gosling’s of ce).
👉 1995 – Java is Born
• "Oak" had to be renamed because of trademark issues.
• It became Java (inspired by Java coffee ☕ , a nod to programmers’ favorite fuel).
• Sun Microsystems launched Java with the slogan:
“Write Once, Run Anywhere” (WORA) — meaning code compiled in Java could run on
any machine with a Java Virtual Machine (JVM).
👉 Late 1990s – Rapid Adoption
• Java quickly became popular for web applets in browsers (though that’s obsolete now).
• Enterprise applications (banks, large systems) started adopting Java because of its
portability and robustness.
👉 2006 – Java Goes Open Source
• Sun Microsystems made Java’s core open source by releasing most of it under the GNU
General Public License (GPL).
👉 2010 – Oracle Acquires Sun Microsystems
• Oracle took over Java and continues to develop it.
• This led to faster releases, with a new version of Java every 6 months.
👉 Recent Evolution
• Java 8 (2014): Introduced lambdas, streams → huge shift.
• Java 11 (2018): Long-term support (LTS), modern APIs.
• Java 17 (2021): Another LTS, new language features.
• Java 21 (2023): Latest LTS — packed with performance improvements, new syntax, and
modern features.
fi
JVM vs JRE vs JDK
⚙ JVM (Java Virtual Machine)
• It is the engine that runs Java bytecode.
• Converts compiled .class les (bytecode) into machine code speci c to the operating
system.
• Handles memory management, garbage collection, security, and execution.
👉 Think of JVM as the translator that ensures your Java program runs the same on Windows,
Linux, or Mac.
📦 JRE (Java Runtime Environment)
• Contains JVM + libraries + supporting les.
• Needed to run Java applications, but cannot be used for development.
• If someone just wants to execute a Java program, installing JRE is enough.
👉 Analogy: If JVM is a car engine, then JRE is the car with engine + fuel + basic accessories to
run it.
🛠 JDK (Java Development Kit)
• Contains JRE + development tools (compiler javac, debugger, documentation tools).
• Needed by developers to write, compile, and run Java programs.
• Without JDK, you can’t code in Java.
👉 Analogy: JDK is the full garage toolkit 🚗 🔧 — it includes the car (JRE), the engine (JVM),
plus all the mechanic’s tools to build and repair.
📊 Relationship Diagram (simple visual ow)
JDK = JRE + Development Tools
JRE = JVM + Libraries
JVM = Executes Bytecode
fi
fi
fl
fi
✅ Quick Example:
1. You write [Link].
2. JDK’s javac compiler converts it → [Link] (bytecode).
3. JRE (with JVM) loads that bytecode.
4. JVM executes it → output appears.
Now, Let’s step into Core Java concepts rst.
Before that I wanna give one clarity. i.e I have adjusted the syllabus little bit , In syllabus Class and
objects are mentioned rst. But before understanding those I feel you should have better idea
about basics.
First Steps in Java:
1⃣ First “Hello World Program”
✍ Steps to Create:
1. Install JDK & set environment variables (JAVA_HOME, PATH).
2. Create a le → [Link].
3. Write this code:
// My First Java Program
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
🔍 Explanation:
fi
fi
fi
• public class HelloWorld → Every Java program must have at least one class.
• public static void main(String[] args) → Entry point of the
program.
• [Link]() → Prints text on console.
🛠 How to Run:
javac [Link] // compiles -> [Link]
java HelloWorld // runs program
✅ Hands-on: Ask students to modify the message & print their name.
2⃣ What are Variables?
• De nition: A variable is a container (memory location) that stores data during program
execution.
• Declaration: dataType variableName = value;
Example:
int age = 25;
double salary = 55000.75;
String name = "John";
Types:
• Local variables (declared inside methods)
• Instance variables (declared in class but outside methods, per object)
• Static variables (shared by all objects, declared with static)
👉 Analogy: Variables are like boxes in a cupboard—each labeled and holding speci c type of
item.
3⃣ Java Keywords
• Reserved words with prede ned meaning.
• Cannot be used as identi ers (like variable names).
fi
fi
fi
fi
👉 Examples:
class, public, static, void, if, else, switch, break, return,
int, double, package, import, try, catch, finally
📌 Java has ~67 keywords (depends on version).
✅ Hands-on: Show what happens if you try int class = 5; → compiler error.
Note: Remember you can’t use keywords as variable name.
4⃣ Understanding & Creating Packages
• Package = folder/directory structure for organizing classes.
• Types:
◦ Built-in packages ([Link], [Link])
◦ User-de ned packages (custom ones you create)
Example (user-de ned package):
1. Create a folder → mypackage.
2. Inside, create [Link]:
package mypackage;
public class MyClass {
public void showMessage() {
[Link]("Hello from MyClass in
mypackage!");
}
}
3. Compile with:
javac -d . [Link]
4. Use it in another class:
import [Link];
public class TestPackage {
fi
fi
public static void main(String[] args) {
MyClass obj = new MyClass();
[Link]();
}
}
✅ Tip: Packages help avoid naming con icts in large projects.
5⃣ What are Data Types?
• Primitive Data Types (8)
◦ byte, short, int, long (integers)
◦ float, double (decimals)
◦ char (single character)
◦ boolean (true/false)
• Non-Primitive Data Types
◦ String, Arrays, Classes, Interfaces
🧩 Primitive Data Types in Java (8 total)
1⃣ byte
• Size: 8 bits (1 byte)
• Range: -128 to 127
• Default value: 0
• Usage: Useful in memory-constrained systems (IoT, embedded), or when working with raw
binary data.
Example:
byte age = 25;
[Link]("Age: " + age);
👉 Best used when you know values will stay small and want to save memory.
fl
2⃣ short
• Size: 16 bits (2 bytes)
• Range: -32,768 to 32,767
• Default value: 0
• Usage: Rarely used in modern apps (int is more common), but useful for large arrays where
memory is a concern.
Example:
short year = 2025;
[Link]("Year: " + year);
3⃣ int
• Size: 32 bits (4 bytes)
• Range: -2,147,483,648 to 2,147,483,647 (~2 billion)
• Default value: 0
• Usage: Most commonly used integer type in Java.
Example:
int population = 1400000000; // 1.4 billion
[Link]("Population: " + population);
⚡ Note: Integer literals are by default int in Java.
4⃣ long
• Size: 64 bits (8 bytes)
• Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
• Default value: 0L
• Usage: For large numbers like distance between stars, big IDs, nancial apps.
Example:
fi
long distance = 15000000000L; // notice the L suffix
[Link]("Distance: " + distance);
⚡ Must add L or l at the end of literal to denote long.
5⃣ float
• Size: 32 bits (4 bytes)
• Range: ~±3.40282347E+38 (approx 7 decimal digits precision)
• Default value: 0.0f
• Usage: Useful for decimal values where precision is not critical (e.g., game graphics,
scienti c calculations).
Example:
float price = 99.99f; // 'f' suffix required
[Link]("Price: " + price);
⚡ Be careful: Floating-point operations can introduce rounding errors.
6⃣ double
• Size: 64 bits (8 bytes)
• Range: ~±1.79769313486231570E+308 (approx 15 decimal digits precision)
• Default value: 0.0d
• Usage: Default type for decimal values in Java. Used in nancial, scienti c, or
mathematical calculations.
Example:
double pi = 3.141592653589793;
[Link]("PI: " + pi);
⚡ Decimal literals are by default double in Java.
7⃣ char
• Size: 16 bits (2 bytes, because Java uses Unicode)
fi
fi
fi
• Range: 0 to 65,535 (represents Unicode characters)
• Default value: \u0000 (null character)
• Usage: Represents single characters like letters, digits, or symbols.
Example:
char grade = 'A';
char symbol = '#';
[Link]("Grade: " + grade + ", Symbol: " +
symbol);
⚡ Since Java is Unicode-based, you can store non-English letters:
char hindiChar = 'क';
[Link](hindiChar);
8⃣ boolean
• Size: Not precisely de ned (JVM-dependent, but often 1 byte used internally)
• Values: true or false
• Default value: false
• Usage: For conditions, ags, and decision-making.
Example:
boolean isJavaFun = true;
boolean isFishTasty = false;
[Link](isJavaFun); // true
⚡ Tip: Don’t confuse boolean with numeric types — true/false cannot be assigned to
0/1 in Java.
🌟 Non-Primitive Data Types (Reference
Types)
Apart from primitives, Java has objects and reference types.
• String: Represents a sequence of characters.
fi
fl
• Arrays: Collection of same type values.
• Classes/Objects: User-de ned types.
• Interfaces, Enums, Collections: Higher-level types.
Example:
String name = "Alice";
int[] numbers = {1, 2, 3, 4, 5};
✅ Summary Table of Primitive Data Types
Data Defaul
Size Range Example
Type t
byte 1 byte -128 to 127 0 byte b = 10;
short 2 bytes -32,768 to 32,767 0 short s = 1000;
int 4 bytes -2B to 2B 0 int i = 100000;
-9 quintillion to 9 long l =
long 8 bytes 0L
quintillion 10000000000L;
oat 4 bytes 7 decimal digits 0.0f float f = 5.5f;
double 8 bytes 15 decimal digits 0.0d double d = 99.99;
char 2 bytes 0–65,535 (Unicode) \u0000' char c = 'A';
JVM-
boolean true/false FALSE boolean flag = true;
dependent
Example:
int count = 100;
double price = 250.75;
char grade = 'A';
boolean isPassed = true;
👉 Interview Tip: By default, integer literals are int, decimals are double.
fl
fi
6⃣ Understanding and Using Casting
• Casting = converting one data type into another.
• Types:
1. Implicit/Widening (smaller → larger type, safe)
2. Explicit/Narrowing (larger → smaller type, possible data loss)
👉 Casting Flow: byte → short → int → long → float → double (widening).
✅ Hands-on: Convert student’s age (int) to double and back.
7⃣ Mastering Operators, Operands, and Expressions
Operators in Java
• Arithmetic: + - * / %
• Relational: == != < > <= >=
• Logical: && || !
• Assignment: = += -= *= /=
• Unary: ++ -- + -
• Bitwise: & | ^ ~ << >> >>>
• Ternary: condition ? value1 : value2
Example:
int a = 10, b = 20;
[Link](a + b); // 30
[Link](a > b); // false
[Link](a < b && b > 15); // true
Expressions
• Combination of variables, operators, and values → produces a result.
• Example:
int result = (a + b) * 2;
✅ Hands-on: Create a calculator program using operators.
🖊 The Scanner Class in Java
🔎 What is Scanner?
• A utility class in [Link] package.
• Used to take input from users via keyboard, les, or other streams.
• Makes console-based programs interactive.
📦 Importing Scanner
Since it lives in the [Link] package, you must import it:
import [Link];
🛠 Basic Example (Taking Input)
import [Link];
public class ScannerExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]); // Create
scanner object
[Link]("Enter your name: ");
String name = [Link](); // Read string input
[Link]("Enter your age: ");
int age = [Link](); // Read integer input
[Link]("Hello " + name + ", you are " +
age + " years old!");
[Link](); // Always close the scanner
}
}
📌 Common Scanner Methods
fi
Method Input Type Example
nextInt() Integer int num = [Link]();
nextDouble() Decimal (double) double price =
nextFloat() Decimal ( oat) [Link]();
float pi = [Link]();
nextLong() Long integer long big = [Link]();
Word (string without
next() spaces)
String word = [Link]();
nextLine() Full line of text String line = [Link]();
nextBoolean( boolean flag =
Boolean
) [Link]();
⚠ Gotcha (nextLine vs next)
• next() reads a single word (stops at space).
• nextLine() reads the entire line (including spaces).
👉 Example:
[Link]("Enter city: ");
String city = [Link](); // If input is "New York", it only
captures "New"
[Link]("Enter city properly: ");
String city2 = [Link](); // Captures "New York"
🎯 Hands-on Mini Programs
1. Calculator with Scanner
import [Link];
public class Calculator {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
int a = [Link]();
[Link]("Enter second number: ");
int b = [Link]();
fl
int sum = a + b;
[Link]("Sum = " + sum);
[Link]();
}
}
2. Voting Eligibility Check
Scanner sc = new Scanner([Link]);
[Link]("Enter your age: ");
int age = [Link]();
if (age >= 18) {
[Link]("You are eligible to vote!");
} else {
[Link]("You are not eligible to vote.");
}
[Link]();
🔑 Best Practices
• Always close the Scanner object using [Link]() (frees resources).
• Be mindful of mixing nextInt() and nextLine() (the newline \n can cause
issues).
⚠ The Issue: nextInt() leaves \n behind
• When you use nextInt(), nextDouble(), etc. → they only read the number, not
the newline character \n (which is when you press Enter).
• That \n stays in the input buffer.
• If you then immediately call nextLine(), it will read that leftover newline and skip your
actual input.
🔎 Example (Problem Case)
import [Link];
public class MixingScanner {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your age: ");
int age = [Link](); // Reads number but leaves \n
[Link]("Enter your name: ");
String name = [Link](); // OOPS! It just reads
leftover \n
[Link]("Name: " + name + ", Age: " +
age);
[Link]();
}
}
🖥 Input & Output
Enter your age: 25
Enter your name:
Name: , Age: 25
👉 See? It skipped name input because nextLine() grabbed the leftover \n instead of
waiting.
✅ Solution
After using nextInt(), nextDouble(), etc., consume the leftover newline with an extra
nextLine().
import [Link];
public class MixingScannerFix {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your age: ");
int age = [Link]();
[Link](); // 👈 consume the leftover \n
[Link]("Enter your name: ");
String name = [Link](); // Now it works fine
[Link]("Name: " + name + ", Age: " +
age);
[Link]();
}
}
🖥 Input & Output
Enter your age: 25
Enter your name: John Doe
Name: John Doe, Age: 25
👉 Now it works perfectly. 🎉
🔑 Rule of Thumb
Whenever you mix nextInt() (or any non-String input) with nextLine(),
➡ Always call an extra nextLine() to clear out the leftover newline before taking the actual
string input.
Java Coding Standards:
1. Naming Conventions
• Classes & Interfaces → PascalCase (start with uppercase, nouns for classes)
class StudentDetails {}
• interface Serializable {}
•
• Methods → camelCase (verbs, describe action)
public void calculateSalary() {}
• Variables → camelCase (nouns, meaningful names)
int employeeAge;
• String customerName;
•
• Constants → ALL_CAPS with underscores
static final int MAX_USERS = 100;
2. Code Layout & Formatting
• Indentation: 4 spaces (avoid tabs).
• Braces: Always use { } even for single statements (avoids errors).
if (isValid) {
• process();
• }
•
• One statement per line.
• Keep line length ≤ 100–120 characters.
3. Comments & Documentation
• Single-line comments for quick notes.
// Calculate monthly interest
• Multi-line comments for explanations.
/*
• * This method calculates compound interest
• * using principal, rate, and time period.
• */
•
• Javadoc for public classes & methods.
/**
• * Calculates the area of a rectangle.
• * @param length the length
• * @param width the width
• * @return area of rectangle
• */
• public int calculateArea(int length, int width) { ... }
•
4. Best Practices
• Use meaningful names (avoid temp, data1, abc).
// ❌ Bad
• int x, y;
• // ✅ Good
• int studentCount, maxMarks;
•
• Avoid hardcoding values → use constants.
double pi = 3.14; // ❌
• static final double PI = 3.14159; // ✅
•
• Keep methods small and focused (ideally ≤ 40 lines).
• One class per le, lename should match class name.
• Handle exceptions properly, never just catch (Exception e) {}.
5. Package Naming
• Always lowercase, use reverse domain naming.
package [Link];
6. Code Readability
• Blank lines to separate logical blocks.
• Group related elds/methods together.
fi
fi
fi
• Consistent use of spaces:
// ❌ Hard to read
• if(a==b){sum=a+b;}
•
• // ✅ Clean
• if (a == b) {
• sum = a + b;
• }
•
7. Class Design Guidelines
• Use encapsulation → private elds + public getters/setters.
• Favor composition over inheritance (when possible).
• Use interfaces for contracts, abstract classes for shared code.
• Follow SOLID principles (good to brie y mention).
✅ Example: Clean vs Messy Code
❌ Bad Code
class Emp{
int a;
String nm;
void show(){
[Link](a+" "+nm);
}
}
✅ Good Code
/**
* Represents an Employee with id and name.
*/
fi
fl
class Employee {
private int id;
private String name;
public Employee(int id, String name) {
[Link] = id;
[Link] = name;
}
public void display() {
[Link]("Employee Id: " + id + ", Name: "
+ name);
}
}
👉 Teaching Tip: Show students both “bad” and “good” code side by side. It really sticks in their
mind.