JAVA CORE CHEATSHEET
Complete Reference Guide
1. JAVA BASICS
Data Types
Type Size Range/Default
byte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
int 4 bytes -2³¹ to 2³¹-1
long 8 bytes -2⁶³ to 2⁶³-1
float 4 bytes ~6-7 significant digits
double 8 bytes ~15-17 significant digits
char 2 bytes Unicode 0 to 65,535
boolean 1 bit true/false
Variable Declaration & Initialization
int age = 25;
String name = "John";
double price = 19.99;
boolean isActive = true;
final int CONSTANT = 100; // Cannot be changed
2. OPERATORS
Arithmetic Operators
Operator Description Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus (remainder) a%b
++ Increment a++, ++a
-- Decrement a--, --a
Comparison & Logical Operators
Operator Description Example
== Equal to a == b
!= Not equal to a != b
< Less than a<b
> Greater than a>b
<= Less than or equal a <= b
>= Greater than or equal a >= b
&& Logical AND a && b
|| Logical OR a || b
! Logical NOT !a
3. CONTROL STRUCTURES
If-Else Statement
if (condition) {
// code
} else if (condition) {
// code
} else {
// code
}
Switch Statement
switch (value) {
case 1: /* code */ break;
case 2: /* code */ break;
default: /* code */
}
Loops
for (int i = 0; i < 10; i++) { }
while (condition) { }
do { } while (condition);
for (String item : collection) { } // Enhanced for
4. ARRAYS
Array Declaration & Initialization
int[] numbers = new int[5];
int[] arr = {1, 2, 3, 4, 5};
String[] names = new String[3];
int[][] matrix = new int[3][3]; // 2D array
arr[0] = 10; // Access element
[Link] // Array length
Array Methods
[Link](arr)
[Link](arr, key)
[Link](arr1, arr2)
[Link](arr, value)
[Link](arr, newLength)
5. STRINGS
String Creation & Methods
Method Description
length() Returns string length
charAt(index) Returns character at index
substring(start, end) Returns substring
toUpperCase() Converts to uppercase
toLowerCase() Converts to lowercase
trim() Removes leading/trailing spaces
startsWith(prefix) Checks if starts with prefix
endsWith(suffix) Checks if ends with suffix
contains(sequence) Checks if contains sequence
indexOf(char) Returns first index of char
replace(old, new) Replaces all occurrences
split(regex) Splits string by regex
equals(other) Compares strings (case-sensitive)
equalsIgnoreCase(other) Compares strings (case-insensitive)
compareTo(other) Lexicographic comparison
6. OBJECT-ORIENTED PROGRAMMING
Class Definition
public class ClassName {
// Fields (variables)
private int age;
// Constructor
public ClassName(int age) {
[Link] = age;
}
// Methods
public void display() {
[Link](age);
}
}
Access Modifiers
Modifier Visibility
public Accessible everywhere
protected Accessible in package and subclasses
default (no modifier) Accessible in same package
private Accessible only in same class
Inheritance
public class Child extends Parent { }
Polymorphism
Method Overriding: Same method name in parent and child class
Method Overloading: Same method name with different parameters
Interfaces & Abstract Classes
interface Shape { void draw(); }
public class Circle implements Shape { }
abstract class Animal { abstract void sound(); }
7. COLLECTIONS FRAMEWORK
List Interface
List<String> list = new ArrayList<>();
List<String> list = new LinkedList<>();
[Link](element)
[Link](index)
[Link](index)
[Link]()
[Link](element)
Set Interface
HashSet: Unordered, no duplicates, fast lookup
TreeSet: Sorted, no duplicates, slower lookup
LinkedHashSet: Insertion-ordered, no duplicates
Map Interface
Map<String, Integer> map = new HashMap<>();
[Link](key, value)
[Link](key)
[Link](key)
[Link](key)
[Link](), [Link](), [Link]()
8. EXCEPTION HANDLING
Try-Catch-Finally
try {
// Code that may throw exception
} catch (Exception e) {
// Handle exception
} finally {
// Always executes
}
Common Exceptions
NullPointerException: Accessing null object
ArrayIndexOutOfBoundsException: Invalid array index
ClassCastException: Invalid type casting
NumberFormatException: Invalid number format
IOException: Input/output error
IllegalArgumentException: Invalid argument
Throwing Exceptions
throw new Exception("Error message");
9. FILE INPUT/OUTPUT
Reading Files
FileReader fr = new FileReader("[Link]");
BufferedReader br = new BufferedReader(fr);
String line = [Link]();
Scanner sc = new Scanner(new File("[Link]"));
Writing Files
FileWriter fw = new FileWriter("[Link]");
BufferedWriter bw = new BufferedWriter(fw);
[Link]("Hello");
[Link]();
[Link]();
10. COMMONLY USED METHODS
System & Math Classes
Method Description
[Link]() Print line to console
[Link]() Current time in milliseconds
[Link]() Absolute value
[Link]() Square root
[Link](a, b) Power (a^b)
[Link](a, b) Maximum value
[Link](a, b) Minimum value
[Link]() Random double 0.0-1.0
[Link]() Round to nearest integer
Object Class Methods
equals(Object): Compare objects
hashCode(): Returns hash code
toString(): Returns string representation
getClass(): Returns class of object
11. IMPORTANT KEYWORDS
static: Class-level (shared by all instances)
final: Cannot be modified (constant)
this: Reference to current object
super: Reference to parent class
abstract: Cannot instantiate, used for abstraction
interface: Contract for classes
instanceof: Type checking operator
new: Creates new object instance
synchronized: Thread-safe method
volatile: Variable visible to all threads
12. GENERICS
Generic Collections
List<String> list = new ArrayList<String>();
Map<String, Integer> map = new HashMap<String, Integer>();
Set<Double> set = new HashSet<Double>();
List<? extends Number> list; // Bounded wildcard
List<? super Integer> list; // Lower bounded
13. LAMBDA EXPRESSIONS & STREAMS
Lambda Syntax
(parameters) -> { body }
Example: (x, y) -> x + y
Stream Operations
[Link]().filter(x -> x > 5).collect([Link]());
[Link]().map(x -> x * 2).forEach([Link]::println);
[Link]().reduce(0, Integer::sum);
[Link]().sorted().collect([Link]());
14. BEST PRACTICES
✓ Follow naming conventions (camelCase for variables, PascalCase for classes)
✓ Keep methods small and focused (Single Responsibility)
✓ Use meaningful variable and method names
✓ Handle exceptions properly, don't silently catch them
✓ Use access modifiers (private, public) appropriately
✓ Avoid null pointer exceptions - use Optional when possible
✓ Use final for constants
✓ Don't reinvent the wheel - use built-in classes and libraries
✓ Write tests for your code
✓ Comment complex logic, not obvious code
✓ Keep classes and methods cohesive
✓ Prefer composition over inheritance