Reserved Keywords
Keywords are strings reserved by the Java language for specific purposes. There are 50 keywords in total, all in lowercase. Note that const and goto are reserved words and cannot be used as identifiers. Additionally, true, false, and null are not keywords; they are literal values representing boolean states and empty references.
| Category | Keywords |
|---|---|
| Data Types | class, interface, enum, byte, short, int, long, float, double, char, boolean, void |
| Flow Control | if, else, switch, case, default, while, do, for, break, continue, return |
| Access Modifiers | private, protected, public |
| Class/Method Modifiers | abstract, final, static, synchronized |
| Inheritance | extends, implements |
| References & Instances | new, this, super, instanceof |
| Exception Handling | try, catch, finally, throw, throws |
| Packaging | package, import |
| Miscellaneous | native, strictfp, transient, volatile, assert, const, goto |
Identifiers
An identifier is the name used for classes, methods, variables, and other elements in Java.
Rules (Mandatory)
- Can contain letters, digits, underscores (
_), and dollar signs ($). - Must not start with a digit.
- Case-sensitive.
- Must not conflict with keywords or reserved words.
Conventions (Recommended)
- Packages: All lowercase (
com.company.project). - Classes & Interfaces: PascalCase (
UserService,Runnable). - Methods & Variables: camelCase (
userName,calculateTotal). - Constants: UPPER_SNAKE_CASE (
MAX_RETRY_COUNT,PI).
Why no leading digits? If integers were allowed at the start, the compiler couldn't distinguish between a number and a variable in expressions like
long x = 123L;. Here,123Lis a numeric literal, not a variable.
Variables and Data Types
A variable is a storage area in memory with a type. The declaration format is: DataType variableName = value;. Variables must be declared before use and are only valid within their enclosing braces {}.
Primitive Types
Java defines specific ranges for numeric types to ensure portability across operating systems.
| Type | Size (Bytes) | Range / Precision |
|---|---|---|
byte |
1 | -128 to 127 |
short |
2 | -32,768 to 32,767 |
int |
4 | -2^31 to 2^31 - 1 |
long |
8 | -2^63 to 2^63 - 1 (Suffix with L) |
float |
4 | ~7 significant digits (Suffix with f) |
double |
8 | ~15 significant digits (Default for decimals) |
char |
2 | Unicode character (0 to 65,535) |
boolean |
VM dependent | true or false |
Notes:
- Integer constants default to
int. UseLforlong(e.g.,long population = 7_000_000_000L;). - Floating-point constants default to
double. Usefforfloat. floatanddoubleare not suitable for precise financial calculations due to binary representation issues. UseBigDecimalfor currency.charuses Unicode. It can hold a letter, a Chinese character, or an escape sequence like\nor\t.booleanvalues are strictlytrue/falseand cannot be represented by0or1.
Reference Types
- String: Not a primitive type. It is immutable. Concatenation is done using
+.String greeting = "Hello"; int count = 5; String result = count + greeting; // "5Hello" // String to int conversion String numericStr = "100"; int value = Integer.parseInt(numericStr); - Arrays: Contain elements of the same type (primitive or reference). Memory is allocated contiguously.
- Declaration:
int[] scores;(Recommended) orint scores[]; - Initialization:
- Static:
int[] ids = {101, 102, 103}; - Dynamic:
double[] prices = new double[10];(Defaults to 0.0 for doubles,nullfor objects).
- Static:
- Access: Use index starting from 0.
scores[0] = 95;. - Tools:
java.util.ArraysprovidestoString(),sort(), andbinarySearch(). - Common Errors:
ArrayIndexOutOfBoundsException(bad index) andNullPointerException(array not initialized).
- Declaration:
Type Conversion
- Implicit (Automatic): Converting a smaller type to a larger type.
inttolong,longtodouble.byte,short, andcharare promoted tointduring arithmetic.
int x = 10; double y = x; // Automatic: int to double char c = 'a'; int code = c; // Automatic: char to int (gets ASCII/Unicode value) - Explicit (Cast): Converting a larger type to a smaller type. May lose precision.
double price = 19.99; int rounded = (int) price; // Cast: results in 19
Operators
Operators perform operations on variables and values.
| Category | Operators |
|---|---|
| Arithmetic | +, -, *, /, %, ++, -- |
| Assignment | =, +=, -=, *=, /=, %= |
| Relational | >, <, >=, <=, ==, != |
| Logical | &&, ` |
| Bitwise | &, ` |
| Ternary | condition ? valueIfTrue : valueIfFalse |
Key Details
- Arithmetic: Integer division truncates decimals (
5 / 2is2). The%is the remainder operator. - Increment/Decrement:
++x(pre-increment) updates before evaluation;x++(post-incerment) evaluates before updating. - Assignment: Extended operators (
+=,-=) handle type casting automatically.short s = 10; s += 5; // Valid: internal cast happens automatically // s = s + 5; // Error: requires explicit cast - Logical Short-Circuit:
&&(AND): If the left side isfalse, the right side is not evaluated.||(OR): If the left side istrue, the right side is not evaluated.
- Bitwise: Operate on individual bits.
<<(Left Shift): Multiplies by 2 per shift.>>(Right Shift): Divides by 2 per shift (sign extension).>>>(Unsigned Right Shift): Fills left bits with 0.
Number Systems & Encoding
Computers store data in Binary (base 2) using Two's Complement for signed integers. The leftmost bit indicates the sign (0 for positive, 1 for negative).
- Literals:
0b101(Binary),077(Octal),0xFF(Hex). - Conversion: Positive numbers have identical representations for Sign-Magnitude, Ones' Complement, and Two's Complement. Negative numbers in Two's Complement are calculated by inverting the bits of the positive number and adding 1.
Character Sets
Characters are mapped to binary numbers via encoding standards.
- ASCII: 7-bit encoding for English characters (128 characters).
- ISO-8859-1 (Latin-1): 8-bit encoding for Western European languages.
- GBK / GB18030: Encodings for Simplified Chinese characters (variable length: 1-4 bytes).
- Unicode: Aims to cover all characters. Java uses Unicode internally.
- UTF-8: The dominant Unicode implementation on the web. It uses 1 byte for ASCII, 3 bytes for most Chinese characters, and 4 bytes for rare symbols.