Language Fundamentals
Syntax and Identifiers
Java follows strict rules for naming classes, variables, and methods. All variables must be explicitly declared before use. Comments are categorized into single-line (//), multi-line (/* ... */), and Javadoc (/** ... */).
Primitive and Reference Types
- Primitive types:
int,double,float,char,boolean,byte,short,long. - Reference types: Instances of classes (e.g.,
String).
float rate = 50.1f;
double preciseValue = 3.14159;
char initial = 'A';
boolean isActive = true;
Type Casting
Conversion between types follows a hierarchy from lower to higher capcaity (e.g., int to double is automatic). Casting from higher to lower requires explicit syntax, which may lead to precision loss or overflow.
long balance = 10_000_000_000L;
int reduced = (int) balance; // Potential data loss
Operators
Java supports arithmetic, relational, logical, and bitwise operators. Short-circuit logic is provided by && and ||. The ternary operator ? : offers a concise conditional alternative to if-else.
Flow Control
User Interaction
The Scanner class handles console input. Always close the scanner to prevent resource leaks.
Scanner input = new Scanner(System.in);
if (input.hasNextInt()) {
int value = input.nextInt();
}
input.close();
Iteration and Branching
- Branches:
if,else if,else, andswitch. - Loops:
while,do-while, andfor(including enhancedforfor arrays). - Control Flow:
breakterminates a loop or exits a switch, whilecontinueskips to the next iteration.
Methods and Recursion
Methods should follow camelCase naming conventions. Java uses pass-by-value, meaning primitive types are copied, while object references are passed by value of the reference.
public int calculateSum(int x, int y) {
return x + y;
}
Array Handling
Arrays are fixed-size collections. They can be initialized statically or dynamically. Advanced operations often involve utility methods in java.util.Arrays.
int[] numbers = {5, 2, 8, 1};
Arrays.sort(numbers);
Object-Oriented Programming (OOP)
Core Principles
- Encapsulation: Use
privatefields withpublicgetters/settters to protect data. - Inheritance:
extendskeyword establishes parent-child relationships. Usesuperto invoke parent constructors or methods. - Polymorphism: Overriding methods allows specific implementations in subclasses. Use
instanceofto verify object types.
Interfaces and Abstract Classes
- Abstract Classes: Declared with
abstract, cannot be instantiated, and may contain both concrete and abstract methods. - Interfaces: Defined with
interface, serve as a contract. Implementation classes must provide definitions for all declared methods.
Exception Mechanism
Java uses try-catch-finally blocks to manage runtime errors. Errors indicate serious problems (e.g., StackOverflowError), while Exception denotes conditions a program should recover from.
try {
// Risky logic
} catch (ArithmeticException e) {
e.printStackTrace();
} finally {
// Cleanup operations
}