The java.lang package provides classes fundamental to the design of the Java programming language. This package is automatically imported into every Java source file (import java.lang.* is implicit).
Instances of Class represent classes and interfaces in a running Java application.
public final class Class<T> implements Serializable, GenericDeclaration, Type, AnnotatedElement, TypeDescriptor.OfField<Class<?>>, Constable
Obtaining Class Objects
// Using class literalClass<String> clazz1 = String.class;// Using Object.getClass()String str = "example";Class<?> clazz2 = str.getClass();// Using Class.forName()Class<?> clazz3 = Class.forName("java.lang.String");
// Constantsdouble pi = Math.PI; // 3.141592653589793double e = Math.E; // 2.718281828459045// Basic operationsint max = Math.max(10, 20); // 20int min = Math.min(10, 20); // 10int abs = Math.abs(-10); // 10// Roundinglong rounded = Math.round(3.7); // 4double ceil = Math.ceil(3.2); // 4.0double floor = Math.floor(3.9); // 3.0// Power and rootsdouble pow = Math.pow(2, 8); // 256.0double sqrt = Math.sqrt(16); // 4.0double cbrt = Math.cbrt(27); // 3.0// Trigonometrydouble sin = Math.sin(Math.PI / 2); // 1.0double cos = Math.cos(0); // 1.0double tan = Math.tan(Math.PI / 4); // ~1.0// Randomdouble random = Math.random(); // [0.0, 1.0)
Thread
Represents a thread of execution in a program.
// Creating threadsThread thread = new Thread(() -> { System.out.println("Running in thread");});thread.start();// Thread operationsThread.currentThread(); // Get current threadThread.sleep(1000); // Sleep for 1 secondthread.join(); // Wait for thread to completethread.interrupt(); // Interrupt the thread// Thread propertiesthread.setName("MyThread");String name = thread.getName();thread.setPriority(Thread.MAX_PRIORITY);boolean alive = thread.isAlive();
StringBuilder and StringBuffer
Mutable sequences of characters.
// StringBuilder (not thread-safe, faster)StringBuilder sb = new StringBuilder();sb.append("Hello");sb.append(" ");sb.append("World");sb.insert(5, ",");sb.delete(0, 6);String result = sb.toString();// StringBuffer (thread-safe, synchronized)StringBuffer buffer = new StringBuffer("Initial");buffer.append(" text");
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Person person = (Person) obj; return age == person.age && Objects.equals(name, person.name); } @Override public int hashCode() { return Objects.hash(name, age); } @Override public String toString() { return "Person{name='" + name + "', age=" + age + "}"; }}