1
Complete Java Basic Introduction Notes 🚀
A comprehensive guide covering fundamental Java concepts with detailed explanations, code
examples, and visual diagrams
📚 TABLE OF CONTENTS
1. Programming Language Concepts
2. Introduction to Java
3. Modules of Java
4. History of Java
5. Internal Architecture of JVM
6. Naming Conventions
7. Identifiers
8. Reserved Words
9. Data Types
10. Types of Variables
11. Variable Arguments (Var-arg) Method
1. Programming Language Concepts
🤔 What is a Programming Language?
A programming language is a formal language that specifies a set of instructions used to produce
various kinds of output. It serves as a medium of communication between humans and computers,
allowing programmers to:
• Control machine behavior: Direct the computer to perform specific tasks
• Express algorithms: Describe step-by-step solutions to problems
• Create software applications: Build programs that solve real-world problems
• Process and manipulate data: Work with information in meaningful ways
Analogy: Think of a programming language like a recipe book for computers. Just as a recipe tells
you how to make a dish step by step, a programming language tells the computer what to do step by
step.
📊 Classification of Programming Languages
Programming languages can be classified in multiple ways based on their characteristics and capabilit‐
ies.
2
1️⃣ Classification by Level of Abstraction
Level Description Characteristics Examples Use Cases
Low-Level Lan‐ Close to ma‐ - Directly inter‐ Machine - Device drivers
guages chine hardware act with hard‐ Language, As‐ - Embedded sys‐
ware sembly Lan‐ tems
- Fast execution guage - Operating sys‐
- Difficult to tem kernels
learn
- Platform-de‐
pendent
Middle-Level Combination of - Both hardware C, C++ - System soft‐
Languages low and high- access and ab‐ ware
level features straction - Game engines
- Balance of con‐ - Compilers
trol and ease
- Portable with
some effort
High-Level Close to human - Easy to learn Java, Python, - Web applica‐
Languages language and use JavaScript, C#, tions
- Platform-inde‐ Ruby - Mobile apps
pendent - Enterprise soft‐
- Slower than ware
low-level - Data science
- Abstract hard‐
ware details
2️⃣ Classification by Programming Paradigm
Programming paradigms represent different approaches to programming and problem-solving:
a) Procedural Programming
• Definition: Programs are structured as a sequence of procedures or functions
• Focus: Step-by-step instructions (procedures) that operate on data
• Characteristics:
• Linear execution flow
• Functions as primary building blocks
• Data and functions are separate
• Top-down approach
Example Languages: C, Pascal, FORTRAN, BASIC
Code Example (Conceptual):
3
// Procedural approach
void calculateArea(int length, int width) {
int area = length * width;
printf("Area: %d", area);
}
int main() {
calculateArea(5, 10);
return 0;
}
b) Object-Oriented Programming (OOP)
• Definition: Programs are organized around objects that combine data and behavior
• Focus: Objects (instances of classes) that encapsulate data and methods
• Core Principles:
• Encapsulation: Bundling data with methods that operate on that data
• Inheritance: Creating new classes from existing ones
• Polymorphism: Objects of different types responding to the same method call
• Abstraction: Hiding complex implementation details
Example Languages: Java, C++, Python, C#, Ruby, Swift
Code Example (Java):
// Object-Oriented approach
class Rectangle {
private int length;
private int width;
public Rectangle(int length, int width) {
[Link] = length;
[Link] = width;
}
public int calculateArea() {
return length * width;
}
}
public class Main {
public static void main(String[] args) {
Rectangle rect = new Rectangle(5, 10);
[Link]("Area: " + [Link]());
}
}
Output:
Area: 50
4
c) Functional Programming
• Definition: Programs are built by composing pure functions
• Focus: Functions as first-class citizens, immutability, no side effects
• Characteristics:
• Functions are treated as data
• Avoid changing state and mutable data
• Declarative rather than imperative
• Emphasis on recursion over loops
Example Languages: Haskell, Lisp, Erlang, Scala, (JavaScript and Python support functional features)
d) Scripting Languages
• Definition: Interpreted languages designed for automating tasks
• Focus: Rapid development and task automation
• Characteristics:
• Interpreted (not compiled)
• Dynamic typing
• Easy to learn
• Excellent for automation
Example Languages: JavaScript, Python, PHP, Ruby, Perl, Shell scripting
5
3️⃣ Classification by Execution Method
Type Description Advantages Disadvantages Examples
Compiled Lan‐ Source code is - Faster execu‐ - Longer devel‐ C, C++, Rust,
guages translated to tion opment cycle Go
machine code - Better perform‐ - Platform-spe‐
before execution ance cific binaries
- Early error de‐
tection
Interpreted Source code is - Faster develop‐ - Slower execu‐ Python, JavaS‐
Languages executed line by ment tion cript, Ruby, PHP
line at runtime - Platform-inde‐ - Runtime errors
pendent
- Easier debug‐
ging
Hybrid (Com‐ Source code is - Platform inde‐ - Requires Java, C#, Kotlin
piled + Inter‐ compiled to in‐ pendence runtime environ‐
preted) termediate - Better perform‐ ment
code, then inter‐ ance than pure
preted interpretation
- Security
through byte‐
code
🎯 How Java Fits In
Java is:
- High-level language: Easy to read and write with English-like syntax
- Object-oriented: Built around the concept of objects and classes
- Hybrid execution: Compiled to bytecode, then interpreted/JIT-compiled by JVM
- Multi-paradigm: Supports OOP, functional programming (Java 8+), and procedural concepts
💡 Why Understanding Programming Language Concepts Matters
1. Choosing the right tool: Different problems require different approaches
2. Learning new languages faster: Understanding concepts makes learning syntax easier
3. Writing better code: Knowing paradigms helps you write more efficient and maintainable code
4. Problem-solving: Different paradigms offer different ways to think about problems
5. Career flexibility: Understanding multiple paradigms makes you a more versatile developer
6
🔑 Key Takeaways
✅ Programming languages are formal ways to communicate with computers
✅ Languages can be classified by level (low/high), paradigm (OOP, functional, etc.), and execution
method
✅ Each classification has its strengths and ideal use cases
✅ Java is a high-level, object-oriented, hybrid-execution language
✅ Understanding these concepts helps you become a better programmer
2. Introduction to Java
🤔 What is Java?
Java is a high-level, class-based, object-oriented programming language designed to be platform-in‐
dependent, allowing developers to “Write Once, Run Anywhere” (WORA). Created by James Gos‐
ling at Sun Microsystems in 1995, Java has become one of the most popular programming languages
in the world.
Simple Definition: Java is a programming language that lets you create software that can run on any
device with a Java Virtual Machine (JVM), regardless of the underlying hardware or operating system.
🎯 Core Philosophy of Java
Write Once, Run Anywhere (WORA)
The WORA principle means:
1. You write Java code once
2. You compile it to bytecode ( .class files)
3. This bytecode runs on any platform with a JVM installed
4. No need to recompile for different operating systems
Example Scenario:
Developer writes code on Windows → Compiles to bytecode
↓
Bytecode runs on:
• Windows computers
• Mac computers
• Linux servers
• Android devices
• Embedded systems
All without any code changes!
⭐ Key Features of Java
1. Simple 🎓
• Easy to learn: Syntax is clean and similar to C/C++ but simpler
• No complex features: Removed confusing features like:
7
• Explicit pointers
• Operator overloading (mostly)
• Multiple inheritance of classes
• Automatic memory management: Garbage collector handles memory cleanup
• Rich API: Built-in libraries for common tasks
Example - Simple Hello World:
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Output:
Hello, World!
2. Object-Oriented 🏗️
Everything in Java (except primitives) is an object. This promotes:
- Code reusability: Through inheritance
- Modularity: Through encapsulation
- Flexibility: Through polymorphism
- Maintainability: Through abstraction
Example - OOP in Action:
8
// Define a class (blueprint)
class Dog {
// Properties (data)
String name;
int age;
// Methods (behavior)
void bark() {
[Link](name + " says: Woof! Woof!");
}
void displayInfo() {
[Link]("Name: " + name + ", Age: " + age + " years");
}
}
public class Main {
public static void main(String[] args) {
// Create objects (instances)
Dog dog1 = new Dog();
[Link] = "Max";
[Link] = 3;
Dog dog2 = new Dog();
[Link] = "Buddy";
[Link] = 5;
// Use objects
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output:
Max says: Woof! Woof!
Name: Max, Age: 3 years
Buddy says: Woof! Woof!
Name: Buddy, Age: 5 years
3. Platform Independent 🌍
How it works:
9
Source Code (.java)
↓
[javac compiler]
↓
Bytecode (.class) ← Platform Independent
↓
[JVM] ← Platform Specific
↓
Machine Code
↓
Execution
Key Point: The bytecode is platform-independent, but each OS has its own JVM that translates
bytecode to native machine code.
Real-World Example:
// This code works on ALL platforms
import [Link];
public class PlatformTest {
public static void main(String[] args) {
String os = [Link]("[Link]");
String home = [Link]("[Link]");
[Link]("Operating System: " + os);
[Link]("User Home: " + home);
}
}
Output on Windows:
Operating System: Windows 10
User Home: C:\Users\YourName
Output on Mac:
Operating System: Mac OS X
User Home: /Users/YourName
Output on Linux:
Operating System: Linux
User Home: /home/yourname
4. Secure 🔒
Java provides multiple layers of security:
1. No Explicit Pointers: Can’t directly access memory addresses
2. Bytecode Verification: JVM verifies bytecode before execution
3. Security Manager: Controls access to system resources
10
4. Exception Handling: Robust error handling mechanism
5. Strong Type Checking: Compile-time and runtime type checking
Example - Type Safety:
public class SecurityExample {
public static void main(String[] args) {
int age = 25;
// String name = age; // ❌ Compile Error: Type mismatch
String name = "John"; // ✅ Correct
int[] numbers = {1, 2, 3};
// [Link](numbers[10]); // ❌ Runtime Error: ArrayIndexOutOfBound‐
sException
}
}
5. Robust 💪
Java emphasizes reliability through:
- Strong memory management: Automatic garbage collection
- Exception handling: try-catch-finally blocks
- Type checking: At compile-time and runtime
- Elimination of error-prone features: No pointers, no memory leaks (mostly)
Example - Exception Handling:
public class RobustExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw an exception
} catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero!");
[Link]("Program continues running...");
}
[Link]("Program completed successfully.");
}
}
Output:
Error: Cannot divide by zero!
Program continues running...
Program completed successfully.
6. Multithreaded 🧵
Java has built-in support for concurrent programming:
- Create multiple threads to perform tasks simultaneously
- Built-in synchronization mechanisms
- Thread-safe collections
11
Example - Simple Multithreading:
class Task extends Thread {
String taskName;
Task(String name) {
[Link] = name;
}
public void run() {
for (int i = 1; i <= 3; i++) {
[Link](taskName + " - Step " + i);
try {
[Link](500); // Pause for 500ms
} catch (InterruptedException e) {
[Link]();
}
}
}
}
public class MultithreadingExample {
public static void main(String[] args) {
Task task1 = new Task("Task A");
Task task2 = new Task("Task B");
[Link](); // Start first thread
[Link](); // Start second thread
}
}
Output (order may vary):
Task A - Step 1
Task B - Step 1
Task A - Step 2
Task B - Step 2
Task A - Step 3
Task B - Step 3
7. Distributed 🌐
Java supports distributed computing through:
- RMI (Remote Method Invocation): Call methods on remote objects
- Sockets: Network communication
- URL and URLConnection: Work with web resources
- Web services: REST APIs, SOAP
Example - URL Connection:
12
import [Link].*;
import [Link].*;
public class DistributedExample {
public static void main(String[] args) {
try {
URL url = new URL("[Link]
HttpURLConnection connection = (HttpURLConnection) [Link]();
int responseCode = [Link]();
[Link]("Response Code: " + responseCode);
[Link]("Content Type: " + [Link]());
[Link]();
} catch (Exception e) {
[Link]();
}
}
}
Output:
Response Code: 200
Content Type: text/html; charset=ISO-8859-1
8. Dynamic 🔄
Java adapts to evolving environments:
- Dynamic loading of classes: Load classes at runtime
- Reflection: Inspect and modify code at runtime
- Dynamic linking: Link new libraries and methods during execution
Example - Dynamic Class Loading:
public class DynamicExample {
public static void main(String[] args) {
try {
// Load class dynamically at runtime
Class<?> cls = [Link]("[Link]");
[Link]("Class loaded: " + [Link]());
[Link]("Package: " + [Link]().getName());
// Create instance dynamically
Object obj = [Link]().newInstance();
[Link]("Instance created: " + [Link]().getSimpleName());
} catch (Exception e) {
[Link]();
}
}
}
Output:
13
Class loaded: [Link]
Package: [Link]
Instance created: ArrayList
9. High Performance ⚡
While Java is interpreted, it achieves high performance through:
- JIT (Just-In-Time) Compiler: Compiles bytecode to native machine code at runtime
- Optimizations: JVM performs runtime optimizations
- Efficient garbage collection: Modern GC algorithms
🎯 Why Learn Java?
Reason Description Real-World Impact
🌟 Industry Demand High demand in job market - Thousands of job openings
- Competitive salaries
- Career stability
📱 Android Development Primary language for Android - 2.5+ billion Android devices
apps - Mobile app market
🏢 Enterprise Applications Dominant in enterprise soft‐ - Banking systems
ware - E-commerce platforms
- Large-scale applications
☁️ Cloud Computing Popular for cloud-based ap‐ - Microservices
plications - Cloud platforms (AWS,
Azure, GCP)
👥 Strong Community Vast community support - Stack Overflow
- GitHub projects
- Forums and tutorials
📚 Rich Ecosystem Extensive libraries and frame‐ - Spring, Hibernate
works - Apache projects
- Third-party libraries
🎓 Learning OOP Excellent for learning OOP - Solid foundation
concepts - Transferable skills
- Design patterns
🔄 Continuous Evolution Regular updates and im‐ - New features (Java 8, 11,
provements 17, 21)
- Modern language features
14
🚀 What Can You Build with Java?
1. Desktop Applications 🖥️
• Tools: JavaFX, Swing, AWT
• Examples:
• IDE (IntelliJ IDEA, Eclipse, NetBeans)
• Media players
• Office applications
2. Web Applications 🌐
• Tools: Spring Boot, JSP, Servlets, Spring MVC
• Examples:
• E-commerce websites
• Banking portals
• Social networks
• Content management systems
3. Mobile Applications 📱
• Platform: Android
• Tools: Android SDK, Android Studio
• Examples:
• Social media apps
• Games
• Productivity apps
• Navigation apps
4. Enterprise Applications 🏢
• Tools: Java EE (Jakarta EE), Spring Framework, Microservices
• Examples:
• Banking systems
• Insurance platforms
• Healthcare systems
• Supply chain management
5. Big Data Technologies 📊
• Tools: Hadoop, Apache Spark, Apache Kafka
• Examples:
• Data processing pipelines
• Real-time analytics
• Stream processing
6. Cloud Applications ☁️
• Platforms: AWS, Azure, Google Cloud
• Examples:
• Serverless functions
• Microservices
• Cloud-native applications
15
7. IoT (Internet of Things) 🔌
• Tools: Java ME, Pi4J
• Examples:
• Smart home devices
• Industrial sensors
• Wearable devices
8. Game Development 🎮
• Tools: LibGDX, jMonkeyEngine
• Examples:
• 2D/3D games
• Minecraft (written in Java!)
📈 Java Popularity and Statistics
• TIOBE Index: Consistently in top 3 programming languages
• GitHub: Millions of Java repositories
• Job Market: One of the most in-demand programming skills
• Companies Using Java:
• Google
• Amazon
• Netflix
• LinkedIn
• Uber
• Airbnb
• Twitter
• eBay
16
💡 Java vs Other Languages - Quick Comparison
Feature Java Python C++ JavaScript
Type System Static Dynamic Static Dynamic
Platform Cross-platform Cross-platform Platform-de‐ Browser/[Link]
(JVM) pendent
Speed Fast Slower Fastest Fast (V8 engine)
Learning Moderate Easy Difficult Easy to Moder‐
Curve ate
Use Cases Enterprise, An‐ Data Science, AI, System soft‐ Web develop‐
droid, Web Scripting ware, Games ment
Memory Man‐ Automatic (GC) Automatic (GC) Manual Automatic (GC)
agement
OOP Support Strong Strong Strong Prototype-based
🔑 Key Takeaways
✅ Java is a high-level, object-oriented, platform-independent programming language
✅ “Write Once, Run Anywhere” is Java’s core philosophy
✅ Java is secure, robust, and supports multithreading natively
✅ Used in web, mobile, enterprise, cloud, and big data applications
✅ Strong industry demand and excellent career opportunities
✅ Great for learning object-oriented programming concepts
✅ Backed by a massive community and rich ecosystem
3. Modules of Java
🤔 What are Java Modules?
Java is divided into several editions or platforms, each designed for specific types of applications
and environments. These modules provide specialized APIs, libraries, and tools tailored for different
development needs.
Think of it like this: Java editions are like different toolkits for different jobs:
- Java SE = Basic toolkit for general applications
- Java EE = Professional toolkit for enterprise/web applications
- Java ME = Compact toolkit for small devices
17
📦 Overview of Java Editions
Java Technology
|
__________________|__________________
| | |
Java SE Java EE Java ME
(Standard) (Enterprise) (Micro)
| | |
Foundation Built on SE Subset of SE
for all Large-scale apps Mobile/Embedded
1️⃣ Java SE (Standard Edition)
📘 What is Java SE?
Java Standard Edition is the core Java platform that provides the fundamental libraries and APIs
needed for general-purpose programming. It is the foundation upon which other Java platforms are
built.
🎯 Key Characteristics
• Purpose: Develop desktop applications, console programs, and applets
• Target: General-purpose programming
• Includes: Core Java libraries, JVM, development tools
• Foundation: Base for Java EE and Java ME
18
🛠️ Components of Java SE
A. Core Libraries (Java APIs)
Package Purpose Common Classes/Inter‐
faces
[Link] Fundamental classes (auto‐ String, Math, System, Object,
matically imported) Thread, Integer, Boolean
[Link] Utility classes ArrayList, HashMap, Date,
Scanner, Collections
[Link] Input/Output operations File, FileReader, FileWriter,
BufferedReader, InputStream,
OutputStream
[Link] New I/O (Non-blocking) Files, Paths, ByteBuffer, Chan‐
nels
[Link] Networking URL, URLConnection, Socket,
ServerSocket
[Link] Mathematical operations BigInteger, BigDecimal
[Link] Date and Time API (Java 8+) LocalDate, LocalTime, LocalD‐
ateTime, ZonedDateTime
[Link] Database connectivity Connection, Statement, Res‐
ultSet, DriverManager
[Link] Security framework MessageDigest, Signature,
KeyStore
[Link] Abstract Window Toolkit (GUI Frame, Button, Label, Panel
- older)
[Link] Swing GUI components (im‐ JFrame, JButton, JLabel,
proved AWT) JPanel, JTable
19
📝 Java SE Code Examples
Example 1: Using Core Libraries
import [Link].*;
import [Link].*;
public class JavaSEDemo {
public static void main(String[] args) {
// [Link] (automatically imported)
String message = "Hello, Java SE!";
[Link](message);
[Link]("String length: " + [Link]());
// [Link] - Collections
ArrayList<String> languages = new ArrayList<>();
[Link]("Java");
[Link]("Python");
[Link]("JavaScript");
[Link]("\nLanguages: " + languages);
// [Link]
double number = [Link](16);
[Link]("\nSquare root of 16: " + number);
// [Link] (Java 8+)
LocalDateTime now = [Link]();
[Link]("Current date and time: " + now);
}
}
Output:
Hello, Java SE!
String length: 15
Languages: [Java, Python, JavaScript]
Square root of 16: 4.0
Current date and time: 2026-02-03T10:30:45.123
20
Example 2: File I/O with Java SE
import [Link].*;
public class FileIOExample {
public static void main(String[] args) {
// Writing to a file
try (FileWriter writer = new FileWriter("[Link]")) {
[Link]("Name: John Doe\n");
[Link]("Age: 20\n");
[Link]("Course: Computer Science\n");
[Link]("Data written to file successfully!");
} catch (IOException e) {
[Link]("Error writing to file: " + [Link]());
}
// Reading from a file
try (BufferedReader reader = new BufferedReader(new FileReader("[Link]"))
) {
[Link]("\nReading from file:");
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]("Error reading file: " + [Link]());
}
}
}
Output:
Data written to file successfully!
Reading from file:
Name: John Doe
Age: 20
Course: Computer Science
🎯 What Can You Build with Java SE?
1. Desktop Applications: Calculators, text editors, media players
2. Command-line Tools: File processors, system utilities
3. Game Development: 2D games, puzzle games
4. Data Processing: File parsers, data analyzers
5. Scientific Applications: Mathematical simulations, calculators
2️⃣ Java EE (Enterprise Edition) / Jakarta EE
📘 What is Java EE?
Java Enterprise Edition (now known as Jakarta EE) is a set of specifications and APIs built on top
of Java SE for developing large-scale, distributed, multi-tier enterprise applications.
21
🎯 Key Characteristics
• Purpose: Build enterprise-level web applications and services
• Target: Large organizations, web servers, distributed systems
• Built on: Java SE (extends its capabilities)
• Renamed: Oracle donated Java EE to the Eclipse Foundation in 2017, renamed to Jakarta EE
🛠️ Key Technologies in Java EE
Technology Full Name Purpose
Servlets Java Servlets Handle HTTP requests and re‐
sponses
JSP JavaServer Pages Create dynamic web pages
with Java
EJB Enterprise JavaBeans Business logic components
JPA Java Persistence API Database ORM (Object-Rela‐
tional Mapping)
JMS Java Message Service Asynchronous messaging
between applications
JNDI Java Naming and Directory In‐ Naming and directory ser‐
terface vices
JAX-RS Java API for RESTful Web Ser‐ Build REST APIs
vices
JAX-WS Java API for XML Web Ser‐ Build SOAP web services
vices
CDI Contexts and Dependency In‐ Dependency injection frame‐
jection work
JSF JavaServer Faces Component-based UI frame‐
work
22
📝 Java EE Code Example
Example: Simple Servlet
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
String name = [Link]("name");
if (name == null || [Link]()) {
name = "Guest";
}
[Link]("<html>");
[Link]("<head><title>Hello Servlet</title></head>");
[Link]("<body>");
[Link]("<h1>Welcome, " + name + "!</h1>");
[Link]("<p>This is a Java EE Servlet example.</p>");
[Link]("</body>");
[Link]("</html>");
}
}
When accessed at [Link] :
<html>
<head><title>Hello Servlet</title></head>
<body>
<h1>Welcome, John!</h1>
<p>This is a Java EE Servlet example.</p>
</body>
</html>
🎯 What Can You Build with Java EE?
1. Web Applications: E-commerce sites, social networks, banking portals
2. REST APIs: Microservices, mobile backends
3. Enterprise Systems: ERP, CRM, supply chain management
4. Distributed Applications: Multi-tier systems, cloud applications
5. Messaging Systems: Real-time notifications, event-driven architectures
23
🆚 Java SE vs Java EE
Aspect Java SE Java EE
Full Name Java Standard Edition Java Enterprise Edition /
Jakarta EE
Purpose General-purpose program‐ Enterprise web applications
ming
Target Applications Desktop apps, console pro‐ Web apps, distributed sys‐
grams tems
Components Core libraries, JVM, basic APIs Servlets, JSP, EJB, JPA, JAX-RS
Complexity Simpler More complex
Server Required No Yes (Tomcat, JBoss, GlassFish,
WildFly)
Learning Curve Moderate Steeper
Use Cases Small to medium applications Large-scale enterprise applic‐
ations
3️⃣ Java ME (Micro Edition)
📘 What is Java ME?
Java Micro Edition is a subset of Java SE designed for resource-constrained devices like mobile
phones, embedded systems, IoT devices, and consumer electronics.
🎯 Key Characteristics
• Purpose: Run Java on devices with limited resources
• Target: Mobile devices, embedded systems, IoT, set-top boxes
• Size: Smaller footprint than Java SE
• Optimized: For memory and processing constraints
🛠️ Components of Java ME
1. Configuration: Defines minimum JVM and library support
- CLDC (Connected Limited Device Configuration): Very constrained devices
- CDC (Connected Device Configuration): More capable devices
2. Profile: Additional APIs for specific device types
- MIDP (Mobile Information Device Profile): Mobile phones
- IMP (Information Module Profile): Embedded devices
24
3. Optional Packages: Additional APIs (multimedia, bluetooth, etc.)
🎯 What Can You Build with Java ME?
1. Mobile Applications: Feature phone apps (before smartphones)
2. IoT Devices: Smart sensors, wearables
3. Embedded Systems: Industrial controllers, automotive systems
4. Set-Top Boxes: TV boxes, entertainment systems
5. Smart Cards: Payment cards, access cards
📉 Current Status of Java ME
• Declining Use: With rise of Android (uses Java SE subset) and iOS
• Still Relevant: IoT, industrial embedded systems, legacy systems
• Alternatives: Android SDK, Raspberry Pi with Java SE
4️⃣ JavaFX
📘 What is JavaFX?
JavaFX is a modern GUI (Graphical User Interface) framework for building rich desktop and inter‐
net applications. It is the successor to Swing for Java GUI development.
🎯 Key Characteristics
• Purpose: Create modern, visually appealing desktop applications
• Replacement: Intended to replace Swing/AWT
• Features: Rich UI controls, CSS styling, multimedia support, 3D graphics
• Cross-platform: Write once, run on Windows, Mac, Linux
25
🛠️ Key Features of JavaFX
Feature Description
FXML XML-based markup language for designing UI
CSS Styling Style UI components with CSS (like web devel‐
opment)
Scene Graph Hierarchical tree of visual elements
Rich UI Controls Buttons, tables, charts, trees, etc.
Multimedia Audio and video playback
2D/3D Graphics Canvas, shapes, transformations, 3D objects
Animation Built-in animation framework
Web View Embed web content (HTML, CSS, JavaScript)
26
📝 JavaFX Code Example
import [Link];
import [Link];
import [Link].*;
import [Link].*;
import [Link];
import [Link];
public class HelloJavaFX extends Application {
@Override
public void start(Stage primaryStage) {
// Create UI components
Label nameLabel = new Label("Enter your name:");
TextField nameField = new TextField();
Button greetButton = new Button("Greet Me");
Label resultLabel = new Label();
// Button action
[Link](e -> {
String name = [Link]();
if ([Link]()) {
[Link]("Please enter your name!");
} else {
[Link]("Hello, " + name + "! Welcome to JavaFX!");
}
});
// Layout
VBox layout = new VBox(10);
[Link](new Insets(20));
[Link]().addAll(nameLabel, nameField, greetButton, resultLabel);
// Scene and Stage
Scene scene = new Scene(layout, 400, 200);
[Link]("JavaFX Hello App");
[Link](scene);
[Link]();
}
public static void main(String[] args) {
launch(args);
}
}
Output: A window with a text field, button, and labels for greeting the user.
🎯 What Can You Build with JavaFX?
1. Desktop Applications: Modern UI apps with rich visuals
2. Data Visualization: Charts, graphs, dashboards
3. Media Players: Audio/video players
4. Business Applications: POS systems, admin panels
5. Educational Tools: Learning applications, simulations
27
🗺️ Java Editions Comparison Table
Feature Java SE Java EE / Java ME JavaFX
Jakarta EE
Purpose General-purpose Enterprise web Resource-con‐ Rich GUI applic‐
apps strained devices ations
Size Medium Large Small Medium
Target Desktop, con‐ Web servers, Mobile, IoT, em‐ Desktop applica‐
sole cloud bedded tions
Complexity Moderate High Low to Moderate Moderate
Server Re‐ No Yes No No
quired
Example Apps Utilities, tools E-commerce, Sensors, feature Media players,
banking phones dashboards
Learning Moderate Steep Easy to Moder‐ Moderate
Curve ate
Current Status Active, evolving Active (Jakarta Declining (leg‐ Active but less
EE) acy) popular
🌟 Which Java Edition Should You Learn?
🎯 For Beginners:
Start with Java SE
- It’s the foundation for all other editions
- Core concepts apply to all Java programming
- Easier to learn and practice
🎯 For Web Development:
Java SE → Java EE (Jakarta EE) → Spring Framework
- Master Java SE first
- Learn Servlets, JSP
- Move to modern frameworks like Spring Boot
🎯 For Mobile Development:
Java SE → Android Development
- Java SE basics
- Android SDK
- Kotlin (modern alternative)
28
🎯 For Desktop Applications:
Java SE → JavaFX or Swing
- Java SE fundamentals
- GUI framework (JavaFX recommended for modern apps)
🎯 For IoT/Embedded:
Java SE → Java ME or Raspberry Pi with Java SE
- Java SE basics
- Embedded development concepts
- IoT platforms
🔑 Key Takeaways
✅ Java SE is the core platform - foundation for all Java development
✅ Java EE (Jakarta EE) is for enterprise web applications and services
✅ Java ME is for small devices with limited resources (less common now)
✅ JavaFX is for building modern desktop applications with rich UIs
✅ Start with Java SE - it’s essential regardless of your specialization
✅ All editions work together - Java EE builds on SE, ME is a subset of SE
✅ Choose your path based on career goals: web (EE), mobile (Android), desktop (FX)
4. History of Java
🌱 The Birth of Java (1991-1995)
🎬 Project Green (1991)
The story of Java begins in June 1991 at Sun Microsystems, a company known for its workstations
and servers.
The Team:
- James Gosling (Father of Java) - Lead architect
- Mike Sheridan - Project manager
- Patrick Naughton - Co-developer
The Original Goal:
- Develop software for consumer electronic devices (set-top boxes, TV, appliances)
- Create a language that could run on different hardware platforms
- Make programming easier for embedded systems
The Challenge:
- C++ was too complex and platform-dependent
- Needed a language that was:
- Platform-independent
- Simple and object-oriented
- Secure and reliable
29
🌳 Oak - The Original Name (1992)
Why “Oak”?
- James Gosling named it “Oak” after an oak tree outside his office window
- Oak symbolized strength and endurance
- The name reflected the robustness they wanted in the language
First Prototype:
- Created a handheld device controller called “Star7 (*7)”
- Demonstrated Oak’s capabilities
- Featured a touchscreen interface with animated character “Duke” (Java’s mascot!)
Problem:
- The name “Oak” was already trademarked by Oak Technologies
- They needed a new name!
☕ Java - The Final Name (1995)
How Did They Choose “Java”?
During a brainstorming session at a local coffee shop, the team came up with several names:
- Silk
- DNA
- Ruby
- Java ☕
Why “Java”?
- Named after Java coffee, a type of coffee from Indonesia
- The team consumed a lot of coffee during development
- Java represents something hot, fresh, and energizing
- The logo features a steaming cup of coffee ☕
Fun Fact: The Java logo and Duke mascot were created to represent the fun and innovative spirit of
the language!
🚀 Public Release (May 23, 1995)
• Java 1.0 was officially announced at SunWorld conference in 1995
• Slogan: “Write Once, Run Anywhere” (WORA)
• Revolutionary Concept: Platform independence through bytecode and JVM
• Initial version included:
• Core libraries
• JVM
• Java compiler
• Applet support for web browsers
30
📈 Evolution of Java (1996-2024)
🎯 Major Java Versions and Timeline
31
Version Release Year Code Name Key Features &
Highlights
JDK 1.0 January 1996 Oak - First official release
- 8 packages, 212
classes
- Applets for web
browsers
- AWT for GUI
JDK 1.1 February 1997 - - Inner classes
- JavaBeans
- JDBC (database con‐
nectivity)
- RMI (Remote Meth‐
od Invocation)
J2SE 1.2 December 1998 Playground - “Java 2” branding
introduced
- Swing GUI (replaced
AWT)
- Collections Frame‐
work
- JIT compiler
J2SE 1.3 May 2000 Kestrel - HotSpot JVM (per‐
formance boost)
- JNDI
- JavaSound API
J2SE 1.4 February 2002 Merlin - First version
under JCP (Java
Community Process)
- assert keyword
- Regular expressions
- NIO (New I/O)
- Logging API
- XML processing
J2SE 5.0 September 2004 Tiger MAJOR RELEASE
- Generics
List<String>
- Enhanced for loop
for(int x : array)
- Autoboxing/Un‐
boxing
- Enums
- Varargs meth‐
32
Version Release Year Code Name Key Features &
Highlights
od(String... args)
- Annotations
@Override
- Static imports
Java SE 6 December 2006 Mustang - Scripting language
support
- Performance im‐
provements
- JDBC 4.0
- Java Compiler API
Java SE 7 July 2011 Dolphin - Strings in switch
- Try-with-re‐
sources
- Diamond operator
<>
- Binary literals
0b1010
- Underscores in
numbers 1_000_000
- Multiple exception
catch
Java SE 8 March 2014 Spider REVOLUTIONARY
RELEASE
- Lambda expres‐
sions (x) -> x * 2
- Stream API (func‐
tional programming)
- Functional inter‐
faces
- Default methods
in interfaces
- Date/Time API
( [Link] )
- Optional class
- Nashorn JavaS‐
cript engine
Java SE 9 September 2017 - - Module system
(Project Jigsaw)
- JShell (REPL)
- Private methods in
interfaces
33
Version Release Year Code Name Key Features &
Highlights
- HTTP/2 Client (in‐
cubator)
Java SE 10 March 2018 - - Local variable
type inference var
- Application Class-
Data Sharing
- Parallel Full GC
Java SE 11 September 2018 - LTS (Long-Term
Support)
- HTTP Client API
(standardized)
- Launch single-file
programs without
compilation
- String methods
( isBlank() ,
lines() , strip() )
- var in lambda
parameters
- Flight Recorder
(open-source)
Java SE 12 March 2019 - - Switch expressions
(preview)
- Shenandoah GC
- Microbenchmark
suite
Java SE 13 September 2019 - - Text blocks (pre‐
view) """
- Switch expressions
(preview 2)
Java SE 14 March 2020 - - Switch expres‐
sions (standard)
- Records (preview)
- Pattern matching for
instanceof (preview)
- Helpful NullPointer‐
Exceptions
Java SE 15 September 2020 - - Text blocks (stand‐
ard)
- Sealed classes (pre‐
34
Version Release Year Code Name Key Features &
Highlights
view)
- Hidden classes
Java SE 16 March 2021 - - Records (standard)
- Pattern matching
for instanceof
(standard)
- Sealed classes (pre‐
view 2)
Java SE 17 September 2021 - LTS (Long-Term
Support)
- Sealed classes
(standard)
- Pattern matching for
switch (preview)
- Strong encapsula‐
tion of JDK internals
- macOS/AArch64
port
Java SE 18 March 2022 - - UTF-8 by default
- Simple web server
- Code snippets in
JavaDoc
Java SE 19 September 2022 - - Virtual threads (pre‐
view)
- Structured concur‐
rency (incubator)
- Pattern matching for
switch (preview 3)
Java SE 20 March 2023 - - Scoped values (in‐
cubator)
- Record patterns
(preview 2)
- Pattern matching for
switch (preview 4)
Java SE 21 September 2023 - LTS (Long-Term
Support)
- Virtual threads
(standard)
- Sequenced collec‐
tions
35
Version Release Year Code Name Key Features &
Highlights
- Record patterns
(standard)
- Pattern matching
for switch (stand‐
ard)
- String templates
(preview)
Java SE 22 March 2024 - - Unnamed variables
and patterns
- Foreign function &
memory API (pre‐
view)
- Stream gatherers
(preview)
Java SE 23 September 2024 - - Primitive types in
patterns
- Module import de‐
clarations (preview)
- Simplified main
method (preview)
🎯 Important Milestones in Java History
1️⃣ 1996: First Release (JDK 1.0)
• Java entered the world
• Web applets became popular
• Netscape Navigator supported Java
2️⃣ 1998: Java 2 Platform (J2SE 1.2)
• Rebranding to “Java 2”
• Split into three editions: J2SE, J2EE, J2ME
• Collections Framework introduced
3️⃣ 2004: Java 5 - Tiger (J2SE 5.0)
• Most significant release since Java 2
• Generics revolutionized type safety
• Enhanced syntax made Java more modern
4️⃣ 2006: Sun Open-Sources Java
• Released under GPL (GNU General Public License)
• Created OpenJDK - open-source implementation
• Community-driven development
36
5️⃣ 2010: Oracle Acquires Sun Microsystems
• Oracle Corporation acquired Sun Microsystems for $7.4 billion
• Oracle became the steward of Java
• Continued development and support
6️⃣ 2014: Java 8 - Most Popular Release
• Lambdas and Streams brought functional programming to Java
• Many companies still use Java 8 today
• Date/Time API solved long-standing pain points
7️⃣ 2017: New Release Cycle
• Oracle announced 6-month release cycle
• Faster feature delivery
• LTS (Long-Term Support) releases every 3 years
8️⃣ 2017: Oracle Donates Java EE to Eclipse Foundation
• Java EE became Jakarta EE
• Community-driven development
• Eclipse Foundation stewardship
9️⃣ 2018-2021: LTS Releases
• Java 11 (2018): First LTS under new release model
• Java 17 (2021): Major LTS with sealed classes
• Java 21 (2023): Latest LTS with virtual threads
📊 Java Release Model
🗓️ New 6-Month Release Cycle (Since 2017)
March Release → September Release → March Release → September Release
(Feature) (LTS) (Feature) (Feature)
Example:
Java 10 (Mar 2018) → Java 11 LTS (Sep 2018) → Java 12 (Mar 2019) → Java 13 (Sep 2019)
Two Types of Releases:
1. Feature Releases (every 6 months)
- New features and enhancements
- Supported for 6 months (until next release)
- For early adopters and experimentation
2. LTS Releases (every 3 years)
- Long-Term Support (5+ years of updates)
- Production-ready for enterprises
- Security patches and bug fixes
- Current LTS versions: Java 8, 11, 17, 21
37
🌟 Java’s Impact on Software Development
📱 Android Revolution
• 2008: Google announced Android with Java as primary language
• Billions of Android devices run Java/Kotlin code
• Made mobile development accessible
🌐 Enterprise Computing
• Java became the backbone of enterprise applications
• Banking, finance, insurance, healthcare rely on Java
• Spring Framework revolutionized Java web development
☁️ Cloud and Microservices
• Java dominates cloud applications
• Microservices architecture (Spring Boot)
• Containerization (Docker, Kubernetes)
📊 Big Data
• Hadoop, Spark, Kafka written in Java
• Data processing at scale
• Real-time analytics
🏆 Java Today (2024-2026)
Current Status:
- 27+ years old and still going strong
- One of the most popular programming languages
- Massive ecosystem and community
- Continuous innovation (virtual threads, pattern matching)
Adoption Statistics (2024):
- TIOBE Index: Top 3 programming languages
- GitHub: Millions of Java repositories
- Job Market: High demand for Java developers
- Enterprise: 90% of Fortune 500 companies use Java
🎭 Java Mascot - Duke
Meet Duke 🎩:
- Created in 1992 during Star7 project
- Triangular character with waving hand
- Represents Java’s friendly and accessible nature
- Appears in Java tutorials, documentation, and events
💡 Interesting Facts About Java
1. Original Target: Not computers, but consumer electronics!
38
2. Name Rejected: “Oak” was trademarked, leading to “Java”
3. Coffee Connection: Named after coffee consumed during development
4. Open Source: Java has been open-source since 2006
5. Minecraft: Popular game Minecraft is written in Java
6. Mars Rover: NASA used Java for Mars rover operations
7. 3 Billion Devices: Oracle’s slogan “3 Billion Devices Run Java” (now many more!)
8. Backwards Compatible: Java maintains backward compatibility religiously
🔑 Key Takeaways
✅ Java was created in 1991 as “Oak” for consumer electronics
✅ Renamed to “Java” in 1995, officially released in 1996
✅ James Gosling is known as the “Father of Java”
✅ Java 5 (2004) and Java 8 (2014) were revolutionary releases
✅ Oracle acquired Sun Microsystems in 2010, becoming Java’s steward
✅ New 6-month release cycle since 2017 for faster innovation
✅ LTS releases (8, 11, 17, 21) are recommended for production use
✅ Java continues to evolve with modern features while maintaining backward compatibility
5. Internal Architecture of JVM
🤔 What is JVM?
JVM (Java Virtual Machine) is an abstract computing machine that enables a computer to run
Java programs and programs written in other languages that are compiled to Java bytecode. It is the
heart of Java’s “Write Once, Run Anywhere” philosophy.
Simple Definition: JVM is like a translator that converts Java bytecode (platform-independent) into
machine code (platform-specific) that your computer can understand and execute.
🎯 Why JVM is Important?
Without JVM:
Java Code → Windows Machine Code → Runs only on Windows ❌
Java Code → Mac Machine Code → Runs only on Mac ❌
Java Code → Linux Machine Code → Runs only on Linux ❌
With JVM:
Java Code → Java Bytecode → JVM (Windows) → Windows Machine Code ✅
→ JVM (Mac) → Mac Machine Code ✅
→ JVM (Linux) → Linux Machine Code ✅
Key Point: The same bytecode runs on any platform with a compatible JVM!
39
📊 JVM Architecture Diagram
🏗️ Complete JVM Architecture
The JVM architecture consists of three main components:
┌─────────────────────────────────────────────┐
│ CLASS LOADER SUBSYSTEM │
│ (Loading → Linking → Initialization) │
└─────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────┐
│ RUNTIME DATA AREAS │
│ • Method Area • PC Register │
│ • Heap • Stack │
│ • Native Method Stack │
└─────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────┐
│ EXECUTION ENGINE │
│ • Interpreter • JIT Compiler │
│ • Garbage Collector │
└─────────────────────────────────────────────┘
1️⃣ Class Loader Subsystem
The Class Loader Subsystem is responsible for loading .class files (bytecode) into memory. It per‐
forms three major activities:
A. Loading
Purpose: Read .class files and load binary data into memory.
40
Types of Class Loaders:
Class Loader Purpose Examples
Bootstrap Class Loader Loads core Java classes [Link] - Classes from
[Link] , [Link] , etc.
Extension Class Loader Loads extension classes Classes from lib/ext direct‐
ory
Application Class Loader Loads application classes Classes from classpath (your
code)
Process:
1. Bootstrap loader tries to load the class first
2. If not found, Extension loader tries
3. If still not found, Application loader tries
4. If not found, throws ClassNotFoundException
B. Linking
Linking consists of three phases:
i. Verification ✅
• Purpose: Ensure bytecode is valid and secure
• Checks:
• File format correctness
• No violation of Java language rules
• No stack overflow/underflow
• Valid type checking
• Outcome: If verification fails, throws VerifyError
ii. Preparation 🔧
• Purpose: Allocate memory for static variables and assign default values
• Example:
java
static int count; // Assigned default value 0
static boolean flag; // Assigned default value false
static String name; // Assigned default value null
iii. Resolution 🔗
• Purpose: Replace symbolic references with direct references
• Explanation:
• Symbolic reference: [Link]() (just a name)
• Direct reference: Memory address where println method actually exists
41
C. Initialization
• Purpose: Assign actual values to static variables and execute static blocks
• Example:
```java
static int count = 100; // Now assigned actual value 100 (not just 0)
static {
[Link](“Static block executed”);
count = 200;
}
```
📝 Class Loader Example
public class ClassLoaderDemo {
static int staticVar = 50; // Initialization phase
static {
[Link]("Static block: staticVar = " + staticVar);
}
public static void main(String[] args) {
[Link]("Main method: staticVar = " + staticVar);
// Display class loaders
ClassLoaderDemo obj = new ClassLoaderDemo();
[Link]("\nClass Loaders:");
[Link]("Application: " + [Link]().getClassLoader());
[Link]("Extension: " + [Link]().getClassLoader().getParent()
);
[Link]("Bootstrap: " + [Link]().getClassLoader().getParent()
.getParent());
}
}
Output:
Static block: staticVar = 50
Main method: staticVar = 50
Class Loaders:
Application: [Link]$AppClassLoader@<address>
Extension: [Link]$PlatformClassLoader@<address>
Bootstrap: null
Note: Bootstrap class loader returns null because it’s implemented in native code (C/C++), not
Java.
2️⃣ Runtime Data Areas (Memory Areas)
These are the memory areas used by JVM during program execution:
42
A. Method Area (Shared) 📚
What is stored:
- Class-level data (metadata)
- Static variables
- Constant pool (string literals, constants)
- Method code (bytecode)
- Constructor code
Characteristics:
- Shared among all threads
- Created at JVM startup
- Exists until JVM shutdown
- One per JVM
Example:
public class Student {
static String schoolName = "ABC School"; // Stored in Method Area
static int totalStudents = 0; // Stored in Method Area
String name; // Instance variable - NOT in Method Area
int age; // Instance variable - NOT in Method Area
}
B. Heap (Shared) 🗃️
What is stored:
- All objects (instances)
- Instance variables (non-static fields)
- Arrays
Characteristics:
- Shared among all threads
- Created at JVM startup
- Garbage Collection happens here
- Divided into generations:
- Young Generation: Newly created objects
- Old Generation (Tenured): Long-lived objects
- Permanent Generation (Java 7) / Metaspace (Java 8+): Class metadata
Example:
43
public class HeapDemo {
String name; // Instance variable - stored in Heap
int age; // Instance variable - stored in Heap
public static void main(String[] args) {
HeapDemo obj1 = new HeapDemo(); // Object in Heap
[Link] = "Alice";
[Link] = 25;
HeapDemo obj2 = new HeapDemo(); // Another object in Heap
[Link] = "Bob";
[Link] = 30;
int[] numbers = {1, 2, 3, 4, 5}; // Array in Heap
}
}
C. Stack (Thread-Specific) 📚
What is stored:
- Local variables
- Method call information (method frames)
- Partial results
- Return addresses
Characteristics:
- One stack per thread (not shared)
- Created when thread starts
- Destroyed when thread ends
- Follows LIFO (Last In, First Out) structure
- Fixed or dynamic size
Stack Frame Structure:
Each method call creates a frame containing:
1. Local Variable Array: Local variables
2. Operand Stack: Intermediate calculations
3. Frame Data: Return address, exception handling
Example:
public class StackDemo {
public static void main(String[] args) { // Frame 1 (main)
int x = 10; // Local variable in Stack
int y = 20; // Local variable in Stack
int result = add(x, y); // Calls add method
[Link]("Result: " + result);
}
public static int add(int a, int b) { // Frame 2 (add)
int sum = a + b; // Local variable in Stack
return sum;
}
}
44
Stack Visualization:
┌─────────────────┐
│ Frame: add │ ← Top (current method)
│ a = 10 │
│ b = 20 │
│ sum = 30 │
├─────────────────┤
│ Frame: main │
│ x = 10 │
│ y = 20 │
│ result = ? │
└─────────────────┘
When add() returns, its frame is popped off the stack.
D. PC Register (Program Counter Register) 🔢
What it stores:
- Address of the current instruction being executed
- Points to the next instruction to execute
Characteristics:
- One per thread
- Very small size
- Not applicable for native methods
Example:
public class PCRegisterDemo {
public static void main(String[] args) {
int a = 5; // PC Register points here
int b = 10; // Then here
int c = a + b; // Then here
[Link](c); // Then here
}
}
E. Native Method Stack 🛠️
What it stores:
- Information for native methods (methods written in C/C++)
- Used when Java calls native code (e.g., system calls, hardware interaction)
Characteristics:
- One per thread
- Size is platform-dependent
Example:
45
public class NativeMethodDemo {
// Native method declaration
public native void nativeMethod();
static {
// Load native library
[Link]("nativelib");
}
}
📊 Memory Areas Comparison
Memory Area Shared/Thread- Stores Garbage Collection
Specific
Method Area Shared Class metadata, stat‐ Yes (Java 8+)
ic variables, constant
pool
Heap Shared Objects, instance Yes
variables, arrays
Stack Thread-specific Local variables, No
method calls
PC Register Thread-specific Current instruction No
address
Native Method Thread-specific Native method in‐ No
Stack formation
46
📊 Memory Allocation Diagram
3️⃣ Execution Engine
The Execution Engine executes the bytecode loaded into memory. It consists of three main compon‐
ents:
A. Interpreter 🔄
How it works:
- Reads bytecode line by line
- Converts each instruction to machine code
- Executes immediately
Advantages:
- ✅ Fast startup (begins execution quickly)
- ✅ Simple implementation
Disadvantages:
- ❌ Slow execution (interprets repeatedly)
- ❌ No optimization
B. JIT Compiler (Just-In-Time Compiler) ⚡
How it works:
- Identifies “hot spots” (frequently executed code)
- Compiles bytecode to native machine code at runtime
- Caches compiled code for reuse
47
Advantages:
- ✅ Faster execution than interpretation
- ✅ Optimizations applied
- ✅ Performance improves over time
Disadvantages:
- ❌ Slower startup (compilation takes time)
- ❌ Consumes more memory
Example:
public class JITDemo {
public static void main(String[] args) {
// This loop will be identified as a "hot spot"
for (int i = 0; i < 1000000; i++) {
calculate(i); // Called many times → JIT compiles it
}
}
public static int calculate(int n) {
return n * 2 + 5;
}
}
What happens:
1. Initially, calculate() is interpreted
2. After several executions, JIT compiler kicks in
3. calculate() is compiled to native code
4. Future calls use compiled version (much faster!)
C. Garbage Collector (GC) 🗑️
Purpose: Automatically manage memory by removing unused objects from the Heap.
How it works:
1. Identifies objects that are no longer referenced
2. Reclaims their memory
3. Prevents memory leaks
When does GC run:
- When heap memory is low
- Periodically in the background
- Can be requested with [Link]() (not guaranteed)
Example:
48
public class GCDemo {
String name;
public GCDemo(String name) {
[Link] = name;
[Link](name + " object created");
}
@Override
protected void finalize() throws Throwable {
[Link](name + " object garbage collected");
}
public static void main(String[] args) {
GCDemo obj1 = new GCDemo("Object1");
GCDemo obj2 = new GCDemo("Object2");
obj1 = null; // obj1 is now eligible for GC
obj2 = null; // obj2 is now eligible for GC
[Link](); // Request garbage collection
[Link]("GC requested");
}
}
Possible Output:
Object1 object created
Object2 object created
GC requested
Object1 object garbage collected
Object2 object garbage collected
Note: The actual order and timing of garbage collection is not guaranteed.
🔄 Interpreter vs JIT Compiler
Aspect Interpreter JIT Compiler
Execution Line by line Compiles to native code
Speed Slower Faster (after compilation)
Startup Fast Slower (compilation over‐
head)
Memory Less More (stores compiled code)
Use Case Short-running programs Long-running programs
49
Modern JVMs use a hybrid approach:
- Start with interpretation (fast startup)
- JIT compiles hot spots during execution (optimize performance)
🚀 How Java Code is Executed (Complete Flow)
Step-by-Step Execution
1. Write Source Code
↓
[Link]
2. Compile with javac
↓
javac [Link]
↓
[Link] (bytecode)
3. Run with java command
↓
java HelloWorld
↓
4. JVM Process Begins
┌─────────────────────────────────┐
│ CLASS LOADER SUBSYSTEM │
│ ─────────────────────────────── │
│ Loading → Linking → Init │
└─────────────────────────────────┘
↓
┌─────────────────────────────────┐
│ RUNTIME DATA AREAS │
│ ─────────────────────────────── │
│ • Method Area (class data) │
│ • Heap (objects) │
│ • Stack (method calls) │
│ • PC Register (instruction ptr) │
└─────────────────────────────────┘
↓
┌─────────────────────────────────┐
│ EXECUTION ENGINE │
│ ─────────────────────────────── │
│ • Interpreter executes bytecode │
│ • JIT compiles hot code │
│ • GC manages memory │
└─────────────────────────────────┘
↓
OUTPUT
50
📝 Complete Example
public class JVMDemo {
// Static variable - Method Area
static int count = 0;
// Instance variable - Heap (when object created)
String name;
public static void main(String[] args) {
// Local variable - Stack
int x = 10;
// Object creation - Heap
JVMDemo obj = new JVMDemo();
[Link] = "Java";
// Method call - new Stack frame
[Link](x);
}
public void display(int num) {
// Local variable - Stack (in display's frame)
int y = num * 2;
[Link]("Name: " + name + ", Y: " + y);
}
}
Memory Allocation:
METHOD AREA:
- Class: JVMDemo
- Static variable: count = 0
- Method bytecode: main(), display()
HEAP:
- Object: JVMDemo instance
- name = "Java"
STACK (Thread: main):
┌─────────────────┐
│ Frame: display │ ← Current
│ this = obj ref │
│ num = 10 │
│ y = 20 │
├─────────────────┤
│ Frame: main │
│ x = 10 │
│ obj = reference │
└─────────────────┘
PC REGISTER:
- Points to current instruction in display()
51
🔑 Key Takeaways
✅ JVM makes Java platform-independent by converting bytecode to native code
✅ Class Loader loads, links, and initializes classes
✅ Method Area stores class metadata and static variables (shared)
✅ Heap stores all objects and arrays (shared, garbage collected)
✅ Stack stores local variables and method calls (one per thread)
✅ Interpreter executes bytecode line by line
✅ JIT Compiler optimizes hot code by compiling to native code
✅ Garbage Collector automatically manages memory
✅ Modern JVMs use hybrid approach (interpretation + JIT) for optimal performance
6. Naming Conventions
🤔 What are Naming Conventions?
Naming conventions are a set of rules and best practices for naming identifiers (classes, methods,
variables, etc.) in Java programs. They make code:
- Readable: Easy to understand
- Maintainable: Easy to modify and debug
- Professional: Follows industry standards
- Consistent: Uniform style across codebase
Analogy: Just like proper grammar makes writing clear, naming conventions make code clear!
🎯 Why Naming Conventions Matter
Benefit Description Example Impact
Readability Code is easier to read and un‐ calculateTotal() vs ct()
derstand
Maintainability Changes are easier to make studentList tells you it’s a
list
Collaboration Team members understand Everyone follows same style
each other’s code
Bug Prevention Clear names reduce misun‐ isActive clearly means
derstandings boolean
Professionalism Demonstrates coding matur‐ Industry-standard practices
ity
52
Comprehensive Naming Convention Rules
1️⃣ Class Names
Rules:
- Use PascalCase (also called UpperCamelCase)
- Start with capital letter
- Should be nouns (represent things/entities)
- Each word starts with a capital letter
- No underscores or special characters
Format: ClassName
Examples:
✅ Good Examples:
public class Student { }
public class BankAccount { }
public class CustomerOrder { }
public class PaymentProcessor { }
public class DatabaseConnection { }
public class OrderManagementSystem { }
❌ Bad Examples:
public class student { } // Should start with capital
public class bank_account { } // No underscores
public class PAYMENTPROCESSOR { } // Not all caps
public class process { } // Too vague, should be noun
public class Order123 { } // Avoid numbers unless meaningful
2️⃣ Interface Names
Rules:
- Use PascalCase (same as classes)
- Should be adjectives or nouns
- Often describe capability or behavior
- Commonly end with “-able”, “-ible” (for capability)
Format: InterfaceName
Examples:
✅ Good Examples:
public interface Runnable { } // Capability
public interface Serializable { } // Capability
public interface Comparable { } // Capability
public interface List { } // Noun (container)
public interface PaymentGateway { }
public interface Drawable { }
public interface Clickable { }
53
❌ Bad Examples:
public interface runnable { } // Should start with capital
public interface run { } // Too vague
public interface IPayment { } // No "I" prefix (C# convention, not Java)
3️⃣ Method Names
Rules:
- Use camelCase (also called lowerCamelCase)
- Start with lowercase letter
- Should be verbs or verb phrases (represent actions)
- Descriptive and meaningful
Format: methodName()
Examples:
✅ Good Examples:
public void calculateTotal() { }
public int getAge() { }
public void setName(String name) { }
public boolean isActive() { }
public boolean hasPermission() { }
public void processPayment() { }
public String toString() { }
public void printReport() { }
Special Naming Patterns:
- get/set: Getters and setters
java
public String getName() { }
public void setName(String name) { }
- is/has/can: Boolean methods
java
public boolean isValid() { }
public boolean hasChildren() { }
public boolean canAccess() { }
❌ Bad Examples:
public void Calculate() { } // Should start with lowercase
public void process_payment() { } // No underscores
public void p() { } // Too short, not descriptive
public void name() { } // Should be verb (e.g., setName)
public boolean valid() { } // Should be isValid()
54
4️⃣ Variable Names
Rules:
- Use camelCase
- Start with lowercase letter
- Should be nouns (represent data/objects)
- Descriptive and meaningful
- Avoid single-letter names (except for loops)
Format: variableName
Examples:
✅ Good Examples:
// Primitive variables
int age = 25;
double salary = 50000.50;
boolean isActive = true;
char grade = 'A';
// Object variables
String studentName = "John Doe";
ArrayList<String> cityList = new ArrayList<>();
BankAccount userAccount = new BankAccount();
LocalDate birthDate = [Link]();
// Descriptive names
int numberOfStudents = 30;
double averageScore = 85.5;
String emailAddress = "user@[Link]";
❌ Bad Examples:
int a = 25; // Too vague (except in loops)
int Age = 25; // Should start with lowercase
int student_age = 25; // No underscores
double s = 50000.50; // Not descriptive
String nm = "John"; // Abbreviated
boolean flag = true; // What flag? Use isActive, hasAccess, etc.
5️⃣ Constant Names
Rules:
- Use ALL_UPPERCASE
- Words separated by underscores
- Declared with static final keywords
- Represent unchangeable values
Format: CONSTANT_NAME
Examples:
✅ Good Examples:
55
public static final int MAX_SIZE = 100;
public static final double PI = 3.14159;
public static final String DEFAULT_COLOR = "Blue";
public static final int MIN_AGE = 18;
public static final int MAX_LOGIN_ATTEMPTS = 3;
public static final String DATABASE_URL = "jdbc:mysql://localhost:3306/mydb";
Usage Example:
public class MathConstants {
public static final double PI = 3.14159;
public static final double E = 2.71828;
public static void main(String[] args) {
double radius = 5.0;
double area = PI * radius * radius;
[Link]("Area: " + area);
}
}
❌ Bad Examples:
public static final int maxSize = 100; // Should be all caps
public static final double Pi = 3.14159; // Should be all caps
public static final String default_color = "Blue"; // Should be all caps
6️⃣ Package Names
Rules:
- Use all lowercase letters
- No uppercase, underscores, or special characters
- Follow reverse domain name convention
- Use dots (.) to separate levels
Format: [Link]
Examples:
✅ Good Examples:
package [Link];
package [Link];
package [Link];
package [Link];
package [Link];
package [Link];
Explanation:
- [Link] : Company domain reversed
- ecommerce : Project name
- payment , shipping : Modules/sub-packages
56
❌ Bad Examples:
package MyPackage; // No capital letters
package [Link]; // No capital letters
package com.my_company.app; // No underscores
7️⃣ Enum Names and Constants
Rules:
- Enum name: PascalCase (like classes)
- Enum constants: ALL_UPPERCASE (like constants)
Examples:
✅ Good Examples:
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public enum PaymentMethod {
CREDIT_CARD, DEBIT_CARD, NET_BANKING, UPI, CASH
}
public enum Status {
ACTIVE, INACTIVE, PENDING, COMPLETED, CANCELLED
}
Usage:
public class EnumDemo {
public static void main(String[] args) {
Day today = [Link];
[Link]("Today is: " + today);
PaymentMethod method = PaymentMethod.CREDIT_CARD;
[Link]("Payment Method: " + method);
}
}
Output:
Today is: MONDAY
Payment Method: CREDIT_CARD
8️⃣ Local Variables vs Instance Variables
Instance Variables (Class-level):
57
public class Student {
// Instance variables - camelCase
private String studentName;
private int studentAge;
private double gpa;
private boolean isEnrolled;
}
Local Variables (Method-level):
public void processOrder() {
// Local variables - camelCase
int orderCount = 0;
double totalPrice = 0.0;
boolean isValid = true;
}
Difference: Both follow same naming convention (camelCase), but:
- Instance variables: Class-level scope, often more descriptive
- Local variables: Method-level scope, can be shorter within context
58
📊 Complete Naming Conventions Summary Table
Element Convention Format Example Notes
Class PascalCase ClassName BankAccount Noun, capitalize
each word
Interface PascalCase InterfaceName Runnable Adjective or
noun, often “-
able”
Method camelCase methodName() calculat‐ Verb, start with
eTotal() lowercase
Variable camelCase variableName studentName Noun, start with
lowercase
Constant ALL_UPPERCASE CONSTANT_NAME MAX_SIZE Use under‐
scores, static
final
Package lowercase [Link] [Link] All lowercase,
ject pp dots separate
Enum Type PascalCase EnumName PaymentMethod Like classes
Enum Con‐ ALL_UPPERCASE ENUM_VALUE CREDIT_CARD Like constants
stant
59
📝 Complete Real-World Example
60
package [Link]; // Package: all lowercase
// Class: PascalCase, Noun
public class BankAccount {
// Constants: ALL_UPPERCASE
public static final double MINIMUM_BALANCE = 1000.0;
public static final int MAX_WITHDRAWAL_LIMIT = 50000;
// Instance variables: camelCase, Nouns
private String accountHolderName;
private long accountNumber;
private double accountBalance;
private boolean isActive;
// Constructor: Same as class name
public BankAccount(String accountHolderName, long accountNumber) {
[Link] = accountHolderName;
[Link] = accountNumber;
[Link] = MINIMUM_BALANCE;
[Link] = true;
}
// Method: camelCase, Verb (getter)
public String getAccountHolderName() {
return accountHolderName;
}
// Method: camelCase, Verb (setter)
public void setAccountHolderName(String accountHolderName) {
[Link] = accountHolderName;
}
// Method: camelCase, Verb (boolean - starts with "is")
public boolean isActive() {
return isActive;
}
// Method: camelCase, Verb (action)
public void depositMoney(double amount) {
// Local variable: camelCase
double newBalance = accountBalance + amount;
accountBalance = newBalance;
[Link]("Deposited: " + amount);
}
// Method: camelCase, Verb (action with validation)
public boolean withdrawMoney(double amount) {
// Local variables: camelCase
boolean isWithdrawalAllowed = false;
double remainingBalance = accountBalance - amount;
if (remainingBalance >= MINIMUM_BALANCE && amount <= MAX_WITHDRAWAL_LIMIT) {
accountBalance = remainingBalance;
isWithdrawalAllowed = true;
[Link]("Withdrawn: " + amount);
} else {
[Link]("Withdrawal failed!");
}
return isWithdrawalAllowed;
}
61
// Method: camelCase, Verb (calculation)
public void displayAccountInfo() {
[Link]("Account Holder: " + accountHolderName);
[Link]("Account Number: " + accountNumber);
[Link]("Balance: " + accountBalance);
[Link]("Status: " + (isActive ? "Active" : "Inactive"));
}
}
// Enum: PascalCase
enum AccountType {
SAVINGS, CURRENT, FIXED_DEPOSIT // Enum constants: ALL_UPPERCASE
}
// Main class
public class BankingApp {
public static void main(String[] args) {
// Object: camelCase
BankAccount myAccount = new BankAccount("John Doe", 1234567890L);
[Link](5000);
[Link](2000);
[Link]();
}
}
Output:
Deposited: 5000.0
Withdrawn: 2000.0
Account Holder: John Doe
Account Number: 1234567890
Balance: 4000.0
Status: Active
💡 Additional Best Practices
1. Avoid Abbreviations
// ❌ Bad
String fn = "John";
String ln = "Doe";
int empId = 123;
// ✅ Good
String firstName = "John";
String lastName = "Doe";
int employeeId = 123;
62
2. Use Meaningful Names
// ❌ Bad
int d; // days? distance? data?
String s; // name? status? string?
boolean flag; // what flag?
// ✅ Good
int numberOfDays;
String studentName;
boolean isLoggedIn;
3. Loop Variables
// ✅ Acceptable for simple loops
for (int i = 0; i < 10; i++) {
[Link](i);
}
// ✅ Better for complex loops
for (int studentIndex = 0; studentIndex < [Link]; studentIndex++) {
[Link](students[studentIndex]);
}
// ✅ Enhanced for loop
for (String studentName : studentNames) {
[Link](studentName);
}
4. Boolean Variables
// ✅ Use question-like names
boolean isActive;
boolean hasPermission;
boolean canEdit;
boolean wasSuccessful;
// ❌ Avoid vague names
boolean flag;
boolean status;
boolean check;
🔑 Key Takeaways
✅ Classes/Interfaces: PascalCase (e.g., BankAccount , Runnable )
✅ Methods/Variables: camelCase (e.g., calculateTotal() , studentName )
✅ Constants: ALL_UPPERCASE (e.g., MAX_SIZE , PI )
✅ Packages: all lowercase (e.g., [Link] )
✅ Classes = Nouns, Methods = Verbs, Boolean methods = is/has/can
✅ Avoid abbreviations, use descriptive names
✅ Consistency is key - follow conventions throughout codebase
✅ Naming conventions improve readability, maintainability, and professionalism
63
7. Identifiers
🤔 What is an Identifier?
An identifier is a name given to a Java program element such as:
- Classes
- Interfaces
- Methods
- Variables
- Packages
- Constants
Simple Definition: An identifier is any name you create in your Java program to identify something.
Analogy: Just like you have a name (e.g., “John”) that identifies you, identifiers are names that
identify program elements.
🎯 Why Identifiers are Important
Identifiers allow you to:
- Refer to elements: Access variables, call methods
- Organize code: Name classes, packages
- Make code readable: Meaningful names improve understanding
📜 Rules for Creating Identifiers
Java has strict rules for valid identifiers. Violating these rules causes compilation errors.
✅ Rule 1: Can Start With
• Letters: a-z , A-Z
• Underscore: _
• Dollar sign: $
❌ Cannot Start With
• Digits: 0-9
• Special characters: @ , # , % , & , etc.
✅ Rule 2: Can Contain (After First Character)
• Letters: a-z , A-Z
• Digits: 0-9
• Underscore: _
• Dollar sign: $
❌ Cannot Contain
• Spaces
• Special characters: @ , # , % , & , - , + , etc.
64
✅ Rule 3: Case Sensitive
• name , Name , NAME are three different identifiers
❌ Rule 4: Cannot Be Reserved Words
• Cannot use Java keywords, literals (true, false, null)
• Full list in section 8 (Reserved Words)
✅ Rule 5: No Length Limit
• Technically unlimited (but keep reasonable for readability)
• Recommended: 1-30 characters for most identifiers
📊 Valid vs Invalid Identifiers
✅ Valid Identifiers
// Starting with letters
name
studentName
MyClass
calculateTotal
processPayment
// Starting with underscore
_name
_count
__temp
// Starting with dollar sign
$price
$value
// Containing digits (not at start)
student1
name2
value123
calculate2Values
// Containing underscore and dollar
student_name
$my_var
total_$_amount
// Single character (except reserved)
a
x
i
j
65
❌ Invalid Identifiers
// Starting with digit
123name // ❌ Error: Illegal start
9students // ❌ Error: Illegal start
// Containing special characters
student@name // ❌ Error: Illegal character @
my-variable // ❌ Error: Illegal character -
total% // ❌ Error: Illegal character %
name#1 // ❌ Error: Illegal character #
// Containing spaces
student name // ❌ Error: Illegal space
my var // ❌ Error: Illegal space
// Reserved words
class // ❌ Error: Reserved keyword
int // ❌ Error: Reserved keyword
public // ❌ Error: Reserved keyword
true // ❌ Error: Reserved literal
false // ❌ Error: Reserved literal
null // ❌ Error: Reserved literal
📝 Code Examples
Example 1: Valid Identifiers
public class IdentifierDemo {
public static void main(String[] args) {
// All valid identifiers
int age = 25;
int age2 = 30;
int _age = 35;
int $age = 40;
int ageOfPerson = 45;
String name = "John";
String firstName = "Jane";
String _lastName = "Doe";
String $email = "john@[Link]";
[Link]("age: " + age);
[Link]("age2: " + age2);
[Link]("_age: " + _age);
[Link]("$age: " + $age);
[Link]("ageOfPerson: " + ageOfPerson);
[Link]("name: " + name);
[Link]("firstName: " + firstName);
[Link]("_lastName: " + _lastName);
[Link]("$email: " + $email);
}
}
Output:
66
age: 25
age2: 30
_age: 35
$age: 40
ageOfPerson: 45
name: John
firstName: Jane
_lastName: Doe
$email: john@[Link]
Example 2: Invalid Identifiers (Compilation Errors)
public class InvalidIdentifiers {
public static void main(String[] args) {
// ❌ All will cause compilation errors
// int 123name = 10; // Error: starts with digit
// int student name = 20; // Error: contains space
// int student@name = 30; // Error: contains @
// int my-variable = 40; // Error: contains hyphen
// int class = 50; // Error: reserved keyword
// int public = 60; // Error: reserved keyword
}
}
📊 Identifier Rules Summary Table
Rule Description Valid Examples Invalid Examples
Start Character Letter, _ , or $ name , _count , 1name , @name ,
$value #name
Subsequent Char‐ Letter, digit, _ , or $ name1 , name@ , my-var ,
acters student_age , price%
$price2
Spaces Not allowed studentName student name
Keywords Not allowed myClass , student‐ class , int , public
Data
Case Sensitivity Distinct identifiers name , Name , NAME N/A
Length No limit (reasonable) calculateTotalPrice Very long names
(poor practice)
67
🎨 Special Cases and Conventions
1. Underscore ( _ ) Usage
Valid but discouraged (except for constants):
// ✅ Valid but not recommended (poor style)
int _age = 25;
String _name = "John";
// ✅ Recommended for constants
public static final int MAX_SIZE = 100;
public static final String DEFAULT_COLOR = "Blue";
// ✅ Good practice for private fields (some conventions)
private int _count; // Some developers use this style
Note: Modern Java discourages leading underscores except in specific cases.
2. Dollar Sign ( $ ) Usage
Valid but avoid in user code:
// ✅ Valid but not recommended
int $price = 100;
String $name = "Product";
When is $ used?
- Generated code: Compilers and tools use $ in generated class names
- Example: Inner class OuterClass$InnerClass
- Frameworks: Some frameworks generate code with $
- User code: Avoid using $ manually
3. Unicode Characters
Java supports Unicode characters in identifiers:
// ✅ Valid (but not common in English codebases)
String न ाम = "John"; // Hindi word for "name"
int 年齢 = 25; // Japanese word for "age"
String имя = "Ivan"; // Russian word for "name"
[Link]("नाम: " + न ाम);
[Link]("年齢: " + 年齢);
[Link]("имя: " + имя);
Output:
नाम: John
年齢: 25
имя: Ivan
68
Best Practice: Stick to English letters for international collaboration and readability.
💡 Best Practices for Identifiers
✅ Do’s
1. Use Meaningful Names
java
// ✅ Good
int studentAge = 20;
String firstName = "John";
double accountBalance = 1000.50;
2. Follow Naming Conventions
java
// ✅ Good
class StudentRecord { } // Class: PascalCase
public void calculateTotal() { } // Method: camelCase
int studentCount = 0; // Variable: camelCase
final int MAX_SIZE = 100; // Constant: ALL_UPPERCASE
3. Be Descriptive but Concise
```java
// ✅ Good
int numberOfStudents = 30;
double averageScore = 85.5;
// ✅ Acceptable in context
for (int i = 0; i < 10; i++) { } // ‘i’ is fine for simple loops
```
1. Use Proper Grammar
java
// ✅ Good
boolean isActive = true; // Singular
List<String> studentNames = new ArrayList<>(); // Plural for collections
❌ Don’ts
1. Avoid Single Letters (except loops)
```java
// ❌ Bad
int a = 25;
String n = “John”;
// ✅ Good
int age = 25;
69
String name = “John”;
```
1. Avoid Abbreviations
```java
// ❌ Bad
int stdCnt = 30;
String fn = “John”;
// ✅ Good
int studentCount = 30;
String firstName = “John”;
```
1. Avoid Meaningless Names
```java
// ❌ Bad
int temp = 25;
String data = “John”;
boolean flag = true;
// ✅ Good
int age = 25;
String studentName = “John”;
boolean isActive = true;
```
1. Avoid Starting with _ or $ (in user code)
```java
// ❌ Discouraged (unless specific convention)
int _count = 10;
String $name = “John”;
// ✅ Better
int count = 10;
String name = “John”;
```
70
📝 Comprehensive Example
public class Student { // Identifier: Student (class name)
// Identifiers: Instance variables
private String studentName; // Valid: camelCase
private int studentAge; // Valid: camelCase
private double gpa; // Valid: camelCase
// Identifier: Constant
public static final int MAX_AGE = 100; // Valid: ALL_UPPERCASE
// Identifier: Constructor
public Student(String studentName, int studentAge) {
[Link] = studentName; // 'this' is a keyword, not identifier
[Link] = studentAge;
}
// Identifier: Method
public void displayInfo() { // Valid: camelCase
// Identifier: Local variable
String info = "Name: " + studentName + ", Age: " + studentAge;
[Link](info);
}
// Identifier: Method with parameters
public double calculateGPA(double marks1, double marks2, double marks3) {
// Identifiers: Local variables
double totalMarks = marks1 + marks2 + marks3;
double averageMarks = totalMarks / 3.0;
return averageMarks;
}
}
public class Main {
public static void main(String[] args) { // 'String' and 'args' are identifiers
// Identifier: Object
Student student1 = new Student("John Doe", 20);
[Link]();
double gpa = [Link](85.5, 90.0, 88.5);
[Link]("GPA: " + gpa);
}
}
Output:
Name: John Doe, Age: 20
GPA: 88.0
Identifiers in this code:
- Classes: Student , Main
- Variables: studentName , studentAge , gpa , student1 , info , marks1 , totalMarks , etc.
- Methods: displayInfo , calculateGPA , main
- Parameters: studentName , studentAge , marks1 , marks2 , marks3 , args
- Constant: MAX_AGE
71
🔑 Key Takeaways
✅ Identifiers are names for program elements (classes, methods, variables, etc.)
✅ Must start with letter, _ , or $ (avoid _ and $ in user code)
✅ Can contain letters, digits, _ , and $ after the first character
✅ Cannot contain spaces or special characters ( @ , # , % , etc.)
✅ Cannot be reserved words (keywords, true, false, null)
✅ Case sensitive: name ≠ Name ≠ NAME
✅ No length limit, but keep reasonable (1-30 characters recommended)
✅ Use meaningful, descriptive names following naming conventions
✅ Avoid abbreviations, single letters (except loops), and vague names
8. Reserved Words
🤔 What are Reserved Words?
Reserved words are predefined words in Java that have special meanings to the compiler. They
cannot be used as identifiers (names for variables, methods, classes, etc.).
Categories of Reserved Words:
1. Keywords (50 total) - Have specific functionality
2. Reserved Literals (3 total) - Represent special values
3. Unused Reserved Words (2 total) - Reserved but not currently used
Total Reserved Words: 55 (50 keywords + 3 literals + 2 unused)
📊 Complete List of Java Reserved Words
1️⃣ Keywords (50)
Java has 50 keywords that are actively used in the language:
72
abstract assert boolean break byte
case catch char class continue
default do double else enum
extends final finally float for
if implements import instanceof int
interface long native new package
private protected public return short
static strictfp super switch synchronized
this throw throws transient try
void volatile while
2️⃣ Reserved Literals (3)
These are not keywords but are reserved:
Literal Type Description
true boolean Boolean literal representing
truth
false boolean Boolean literal representing
falsity
null reference Represents null reference (no
object)
3️⃣ Unused Reserved Words (2)
Reserved for potential future use, but currently not used in Java:
Word Status Note
goto Reserved but unused Legacy from C/C++; Java
uses labels instead
const Reserved but unused Use final instead for con‐
stants
73
📚 Keywords by Category
Let’s organize keywords by their purpose:
A. Data Type Keywords (8)
Used to define data types:
Keyword Type Size Range
byte Integer 1 byte -128 to 127
short Integer 2 bytes -32,768 to 32,767
int Integer 4 bytes -2³¹ to 2³¹-1
long Integer 8 bytes -2⁶³ to 2⁶³-1
float Floating-point 4 bytes ~1.4E-45 to ~3.4E38
double Floating-point 8 bytes ~4.9E-324 to
~1.8E308
char Character 2 bytes 0 to 65,535 (Unicode)
boolean Boolean 1 bit true or false
Example:
public class DataTypeKeywords {
public static void main(String[] args) {
byte age = 25;
short year = 2024;
int population = 1000000;
long distance = 9460730472580800L;
float price = 19.99f;
double pi = 3.14159265359;
char grade = 'A';
boolean isActive = true;
[Link]("Age (byte): " + age);
[Link]("Year (short): " + year);
[Link]("Population (int): " + population);
[Link]("Distance (long): " + distance);
[Link]("Price (float): " + price);
[Link]("Pi (double): " + pi);
[Link]("Grade (char): " + grade);
[Link]("Is Active (boolean): " + isActive);
}
}
74
B. Access Modifier Keywords (3)
Control access to classes, methods, and variables:
Keyword Scope Description
public Everywhere Accessible from any class
private Same class only Accessible only within the
same class
protected Same package + subclasses Accessible within package
and by subclasses
Note: Default (no keyword) is package-private (accessible within same package only).
Example:
public class AccessModifierDemo {
public int publicVar = 10; // Accessible everywhere
private int privateVar = 20; // Only within this class
protected int protectedVar = 30; // Within package + subclasses
int defaultVar = 40; // Within package only (no keyword)
public void display() {
[Link]("Public: " + publicVar);
[Link]("Private: " + privateVar);
[Link]("Protected: " + protectedVar);
[Link]("Default: " + defaultVar);
}
}
C. Class-Related Keywords (6)
Used in class definitions:
75
Keyword Purpose Example
class Define a class class Student { }
interface Define an interface interface Runnable { }
enum Define an enumeration enum Day { MONDAY, TUES‐
DAY }
extends Inherit from a class class Dog extends Animal
{ }
implements Implement an interface class MyClass implements
Runnable { }
abstract Define abstract class/method abstract class Shape { }
Example:
// Interface
interface Animal {
void makeSound();
}
// Abstract class
abstract class Mammal implements Animal {
abstract void eat();
}
// Concrete class
class Dog extends Mammal {
@Override
public void makeSound() {
[Link]("Woof!");
}
@Override
void eat() {
[Link]("Dog is eating");
}
}
// Enum
enum Size {
SMALL, MEDIUM, LARGE
}
D. Object-Related Keywords (4)
Used with objects:
76
Keyword Purpose Example
new Create new object Student s = new Student();
this Reference to current object [Link] = name;
super Reference to parent class [Link]();
instanceof Check object type if (obj instanceof String)
Example:
class Parent {
void display() {
[Link]("Parent class");
}
}
class Child extends Parent {
void display() {
[Link](); // Call parent method
[Link]("Child class");
}
void showThis() {
[Link]("this reference: " + this);
}
}
public class ObjectKeywords {
public static void main(String[] args) {
Child child = new Child(); // 'new' keyword
[Link]();
[Link]();
// instanceof keyword
if (child instanceof Parent) {
[Link]("child is an instance of Parent");
}
}
}
Output:
Parent class
Child class
this reference: Child@<hashcode>
child is an instance of Parent
E. Control Flow Keywords (12)
Control program flow:
77
Keyword Purpose Example
if Conditional execution if (x > 0) { }
else Alternative condition if (x > 0) { } else { }
switch Multi-way branch switch (day) { }
case Switch case label case 1: break;
default Default switch case default: break;
for Loop for (int i = 0; i < 10; i+
+) { }
while Loop while (condition) { }
do Do-while loop do { } while (condition);
break Exit loop/switch break;
continue Skip to next iteration continue;
return Return from method return value;
assert Assert condition assert x > 0;
Example:
78
public class ControlFlowDemo {
public static void main(String[] args) {
// if-else
int age = 20;
if (age >= 18) {
[Link]("Adult");
} else {
[Link]("Minor");
}
// switch-case
int day = 3;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Other day");
}
// for loop with break
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit loop at 5
}
[Link](i + " ");
}
[Link]();
// while loop with continue
int j = 0;
while (j < 5) {
j++;
if (j == 3) {
continue; // Skip 3
}
[Link](j + " ");
}
[Link]();
// do-while
int k = 1;
do {
[Link](k + " ");
k++;
} while (k <= 5);
[Link]();
}
}
Output:
79
Adult
Wednesday
1 2 3 4
1 2 4 5
1 2 3 4 5
F. Exception Handling Keywords (5)
Handle errors and exceptions:
Keyword Purpose Example
try Start exception-handling try { }
block
catch Handle exception catch (Exception e) { }
finally Always execute finally { }
throw Throw an exception throw new Exception();
throws Declare exceptions void method() throws IOEx‐
ception { }
Example:
public class ExceptionDemo {
public static void main(String[] args) {
try {
int result = divide(10, 0);
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: " + [Link]());
} finally {
[Link]("Finally block always executes");
}
}
public static int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return a / b;
}
}
Output:
Error: Cannot divide by zero
Finally block always executes
80
G. Modifier Keywords (7)
Modify behavior of classes, methods, and variables:
Keyword Purpose Applies To
static Class-level member Variables, methods, blocks
final Cannot be changed/overrid‐ Variables, methods, classes
den
abstract Incomplete implementation Classes, methods
synchronized Thread-safe Methods, blocks
volatile Visible across threads Variables
transient Not serialized Variables
native Implemented in native code Methods
Example:
81
public class ModifierDemo {
// static: class-level
static int count = 0;
// final: constant
final int MAX_SIZE = 100;
// volatile: thread-visible
volatile boolean flag = true;
// transient: not serialized
transient String password = "secret";
// static method
public static void incrementCount() {
count++;
}
// final method: cannot be overridden
public final void displayMax() {
[Link]("Max Size: " + MAX_SIZE);
}
// synchronized method: thread-safe
public synchronized void threadSafeMethod() {
[Link]("Thread-safe operation");
}
}
// abstract class
abstract class Shape {
abstract void draw(); // abstract method
}
// final class: cannot be extended
final class MathUtils {
public static int add(int a, int b) {
return a + b;
}
}
H. Package and Import Keywords (2)
Organize code:
Keyword Purpose Example
package Declare package package [Link];
import Import classes import [Link];
Example:
82
package [Link]; // package declaration
import [Link]; // import specific class
import [Link].*; // import all classes from package
public class PackageDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
[Link]("Java");
[Link](list);
}
}
I. Other Keywords (3)
Keyword Purpose Example
void No return value public void display() { }
strictfp Strict floating-point strictfp class Calculator
{ }
var Local variable type inference var list = new ArrayL‐
(Java 10+) ist<String>();
Note: var is not technically a keyword but a reserved type name.
Example:
public class OtherKeywords {
// void: no return
public void printMessage(String message) {
[Link](message);
}
// strictfp: strict floating-point calculations
public strictfp double calculate() {
return 1.0 / 3.0;
}
public static void main(String[] args) {
// var: type inference (Java 10+)
var name = "John"; // Compiler infers String
var age = 25; // Compiler infers int
var list = new ArrayList<String>(); // Compiler infers ArrayList<String>
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
83
❌ Common Mistakes with Reserved Words
Mistake 1: Using Keywords as Identifiers
// ❌ ERROR: Cannot use keywords as variable names
int class = 10; // Error: 'class' is a keyword
String public = "John"; // Error: 'public' is a keyword
boolean if = true; // Error: 'if' is a keyword
Mistake 2: Using Reserved Literals as Identifiers
// ❌ ERROR: Cannot use true, false, null as identifiers
int true = 1; // Error: 'true' is a literal
boolean false = false; // Error: 'false' is a literal
String null = "empty"; // Error: 'null' is a literal
Mistake 3: Case Confusion
// ✅ These are VALID (keywords are case-sensitive)
int Public = 10; // Valid: 'Public' is not a keyword
String Class = "Java"; // Valid: 'Class' is not a keyword
boolean If = true; // Valid: 'If' is not a keyword
// But NOT recommended (confusing!)
Best Practice: Avoid names similar to keywords even if technically valid.
84
📝 Complete Example: Reserved Words in Action
package [Link]; // 'package' keyword
import [Link].*; // 'import' keyword
// 'public', 'class' keywords
public class ReservedWordsDemo {
// 'private', 'static', 'final', 'int' keywords
private static final int MAX_SIZE = 100;
// 'public', 'void' keywords
public void processData() { // 'void' keyword
// 'int' keyword
int count = 0;
// 'for', 'break' keywords
for (int i = 0; i < 10; i++) { // 'int' keyword
if (i == 5) { // 'if' keyword
break; // 'break' keyword
}
count++;
}
// 'boolean', 'true', 'false' keywords/literals
boolean isActive = true;
// 'if', 'else' keywords
if (isActive) {
[Link]("Active");
} else {
[Link]("Inactive");
}
// 'try', 'catch', 'finally' keywords
try {
int result = 10 / 0;
} catch (ArithmeticException e) { // 'catch' keyword
[Link]("Error");
} finally { // 'finally' keyword
[Link]("Cleanup");
}
}
// 'public', 'static', 'void' keywords
public static void main(String[] args) { // 'static', 'void' keywords
// 'new' keyword
ReservedWordsDemo demo = new ReservedWordsDemo();
[Link]();
}
}
🔑 Key Takeaways
✅ 55 total reserved words: 50 keywords + 3 literals + 2 unused
✅ Keywords have specific functionality in Java
✅ Reserved literals: true , false , null
85
✅ Unused: goto , const (reserved for potential future use)
✅ Cannot be used as identifiers (variable, method, class names)
✅ Case-sensitive: int is keyword, but Int is not (though not recommended)
✅ Categorized by purpose: data types, access modifiers, control flow, etc.
✅ Understanding reserved words is fundamental to writing valid Java code
9. Data Types
🤔 What are Data Types?
A data type specifies:
1. Type of data a variable can hold (numbers, text, true/false, etc.)
2. Size of memory required
3. Range of values that can be stored
4. Operations that can be performed
Simple Definition: Data types tell Java what kind of data you want to store and how much space to
reserve for it.
Analogy: Think of data types as containers of different sizes:
- byte = Small box (holds small numbers)
- int = Medium box (holds regular numbers)
- long = Large box (holds very large numbers)
- String = Elastic bag (holds text of any length)
🎯 Why Data Types are Important
1. Memory Efficiency: Use appropriate size to save memory
2. Type Safety: Prevent errors (e.g., can’t assign text to a number variable)
3. Performance: Correct types improve performance
4. Clarity: Makes code more understandable
📊 Classification of Java Data Types
Java Data Types
|
______________|______________
| |
Primitive Types Non-Primitive Types
(8 types) (Reference Types)
| |
_____|_____ ____|____
| | | |
Numeric Non-Numeric Classes Arrays
| Interfaces
|____ Enums
| | Strings
Integer Floating-Point
Types Types
86
1️⃣ Primitive Data Types (8 Types)
Primitive types are built-in data types provided by Java. They store simple values directly in
memory.
📊 Primitive Data Types Table
Type Size Min Value Max Default Example Used For
Value
byte 1 byte (8 -128 127 0 byte b = Small in‐
bits) 100; tegers,
saving
memory
short 2 bytes (16 -32,768 32,767 0 short s = Medium in‐
bits) 1000; tegers
int 4 bytes (32 -2,147,483 2,147,483, 0 int i = Most
bits) ,648 647 100000; common
integer
type
long 8 bytes (64 -2⁶³ 2⁶³-1 0L long l = Very large
bits) 100000L; integers
float 4 bytes (32 ~1.4E-45 ~3.4E38 0.0f float f = Decimal
bits) 5.5f; numbers
(less preci‐
sion)
double 8 bytes (64 ~4.9E-324 ~1.8E308 0.0d double d = Decimal
bits) 5.5; numbers
(more pre‐
cision)
char 2 bytes (16 0 65,535 ‘\u0000’ char c = Single
bits) 'A'; character
(Unicode)
boolean 1 bit - - false boolean b True/false
= true; values
87
📊 Data Types Hierarchy Diagram
A. Integer Types (4 Types)
Used to store whole numbers (no decimals).
i. byte (1 byte = 8 bits)
Characteristics:
- Smallest integer type
- Range: -128 to 127
- Saves memory in large arrays
Example:
public class ByteDemo {
public static void main(String[] args) {
byte age = 25;
byte temperature = -10;
byte maxByte = 127;
byte minByte = -128;
[Link]("Age: " + age);
[Link]("Temperature: " + temperature);
[Link]("Max byte value: " + maxByte);
[Link]("Min byte value: " + minByte);
// byte overflow
// byte overflow = 128; // ❌ Error: out of range
}
}
Output:
88
Age: 25
Temperature: -10
Max byte value: 127
Min byte value: -128
ii. short (2 bytes = 16 bits)
Characteristics:
- Twice the size of byte
- Range: -32,768 to 32,767
- Rarely used in modern programming
Example:
public class ShortDemo {
public static void main(String[] args) {
short year = 2024;
short elevation = -500;
short maxShort = 32767;
short minShort = -32768;
[Link]("Year: " + year);
[Link]("Elevation: " + elevation + " meters");
[Link]("Max short value: " + maxShort);
[Link]("Min short value: " + minShort);
}
}
Output:
Year: 2024
Elevation: -500 meters
Max short value: 32767
Min short value: -32768
iii. int (4 bytes = 32 bits)
Characteristics:
- Most commonly used integer type
- Range: -2,147,483,648 to 2,147,483,647 (about ±2.1 billion)
- Default type for integer literals
Example:
89
public class IntDemo {
public static void main(String[] args) {
int population = 1000000;
int balance = -5000;
int maxInt = 2147483647;
int minInt = -2147483648;
[Link]("Population: " + population);
[Link]("Balance: $" + balance);
[Link]("Max int value: " + maxInt);
[Link]("Min int value: " + minInt);
// Underscores for readability (Java 7+)
int largeNumber = 1_000_000_000; // 1 billion
[Link]("Large number: " + largeNumber);
}
}
Output:
Population: 1000000
Balance: $-5000
Max int value: 2147483647
Min int value: -2147483648
Large number: 1000000000
iv. long (8 bytes = 64 bits)
Characteristics:
- Largest integer type
- Range: -2⁶³ to 2⁶³-1 (about ±9.2 quintillion)
- Must use L or l suffix (uppercase L recommended)
Example:
public class LongDemo {
public static void main(String[] args) {
long distanceToSun = 149600000000L; // km
long worldPopulation = 7800000000L;
long maxLong = 9223372036854775807L;
long minLong = -9223372036854775808L;
[Link]("Distance to Sun: " + distanceToSun + " km");
[Link]("World Population: " + worldPopulation);
[Link]("Max long value: " + maxLong);
[Link]("Min long value: " + minLong);
// Underscores for readability
long trillion = 1_000_000_000_000L;
[Link]("One trillion: " + trillion);
}
}
Output:
90
Distance to Sun: 149600000000 km
World Population: 7800000000
Max long value: 9223372036854775807
Min long value: -9223372036854775808
One trillion: 1000000000000
B. Floating-Point Types (2 Types)
Used to store decimal numbers (fractional values).
i. float (4 bytes = 32 bits)
Characteristics:
- Single-precision floating-point
- About 6-7 significant decimal digits
- Must use f or F suffix
- Use when memory is a concern and precision isn’t critical
Example:
public class FloatDemo {
public static void main(String[] args) {
float price = 19.99f;
float temperature = -40.5f;
float pi = 3.14159f;
[Link]("Price: $" + price);
[Link]("Temperature: " + temperature + "°C");
[Link]("Pi (float): " + pi);
// Scientific notation
float scientific = 1.23e-4f; // 0.000123
[Link]("Scientific: " + scientific);
}
}
Output:
Price: $19.99
Temperature: -40.5°C
Pi (float): 3.14159
Scientific: 1.23E-4
ii. double (8 bytes = 64 bits)
Characteristics:
- Double-precision floating-point
- About 15-16 significant decimal digits
- Default type for floating-point literals
- Most commonly used for decimal numbers
Example:
91
public class DoubleDemo {
public static void main(String[] args) {
double salary = 50000.50;
double pi = 3.141592653589793;
double avogadro = 6.02214076e23; // Avogadro's number
[Link]("Salary: $" + salary);
[Link]("Pi (double): " + pi);
[Link]("Avogadro's Number: " + avogadro);
// More precision than float
double preciseValue = 1.23456789012345;
[Link]("Precise value: " + preciseValue);
}
}
Output:
Salary: $50000.5
Pi (double): 3.141592653589793
Avogadro's Number: 6.02214076E23
Precise value: 1.23456789012345
float vs double Comparison:
public class FloatVsDouble {
public static void main(String[] args) {
float floatPi = 3.14159265358979323846f;
double doublePi = 3.14159265358979323846;
[Link]("float Pi: " + floatPi); // Less precision
[Link]("double Pi: " + doublePi); // More precision
}
}
Output:
float Pi: 3.1415927
double Pi: 3.141592653589793
Notice: float loses precision after ~7 digits.
C. Character Type (1 Type)
char (2 bytes = 16 bits)
Characteristics:
- Stores single character using Unicode
- Range: 0 to 65,535 (unsigned)
- Enclosed in single quotes ' '
- Can store letters, digits, symbols, special characters
92
Example:
public class CharDemo {
public static void main(String[] args) {
char grade = 'A';
char symbol = '$';
char digit = '5';
char newline = '\n';
char tab = '\t';
[Link]("Grade: " + grade);
[Link]("Symbol: " + symbol);
[Link]("Digit: " + digit);
[Link]("Before newline" + newline + "After newline");
[Link]("Before tab" + tab + "After tab");
// Unicode representation
char heart = '\u2665'; // ♥ symbol
char smiley = '\u263A'; // ☺ symbol
[Link]("Heart: " + heart);
[Link]("Smiley: " + smiley);
// ASCII value
char a = 65; // 'A'
char b = 66; // 'B'
[Link]("ASCII 65: " + a);
[Link]("ASCII 66: " + b);
}
}
Output:
Grade: A
Symbol: $
Digit: 5
Before newline
After newlineBefore tab After tab
Heart: ♥
Smiley: ☺
ASCII 65: A
ASCII 66: B
Escape Sequences:
93
Escape Meaning
\n Newline
\t Tab
\' Single quote
\" Double quote
\\ Backslash
\r Carriage return
\b Backspace
D. Boolean Type (1 Type)
boolean (1 bit)
Characteristics:
- Stores only two values: true or false
- Default value: false
- Used for logical operations and conditional statements
- Size: JVM-dependent (typically 1 byte, but logically 1 bit)
Example:
public class BooleanDemo {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isRaining = false;
boolean hasLicense = true;
[Link]("Is Java fun? " + isJavaFun);
[Link]("Is it raining? " + isRaining);
[Link]("Has license? " + hasLicense);
// Comparison operations return boolean
int age = 20;
boolean isAdult = age >= 18;
[Link]("Is adult? " + isAdult);
// Logical operations
boolean canDrive = hasLicense && isAdult;
[Link]("Can drive? " + canDrive);
}
}
Output:
94
Is Java fun? true
Is it raining? false
Has license? true
Is adult? true
Can drive? true
2️⃣ Non-Primitive Data Types (Reference Types)
Non-primitive types are created by the programmer and are used to store complex data. They
store references (addresses) to objects, not the actual values.
A. String
Characteristics:
- Stores sequence of characters
- Immutable (cannot be changed after creation)
- Enclosed in double quotes " "
- Most commonly used reference type
Example:
public class StringDemo {
public static void main(String[] args) {
String name = "John Doe";
String email = "john@[Link]";
String address = "123 Main St, Anytown, USA";
[Link]("Name: " + name);
[Link]("Email: " + email);
[Link]("Address: " + address);
// String methods
[Link]("Length: " + [Link]());
[Link]("Uppercase: " + [Link]());
[Link]("Lowercase: " + [Link]());
[Link]("Starts with 'John': " + [Link]("John"));
}
}
Output:
Name: John Doe
Email: john@[Link]
Address: 123 Main St, Anytown, USA
Length: 8
Uppercase: JOHN DOE
Lowercase: john doe
Starts with 'John': true
95
B. Arrays
Characteristics:
- Store multiple values of the same type
- Fixed size (cannot grow or shrink after creation)
- Indexed from 0 to length-1
Example:
public class ArrayDemo {
public static void main(String[] args) {
// Integer array
int[] numbers = {10, 20, 30, 40, 50};
[Link]("First number: " + numbers[0]);
[Link]("Last number: " + numbers[4]);
[Link]("Array length: " + [Link]);
// String array
String[] fruits = {"Apple", "Banana", "Orange"};
[Link]("\nFruits:");
for (int i = 0; i < [Link]; i++) {
[Link]((i+1) + ". " + fruits[i]);
}
}
}
Output:
First number: 10
Last number: 50
Array length: 5
Fruits:
1. Apple
2. Banana
3. Orange
C. Classes
Characteristics:
- User-defined data types
- Blueprints for creating objects
- Can contain variables (fields) and methods
Example:
96
// Define a class
class Student {
String name;
int age;
void displayInfo() {
[Link]("Name: " + name + ", Age: " + age);
}
}
public class ClassDemo {
public static void main(String[] args) {
// Create object
Student student1 = new Student();
[Link] = "Alice";
[Link] = 20;
[Link]();
Student student2 = new Student();
[Link] = "Bob";
[Link] = 22;
[Link]();
}
}
Output:
Name: Alice, Age: 20
Name: Bob, Age: 22
97
📊 Primitive vs Non-Primitive Comparison
Aspect Primitive Types Non-Primitive Types
Definition Built-in (predefined by Java) User-defined or library-
defined
Size Fixed size Size varies
Stores Actual value Reference (memory address)
Memory Stack Heap (object), Stack (refer‐
ence)
Default Value Depends on type (0, 0.0, null
false, ‘\u0000’)
Can Call Methods No Yes
Examples int , char , boolean , String , Array , ArrayList ,
double classes
Null Assignment Cannot be null Can be null
Example:
public class PrimitiveVsNonPrimitive {
public static void main(String[] args) {
// Primitive
int primitiveInt = 10;
[Link]("Primitive int: " + primitiveInt);
// [Link](); // ❌ Error: primitives don't have methods
// Non-Primitive (Wrapper class)
Integer nonPrimitiveInt = 10;
[Link]("Non-Primitive Integer: " + nonPrimitiveInt);
[Link]("As String: " +
[Link]()); // ✅ Can call methods
// Non-Primitive can be null
Integer nullableInt = null;
[Link]("Nullable Integer: " + nullableInt);
// int primitiveNull = null; // ❌ Error: primitives cannot be null
}
}
Output:
Primitive int: 10
Non-Primitive Integer: 10
As String: 10
Nullable Integer: null
98
🔄 Type Conversion and Casting
Type Conversion Diagram
A. Widening (Implicit/Automatic Conversion)
Definition: Converting smaller type to larger type automatically.
Direction: byte → short → int → long → float → double
No data loss, compiler does it automatically.
Example:
public class WideningDemo {
public static void main(String[] args) {
// Automatic widening
byte b = 10;
short s = b; // byte → short
int i = s; // short → int
long l = i; // int → long
float f = l; // long → float
double d = f; // float → double
[Link]("byte: " + b);
[Link]("short: " + s);
[Link]("int: " + i);
[Link]("long: " + l);
[Link]("float: " + f);
[Link]("double: " + d);
}
}
99
Output:
byte: 10
short: 10
int: 10
long: 10
float: 10.0
double: 10.0
B. Narrowing (Explicit Casting)
Definition: Converting larger type to smaller type manually.
Direction: double → float → long → int → short → byte
Possible data loss, must use explicit cast.
Syntax: (targetType) value
Example:
public class NarrowingDemo {
public static void main(String[] args) {
// Explicit narrowing
double d = 100.99;
float f = (float) d; // double → float
long l = (long) f; // float → long (loses decimal)
int i = (int) l; // long → int
short s = (short) i; // int → short
byte b = (byte) s; // short → byte
[Link]("double: " + d);
[Link]("float: " + f);
[Link]("long: " + l);
[Link]("int: " + i);
[Link]("short: " + s);
[Link]("byte: " + b);
// Data loss example
int largeInt = 130;
byte smallByte = (byte) largeInt; // Overflow!
[Link]("Large int: " + largeInt);
[Link]("Small byte: " + smallByte); // -126 (overflow)
}
}
Output:
double: 100.99
float: 100.99
long: 100
int: 100
short: 100
byte: 100
Large int: 130
Small byte: -126
100
Explanation: 130 is out of byte range (-128 to 127), causing overflow.
🔑 Key Takeaways
✅ 8 primitive types: byte, short, int, long, float, double, char, boolean
✅ int is the most common integer type, double is the most common floating-point type
✅ Primitive types store actual values directly in memory (stack)
✅ Non-primitive types store references to objects (heap)
✅ Widening (small → large) is automatic; Narrowing (large → small) requires explicit cast
✅ Primitive types have fixed size and default values
✅ Non-primitive types can be null and have methods
✅ Choose appropriate data type for memory efficiency and performance
10. Types of Variables
🤔 What is a Variable?
A variable is a named storage location in memory that holds data which can be changed during
program execution.
Analogy: Think of variables as labeled boxes:
- The label is the variable name
- The contents are the variable value
- You can change the contents but the label stays the same
🎯 Classification of Variables
Java has three types of variables based on their scope and lifetime:
1. Local Variables (Inside methods/blocks)
2. Instance Variables (Inside class, outside methods - non-static)
3. Static Variables (Inside class with static keyword - class-level)
101
📊 Variable Types Diagram
1️⃣ Local Variables
📘 Definition
Local variables are declared inside methods, constructors, or blocks. They exist only during the
execution of that method/block.
102
⚙️ Characteristics
Characteristic Description
Declared Inside methods, constructors, or blocks
Scope Only within the method/block where declared
Lifetime Created when method is called, destroyed
when method exits
Default Value No default value - must be initialized before
use
Access Modifiers Cannot use access modifiers (public, private,
protected)
Memory Stored in Stack memory
Shared No - each method call has its own copy
103
📝 Example: Local Variables
public class LocalVariableDemo {
public void calculateSum() {
// Local variables - declared inside method
int num1 = 10;
int num2 = 20;
int sum = num1 + num2;
[Link]("num1: " + num1);
[Link]("num2: " + num2);
[Link]("Sum: " + sum);
}
public void displayMessage() {
// Different method, different local variables
String message = "Hello from displayMessage!";
[Link](message);
// Cannot access num1, num2, sum from calculateSum()
// [Link](sum); // ❌ Error: cannot find symbol
}
public static void main(String[] args) {
LocalVariableDemo demo = new LocalVariableDemo();
[Link]();
[Link]();
// Cannot access local variables from methods here
// [Link](message); // ❌ Error: cannot find symbol
}
}
Output:
num1: 10
num2: 20
Sum: 30
Hello from displayMessage!
⚠️ Local Variables Must Be Initialized
public class UninitializedLocal {
public static void main(String[] args) {
int x;
// [Link](x); // ❌ Error: variable x might not have been initial‐
ized
int y = 10; // ✅ Initialized
[Link]("y: " + y);
}
}
104
Key Point: Local variables do not have default values - you must assign a value before using
them.
🔍 Scope Example
public class ScopeDemo {
public static void main(String[] args) {
int outerVar = 10;
[Link]("Outer variable: " + outerVar);
if (true) {
int innerVar = 20; // Local to this block
[Link]("Inner variable: " + innerVar);
[Link]("Can access outer: " + outerVar); // ✅ Can access
}
// [Link](innerVar); // ❌ Error: cannot find symbol
[Link]("Can still access outer: " + outerVar); // ✅ Can access
}
}
Output:
Outer variable: 10
Inner variable: 20
Can access outer: 10
Can still access outer: 10
2️⃣ Instance Variables (Non-Static)
📘 Definition
Instance variables are declared inside a class but outside methods. They belong to an instance
(object) of the class.
105
⚙️ Characteristics
Characteristic Description
Declared Inside class, outside methods (without
static )
Scope Throughout the class (all methods can access)
Lifetime Created when object is created, destroyed
when object is destroyed
Default Value Automatically initialized with default values
Access Modifiers Can use access modifiers (public, private, pro‐
tected)
Memory Stored in Heap memory (with the object)
Shared No - each object has its own copy
📊 Default Values for Instance Variables
Data Type Default Value
byte , short , int , long 0
float , double 0.0
char '\u0000' (null character)
boolean false
All object references (String, arrays, etc.) null
106
📝 Example: Instance Variables
public class Student {
// Instance variables - declared inside class, outside methods
String name; // Default: null
int age; // Default: 0
double gpa; // Default: 0.0
boolean isEnrolled; // Default: false
// Method to display student info
public void displayInfo() {
// Can access instance variables from any method
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("GPA: " + gpa);
[Link]("Enrolled: " + isEnrolled);
}
public static void main(String[] args) {
// Create first student
Student student1 = new Student();
[Link] = "Alice";
[Link] = 20;
[Link] = 3.8;
[Link] = true;
[Link]("Student 1:");
[Link]();
// Create second student
Student student2 = new Student();
[Link] = "Bob";
[Link] = 22;
[Link] = 3.5;
[Link] = true;
[Link]("\nStudent 2:");
[Link]();
// Each object has its own copy of instance variables
[Link]("\nVerification:");
[Link]("[Link]: " + [Link]);
[Link]("[Link]: " + [Link]);
}
}
Output:
107
Student 1:
Name: Alice
Age: 20
GPA: 3.8
Enrolled: true
Student 2:
Name: Bob
Age: 22
GPA: 3.5
Enrolled: true
Verification:
[Link]: Alice
[Link]: Bob
Key Point: Each object ( student1 , student2 ) has its own separate copy of instance variables.
📝 Example: Default Values
public class DefaultValuesDemo {
// Instance variables with default values
int intValue;
double doubleValue;
boolean booleanValue;
char charValue;
String stringValue;
public void displayDefaults() {
[Link]("int default: " + intValue);
[Link]("double default: " + doubleValue);
[Link]("boolean default: " + booleanValue);
[Link]("char default: [" + charValue + "]");
[Link]("String default: " + stringValue);
}
public static void main(String[] args) {
DefaultValuesDemo demo = new DefaultValuesDemo();
[Link]();
}
}
Output:
int default: 0
double default: 0.0
boolean default: false
char default: [ ]
String default: null
108
3️⃣ Static Variables (Class Variables)
📘 Definition
Static variables are declared with the static keyword inside a class but outside methods. They
belong to the class itself, not to any specific object.
⚙️ Characteristics
Characteristic Description
Declared Inside class with static keyword
Scope Throughout the class
Lifetime Created when program starts, destroyed when
program ends
Default Value Automatically initialized with default values
Access Modifiers Can use access modifiers (public, private, pro‐
tected)
Memory Stored in Method Area (part of Heap in
modern JVMs)
Shared Yes - single copy shared by all objects of the
class
Access Can be accessed without creating an object
(using class name)
109
📝 Example: Static Variables
110
public class BankAccount {
// Static variable - shared by all objects
static int totalAccounts = 0;
static String bankName = "ABC Bank";
// Instance variables - unique per object
String accountHolderName;
long accountNumber;
double balance;
// Constructor
public BankAccount(String name, long number, double balance) {
[Link] = name;
[Link] = number;
[Link] = balance;
totalAccounts++; // Increment shared counter
}
public void displayInfo() {
[Link]("Bank: " + bankName); // Access static variable
[Link]("Account Holder: " + accountHolderName);
[Link]("Account Number: " + accountNumber);
[Link]("Balance: $" + balance);
}
public static void displayTotalAccounts() {
// Static method can access static variables
[Link]("Total Accounts: " + totalAccounts);
[Link]("Bank Name: " + bankName);
// Cannot access instance variables here
// [Link](accountHolderName); // ❌ Error
}
public static void main(String[] args) {
// Access static variable without creating object
[Link]("Initial total accounts: " + [Link]);
// Create objects
BankAccount account1 = new BankAccount("Alice", 1001, 5000);
BankAccount account2 = new BankAccount("Bob", 1002, 7500);
BankAccount account3 = new BankAccount("Charlie", 1003, 3000);
[Link]("\nAccount 1:");
[Link]();
[Link]("\nAccount 2:");
[Link]();
[Link]("\nAccount 3:");
[Link]();
// Display total accounts
[Link]("\nTotal Accounts Summary:");
[Link]();
// All objects share same static variable
[Link]("\nVerification:");
[Link]("[Link]: " + [Link]);
[Link]("[Link]: " + [Link]);
[Link]("[Link]: " + [Link]);
[Link]("[Link]: " + [Link]);
111
}
}
Output:
Initial total accounts: 0
Account 1:
Bank: ABC Bank
Account Holder: Alice
Account Number: 1001
Balance: $5000.0
Account 2:
Bank: ABC Bank
Account Holder: Bob
Account Number: 1002
Balance: $7500.0
Account 3:
Bank: ABC Bank
Account Holder: Charlie
Account Number: 1003
Balance: $3000.0
Total Accounts Summary:
Total Accounts: 3
Bank Name: ABC Bank
Verification:
[Link]: 3
[Link]: 3
[Link]: 3
[Link]: 3
Key Point: totalAccounts is shared by all objects. When any object increments it, all objects see
the updated value.
112
📝 Example: Static vs Instance
public class Counter {
static int staticCount = 0; // Shared by all objects
int instanceCount = 0; // Unique per object
public void increment() {
staticCount++;
instanceCount++;
}
public void display() {
[Link]("Static Count: " + staticCount);
[Link]("Instance Count: " + instanceCount);
}
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
[Link]("After creating 3 objects:\n");
[Link]();
[Link]();
[Link]();
[Link]("\nIncrementing c1:");
[Link]();
[Link]();
[Link]("\nIncrementing c2:");
[Link]();
[Link]();
[Link]("\nIncrementing c3:");
[Link]();
[Link]();
[Link]("\nFinal state of all objects:");
[Link]("c1:"); [Link]();
[Link]("c2:"); [Link]();
[Link]("c3:"); [Link]();
}
}
Output:
113
After creating 3 objects:
Static Count: 0
Instance Count: 0
Static Count: 0
Instance Count: 0
Static Count: 0
Instance Count: 0
Incrementing c1:
Static Count: 1
Instance Count: 1
Incrementing c2:
Static Count: 2
Instance Count: 1
Incrementing c3:
Static Count: 3
Instance Count: 1
Final state of all objects:
c1:
Static Count: 3
Instance Count: 1
c2:
Static Count: 3
Instance Count: 1
c3:
Static Count: 3
Instance Count: 1
Explanation:
- staticCount : Shared - increments from 0 → 3 across all objects
- instanceCount : Not shared - each object has its own count (1 for each)
114
📊 Complete Comparison Table
Feature Local Variables Instance Variables Static Variables
Declaration Inside methods/ Inside class, outside Inside class with
blocks methods static
Scope Within method/block Throughout class Throughout class
Lifetime Method execution Object lifetime Program lifetime
Default Value None (must initialize) Auto-initialized Auto-initialized
Memory Stack Heap Method Area
Access Modifiers No Yes Yes
Shared No No (unique per ob‐ Yes (single copy for
ject) class)
Access Within method only Through object Through class name
or object
Example int x = 10; (inside int age; (inside static int count;
method) class)
115
📝 Comprehensive Example: All Variable Types
116
public class VariableTypesDemo {
// Static variable - shared by all objects
static int objectCount = 0;
static String companyName = "TechCorp";
// Instance variables - unique per object
String employeeName;
int employeeId;
double salary;
// Constructor
public VariableTypesDemo(String name, int id, double salary) {
// 'this' refers to instance variables
[Link] = name;
[Link] = id;
[Link] = salary;
// Increment static variable
objectCount++;
}
public void calculateBonus() {
// Local variables - exist only in this method
double bonusPercentage = 0.10;
double bonusAmount = salary * bonusPercentage;
String message = "Bonus calculated";
[Link]("Employee: " + employeeName);
[Link]("Salary: $" + salary);
[Link]("Bonus: $" + bonusAmount);
[Link](message);
}
public void displayInfo() {
// Can access static, instance, and local variables
String separator = "================="; // Local variable
[Link](separator);
[Link]("Company: " + companyName); // Static
[Link]("Employee: " + employeeName); // Instance
[Link]("ID: " + employeeId); // Instance
[Link]("Salary: $" + salary); // Instance
[Link](separator);
}
public static void displayCompanyInfo() {
// Static method can access only static variables
[Link]("Company: " + companyName);
[Link]("Total Employees: " + objectCount);
// Cannot access instance variables here
// [Link](employeeName); // ❌ Error
}
public static void main(String[] args) {
[Link]("Initial company info:");
[Link]();
[Link]("\nCreating employees:");
VariableTypesDemo emp1 = new VariableTypesDemo("Alice", 101, 50000);
VariableTypesDemo emp2 = new VariableTypesDemo("Bob", 102, 60000);
117
[Link]("\nEmployee 1 Details:");
[Link]();
[Link]();
[Link]("\nEmployee 2 Details:");
[Link]();
[Link]();
[Link]("\nFinal company info:");
[Link]();
}
}
Output:
Initial company info:
Company: TechCorp
Total Employees: 0
Creating employees:
Employee 1 Details:
=================
Company: TechCorp
Employee: Alice
ID: 101
Salary: $50000.0
=================
Employee: Alice
Salary: $50000.0
Bonus: $5000.0
Bonus calculated
Employee 2 Details:
=================
Company: TechCorp
Employee: Bob
ID: 102
Salary: $60000.0
=================
Employee: Bob
Salary: $60000.0
Bonus: $6000.0
Bonus calculated
Final company info:
Company: TechCorp
Total Employees: 2
🔑 Key Takeaways
✅ Local variables: Declared in methods/blocks, must be initialized, not shared
✅ Instance variables: Declared in class, auto-initialized, unique per object
✅ Static variables: Declared with static , shared by all objects, accessed via class name
✅ Local variables have no default value, instance/static variables have default values
✅ Memory: Local (Stack), Instance (Heap), Static (Method Area)
✅ Scope: Local (method), Instance/Static (class)
118
✅ Lifetime: Local (method execution), Instance (object lifetime), Static (program lifetime)
✅ Use static for shared data (counters, constants), instance for object-specific data
11. Variable Arguments (Var-arg) Method
🤔 What is Variable Arguments (Varargs)?
Variable arguments (varargs) is a feature introduced in Java 5 that allows a method to accept
zero or more arguments of the same type without explicitly defining an array.
Simple Definition: Varargs lets you pass any number of arguments to a method without worrying
about the exact count.
Syntax: dataType... variableName
The three dots ( ... ) indicate that the method can accept variable number of arguments.
🎯 Why Use Varargs?
Before Varargs (Java 1.4 and earlier)
// Without varargs - need method overloading or array
public class BeforeVarargs {
public static int sum(int a, int b) {
return a + b;
}
public static int sum(int a, int b, int c) {
return a + b + c;
}
public static int sum(int[] numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
public static void main(String[] args) {
[Link]("Sum of 2 numbers: " + sum(10, 20));
[Link]("Sum of 3 numbers: " + sum(10, 20, 30));
[Link]("Sum of array: " + sum(new int[]{10, 20, 30, 40})); //
Verbose!
}
}
119
With Varargs (Java 5+)
// With varargs - single method handles all cases
public class WithVarargs {
public static int sum(int... numbers) { // Varargs
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
public static void main(String[] args) {
[Link]("Sum of 2 numbers: " + sum(10, 20));
[Link]("Sum of 3 numbers: " + sum(10, 20, 30));
[Link]("Sum of 5 numbers: " + sum(10, 20, 30, 40, 50));
[Link]("Sum of 0 numbers: " + sum()); // Zero arguments!
}
}
Output:
Sum of 2 numbers: 30
Sum of 3 numbers: 60
Sum of 5 numbers: 150
Sum of 0 numbers: 0
Benefits:
- ✅ No need for method overloading
- ✅ Cleaner, more readable code
- ✅ Flexible - accepts 0, 1, 2, … N arguments
- ✅ Type-safe (unlike using Object[] )
📜 Varargs Rules and Restrictions
Rule 1: Only ONE Varargs Parameter Per Method
// ❌ INVALID: Multiple varargs
public static void method(int... numbers, String... names) {
// Error: Cannot have multiple varargs
}
// ✅ VALID: Single varargs
public static void method(int... numbers) {
// OK
}
120
Rule 2: Varargs Must Be LAST Parameter
// ❌ INVALID: Varargs not last
public static void method(int... numbers, String name) {
// Error: Varargs must be last parameter
}
// ✅ VALID: Varargs is last
public static void method(String name, int... numbers) {
// OK
}
Rule 3: Can Mix Regular Parameters with Varargs
// ✅ VALID: Regular parameter + varargs
public static void displayStudentMarks(String studentName, int... marks) {
[Link]("Student: " + studentName);
[Link]("Marks: ");
for (int mark : marks) {
[Link](mark + " ");
}
[Link]();
}
public static void main(String[] args) {
displayStudentMarks("Alice", 85, 90, 88);
displayStudentMarks("Bob", 78, 82, 90, 85, 88);
displayStudentMarks("Charlie", 95); // One mark
// displayStudentMarks("David"); // ❌ Error: studentName required
}
Output:
Student: Alice
Marks: 85 90 88
Student: Bob
Marks: 78 82 90 85 88
Student: Charlie
Marks: 95
121
Rule 4: Varargs is Treated as an Array Internally
public class VarargsAsArray {
public static void printNumbers(int... numbers) {
// Varargs behaves like an array
[Link]("Type: " + [Link]().getName());
[Link]("Length: " + [Link]);
// Access like array
for (int i = 0; i < [Link]; i++) {
[Link]("numbers[" + i + "]: " + numbers[i]);
}
}
public static void main(String[] args) {
printNumbers(10, 20, 30);
}
}
Output:
Type: [I
Length: 3
numbers[0]: 10
numbers[1]: 20
numbers[2]: 30
Explanation: [I means “array of int”.
📝 Comprehensive Examples
Example 1: Calculate Sum of Numbers
public class SumCalculator {
public static int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
public static void main(String[] args) {
[Link]("Sum: " + sum(10, 20));
[Link]("Sum: " + sum(5, 10, 15, 20));
[Link]("Sum: " + sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
[Link]("Sum: " + sum()); // Zero arguments
}
}
Output:
122
Sum: 30
Sum: 50
Sum: 55
Sum: 0
Example 2: Find Maximum Number
public class MaxFinder {
public static int findMax(int... numbers) {
if ([Link] == 0) {
throw new IllegalArgumentException("At least one number required");
}
int max = numbers[0];
for (int i = 1; i < [Link]; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
return max;
}
public static void main(String[] args) {
[Link]("Max: " + findMax(10, 5, 8, 20, 15));
[Link]("Max: " + findMax(100, 50, 75, 200, 150, 180));
[Link]("Max: " + findMax(42));
// [Link]("Max: " + findMax()); // Exception: no arguments
}
}
Output:
Max: 20
Max: 200
Max: 42
123
Example 3: String Concatenation
public class StringConcatenator {
public static String concatenate(String separator, String... words) {
if ([Link] == 0) {
return "";
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < [Link]; i++) {
[Link](words[i]);
if (i < [Link] - 1) {
[Link](separator);
}
}
return [Link]();
}
public static void main(String[] args) {
[Link](concatenate(", ", "Apple", "Banana", "Orange"));
[Link](concatenate(" - ", "Java", "Python", "C++", "JavaScript"));
[Link](concatenate(" | ", "One"));
[Link](concatenate(", ")); // Zero words
}
}
Output:
Apple, Banana, Orange
Java - Python - C++ - JavaScript
One
Example 4: Formatted Message Logging
public class Logger {
public static void log(String level, String message, Object... args) {
[Link]("[" + level + "] " + message);
if ([Link] > 0) {
[Link](" | Data: ");
for (Object arg : args) {
[Link](arg + " ");
}
}
[Link]();
}
public static void main(String[] args) {
log("INFO", "Application started");
log("DEBUG", "User logged in", "UserID: 123", "IP: [Link]");
log("ERROR", "Database connection failed", "Port: 3306", "Timeout: 30s");
log("WARNING", "Low memory", "Available: 10MB");
}
}
Output:
124
[INFO] Application started
[DEBUG] User logged in | Data: UserID: 123 IP: [Link]
[ERROR] Database connection failed | Data: Port: 3306 Timeout: 30s
[WARNING] Low memory | Data: Available: 10MB
Example 5: Calculate Average
public class AverageCalculator {
public static double calculateAverage(double... numbers) {
if ([Link] == 0) {
return 0.0;
}
double sum = 0;
for (double num : numbers) {
sum += num;
}
return sum / [Link];
}
public static void main(String[] args) {
[Link]("Average: " + calculateAverage(10.5, 20.3, 30.7));
[Link]("Average: " + calculateAverage(85, 90, 78, 92, 88));
[Link]("Average: " + calculateAverage(100));
[Link]("Average: " + calculateAverage());
}
}
Output:
Average: 20.5
Average: 86.6
Average: 100.0
Average: 0.0
125
🆚 Varargs vs Array Parameter
Feature Varargs Array Parameter
Syntax void method(int... nums) void method(int[] nums)
Method Call method(1, 2, 3) method(new int[]{1, 2, 3})
Zero Arguments method() ✅ method(new int[0]) or
method(null)
Readability More readable Less readable
Flexibility More flexible Less flexible
Internal Treated as array Actual array
Example Comparison:
public class VarargsVsArray {
// Varargs
public static void varargsMethod(int... numbers) {
[Link]("Varargs: ");
for (int num : numbers) {
[Link](num + " ");
}
[Link]();
}
// Array parameter
public static void arrayMethod(int[] numbers) {
[Link]("Array: ");
for (int num : numbers) {
[Link](num + " ");
}
[Link]();
}
public static void main(String[] args) {
// Varargs - cleaner syntax
varargsMethod(1, 2, 3, 4, 5);
varargsMethod(); // Zero arguments
// Array - verbose syntax
arrayMethod(new int[]{1, 2, 3, 4, 5});
arrayMethod(new int[0]); // Zero arguments
}
}
Output:
Varargs: 1 2 3 4 5
Varargs:
Array: 1 2 3 4 5
Array:
126
🔍 Common Use Cases for Varargs
1. String Formatting
[Link]("Name: %s, Age: %d", "John", 25); // Uses varargs internally
2. Mathematical Operations
[Link](10, 20); // Can be designed with varargs for multiple values
3. Collection Operations
[Link]("A", "B", "C"); // Uses varargs
4. Logging/Debugging
[Link]([Link], "Message", arg1, arg2, arg3);
⚠️ Pitfalls and Best Practices
Pitfall 1: Ambiguity with Overloading
public class AmbiguousOverloading {
public static void method(int... nums) {
[Link]("Varargs int");
}
public static void method(int num1, int num2) {
[Link]("Two ints");
}
public static void main(String[] args) {
method(10, 20); // Which method is called?
}
}
Output:
Two ints
Explanation: More specific method (fixed parameters) takes precedence over varargs.
127
Pitfall 2: Null Argument
public class NullVarargs {
public static void print(String... words) {
if (words == null) {
[Link]("Null array");
} else {
[Link]("Length: " + [Link]);
}
}
public static void main(String[] args) {
print("A", "B"); // Normal call
print(); // Zero arguments
print((String[]) null); // Explicit null
}
}
Output:
Length: 2
Length: 0
Null array
🔑 Key Takeaways
✅ Varargs allows methods to accept variable number of arguments (0 or more)
✅ Syntax: dataType... variableName
✅ Only one varargs per method, and it must be the last parameter
✅ Can mix regular parameters with varargs
✅ Varargs is treated as an array internally
✅ More readable than using arrays for variable arguments
✅ Commonly used in String formatting, logging, collections (e.g., [Link]() )
✅ Introduced in Java 5 to simplify method calls
✅ Type-safe alternative to using Object[]
🎓 Summary and Next Steps
Congratulations! You’ve completed the comprehensive guide to Java Basic Introduction. Let’s recap
what you’ve learned:
✅ Key Concepts Covered
1. Programming Language Concepts
- Classification by level, paradigm, and execution
- Java as a high-level, OOP, hybrid language
2. Introduction to Java
- WORA philosophy, key features
- Why learn Java, what you can build
128
3. Modules of Java
- Java SE (Standard Edition)
- Java EE (Enterprise Edition)
- Java ME (Micro Edition)
- JavaFX
4. History of Java
- From Oak (1991) to Java 23 (2024)
- Major milestones and LTS releases
5. Internal Architecture of JVM
- Class Loader Subsystem
- Runtime Data Areas
- Execution Engine
6. Naming Conventions
- Classes, methods, variables, constants
- Packages, enums
7. Identifiers
- Rules for valid identifiers
- Best practices
8. Reserved Words
- 50 keywords, 3 literals, 2 unused
9. Data Types
- 8 primitive types
- Non-primitive (reference) types
- Type conversion (widening and narrowing)
10. Types of Variables
◦ Local, instance, static variables
◦ Scope, lifetime, memory location
11. Variable Arguments (Varargs)
◦ Syntax, rules, restrictions
◦ Use cases and best practices
🚀 Next Steps in Your Java Journey
Now that you have a solid foundation, here’s what to learn next:
1. Operators and Expressions (Next Topic)
• Arithmetic, relational, logical, bitwise operators
• Operator precedence and associativity
2. Control Flow Statements
• if-else, switch-case
• for, while, do-while loops
• break, continue, return
129
3. Arrays
• Single and multi-dimensional arrays
• Array manipulation and iteration
4. Object-Oriented Programming
• Classes and objects (deep dive)
• Constructors
• this and super keywords
• Inheritance, polymorphism, encapsulation, abstraction
5. String Handling
• String class methods
• StringBuilder and StringBuffer
• String manipulation
6. Exception Handling
• try-catch-finally
• throw and throws
• Custom exceptions
7. Collections Framework
• ArrayList, LinkedList, HashSet, HashMap
• Iterators and comparators
8. Advanced Topics
• Multithreading
• File I/O
• Generics
• Lambda expressions and Stream API
📚 Practice Exercises
To solidify your understanding, try these exercises:
Exercise 1: Data Types and Variables
Create a program that:
- Declares variables of all 8 primitive types
- Demonstrates widening and narrowing type conversions
- Shows default values for instance variables
Exercise 2: Variable Types
Create a class Library with:
- Static variable totalBooks
- Instance variables bookName , author , price
- Methods to add books, display book info, and show total books
Exercise 3: Varargs
Create methods using varargs:
- findMin(int... numbers) - Find minimum number
130
- concatenate(String separator, String... words) - Join strings
- average(double... values) - Calculate average
💡 Important Reminders
✅ Practice regularly - Programming is a skill that improves with practice
✅ Write clean code - Follow naming conventions and best practices
✅ Understand concepts deeply - Don’t just memorize syntax
✅ Build projects - Apply what you learn in real projects
✅ Debug actively - Learn from errors and exceptions
✅ Read documentation - Java API docs are your best friend
✅ Ask questions - Use Stack Overflow, forums, communities
🎉 Congratulations!
You now have a comprehensive understanding of Java basics. This solid foundation will serve you well
as you progress to more advanced topics. Keep learning, keep coding, and most importantly, have
fun with Java! 🚀
Happy Coding! ☕
Generated with ❤️ for Java learners worldwide