Java Fundamentals
To write good Java code, you must understand the machine it runs on: the JVM. Java is unique because it doesn’t compile to machine code directly; it compiles to a universal intermediate language.1. How Java Works (The JVM)
Unlike C++ which compiles to machine code specific to your CPU (e.g., x86 Windows), Java compiles to Bytecode.The Process
- javac: The compiler translates your human-readable source code into Bytecode (
.classfiles). This bytecode is platform-agnostic. - Classloader: When you run the app, the JVM loads these classes into memory.
- Interpreter: Initially, the JVM interprets bytecode line-by-line. This allows fast startup but is slower than native code.
- JIT (Just-In-Time) Compiler: This is the magic. The JVM watches your code run. If it sees a block of code running frequently (“hot spot”), it compiles it to Native Machine Code on the fly. This gives Java near-native performance.
2. Anatomy of a Java Program
Everything in Java is a class. There are no global functions or variables.3. Variables & Data Types
Java has a strict distinction between Primitives and Reference Types. This is a common source of confusion.Primitive Types (Stored on Stack)
These hold the actual value. They are fast, lightweight, and not objects.| Type | Size | Description |
|---|---|---|
byte | 8-bit | Very small numbers (-128 to 127) |
short | 16-bit | Small numbers |
int | 32-bit | Default for numbers. (-2B to 2B) |
long | 64-bit | Huge numbers. Use suffix L (e.g., 100L) |
float | 32-bit | Decimal. Use suffix f (e.g., 10.5f) |
double | 64-bit | Default for decimals. Precise. |
boolean | ? | true or false |
char | 16-bit | Single Unicode character |
Reference Types (Stored on Heap)
These hold a reference (memory address) to an object on the Heap. The variable itself is just a pointer.String,Integer(Wrapper),ArrayList,MyClass- Default value:
null.
Type Inference (var)
Since Java 10, you can use var to let the compiler infer the type. This reduces boilerplate but keeps type safety.
4. Control Flow
Branching
Switch Expressions (Java 14+)
The modern, concise way to switch. It returns a value and doesn’t needbreak statements (no fall-through).
Loops
1. Enhanced For-Loop (For-Each) The preferred way to iterate over arrays and collections. Readability is king.i).
5. Methods
Methods define behavior. In Java, methods must belong to a class.Overloading
You can have multiple methods with the same name but different parameters.Varargs
Pass a variable number of arguments. Internally, it’s treated as an array.Summary
- JVM: The engine that runs Java. Compiles bytecode to native code.
- Primitives: Stack-allocated values (
int,boolean). - References: Heap-allocated objects (
String,List). - Control Flow: Use modern switch expressions and enhanced for-loops for cleaner code.