# Review No. 4

Published 2023-06-10

This page contains Java concepts (but not only) briefly explained.

# What is a literal in Java ?

A literal is any constant value which can be assigned to a variable. Examples: 35, "any string", 3.14d, 0x7e4, 0b11010.

# String literal vs String object

String literal: created in the String Pool, and we keep references. String object: created with "new String()"

# What is a Thread Scheduler in Java?

The thread scheduler is responsible (based on the priority of the threads and current status) for selecting the next thread to be executed or for stopping a thread for a moment.

# Runtime class in Java

Runtime class in Java is used to interact with JVM (you can start/stop external processes, allocate memory, work with Garbage Collector). There is only one instance of the Runtime class in the JVM (=singleton).

# How many bits are using in Unicode, ASCII, UTF-16, and UTF-8 ?

  • Unicode requires 16 bits.
  • ASCII require 7 bits (8 bits used).
  • UTF-8 represents characters using 8, 16, 24, 32 bits.
  • UTF-16 uses 16 or 32 bits.

# Does Java allow Default Arguments?

No.

# Break statement with labels in Java

first:
for( int i = 0; i < 10; i++) {
  second:
  for(int j = 0; j < 5; j ++ ) {
      // some code
      break xxxxx;
    }
}

xxxxx could be "first" or "second". The code will continue after the loop labeled with "xxxxx".

# Where import statement is placed in a Java program ?

It is allowed at the beginning of the program file after package statement.

# What environment variables are generally set up for Java programs?

CLASSPATH (location of the .class files) and PATH (the location of the executable files).

# Can we restart a thread in Java ?

A thread can only be started once in Java.

# Top-level vs Nested vs Inner classes

Top-level class (it is an OuterClass) = the main class in a .java file. Nested classes are simply static/non-static inner classes.

public class OuterClass {

    class InnerClass {
      // Some code here
    }

    static class StaticInnerClass {
      // Some code here
    }
}

# OutOfMemoryError handling

There are some ways to fix this error:

  • increase the size of the HEAP
  • use memory-efficient data structures (we can use "in-memory" databases for instance - Redis, H2)
  • reduce the number of objects being created

# constructor chaining

Constructor chaining the process of calling one constructor from another constructor. We can use "this()" or "super()".

class ClassA
{
  // default constructor 
  ClassA() {
     this(10);
     System.out.println("The Default constructor");
  }

  // constructor with one parameter
  ClassA(int x)
  {
     // some code here
  }
}

# Compiler vs Interpreter vs Transpiler

  • Compiler: high-level language --> bytecode or machine code
  • Interpreter: run the source code (high-level, bytecode or machine code) line-by-line
  • Transpiler: high-level language --> high-level language

# What a Shallow Copy/Deep Copy is in Java ?

  • Shallow copy = a reference copy. The new object receive the reference from the other one.
  • Deep copy = when we create a new object and copy the old object value to the new object (using clone() method or manually). However, for Maps is not true.

# Externalizable interface

Externalizable interface = a sub-interface of the Serializable interface, which contains writeExternal() and readExternal(), used for customizing the serialization and deserialization process.

# Reflection vs Introspection

Reflection : Introspection + the possibility to modify an object at runtime. Introspection: we can inspect the state and behavior of an object (without modifying or changing it) at runtime.

# Locale vs TimeZone class

Locale : cultural conventions and formatting rules for a specific region/country.

TimeZone: is not related to a country, but with the time zones.

# "==" operator vs equals() method

For objects, == operator compares the memory location. equals() method, compare the hashCode() values.

# volatile vs synchronized

volatile: each thread have access to the latest value of a variable (the variable is thread-safe). synchronized : only one thread can execute that code (method) at a time.

# What a Livelock is ?

A Livelock : when two or more threads keep on transferring states between one another instead of waiting infinitely as in the Deadlock.

# Copy constructor

A Copy constructor is a constructor which receive as input an object from the same class and create a new copy of that class.

class ClassA{
String department;
String service;
   ClassA(ClassA ib){
     this.departments = ib.departments;
     this.services = ib.services;
   }
}

# How can we create a shallow copy of a Map in Java ?

This is done by using the clone() method of the Map class.

Example:
HashMap<String, Integer> shallowCopiedMap = (HashMap<String, Integer>) map.clone();

# What is the search order in Maven for a dependency ?

local repository -> the Central Repository -> the remote repositories

# Can the main method be Overloaded ?

Yes, it can be. But the main method cannot be overridden because is a static class.

# Queue vs Stack

Queue: follows First-In-First-Out (FIFO) principle Stack: follows Last-In-First-Out (LIFO) principle

# Busy waiting/spinning technique

Busy spinning or waiting in multi-threading environment is a technique in which a process repeatedly checks if a particular condition is true instead of wait() or sleep() method and without releasing the CPU. This in not generally efficient. This techniques could be efficient when the condition becomes true quickly (in milliseconds, microseconds or even in nanoseconds).

# ResourceBundle class

Java ResourceBundle class (java.util.ResourceBundle) is used to store texts and components that are locale sensitive.

ResourceBundle class limitations:

  • does not support multiple bundles for the same Locale
  • we cannot have images/video/audio as data type

# Pre-emptive Scheduling vs Time Slicing Scheduler

  • Pre-emptive Scheduling: a higher-priority thread can interrupt the execution of a lower-priority thread at any time.
  • Time Slicing Scheduler: the execution of threads is divided into equal time slices, and each thread is executed for a fixed amount of time before being preempted.

The Scheduler behaviour depends on OS, the number and priority of other threads, and the availability of system resources.

# How we can access an Inner class ?

Example:
// Creating an instance of an outer class inside main()
Outer outer1 = new Outer();

// Creating an instance of inner class inside main()
Outer.Inner inner1 = outer1.new Inner();

# Can a static method be overloaded or overridden?

  • overloaded: YES
  • overridden: NO

# Can we mark as "public static" a Nested Interface ?

NO.

# java.lang.reflect.Proxy class in Java

java.lang.reflect.Proxy (Proxy Class) is used for creating dynamic proxies (objects that can be used to intercept method invocations on other objects).

# Synchronized vs Concurrent Collection

  • Synchronized Collection: thread-safe, but the entire Collection is locked.
  • Concurrent Collection: thread-safe, but NOT the entire Collection is locked (the collection is divided per segments).

# Can we make the main() thread a daemon thread?

NO, we cannot.

# AtomicInteger class

AtomicInteger class : Defines thread-safe methods for the underlying int value. The atomic operations are thread safe. This is implemented using compare-and-swap (CAS) technique.

An atomic operation is an operation that is indivisible and uninterruptible.

# Copy a list to another one

List<Integer> list1 = new ArrayList<>();
ArrayList<Integer> arrayList1 = new ArrayList<Integer>();
list1.addAll(arrayList1);

# PriorityQueue in Java

PriorityQueue is a collection class, where elements are ordered according to their priority. For the same priority, FIFO is used.

# Iterator and Enumeration interfaces

  • Iterator is a more modern interface for iterating over a collection
  • Enumeration is an older interface for iterating over a collection. It is not very used now.

# Which is the result of "System.out.println('a' + 'b' )"?

It is not "ab". ASCII values of 'a' = 97, ASCII values of 'b' = 98. The result is 97+98=195.

# keySet() and values() methods of a Map in Java

  • keySet(): returns a set of all the keys in a Map
  • values(): returns a collection of all the values in a Map

# Dictionary class in Java

Dictionary = abstract class. It is obsolete, we use Map interface now.

Example
Dictionary phoneBook = new Hashtable();

# unmodifiableCollection() method

Collections.unmodifiableCollection() method makes a Collection read-only.

# Shutdown hook in Java

A Shutdown hook in Java is a special type of thread that runs just before the JVM shuts down.

# IdentityHashMap vs HashMap classes

  • IdentityHashMap : uses reference-equality for comparison
  • HashMap: uses object values for comparison

# ThreadLocal class

The ThreadLocal class is used to create thread local variables which can only be read and written by the same thread.

set() and get() methods are used to set or to read this type of variable.