Coding Techniques
Java Basics, Syntax and Data Types · Study material
Fields have defaults, local variables do not
Instance and static fields start with 0, false, '\u0000' or null; local variables have no default and the compiler refuses to read one before it is definitely assigned. Variables live only inside the block where they are declared.
public class Main {
// Fields get default values automatically …
static int count;
static double rate;
static boolean active;
static char initial;
static String name; // reference types default to null
public static void main(String[] args) {
System.out.println(count + " " + rate + " " + active + " " + (int) initial + " " + name);
// … but LOCAL variables do not: they must be assigned before use
int total;
// System.out.println(total); compile error: variable total might not have been initialized
total = 10;
{
int inner = total * 2; // block scope: inner exists only inside these braces
System.out.println(inner);
}
System.out.println(total);
}
}
0 0.0 false 0 null 20 10
Choosing the right numeric type
| Data | Use |
|---|---|
| Counts, indexes, ages, marks | int |
| Phone numbers, IDs, timestamps in ms, file sizes | long (or String for phone numbers) |
| Measurements, scientific values | double |
| Money | long paise/cents or java.math.BigDecimal – never double |
| Yes/no flags | boolean |
| Single characters | char |
| Raw bytes from files or networks | byte |
Detecting overflow instead of ignoring it
int a = 2_000_000_000, b = 2_000_000_000;
int wrong = a + b; // -294967296: silent wrap-around
long right = (long) a + b; // 4000000000: widen BEFORE adding
int safe = Math.addExact(a, b); // throws ArithmeticException: integer overflow
// Same idea for multiplication
long bytes = 1024 * 1024 * 1024 * 4; // ✘ overflows in int, then widened: 0
long bytes2 = 1024L * 1024 * 1024 * 4; // ✔ 4294967296 Java basics checklist
- One public class per file, named like the file.
- Follow naming conventions: ClassName, methodName, CONSTANT_NAME.
- Use int by default, long for big counts, double for measurements, BigDecimal for money.
- Add L and f suffixes; use underscores in long literals.
- Use var only when the type is obvious from the right-hand side.
- Make values that never change final.
- Format output with printf/String.format instead of long + chains.