Java Development Kit, Runtime, and Virtual Machine
JDK (Java Development Kit): The complete toolkit for Java development. It encompasses the Java Runtime Environment (JRE), development tools, and fundamental class libraries. The JDK provides essential utilities like javac (compiler), java (launcher), and jar (archiver) for compiling, debugging, and executing Java applications.
JRE (Java Runtime Environment): The environment required to run Java applications. It includes the Java Virtual Machine (JVM), core class libraries, and supporting files. Users can install only the JRE if they only need to run Java programs without development capabilities.
JVM (Java Virtual Machine): The execution engine that translates Java bytecode into machine-specific instructions for the host platform. The JVM is the cornerstone of Java's platform independence, enabling bytecode to execute on any system with a compatible JVM without source code modifications.
Hierarchy: JDK → JRE → JVM
- JDK: Full development environment
- JRE: Runtime-only environment for end users
- JVM: Platform-specific execution engine
For local development machines, install the full JDK. Server deployments typically require JDK configuration aswell.
Environment Configuration
- Right-click This PC → Properties → Advanced System Settings → Environment Variables
- Create a new system variable:
- Variable name:
JAVA_HOME - Variable value: Path to the JDK installation directory (e.g.,
C:\Program Files\Java\jdk-17)
- Variable name:
- Edit the Path variable and add
%JAVA_HOME%\binat the beginning - Verify installation by opening Command Prompt and running
java -version
Code Compilation and Execution
Compilation Process:
javac(Java Compiler): Translates.javasource files into.classbytecode filesjava(Java Launcher): Loads and executes the specified class, with the JVM converting bytecode to native system instructions
Java's Cross-Platform Mechanism: The JVM acts as an intermediary between Java bytecode and the operating system. Bytecode compiled on one platform runs on any platform with a JVM installed. This is the principle of "write once, run anywhere."
Command Reference:
d:— Switch drivescd— Change directoryjavac MyClass.java— Compile source filejava MyClass— Execute class
Execution Flow:
Source Code (.java) → javac Compiler → Bytecode (.class) → java Launcher → Native System Instructions
IntelliJ IDEA Setup
Creating a New Project:
- File → New → Project
Creating a Package:
- Packages organize related classes and provide namespace separation
- Right-click src folder → New → Package
Creating a Class:
- Right-click package → New → Java Class
Fundamental Java Concepts
Class Structure
class ClassName {
// Class members go here
}
Rules:
- A
.javafile can contain only onepublicclass - The
publicclass name must match the filename exactly
Comments
/**
* Documentation comment
*/
public class Example {
// Single-line comment
/*
* Multi-line comment
* spanning several lines
*/
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
Keywords
Reserved words in the Java language that have predefined meanings. Keywords cannot be used as identifiers. All Java keywords are lowercase.
Examples: class, public, static, void, final, if, else, for, while
Identifiers
Names assigned to variables, classes, methods, parameters, and constants.
Naming Rules:
- Can contain only letters, digits,
$, and_(Chinese characters compile but violate conventions) - Cannot start with a digit
- Cannot be Java keywords
Naming Conventions:
| Element | Convention | Example |
|---|---|---|
| Project | lowercase with hyphens | user-service |
| Package | all lowercase | com.example.utils |
| Class | PascalCase | UserService, HttpClient |
| Variable | camelCase | userName, totalCount |
| Constant | UPPER_SNAKE_CASE | MAX_RETRY_COUNT |
| Method | camelCase | getUser(), calculateSum() |
Principle: Names should be self-explanatory. Abbreviations are acceptable only if widely understood.
Variables and Constants
Variable: A named storage location whose value can change during program execution.
int count; // Declaration
count = 100; // Assignment
int total = 50; // Declaration with initialization
Important: Within the same scope (enclosed by {}), a variable cannot be declared twice.
Constant: A named value that cannot change after enitialization. Declared with the final keyword.
final int MAX_SIZE = 100;
MAX_SIZE = 200; // Compilation error: cannot assign to final variable
Primitive Data Types
Java provides eight primitive data types organized into four categories.
Integer Types
| Type | Size | Bits | Range | Default |
|---|---|---|---|---|
| byte | 1 | 8 | -2^7 to 2^7-1 (-128 to 127) | 0 |
| short | 2 | 16 | -2^15 to 2^15-1 | 0 |
| int | 4 | 32 | -2^31 to 2^31-1 | 0 |
| long | 8 | 64 | -2^63 to 2^63-1 | 0 |
Floating-Point Types
| Type | Size | Range Comparison | Default |
|---|---|---|---|
| float | 4 | Larger than int | 0.0f |
| double | 8 | Larger than long | 0.0 |
Character and Boolean Types
| Type | Size | Range | Default |
|---|---|---|---|
| char | 2 | 0 to 65535 (Unicode) | '\u0000' |
| boolean | 1 or 4 | true/false | false |
Range Explanation
byte: 8 bits total, with 1 sign bit and 7 magnitude bits, allowing values from -128 to 127.
Why float range exceeds long: Float uses IEEE 754 representation with separate exponent and mantissa fields, allowing representation of extremely large magnitudes despite using fewer bytes. Long stores exact integer values, so its range is limited by bit count.
Declaration Examples
byte minValue = -128;
short shortNum = 32;
int defaultInt = -999;
long bigNum = 12345L; // 'L' suffix required
float decimalNum = 3.14F; // 'F' suffix required
decimalNum = (float) 2.718; // Explicit cast
double pi = 3.14159;
char letter = 'A';
boolean flag = true;
boolean[] flags = {true, false}; // Arrays use 4 bytes per boolean
Beyond primitives, Java supports reference types with a default value of null.
Type Conversion
Implicit (Automatic) Conversion
The compiler automatically converts smaller types to larger types when no data loss occurs.
byte smallValue = 50;
int largerValue = smallValue; // byte automatically converts to int
// int to byte: Compilation error - possible data truncation
// smallValue = largerValue; // Not allowed
Explicit (Cast) Conversion
Manual conversion using the cast operator. Data loss may occur.
int intValue = 200;
byte byteValue = (byte) intValue; // Explicit cast - may cause data corruption
System.out.println(byteValue); // Output: -56 (wrapped around)
Warning: Boolean cannot be converted to or from any other type.
Special Literals
Character Literals:
int code = 'Z'; // 90 (Unicode value)
char unicodeChar = '\u03A9'; // Omega symbol (hex 03A9)
char maxChar = 65535; // Maximum char value
// Escape sequences
char newline = '\n';
char tab = '\t';
char carriageReturn = '\r';
char backslash = '\\';
char quote = '\"';
Number System Prefixes:
int binary = 0B1111; // Binary: 15
int octal = 017; // Octal: 15 (starts with 0)
int hex = 0xFF; // Hexadecimal: 255 (starts with 0x)
Input and Output
Use the Scanner class to read console input. System.in represents the standard input stream.
import java.util.Scanner;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter first number:");
int first = scanner.nextInt();
System.out.println("Enter second number:");
int second = scanner.nextInt();
System.out.println("Sum: " + (first + second));
scanner.close(); // Release system resources
}
Output Methods:
println()— Prints with newline, optional parameterprint()— Prints without newline, requires parameter
Operators
Arithmetic Operators
| Operator | Description |
|---|---|
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| / | Division |
| % | Modulo (remainder) |
Priority: Multiplication, division, and modulo execute before addition and subtraction.
Integer Arithmetic: Operations between integer types yield int. Only long operands produce long results.
Modulo Sign Rule: The sign of A % B matches the sign of A.
Increment and Decrement
int num = 10;
num++; // Post-increment: use current value, then increment
++num; // Pre-increment: increment first, then use value
num--; // Post-decrement
--num; // Pre-decrement
Example with byte type:
byte b = 20;
b++; // Allowed: auto-cast back to byte
b = (byte)(b + 1); // Required: explicit cast for compound operations
Worked Example:
int i = 1, j = 2;
int k = i++ + ++i + j++ + ++j;
// = 1 + 3 + 2 + 4
// Result: i = 3, j = 4, k = 10
Comparison Operators
| Operator | Description |
|---|---|
| > | Greater than |
| < | Less than |
| >= | Greater than or equal |
| <= | Less than or equal |
| == | Equal |
| != | Not equal |
All comparison operators return boolean (true or false).
System.out.println(10 == 10); // true
System.out.println(3.5 == 3.5f); // true
System.out.println(100 != 50); // true
Logical Operators
| Operator | Description |
|---|---|
| && | Logical AND — true only if both operands are true |
| || | Logical OR — true if at least one operand is true |
| ! | Logical NOT — inverts the boolean value |
boolean result;
result = (5 > 3) && (10 < 20); // true && true = true
result = (5 > 3) || (10 > 20); // true || false = true
result = !(true); // false
Short-Circuit Evaluation
Java optimizes logical expressions by stopping evaluation when the result is already determined.
int x = 5, y = 10;
boolean result;
// Short-circuit with AND: second operand skipped if first is false
result = (x > 10) && (y++ > 5);
System.out.println("y = " + y); // y = 10 (y++ never executed)
// Short-circuit with OR: second operand skipped if first is true
x = 5;
y = 10;
result = (x > 0) || (y++ > 20);
System.out.println("y = " + y); // y = 10 (y++ never executed)