# Review No. 5

Published 2024-01-02

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

# What are the class members in Java ?

In Java, class members refer to the variables and methods or nested classes that are defined within a class.

# What "new" keyword is doing in Java ?

When we use the new keyword, a memory is allocated to that object and the reference for that object is returned (we can also, create the object, but this is not mandatory).

ObjectClass obj = new ObjectClass();  
Example:
var animal1 = new Animal(3, "Dog");
var animal2 = new Animal(3, "Dog");
var animal3 = animal2;

System.out.println("animal1="+animal1);
System.out.println("animal2="+animal2);
System.out.println("animal3="+animal3);

will return something like this:

animal1=com.example.demo.Animal@60094a13
animal2=com.example.demo.Animal@5aceec94
animal3=com.example.demo.Animal@5aceec94

# What is the result of System.out.println(object) in Java ?

The result is the class name (including the package) + identity hash code (in hexadecimal)

When we run

Example:
var animal = new Animal(3, "Dog");

int x = System.identityHashCode(animal);
System.out.println("x="+x);
String hex = Integer.toHexString(x);
System.out.println("hex="+hex);

System.out.println("animal="+animal);

we will receive:

x=1888639813
hex=70925b45
animal=com.example.demo.Animal@70925b45

# How can we reverse easier a String ?

String word = "ABCDEF";
String word2 = new StringBuilder(word).reverse().toString();
System.out.println(word2);

# How can we get the last character of a String ?

String word = "ABCDEF";
char lastChar = new StringBuilder(word).reverse().toString().charAt(0);
System.out.println("lastChar="+lastChar);
String word = "ABCDEF";
char lastChar = word.charAt(word.length()-1);
System.out.println("lastChar="+lastChar);

# @Deprecated vs @deprecated

  • @Deprecated is an annotation that is read by the compiler. During the compilation you will see a warning if the method marked as @Deprecated is used.

  • @deprecated is a JavaDoc tag used to provide documentation about the deprecation.

# What an object need to have in order to be serializable?

  1. to implement Serializable interface (which has no methods and acts as a marker);
  2. to have a non-argument constructor;

# Is the non-argument constructor added by the compiler ?

The compiler adds a default no-argument constructor in every Java class ONLY WHEN no constructor is defined for that class. If we define a constructor in a class, the compiler will add no additional constructor to that class.

# What is a marker interface in Java ?

A marker interface is an empty interface (no field or methods) used just to send a message to the compiler and JVM. For instance, Serializable, Cloneable and Remote (declares a set of methods that may be invoked from a remote JVM) are marker interfaces.

# What is StringTokenizer class used at ?

StringTokenizer class is used to split a string using a pattern. Please take a look at the code below:

String str = "fruit:Apple,size:Large,color:Red";

StringTokenizer tokenizer1 = new StringTokenizer(str, ",");
StringTokenizer tokenizer2 = new StringTokenizer(str, ",:");

while (tokenizer1.hasMoreElements()) {
    System.out.println("tokenizer1.nextToken() = " + tokenizer1.nextToken());
}

System.out.println("-------------------");

while (tokenizer2.hasMoreElements()) {
    System.out.println("tokenizer2.nextToken() = " + tokenizer2.nextToken());
}

and the result is :

tokenizer1.nextToken() = fruit:Apple
tokenizer1.nextToken() = size:Large
tokenizer1.nextToken() = color:Red
-------------------
tokenizer2.nextToken() = fruit
tokenizer2.nextToken() = Apple
tokenizer2.nextToken() = size
tokenizer2.nextToken() = Large
tokenizer2.nextToken() = color
tokenizer2.nextToken() = Red

The same result we can have using the split() method:

String str = "fruit:Apple,size:Large,color:Red";
String [] strArray = str.split("[:,]");
Arrays.stream(strArray).forEach(System.out::println);

# What is DelayQueue class used for ?

This is a queue which contains Delayed (interface) elements. The elements contain getDelay() method which returns the remaining delay associated with this object. An element can be taken when a wait time ("delay") assigned to that element has expired. DelayQueue is blocking (implements BlockingQueue) and unbounded.

# What are the Sets in Java ?

The Sets in Java, are Collections with no duplicates. HashSet, LinkedHashSet, EnumSet and TreeSets are implementation of Sets in Java.

For HashSet, LinkedHashSetthe check for duplication is based on hashing algorithm. For doing this we keep a hash table.

# What is Hashing ?

The Hashing is the process of converting an object into an integer value. The integer value helps in indexing and faster searches.

# Which Map class is better to use for caching ?

LinkedHashMap keeps the order of insertion or the order of access (LRU - Least Recently Used). If we are putting a limit on the LinkedHashMap we will keep in that object the LRU element or the last inserted elements.

LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)
  • accessOrder = false --> the insertion order is kept
  • accessOrder = true --> the access order is kept

# How can we sort a list ?

Using the Collections.sort() method.

Example
ArrayList<String> list = new ArrayList<>();
list.add("AAA");
list.add("BBB");
list.add("AAA");
list.add("DDD");

Collections.sort(list);

System.out.println("list = " + list);

# What Properties class is used for ?

Properties class allows String key/value pairs to be read from or written to a stream (generally a file).

Properties is a subclass of Hashtable.

# ObjectInputStream vs ObjectOutputStream

ObjectInputStream and ObjectOutputStream are used to read/write Object from/into files. The object must implement Serializable interface and must have a no-args constructor.

# Which are the SOLID principles in Java ?

SOLID principles are :

  • Single Responsibility Principle : each class must have ONE single role. For instance, if a User class have "password" attribute, it is against this principle to have a hashPassword() method in the User class. Hashing is another role and on the other hand, this could be used in another class as well.
  • Open/Closed Principle: a module (class, method) should be open to extension but closed for modification. The design of the application must be done in such a way, a new functionality must be done by adding classes not by modifying the existing ones.

  • Liskov Substitution Principle

Supposing we have in an application, a class A and 2 subclasses A1 and A2 line below:

A a1 = new A1();
A a2 = new A2();

In this case, following Liskov Substitution Principle, the references a1 and a2 must behave in the same manner.

  • Interface Segregation Principle: We need avoid large/very large interfaces if possible. This could be more difficult to design at the beginning, but in the future that makes the work easier.

  • Dependency Inversion Principle: High-level modules should not depend on low-level modules. Both should depend on abstractions.

# Which are the 6 scopes in Maven (for dependencies) ?

  • Compile (default) scope : used for build, test, run

  • Provided scope : used for build and test. The dependency is supposed to be installed on the deployment environment (web application/container)

  • Test scope : compile (the tests), run (the tests)

  • Runtime scope : used for test, run (a JDBC driver, for instance)

  • System scope (deprecated) : is similar to the provided scope, but that dependency requires us to directly point to a specific jar on the system.

  • Import scope : import the dependencies found in that dependency (it is used together with the dependency of pom type).

# What is "dependencyManagement" tag used for in Maven ?

This tag is used in multi-modules application. It is used into a pom.xml file, to specify the default version of dependencies for that project (this list of default versions could be used by the child modules as well).

# What is a BOM in Maven ?

A BOM (stands for Bill Of Materials) is a normal POM (stands for Project Object Model) file with a dependencyManagement section.

# How can we import/ used the predefined version of dependencies in a child module ?

We can:

1) inherit from the parent directly, if we are using the tag in our project

<parent>
    <groupId> </groupId>
    <artifactId> </artifactId>
    <version> </version>
</parent>

AND/OR

2) Import the BOMs as we need

This is done by adding "dependencyManagement" tag in the project's POM:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId> </groupId>
            <artifactId> </artifactId>
            <version> </version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

# What "pluginManagement" tag/element is used for in Maven POM ?

pluginManagement is used for defining versions and configurations for plugins. It is similar to dependencyManagement and it is defined in parent POM in the "build" section.

# What are the Maven profiles ?

Maven Profiles which allows to define multiple set of configurations and activate them based on certain conditions. For instance, the build will use a application.properties file specific to the activated Maven profile.

# What is Maven settings.xml file used for ?

If pom.xml keeps the project settings, the settings.xml keeps Maven settings like:

  • username/password, keys for particular repositories (for download or upload - done during "deploy" phase)
  • mirrors for repositories (for download).

# "repositories" vs "distributionManagement" in pom.xml

"repositories" - used for downloading dependencies. After download, the artifact will be kept in the local repository (".m2").

"distributionManagement" - used for uploading artifacts during "deploy" phase.

# Where are the plugins set in Maven ?

The plugins are set in pom.xml, in "build" section:

Example:
<build>
  <plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>${parent.version}</version>
    </plugin>
  <plugins>
<build>