Show 25 50 100
PDF
4 result(s) in Java with 2+ ★ Clear

Index

Showing 4 topics
  1. JDK, JRE and JVM
  2. String, StringBuilder and StringBuffer
  3. Exception Handling in Java
  4. Java Collections Framework
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
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.
3 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.
4 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.