Introduction to Java
A complete beginner-friendly guide to understanding what Java is, how it works, and why it matters.
What is Java?
Java is a high-level, object-oriented, class-based programming language designed to have as few implementation dependencies as possible. It was created by James Gosling at Sun Microsystems and released in 1995. Today it is owned and maintained by Oracle Corporation.
The most important principle behind Java is "Write Once, Run Anywhere" (WORA). This means Java code compiled on one platform can run on any other platform that has a Java Virtual Machine (JVM) installed — without recompiling.
💡 Quick fact: As of 2024, Java consistently ranks among the top 3 most used programming languages worldwide (TIOBE Index).
A Brief History of Java
| Year | Milestone |
|---|---|
| 1991 | Project "Oak" started by James Gosling at Sun Microsystems |
| 1995 | Renamed to Java; officially released to the public |
| 1996 | Java 1.0 released — first stable version |
| 2004 | Java 5 — Generics, Annotations, Autoboxing introduced |
| 2014 | Java 8 — Lambda Expressions and Stream API (biggest modern update) |
| 2017 | Java 9 — Module System (Project Jigsaw) |
| 2021 | Java 17 — LTS release with Records, Sealed Classes |
| 2023 | Java 21 — LTS release with Virtual Threads (Project Loom) |
How Java Works: Compilation & Execution
Unlike C or C++ which compile directly to machine code, Java uses a two-step process:
-
Compilation: The Java compiler (
javac) converts your.javasource file into bytecode — a platform-neutral.classfile. - Execution: The Java Virtual Machine (JVM) on the target machine reads the bytecode and translates it into native machine instructions at runtime.
YourProgram.java ? [javac compiler] ? YourProgram.class (bytecode)
YourProgram.class ? [JVM on any OS] ? Runs on Windows / Mac / Linux
This two-step design is why Java is platform-independent. The bytecode is the same everywhere; only the JVM differs per operating system.
Written by you
and creates bytecode
on your operating system
on the console
Easy way to remember: You write source code,
javac translates it, and the JVM runs
the translated bytecode.
JDK vs JRE vs JVM
These three terms confuse most beginners. Here's a clear breakdown:
| Term | Full Form | What it does | Who needs it? |
|---|---|---|---|
| JVM | Java Virtual Machine | Executes bytecode. Abstract layer between Java program and OS. | Everyone (included in JRE) |
| JRE | Java Runtime Environment | JVM + core libraries needed to run Java programs. | End users who only run Java apps |
| JDK | Java Development Kit |
JRE + compiler (javac) +
debugger + dev tools.
|
Developers who write Java code |
📌 Simple rule: To write Java ? install JDK. To run a Java app ? JRE is enough.
Variables in Java
A variable is a named location used to store a value while a program runs. Every Java variable has a data type, a name, and a current value. Java is statically typed, so the type is checked when the code is compiled.
int age = 25;
String name = "Asha";
boolean isLearning = true;
The general declaration format is:
dataType variableName = value;
In the example above, int,
String, and
boolean are data types.
age, name,
and isLearning are variable names.
Declaration, initialization, and reassignment
int score; // declaration
score = 95; // initialization
score = 100; // reassignment
System.out.println(score); // 100
A local variable must be assigned a value before it is read. Java does not automatically give local variables a default value.
Common types of variables
| Kind | Declared where? | Lifetime | Example |
|---|---|---|---|
| Local variable | Inside a method, constructor, or block | Until that block finishes | int count = 0; |
| Instance variable |
Inside a class, without static
|
As long as its object exists | String title; |
| Static variable |
Inside a class, with static
|
As long as the class is loaded | static int total; |
class Student {
String name = "Ravi"; // instance variable
static int studentCount = 0; // static variable
void display() {
int marks = 85; // local variable
System.out.println(name + ": " + marks);
}
}
Constants with final
Use final when a variable should be
assigned only once. Constants are usually written in uppercase with
underscores.
final double PI = 3.14159;
// PI = 3.14; // Compile-time error: PI cannot be changed
Type inference with var
Since Java 10, var can infer the type of
a local variable from its initializer. The type is still fixed after
compilation.
var language = "Java"; // inferred as String
var version = 21; // inferred as int
// var empty; // Compile-time error: an initializer is required
Variable naming rules
-
Names may contain letters, digits,
_, and$, but cannot start with a digit. -
Names are case-sensitive:
totalandTotalare different. -
Java keywords such as
class,int, andstaticcannot be used as names. -
Use camelCase for ordinary variables, such as
totalMarks. -
Choose descriptive names instead of unclear names like
xordata1.
💡 Best practice: Declare a variable close to where it is first used, initialize it immediately when possible, and choose a name that explains what it stores.
Key Features of Java
Platform Independent
Bytecode runs on any device with a JVM — Windows, Mac, Linux, Android.
Secure
No explicit pointers. Security manager controls resource access. Bytecode verifier checks code before execution.
Object-Oriented
Everything revolves around objects and classes. Supports Encapsulation, Inheritance, Polymorphism, and Abstraction.
Multithreaded
Built-in support for concurrent execution of multiple threads, making programs faster and more responsive.
Automatic Memory Management
Garbage Collector automatically frees unused memory — no manual memory deallocation needed.
Rich Standard Library
Thousands of built-in classes for collections, I/O, networking, database access, GUI, and more.
Your First Java Program
Let's break down a simple Java program line by line.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Output
Line-by-line explanation
| Line | Explanation |
|---|---|
public class HelloWorld |
Defines a class named HelloWorld. In Java,
every program lives inside a class.
public means it's accessible
from anywhere.
|
public static void main(String[] args)
|
The entry point of every Java application.
The JVM always looks for this exact signature to start
execution. static means it
belongs to the class, not an object.
|
System.out.println(...) |
Prints text to the console followed by a newline.
System is a built-in class,
out is the standard output
stream, println is the method.
|
Print Output in Java
Java writes console output through
System.out. Use
print() when the cursor should stay on
the same line and println() when the
cursor should move to a new line. Use
printf() when you need formatted output.
System.out.print("Hello ");
System.out.println("Java");
System.out.printf("Score: %d%%", 95);
Score: 95%
-
Join text and values with
+:"Age: " + age. -
Use
%dfor integers,%ffor decimals, and%sfor strings withprintf(). -
Escape special characters with sequences such as
\nfor a new line and\tfor a tab.
Taking Input with Scanner
The Scanner class reads input from the
keyboard. Create one Scanner for
System.in, then use a method that
matches the expected type.
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println(name + " is " + age + " years old.");
scanner.close();
| Method | Reads |
|---|---|
nextInt() |
An integer |
nextDouble() |
A decimal number |
next() |
One word |
nextLine() |
A complete line, including spaces |
Common issue: After
nextInt(), call
nextLine() once to consume the pending
line break before reading the next full line.
Identifiers
Identifiers are the names given to classes, methods, variables, and other program elements. Good identifiers make code easier to understand.
class StudentProfile { // class identifier
String studentName; // variable identifier
void printProfile() { // method identifier
System.out.println(studentName);
}
}
- Use letters, digits, underscores, and dollar signs; never begin with a digit.
-
Identifiers are case-sensitive:
totalandTotaldiffer. - Do not use spaces or Java keywords.
-
Prefer
camelCasefor variables and methods, andPascalCasefor classes.
Java Keywords
Keywords are reserved words with special meaning to the compiler. They cannot be used as identifiers.
classpublicprivatestaticvoidnewifelseforwhilereturnfinalimportextendsinterface
For example, class defines a class and
return sends a value back from a method.
Java also has contextual keywords such as
var, whose meaning depends on where it
is used.
Data Types
A data type defines what kind of value a variable can hold and which operations are valid for it. Java types are divided into primitive types and reference types.
| Type | Size | Example | Use |
|---|---|---|---|
byte |
8-bit | byte level = 3; |
Very small whole numbers |
short |
16-bit | short count = 1200; |
Small whole numbers |
int |
32-bit | int age = 25; |
Default whole-number choice |
long |
64-bit |
long population = 8_000_000_000L;
|
Large whole numbers |
float |
32-bit | float rate = 2.5f; |
Single-precision decimals |
double |
64-bit | double price = 19.99; |
Default decimal choice |
char |
16-bit | char grade = 'A'; |
One UTF-16 character |
boolean |
true /
false
|
boolean active = true; |
Conditions and flags |
Reference types store a reference to an object,
such as String, arrays, and custom
classes. They can hold null; primitives
cannot.
int age = 25;Stores the value directly
String name = "Asha";Points to an object
Beginner rule: Start with
int for whole numbers and
double for decimals. Choose a
reference type when you need text, collections, arrays, or your
own objects.
Literals
A literal is a fixed value written directly in source code. Java supports several literal forms.
int decimal = 42;
int binary = 0b1010;
int hexadecimal = 0x2A;
long largeNumber = 1_000_000L;
double temperature = 36.5;
char initial = 'J';
String message = "Hello, Java";
boolean ready = true;
String nothing = null;
Use underscores to make long numbers easier to read. The underscores are ignored by the compiler and cannot appear at the beginning or end of a number.
Wrapper Classes
Wrapper classes represent primitive values as objects. They are useful with collections and APIs that require objects.
| Primitive | Wrapper |
|---|---|
int |
Integer |
double |
Double |
boolean |
Boolean |
char |
Character |
Integer boxed = 42; // autoboxing: int to Integer
int number = boxed; // unboxing: Integer to int
int value = Integer.parseInt("123");
Operators
Operators combine values and produce a result.
| Category | Operators | Example |
|---|---|---|
| Arithmetic | + - * / % |
total = price * quantity; |
| Comparison |
== != > < >= <=
|
age >= 18 |
| Logical | && || ! |
age >= 18 && citizen
|
| Assignment | = += -= *= /= |
score += 5; |
| Unary | ++ -- + - |
count++; |
| Conditional | ? : |
status = age >= 18 ? "Adult" : "Minor";
|
Remember: = assigns a
value, while == compares values. Use
equals() when comparing the contents
of most objects, especially strings.
Decision Making
Decision statements run different code depending on whether a condition is true or false.
if / else
marks = 76
marks >= 90 true?
marks >= 60 true?
int marks = 76;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 60) {
System.out.println("Grade B");
} else {
System.out.println("Needs improvement");
}
Use switch when comparing one value with
several fixed options.
int day = 2;
switch (day) {
case 1 -> System.out.println("Monday");
case 2 -> System.out.println("Tuesday");
default -> System.out.println("Another day");
}
Loops and Jump Statements
Loops repeat a block of code. Use
for when the number of repetitions is
known, while when a condition controls
repetition, and do-while when the body
must run at least once.
for (int i = 1; i <= 5; i++) {
if (i == 3) continue; // skip this iteration
if (i == 5) break; // stop the loop
System.out.println(i);
}
int attempts = 0;
while (attempts < 3) {
attempts++;
}
-
breakexits the nearest loop or switch. -
continueskips the current iteration and starts the next one. -
returnexits the current method, optionally returning a value.
Project: Number Guessing Game
Use input, variables, operators, decisions, and loops together in this beginner project. The program chooses a number from 1 to 100 and gives the player hints until the answer is found.
import java.util.Random;
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
Random random = new Random();
Scanner scanner = new Scanner(System.in);
int target = random.nextInt(100) + 1;
int attempts = 0;
int guess;
System.out.println("Guess a number from 1 to 100.");
do {
System.out.print("Your guess: ");
guess = scanner.nextInt();
attempts++;
if (guess < target) {
System.out.println("Too low!");
} else if (guess > target) {
System.out.println("Too high!");
} else {
System.out.println("Correct in " + attempts + " attempts!");
}
} while (guess != target);
scanner.close();
}
}
🎯 Challenge: Add a maximum of seven attempts, reject guesses outside 1–100, and ask the player whether they want to play again.
How to Compile & Run
Using the command line (after installing JDK):
# Step 1 — Save your file as HelloWorld.java
# Step 2 — Compile it
javac HelloWorld.java
# Step 3 — Run it
java HelloWorld
⚠️ The filename must match the class
name exactly, including capitalisation.
HelloWorld.java for
public class HelloWorld.
Where is Java Used?
- Android Development — Android apps were historically written in Java (now also Kotlin).
- Enterprise Backend — Large-scale server-side applications using Spring Boot, Hibernate, Jakarta EE.
- Web Applications — Java Servlets, JSP, and modern REST APIs.
- Big Data — Apache Hadoop, Apache Spark, and Kafka are written in Java.
- Cloud & Microservices — Popular with AWS, GCP, and Azure backend services.
- Embedded Systems & IoT — Smart cards, set-top boxes, and industrial controllers.
- Scientific Computing — Used in research tools and simulations.
Java vs Other Languages
| Feature | Java | C++ | Python |
|---|---|---|---|
| Platform Independent | ✅ Yes (JVM) | ❌ No | ✅ Yes (interpreter) |
| Memory Management | Automatic (GC) | Manual | Automatic (GC) |
| Speed | Fast (JIT compiled) | Very Fast | Slower |
| Syntax Complexity | Medium | High | Low |
| Primary Use | Enterprise, Android | Systems, Games | Data Science, Scripting |
| Strongly Typed | ✅ Yes | ✅ Yes | ❌ Dynamically typed |
