Basics
Hello World & Structure
// File: Main.java
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
System.out.print("No newline");
System.out.printf("Name: %s, Age: %d%n", "Alice", 25);
}
}
// Comments
// Single line comment
/* Multi-line
comment */
/** Javadoc comment */
Variables
int age = 25;
double price = 9.99;
boolean active = true;
char grade = 'A';
String name = "Alice";
// Constants
final double PI = 3.14159;
final int MAX = 100;
// var (Java 10+)
var list = new ArrayList<String>();
var message = "Hello";
// Type casting
int x = (int) 3.7; // 3
double d = (double) 5; // 5.0
Data Types
Primitives
byte b = 127; // 8-bit -128 to 127
short s = 32000; // 16-bit
int i = 2_000_000; // 32-bit (default int)
long l = 9_000_000_000L; // 64-bit (needs L)
float f = 3.14f; // 32-bit (needs f)
double d = 3.14159265; // 64-bit (default)
boolean flag = true; // true/false
char c = 'A'; // unicode char (U+0041)
// Wrapper classes (for collections)
Integer, Double, Boolean, Character, Long
Operators
+ - * / % // arithmetic
++x x++ // pre/post increment
--x x-- // pre/post decrement
x += 5; x -= 2; x *= 3; x /= 2;
== != > >= < <= // comparison
&& || ! // logical
& | ^ ~ // bitwise
<< >> >>> // shift
int x = (condition) ? 1 : 0; // ternary
x instanceof String // type check
Control Flow
if / switch / loops
// if-else
if (score >= 90) {
System.out.println("A");
} else if (score >= 70) {
System.out.println("B");
} else {
System.out.println("F");
}
// switch
switch (day) {
case "Mon": System.out.println("Monday"); break;
default: System.out.println("Other");
}
// for
for (int i = 0; i < 5; i++) { System.out.println(i); }
// while
int i = 0;
while (i < 5) { System.out.println(i++); }
// for-each
for (String item : list) { System.out.println(item); }
// do-while
do { System.out.println(i++); } while (i < 5);
Arrays
Array Basics
// Declare & initialize
int[] nums = {1, 2, 3, 4, 5};
String[] names = new String[3];
names[0] = "Alice";
int len = nums.length; // 5
nums[0] // 1
// 2D array
int[][] matrix = {{1,2,3},{4,5,6}};
matrix[1][2] // 6
// Sorting
import java.util.Arrays;
Arrays.sort(nums);
Arrays.fill(nums, 0);
int[] copy = Arrays.copyOf(nums, nums.length);
System.out.println(Arrays.toString(nums));
Strings
String Methods
String s = "Hello World";
s.length() // 11
s.toUpperCase() // "HELLO WORLD"
s.toLowerCase() // "hello world"
s.trim() // remove whitespace
s.charAt(0) // 'H'
s.substring(0, 5) // "Hello"
s.indexOf("World") // 6
s.contains("World") // true
s.startsWith("He") // true
s.endsWith("ld") // true
s.replace("World","Java") // "Hello Java"
s.split(" ") // ["Hello","World"]
s.equals("Hello World") // true (use this, not ==)
s.equalsIgnoreCase("HELLO") // true
String.format("Hi %s, age %d", name, age);
// StringBuilder (mutable)
StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" ").append("World");
sb.toString(); // "Hello World"
OOP — Classes
Class & Inheritance
public class Animal {
private String name; // private field
protected int age; // accessible by subclasses
// Constructor
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
// Getter
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String speak() { return name + " makes a sound."; }
@Override
public String toString() { return "Animal(" + name + ")"; }
}
// Inheritance
public class Dog extends Animal {
public Dog(String name, int age) {
super(name, age); // call parent constructor
}
@Override
public String speak() { return getName() + " barks!"; }
}
// Interface
public interface Swimmable {
void swim(); // abstract by default
default void float_() { System.out.println("Floating"); }
}
public class Duck extends Animal implements Swimmable {
public void swim() { System.out.println("Duck swimming"); }
}
Collections
ArrayList & HashMap
import java.util.*;
// ArrayList
ArrayList<String> list = new ArrayList<>();
list.add("Alice");
list.add(0, "Bob"); // add at index
list.get(0); // "Bob"
list.set(0, "Charlie"); // update
list.remove(0); // by index
list.remove("Alice"); // by value
list.size();
list.contains("Alice");
Collections.sort(list);
// HashMap
HashMap<String,Integer> map = new HashMap<>();
map.put("age", 25);
map.get("age"); // 25
map.getOrDefault("x",0); // 0
map.containsKey("age");
map.remove("age");
for (var entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// HashSet (no duplicates)
HashSet<Integer> set = new HashSet<>();
set.add(1); set.contains(1); set.remove(1);
Exceptions
try / catch / finally
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("Always runs");
}
// Throw exception
throw new IllegalArgumentException("Invalid input");
// Custom exception
public class MyException extends RuntimeException {
public MyException(String message) {
super(message);
}
}
// throws declaration
public void readFile() throws IOException {
// ...
}