Show 25 50 100
PDF
10 result(s) in Java Clear

Index

Showing 10 topics
  1. JDK, JRE and JVM
  2. Java Data Types and Wrapper Classes
  3. String, StringBuilder and StringBuffer
  4. OOP in Java
  5. Exception Handling in Java
  6. Java Collections Framework
  7. Multithreading in Java
  8. static and final in Java
  9. Java 8 Features: Lambda and Streams
  10. Java Memory and Garbage Collection
1 Index

Java source code is compiled by javac into bytecode (.class). The JVM runs that bytecode on any operating system, which makes Java platform independent.

JDK contains the JRE, the JRE contains the JVM

JDK contains the JRE, the JRE contains the JVM

Structure of a Java program Java 7 lines
public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}
// javac Hello.java   → Hello.class
// java Hello         → runs on the JVM

Q & A

  1. Why is main public static void?
    public: the JVM must call it from outside. static: it runs without creating an object. void: it returns nothing to the JVM.
  2. Is Java fully object oriented?
    Not 100%, because it has primitive types (int, char, ...) and static members.
2 Index
PrimitiveSizeWrapper
byte1 byteByte
short2 bytesShort
int4 bytesInteger
long8 bytesLong
float4 bytesFloat
double8 bytesDouble
char2 bytes (Unicode)Character
booleanJVM specificBoolean

Autoboxing converts a primitive to its wrapper automatically (int → Integer); unboxing is the reverse. Collections can only store objects, so they use wrappers.

Java 10 lines
Integer a = 5;              // autoboxing
int b = a;                  // unboxing
int n = Integer.parseInt("42");
String s = String.valueOf(99);

Integer x = 127, y = 127;
System.out.println(x == y);          // true  (cached -128..127)
Integer p = 128, q = 128;
System.out.println(p == q);          // false (different objects)
System.out.println(p.equals(q));     // true
3 Index
StringStringBuilderStringBuffer
ImmutableMutableMutable
Thread-safe (because immutable)Not thread-safeThread-safe (synchronized)
Slow for many changesFastestSlower than StringBuilder
Java 10 lines
String s1 = "hello";               // string pool
String s2 = "hello";               // same pool object
String s3 = new String("hello");   // new heap object
System.out.println(s1 == s2);      // true  (same reference)
System.out.println(s1 == s3);      // false
System.out.println(s1.equals(s3)); // true  (same content)

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) sb.append(i);
System.out.println(sb.reverse());  // 43210

Q & A

  1. == vs equals()?
    == compares references (same object?). equals() compares content. Always use equals() for strings.
  2. Why is String immutable?
    For security (class names, URLs, passwords), string pool sharing, thread safety and caching the hashCode.
4 Index
Java 17 lines
abstract class Animal {
    protected String name;
    Animal(String name) { this.name = name; }
    abstract void sound();                       // must be overridden
    void sleep() { System.out.println(name + " sleeps"); }
}

interface Pet { void play(); }

class Dog extends Animal implements Pet {
    Dog(String name) { super(name); }            // call parent constructor
    @Override void sound() { System.out.println("Woof"); }
    public void play() { System.out.println(name + " plays"); }
}

Animal a = new Dog("Tommy");   // upcasting → run-time polymorphism
a.sound();                     // Woof
  • extends — one class only; implements — many interfaces.
  • super — parent constructor or method; this — current object.
  • final class cannot be extended, final method cannot be overridden, final variable cannot be reassigned.
  • All non-static, non-final, non-private methods are virtual by default in Java.
5 Index
Checked exceptionUnchecked exception
Checked at compile timeHappens at run time
Must be caught or declared with throwsNot forced
IOException, SQLException, FileNotFoundExceptionNullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException

Hierarchy: Throwable → Error (OutOfMemoryError, StackOverflowError — do not catch) and Exception → RuntimeException (unchecked).

Java 19 lines
try {
    int[] arr = new int[3];
    arr[5] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Bad index: " + e.getMessage());
} finally {
    System.out.println("finally always runs");
}

// try-with-resources closes the reader automatically
try (BufferedReader br = new BufferedReader(new FileReader("a.txt"))) {
    System.out.println(br.readLine());
} catch (IOException e) {
    e.printStackTrace();
}

class InsufficientBalanceException extends Exception {     // custom checked exception
    InsufficientBalanceException(String msg) { super(msg); }
}

Q & A

  1. throw vs throws?
    throw actually throws one exception object inside a method. throws in the method signature declares which checked exceptions the method may throw.
  2. final vs finally vs finalize?
    final: keyword for constants / no override / no inheritance. finally: block that always runs after try-catch. finalize(): old GC hook, deprecated.
6 Index

List, Set, Queue and Map with their common implementations

List, Set, Queue and Map with their common implementations

ClassOrderDuplicatesLookup
ArrayListInsertionYesget(i) O(1)
LinkedListInsertionYesget(i) O(n)
HashSetNoneNoO(1)
TreeSetSortedNoO(log n)
HashMapNoneKeys uniqueO(1)
TreeMapSorted by keyKeys uniqueO(log n)
Java 9 lines
List<Integer> list = new ArrayList<>(List.of(5, 2, 8));
Collections.sort(list);                      // [2, 5, 8]

Map<String, Integer> freq = new HashMap<>();
for (String w : "a b a c a".split(" "))
    freq.put(w, freq.getOrDefault(w, 0) + 1);
System.out.println(freq);                    // {a=3, b=1, c=1}

Set<String> set = new TreeSet<>(List.of("b", "a", "b"));   // [a, b]

Q & A

  1. HashMap vs Hashtable?
    HashMap is not synchronized, allows one null key, faster. Hashtable is synchronized (legacy) and allows no null. For threads use ConcurrentHashMap.
  2. How does HashMap work?
    hashCode() picks a bucket; entries in the same bucket form a linked list (a red-black tree after 8 entries); equals() finds the exact key.
7 Index

A thread is a lightweight unit of execution inside a process. Create one by extending Thread or implementing Runnable (preferred).

New → Runnable → Running → Terminated

New → Runnable → Running → Terminated

Java 16 lines
class Counter {
    private int count = 0;
    public synchronized void increment() { count++; }   // one thread at a time
    public int get() { return count; }
}

Counter c = new Counter();
Runnable task = () -> { for (int i = 0; i < 1000; i++) c.increment(); };
Thread t1 = new Thread(task), t2 = new Thread(task);
t1.start(); t2.start();
t1.join();  t2.join();            // wait for both
System.out.println(c.get());      // 2000

ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(() -> System.out.println("from the pool"));
pool.shutdown();

start() creates a new thread and calls run(); calling run() directly just runs it on the current thread.

8 Index
  • static variable — one copy for the whole class.
  • static method — called with the class name; cannot use this or instance members.
  • static block — runs once when the class loads.
  • final — constant variable, method that cannot be overridden, class that cannot be extended (e.g. String).
Java 6 lines
class Config {
    static final double PI = 3.1416;   // constant
    static int instances;
    static { System.out.println("class loaded"); }
    Config() { instances++; }
}
9 Index

Java 8 added lambda expressions, functional interfaces (one abstract method), the Stream API, Optional, default methods in interfaces and the new Date/Time API.

Java 12 lines
List<String> names = List.of("Rahim", "Karim", "Sumi", "Ria");

List<String> result = names.stream()
    .filter(n -> n.length() > 3)
    .map(String::toUpperCase)
    .sorted()
    .collect(Collectors.toList());    // [KARIM, RAHIM, SUMI]

int sum = IntStream.rangeClosed(1, 100).sum();   // 5050

Optional<String> first = names.stream().filter(n -> n.startsWith("Z")).findFirst();
System.out.println(first.orElse("none"));
10 Index
  • Stack — method calls and local variables, one per thread.
  • Heap — all objects; shared by threads; divided into Young generation (Eden, Survivor) and Old generation.
  • Method area / Metaspace — class metadata and static variables.
  • An object becomes eligible for GC when no reference points to it. System.gc() is only a request.