int x = 5;
String s = "hello";
boolean flag = true;
if / else
Control
if (x > 0) {
System.out.println("Positive");
} else if (x < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
switch
Control
switch (day) {
case 1:
System.out.println("Mon");
break;
case 2:
System.out.println("Tue");
break;
default:
System.out.println("Other");
}
for Loop
Loop
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
for (String s : arr) {
System.out.println(s);
}
while / do-while
Loop
while (x < 5) {
x++;
}
do {
x--;
} while (x > 0);
break / continue
Loop
for (int i = 0; i < 10; i++) {
if (i == 5) break;
if (i % 2 == 0) continue;
System.out.println(i);
}
Methods
Function
int add(int a, int b) {
return a + b;
}
void greet(String name) {
System.out.println("Hello, " + name);
}
Method Overloading
Function
int sum(int a, int b) { return a + b; }
double sum(double a, double b) { return a + b; }
Classes & Objects
OOP
class Animal {
String name;
Animal(String n) { name = n; }
void speak() { System.out.println("Hi, I'm " + name); }
}
Animal a = new Animal("Dog");
a.speak();
Static
OOP
class MathUtil {
static int square(int x) { return x * x; }
}
int y = MathUtil.square(5);
Inheritance
OOP
class Animal {
void speak() { System.out.println("Animal"); }
}
class Dog extends Animal {
void speak() { System.out.println("Woof"); }
}
Dog d = new Dog();
d.speak();
Polymorphism
OOP
Animal a = new Dog();
a.speak(); // Woof
Abstract Classes
OOP
abstract class Shape {
abstract double area();
}
class Circle extends Shape {
double r;
Circle(double r) { this.r = r; }
double area() { return Math.PI * r * r; }
}
Interfaces
OOP
interface Drawable {
void draw();
}
class Square implements Drawable {
public void draw() { System.out.println("Draw Square"); }
}
int[] arr = {1, 2, 3};
arr[0] = 10;
System.out.println(arr.length);
Arrays.sort(arr);
for (int n : arr) {
System.out.println(n);
}
Lists
Collections
import java.util.List;
import java.util.ArrayList;
List list = new ArrayList<>();
list.add("a");
list.get(0);
list.size();
list.remove("a");
for (String s : list) {
System.out.println(s);
}
Maps
Map
import java.util.HashMap;
HashMap map = new HashMap<>();
map.put("a", 1);
map.get("a");
map.containsKey("a");
map.remove("a");
for (String k : map.keySet()) {
System.out.println(k + ": " + map.get(k));
}