Named containers that store a value. The type (int, double, boolean, String) tells Java what kind of data to expect.
int x = 5;
double d = 3.14;
boolean flag = true;
String s = "hello";Prints text or values to the console. Use println to add a newline after, print to stay on the same line.
System.out.println("text");
System.out.print("no newline");
System.out.println("val: " + x);Runs different code based on a condition. Use else if to check additional conditions, else to catch everything that didn't match.
if (x > 0) {
// ...
} else if (x == 0) {
// ...
} else {
// ...
}Repeat a block of code. Use for when you know the count, while when you have a condition, for-each to iterate a collection.
// for
for (int i = 0; i < 10; i++) { }
// while
while (condition) { }
// for-each
for (String item : list) { }A fixed-size, ordered list of values all of the same type. Good when you know the size upfront and need fast index access.
int[] nums = {1, 2, 3};
nums[0] // access
nums.length // sizeA resizable list from the Java standard library. Use it when the number of items can grow or shrink at runtime.
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add("item");
list.get(0);
list.size();Built-in actions you can call on any String to inspect or transform its text. Always use equals() to compare strings, not ==.
s.length()
s.toUpperCase()
s.substring(0, 3)
s.indexOf(",")
s.equals("other")A class is a blueprint for objects. The constructor runs when you create a new instance and sets up its initial state.
public class Dog {
private String name;
public Dog(String name) {
this.name = name;
}
public String getName() {
return name;
}
}Lets a child class reuse and extend a parent class. Use super() to call the parent constructor, @Override to replace a parent method.
public class Dog extends Animal {
public Dog(String name) {
super(name); // call parent
}
@Override
public String sound() {
return "Woof!";
}
}A contract that any implementing class must fulfill. Use interfaces to define shared behavior across unrelated classes.
interface Printable {
void print();
}
class Doc implements Printable {
public void print() { ... }
}A partial blueprint. Abstract methods have no body and must be implemented by subclasses. Use when subclasses share some code but differ on specifics.
abstract class Shape {
public abstract double area();
}
class Circle extends Shape {
public double area() {
return Math.PI * r * r;
}
}Reads input typed by the user at the console. Always close the Scanner when done to release the underlying stream.
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
int n = sc.nextInt();
sc.close();Handles errors that might occur at runtime without crashing the program. The catch block runs only if the try block throws an exception.
try {
// risky code
} catch (Exception e) {
System.out.println(e.getMessage());
}