# Review No. 3

Published 2023-06-10

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

# BlockingQueue

BlockingQueue (interface): if you want to do something on this queue type (insert/read) but you cannot do it now (no space, the element you read is not available) the thread will wait until the operation will be doable. This is a thread-safe queue. Classes which implement BlockingQueue interface: ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue. BlockingQueue interface has methods like put() and take().

# System class

System class : provides access to system resources.

Examples:

// Exits the program normally
System.exit(0);

// Exits the program with an error code
System.exit(1);

// Get Java version
String javaVersion = System.getProperty("java.version");

// Get specific environment variable
String path = System.getenv("PATH");

// List all environment variables
System.out.println("\nAll Environment Variables:");
for (String envName : System.getenv().keySet()) {
   System.out.println(envName + " = " + System.getenv(envName));
}

# File class

File class : creates objects that provide access to the files and directories of a local file system.

# break vs continue

  • break : to exit from the loop (switch, for, do, or while).
  • continue : to end the current loop iteration and return control to the loop statement.

# asList() method in Java

asList(): used to convert an array of String objects into a List of Strings.

Example:

import java.util.Arrays;
import java.util.List;

public class AsListExample {
    public static void main(String[] args) {
        
        // Creating an array of Strings
        String[] fruitsArray = { "Apple", "Banana", "Cherry", "Date" };

        // Converting the array to a List using asList()
        List<String> fruitsList = Arrays.asList(fruitsArray);

        // Printing the List
        System.out.println("Fruits List: " + fruitsList);

        // Accessing elements in the list
        System.out.println("First fruit: " + fruitsList.get(0));

        // Modifying an element in the list
        fruitsList.set(1, "Blueberry");
        System.out.println("Modified Fruits List: " + fruitsList);

        // Trying to add or remove elements (will throw UnsupportedOperationException)
        try {
            fruitsList.add("Elderberry");  // This will throw an exception
        } catch (UnsupportedOperationException e) {
            System.out.println("Cannot add elements: " + e.getMessage());
        }
    }
}

If you want to add or remove elements you need to use the following code (using new ArrayList<>()):

List<String> modifiableList = new ArrayList<>(Arrays.asList("Apple", "Banana", "Cherry"));
// This works without exception
modifiableList.add("Date");
// Output: [Apple, Banana, Cherry, Date]
System.out.println(modifiableList); 

# Serializable interface

Only the classes which implements Serializable interface can be serializable. This interface has no methods (it is a marker interface).

# Why we are handling Exceptions?

If the Exceptions are not handled, the application will stop when an exception happens.

# What is type casting?

Type casting is a way of converting data from one data type to another data type (manually or automatically).

# "System.exit(0)" and "finally" block

System.exit(0) stop the execution of the application. No other block will run (not even "finally").

# What is a daemon ?

Daemon = low priority thread, created to support the user threads. Are background threads. Its life depends on user threads.

# Which method is used to create the daemon thread ?

setDaemon(true), but before the thread starts.

# The role of the serialVersionUID in serialization

The serialVersionUID is a unique identifier that is associated with a class. This ID is used to see if a class changed to prevent deserialization errors.

# Reflexion in Java

Reflexion in Java = the possibility of examining or modifying the run time behavior of a class at run time. We can also create objects dynamically.

Reflexion = Introspection + possibility of modifying the run time behavior.

getClass() : returns the Class object that represents the type of an object.

String str1 = "AAA";
System.out.println("" + str1.getClass());

// No object created for this class
Class class1 = MyClass.class;

// We have an object created for this class
MyClass myClass = new MyClass(10);
Class class2 = myClass.getClass();

System.out.println("class2.getName() = " + class2.getName());

# Class.forName() vs ClassLoader.loadClass()

  • Class.forName(): (in Java reflection) -> loads a class using the system class loader
  • ClassLoader.loadClass(): (in Java reflection) -> loads a class using a custom class loader (lazy load is used).

# String split() method

String str1 = "AAA,BBB";
String[] words = str1.split(",");

"words" will contain two elements: "AAA" and "BBB".

# infinite loops in Java

Example no. 1
for (;;) {
   // Java code 
}
Example no. 2
while(true){
   // Java code 
}
Example no. 3
do{
   // Java code 
}while(true);

# reverse() method of the Collections class

reverse() method takes a List as an argument and returns a reversed version of the List.

Collections.reverse(cars);

# Thread priority

In Java, a thread's priority is an integer in the range 1 to 10. The larger the integer, the higher the priority. The Thread class defines these priority types as constants MIN_PRIORITY, NORM_PRIORITY, and MAX_PRIORITY, with values 1, 5, and 10, respectively. NORM_PRIORITY is the default priority for a new Thread.

To set the priority setPriority() method is used.

# Race condition in multi-thread environment

A Race condition is a situation where two or more threads access shared data simultaneously and interfere with each other's execution. A Race condition is an issue.

# What is Wrapper class in Java ?

A wrapper classes are objects encapsulating primitive Java types. (boolean, char, int = primitives; Boolean, Character, Integer = wrappers). Using wrappers, we can perform operations on primitive data types as you can perform on objects, such as storing them in Collections.

# ThreadGroup class in Java

We can associate a thread with a Thread Group. The purpose of ThreadGroup class in Java is to group related threads together for easier management.

# Nested Interface

Nested Interface = an interface which is defined inside a class or in another interface.

# NavigableSet vs SortedSet interfaces

NavigableSet is a sub interface of the SortedSet interface. NavigableSet interface provides navigation methods and descending iterator that allows the elements in the set can be traversed in descending order.

# NavigableMap interfaces

Contains some methods for retrieve elements in a Map easier:

  • descendingMap() returns a NavigableMap which is a view of the original Map. The order of the elements in this view map is reverse of the order of the original map.
  • headMap() returns a map with elements less than the specified key
  • tailMap() returns a map with elements greater than or equal to the specified key
  • subMap() returns a map with elements between two specified keys

# Cloneable interface

Cloneable interface is a marker interface. When a class implements Cloneable, we can use the clone() method.

# Ways to iterate elements of a list in Java

List<String> countries = Arrays.asList("Canada", "France", "Italy");

// using "for" loop
for (int i = 0; i < countries.size(); i++) {
    System.out.println(countries.get(i));
}

// using "for" loop
for (String country : countries) {
    System.out.println(country);
}

// Using Iterator
Iterator<String> cIterator = countries.iterator();

while(cIterator.hasNext()) {
    System.out.println(cIterator.next());
}

// Using ListIterator = extension of Iterator
// Could add elements to a List; is bidirectional
ListIterator<String> cListIterator = countries.listIterator();

while(cListIterator.hasNext()) {
    System.out.println(cListIterator.next());
}

while(cListIterator.hasPrevious()) {
    System.out.println(cListIterator.previous());
}

// Using Streams
countries.stream().forEach(country -> System.out.println(country));

# add() vs put() method

  • add() method : adds an element to the end of a List
  • put() method : adds a key-value pair to a Map

# Fail-fast vs Fail-safe iterator

  • Fail-fast iterator (on HashMap, ArrayList, Vector, HashSet) -> works on the collection directly => could throw an error if the collection is modified during iteration.
  • Fail-safe iterator (on Concurrent Collections: CopyOnWriteArrayList, ConcurrentHashMap) -> works on a copy of the collection => no errors are thrown during the iteration.

For more information you can read about Concurrent Collections.

# Load factor & capacity of a Map

The load factor is the measure that decides when to increase the capacity of the Map. The default load factor is 75% of the capacity.

# Static synchronization

Static synchronization is a form of synchronization that ensures that only one Thread can access a static method or a static variable at a time.

# statically typed vs dynamically typed languages

  • statically typed (C, C++, Java, Go): the type of variable is known at compilation time
  • dynamically typed (Python, PHP, JavaScript): the type of variable is known at runtime

# Can we mark a constructor as synchronized in Java?

YES.

# What is Scanner class used for ?

The Scanner class is used to read different data from a string, from a file, from a stream (from the keyboard, for instance).

// sc = a reference to a Scanner object
// Scanner(System.in) = the constructor of the Scanner
// System.in = the object on which the Scanner is listening
Scanner sc = new Scanner(System.in);

// String input
String name = sc.nextLine();
int age = sc.nextInt();

# What is the Spring configuration file used for ?

The Spring configuration file is used to specify the configuration of the beans and their dependencies in Spring framework.

# CLASSPATH variable

  • when we run java -jar command, Java uses the Class Path defined in the MANIFEST.MF file (-cp and -classpath are ignored completely by JVM);
  • when we run java -cp command, Java uses the Class Path specified in the command;
  • when java command has no -cp argument, the Class Path is the one specified as environment variable (OS level) (if defined).