Java is a platform-independent lanugage, enabling 'write once, run anywhere' through the Java Virtual Machine (JVM). The JDK (Java Development Kit) provides tools for development, including the compiler javac and runtime environment java. To set up the environment, configure JAVA_HOME to point to the JDK installation directory and add the JDK's bin folder to the Path variable.
A basic program begins with a .java file containing a class definition. The entry point is the main method:
package com.example;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
The compilation process transforms source code into bytecode using javac, which is then executed by the JVM. Each operating system has its own JVM implementation, allowing bytecode to run seamlessly across platforms.
Identifiers—used for variables, methods, classes, and constants—must start with a letter, underscore (_), or dollar sign ($) and cannot be keywords. Use lowercase for variable names and uppercase for constants. Follow camelCase conventions for readability.
Variables store mutable data and must be declared with a type and initialized before use. Constants are defined using final:
final double PI = 3.14159;
Java supports eight primitive types: byte, short, int, long (integers); float, double (floating-point); char (single character); and boolean (true/false). For example:
int age = 25;
char grade = 'A';
boolean passed = true;
Type conversion includes implicit promotion (smaller to larger) and explicit casting (e.g., (double) 5 / 2). Note that integer division truncates decimals.
Input handling uses Scanner from java.util:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int value = scanner.nextInt();
scanner.close(); // Always close after use
Operators include arithmetic (+, -, *, /, %), comparison (==, !=, <, >), and logical (&&, ||, !). The && operator exhibits short-circuit behavior: if the left operand is false, the right is not evaluated.
Bitwise opreations such as &, |, ^, ~, <<, >>, and >>> manipulate binary representations. For instance:
int result = 12 & 11; // Binary: 1100 & 1011 → 1000 → 8
Control flow structures like if-else, switch, and loops (for, while, do-while) manage program execution. The break statement exits a loop immediately, while continue skips the current iteration.
Arrays store fixed-size sequences of elements of the same type:
int[] numbers = {1, 2, 3, 4};
System.out.println(numbers.length); // Output: 4
System.out.println(Arrays.toString(numbers)); // [1, 2, 3, 4]
Multidimensional arrays represent grids. Access elements via indices:
int[][] matrix = new int[3][3];
matrix[0][1] = 5;
System.out.println(Arrays.deepToString(matrix));
Always validate array bounds to avoid ArrayIndexOutOfBoundsException. Use length to determine size safely during iteration.