Unit 1 — Java Introduction & Flow Control
Introduction to Java, JVM/JRE/JDK, and Your First Program
Learning Objectives
● Understand what Java is and why it is platform-independent
● Differentiate JVM, JRE, and JDK
● Compare Java with C and C++
● Write, compile, and run the first Java program
1. What is Java?
Java is a high-level, object-oriented, platform-independent programming language created by James
Gosling at Sun Microsystems (1995), now owned by Oracle.
The famous Java motto is: "Write Once, Run Anywhere" (WORA).
This works because Java code is not compiled directly into machine code. Instead:
Source Code (.java) --> Compiler (javac) --> Bytecode (.class) --> JVM --> Machine Code
2. JDK, JRE, and JVM — The Beginner's Confusion, Solved
Think of it like a restaurant:
● JVM (Java Virtual Machine) = the kitchen that actually cooks (executes) the bytecode. It is
platform-specific (different JVM for Windows, Linux, Mac) but the bytecode it accepts is the same
everywhere.
● JRE (Java Runtime Environment) = JVM + libraries needed to *run* a Java program. This is what a
customer needs to eat the food (run apps), but not cook.
● JDK (Java Development Kit) = JRE + compiler (javac) + development tools. This is the full chef's
kit — needed to *write and compile* Java programs.
Component Contains Who needs it
JVM Bytecode execution engine Everyone (embedded inside JRE)
JRE JVM + core libraries End users who only run Java apps
JDK JRE + compiler + dev tools Developers (you!)
3. Java vs C vs C++
Feature C C++ Java
Paradigm Procedural Procedural + OOP Pure OOP (mostly)
Platform dependency Compiled to native Compiled to native Compiled to bytecode, runs
machine code machine code on any JVM
Pointers Yes, explicit Yes, explicit No explicit pointers
(references only)
Memory management Manual (malloc/free) Manual (new/delete) Automatic (Garbage
Collector)
Multiple inheritance N/A Yes (classes) No for classes, Yes for
interfaces
Header files Yes (.h) Yes (.h) Not needed (import
packages)
4. Your First Java Program
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Line-by-line for beginners:
● `public class HelloWorld` → declares a class named HelloWorld. The file must be saved as
[Link] (class name = file name, case-sensitive).
● `public static void main(String[] args)` → the entry point. JVM always looks for this exact signature to
start execution.
● `[Link](...)` → prints text to console with a new line at the end.
Compiling and running (from terminal):
javac [Link] // creates [Link] (bytecode)
java HelloWorld // JVM runs the bytecode
5. A Second Example — Simple Calculation
public class SimpleMath {
public static void main(String[] args) {
int a = 10;
int b = 3;
[Link]("Sum = " + (a + b));
[Link]("Product = " + (a * b));
[Link]("Division = " + (a / b)); // integer division -> 3
[Link]("Remainder = " + (a % b));
}
}
Output:
Sum = 13
Product = 30
Division = 3
Remainder = 1
Key Points
● Java achieves platform independence through bytecode + JVM.
● JDK = tools to develop; JRE = environment to run; JVM = engine that executes bytecode.
● Every standalone Java program needs a `main` method with the exact signature shown above.
● Unlike C/C++, Java has no explicit pointers and handles memory automatically.
Variables, Data Types, and Operators
Learning Objectives
● Declare and use variables correctly
● Understand Java's primitive data types and their sizes
● Apply arithmetic, relational, logical, assignment, and bitwise operators
● Understand type casting (widening and narrowing)
1. Variables
A variable is a named memory location. Java is statically typed — you must declare the type before use.
int age = 25;
double price = 99.99;
char grade = 'A';
boolean isPassed = true;
String name = "Chandan"; // String is a class, not a primitive
2. The 8 Primitive Data Types
Type Size Range (approx) Example
byte 1 byte -128 to 127 `byte b = 100;`
short 2 bytes -32,768 to 32,767 `short s = 20000;`
int 4 bytes ~ -2.1B to 2.1B `int x = 100000;`
long 8 bytes very large `long l = 100000L;`
float 4 bytes ~6-7 decimal digits `float f = 3.14f;`
precision
double 8 bytes ~15 decimal digits `double d = 3.14159;`
precision
char 2 bytes single Unicode character `char c = 'A';`
boolean 1 bit (JVM-dependent) true / false `boolean flag = false;`
Analogy: think of these types as different sized containers — `byte` is a teacup, `long` is a bucket. Pick the
smallest container that safely holds your data.
3. Example: All Data Types in Action
public class DataTypesDemo {
public static void main(String[] args) {
byte age = 20;
short year = 2026;
int population = 1400000000;
long distanceToSun = 149600000000L; // note the 'L' suffix
float pi = 3.14f; // note the 'f' suffix
double preciseValue = 3.14159265358979;
char letter = 'J';
boolean isJavaFun = true;
[Link]("Age: " + age);
[Link]("Year: " + year);
[Link]("Population: " + population);
[Link]("Distance to Sun (km): " + distanceToSun);
[Link]("Pi (float): " + pi);
[Link]("Pi (double): " + preciseValue);
[Link]("First letter: " + letter);
[Link]("Is Java fun? " + isJavaFun);
}
}
4. Type Casting
Widening (implicit, automatic) — small type to big type, no data loss:
int num = 100;
double d = num; // int -> double automatically
[Link](d); // 100.0
Narrowing (explicit, manual) — big type to small type, possible data loss:
double price = 99.99;
int rounded = (int) price; // must cast explicitly
[Link](rounded); // 99 (decimal part truncated, NOT rounded)
5. Operators with Examples
Arithmetic: `+ - * / %`
int a = 15, b = 4;
[Link](a + b); // 19
[Link](a - b); // 11
[Link](a * b); // 60
[Link](a / b); // 3 (integer division)
[Link](a % b); // 3 (remainder)
Relational: `== != > < >= <=` → always return boolean
[Link](10 > 5); // true
[Link](10 == 5); // false
Logical: `&& || !`
int marks = 85;
boolean attendance = true;
[Link](marks > 40 && attendance); // true (both conditions true)
[Link](marks > 90 || attendance); // true (one condition true)
[Link](!attendance); // false
Assignment (compound): `= += -= *= /= %=`
int x = 10;
x += 5; // x = x + 5 -> 15
x -= 3; // x = x - 3 -> 12
x *= 2; // x = x * 2 -> 24
Increment/Decrement: `++ --`
int i = 5;
[Link](i++); // prints 5, THEN increments -> i becomes 6
[Link](++i); // increments FIRST -> i becomes 7, prints 7
Bitwise (used heavily in system-level & security-related programming): `& | ^ ~ << >>`
int p = 5; // binary 0101
int q = 3; // binary 0011
[Link](p & q); // 1 (AND)
[Link](p | q); // 7 (OR)
[Link](p ^ q); // 6 (XOR)
[Link](p << 1); // 10 (left shift = multiply by 2)
[Link](p >> 1); // 2 (right shift = divide by 2)
Key Points
● Choose the smallest data type that fits your value range to save memory.
● Widening happens automatically; narrowing needs an explicit cast and can lose data.
● `%` gives the remainder, not a percentage — a very common beginner confusion.
● Post-increment (`i++`) uses the old value first; pre-increment (`++i`) uses the new value first.
Input/Output, Expressions, Comments, if-else, and switch
Learning Objectives
● Read user input using Scanner
● Understand expressions, blocks, and comment types
● Apply if-else-if ladders for decision making
● Use switch statements including modern switch expressions
1. Taking Input — the Scanner class
import [Link];
public class InputDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Enter your age: ");
int age = [Link]();
[Link]("Hello " + name + ", you are " + age + " years old.");
[Link]();
}
}
Common Scanner methods: `nextInt()`, `nextDouble()`, `nextLine()`, `next()` (single word),
`nextBoolean()`.
Beginner trap: mixing `nextInt()` then `nextLine()` — the leftover newline gets consumed by
`nextLine()`, producing an empty string. Fix: add an extra `[Link]();` after `nextInt()` if a line-read
follows.
2. Expressions, Blocks, and Comments
An expression produces a value: `a + b`, `x > 10`, `i++`.
A block is code wrapped in `{ }` — defines scope.
// single-line comment
/* multi-line
comment */
/** Javadoc comment — used to auto-generate documentation
* @author CK
*/
public class CommentDemo {
public static void main(String[] args) {
int x = 5; // block starts implicitly with the method body
{
int y = 10; // y only exists inside this inner block
[Link](x + y);
}
// y is NOT accessible here — out of scope
}
}
3. if...else — Decision Making
public class GradeCalculator {
public static void main(String[] args) {
int marks = 76;
if (marks >= 90) {
[Link]("Grade: A+");
} else if (marks >= 75) {
[Link]("Grade: A");
} else if (marks >= 60) {
[Link]("Grade: B");
} else if (marks >= 40) {
[Link]("Grade: C");
} else {
[Link]("Grade: Fail");
}
}
}
Output: `Grade: A`
4. switch Statement
Classic form (needs `break` to stop fall-through):
public class DayNameDemo {
public static void main(String[] args) {
int day = 3;
String dayName;
switch (day) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break;
case 4: dayName = "Thursday"; break;
case 5: dayName = "Friday"; break;
case 6: dayName = "Saturday"; break;
case 7: dayName = "Sunday"; break;
default: dayName = "Invalid day"; break;
}
[Link](dayName); // Wednesday
}
}
Modern switch expression (Java 14+, master-level enhancement):
public class ModernSwitchDemo {
public static void main(String[] args) {
int day = 3;
String dayName = switch (day) {
case 1, 7 -> "Weekend-adjacent";
case 2, 3, 4, 5, 6 -> "Weekday";
default -> "Invalid";
};
[Link](dayName); // Weekday
}
}
Advantages over classic switch: no fall-through bugs, no `break` needed, can return a value directly.
Key Points
● `Scanner` is the standard beginner tool for console input; remember to `close()` it.
● Comments (`//`, `/* */`, `/** */`) don't affect execution but Javadoc comments generate
documentation.
● `if-else-if` evaluates top to bottom — order conditions from most specific to least specific.
● Forgetting `break` in a classic `switch` causes fall-through — a classic beginner bug. The modern
arrow-based switch avoids this entirely.