# Review No. 2

Published 2023-06-10

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

# Iterator vs ListIterator

  • Iterator (interface): you can traverse elements in a Collection (which extends Iterable interface) in a forward direction
  • ListIterator (interface): you can traverse elements in a Collection in both forward and backward directions

# yield() vs sleep() vs wait() on Threads

  • yield() : a static method of Thread class which stops the currently executing thread for letting the other threads (with the same or higher priority) run. After a while, the thread will restart automatically again.

  • sleep() : a static method of Thread class which stops the currently executing thread for a specified time in milliseconds.

  • wait() : the calling thread stops its execution until notify() or notifyAll() method is invoked by some other thread. (when using Monitors).

# MessageFormat.format() vs String.format()

    Object[] arguments = { 10,
                           new Date(System.currentTimeMillis()),
                           "apple",
                           "$" 
                          };

	String result = MessageFormat.format("Today, {1, date} this {2} costs {3}{0, number}.",
				                          arguments);

	System.out.println(result);
	String name="big lakes";
	String formattedName = String.format("Today I have seen 2 %s.",name);
	System.out.println(formattedName);

The output will be something like this:

Today, Jul 16, 2023 this apple costs $10.
Today I have seen 2 big lakes.

String.format() accepts type specifiers as arguments (eg. %d for numbers, %s for strings).

# DecimalFormat class

DecimalFormat class is used for formatting numbers as per customized format and as per locale.

Example:
String pattern = "###,###.###";
DecimalFormat decimalFormat = new DecimalFormat(pattern);

String format = decimalFormat.format(3000.13);
System.out.println(format);

# transient variable

A transient variable : is not serialized during serialization and which is initialized by its default value during de-serialization. This allows you to exclude fields that are not relevant or that can be recreated dynamically.

# thread status

  • NEW − thread created but it have never run.
  • RUNNABLE − thread executing a task.
  • WAITING − when a thread waits for a signal from another thread to start (after a wait()).
  • TIMED_WAITING − starts when the timeout expire or when an event occurs (after a sleep()).
  • TERMINATED(Dead) − the thread completes its task or otherwise terminates.
  • BLOCKED − when a lock/deadlock occurs

For listing the threads statuses we can run the following Java code:

Thread.State[] states = Thread.State.values();

for (Thread.State state : states)
{
    System.out.println(state);
}

# Member Inner class vs Local Inner class

Outer.java
public class Outer {

    public class MemberInner {    }

    public static class Inner2 {    }

    public void method(){

        class LocalInner{    }
        
        LocalInner yesThisActuallyCompiles = new LocalInner();
    }
}

Local Inner class is defined into a method.

# Can we invoke an external process in Java?

Yes, by using Runtime.getRuntime().exec() method (java.lang.Runtime is a class). We can start an external process and interact with it from within our Java program.

// Create a process and execute notepad.exe. Destroy the process after 3 minutes.
Process process = Runtime.getRuntime().exec("notepad.exe");
Thread.sleep(3000);
process.destroy();

# System.out.println()

System = class

out = object

println() = method which prints a line of text to the standard output stream.

# CharSequence interface

CharSequence interface is implemented by String, StringBuffer, StringBuilder.

# toArray() method on Lists

Convert a list into an array.

ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");

String[] myArray = new String[list.size()];
list.toArray(myArray);

# compareTo() method in Java for the String

compareTo() method : compares two strings lexicographically and return an integer value(+/-) indicating their relative order.

Example:
  String s1 = "AAA";
  String s2 = "CCC";
  int result = s1.compareTo(s2);
  System.out.println(result);

This will return :

-2

# Deque interface

Deque comes from Double Ended Queue.

Deque interface (extends the Queue interface) has 3 known implementations:

  • ArrayDeque, ArrayList: provides better performance for add and remove operations at both ends of the deque
  • LinkedList: provides better performance for add and remove operations in the middle of the deque

# Collection vs Collections

  • Collection is an interface that defines the methods for working with collections in Java
  • Collections is a class which implements the Collection interface.

# Setting default Locale in Java

Example:
// set the default locale  
Locale.setDefault(new Locale("en", "US", "WIN"));  

or

-Duser.language=en -Duser.country=US

If these properties are not set, the Locale class will use the default Locale of the JVM.

# Convert a List to a Set

Example:
List list1 = new ArrayList<>(List.of("BMW", "AUDI", "DACIA", "AUDI"));
HashSet hs1 = new HashSet<>(list1);
TreeSet ts1 = new TreeSet<>(list1);

We can use new HashSet<>(list) constructor or the new TreeSet<>(list) constructor.

# Create an ArrayList from Array

Example:
String[] array = new String[]{"BMW", "Audi", "Peugeot"};

ArrayList aList = new ArrayList(List.of(array));

// is mutable
aList.add("Audi");
System.out.println("aList = " + aList);

# How we can avoid Deadlocks

  • Using timeouts
  • Use thread-safe classes and data structures
  • Always assign a different numeric value to each lock
  • Use a Deadlock detection algorithm

# stop() method for a thread

stop() method is deprecated and can cause unpredictable results. Use a boolean flag and Thread.interrupt() method instead.

# What are the modules in Core Container of Spring framework ?

The Core Container consists of :

  • Core & Beans modules - implements BeanFactory
  • Context modules - implements ApplicationContext
  • Expression Language (SpEL) module - used with @Value annotation

# What kind of testing can be done in Spring Test Module ?

Unit tests, Integration tests.

# How can we prevent users from creating more than one instance of singleton object by using clone() method ?

Add clone() method to the Singleton class and throw a CloneNotSupportedException in the clone() method.

# How can you prevent SQL Injection in Java Code ?

One way to prevent SQL injection in Java code is by using parameterized queries instead of concatenating dynamic values into the SQL statement.

# Which are the way we can inject an Object in another Object in Spring ?

  • Constructor Based DI
Example
public class StudentService {

  private final Student student;
  
  public StudentService(Student student) {
    this.student = student;
  }
}
  • Field or Property-Based DI
Example
public class StudentService {

  @Autowired
  private final Student student;
  
}
  • Setter Based DI
Example
public class StudentService {

   private final Student student;
  
   @Autowired
   public void setStudent(Student student) {
      this.student = student;
   }
}

# virtual method invocation in Java concept

If we have :

class A {
  public void test() { }
}
...
class B extends A {
  public void test() { }
}

and

A obj = new B();
obj.test();

during the runtime, the real object method will be call.

# final variable vs constant in Java

A final variable is a variable that cannot be changed after it has been assigned a value, while a constant is a variable that has a value that cannot be changed. The constants are final variables. The constants are written in uppercase (convention).

# Abstraction vs Encapsulation

Abstraction focuses on hiding implementation details and showing only the essential features of an object, while encapsulation focuses on hiding data within an object.