# Review No. 7

Published 2024-01-13

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

# What are the class members in Java ?

In Java, class members are the variables, methods, and nested classes that are defined within a class. Constructors are not members.

# What is the difference between "import static com.demo.ClassA" and "import com.demo.ClassA" ?

"import static com.demo.ClassA" will import only the static members.

# What is a Locale in Java

Locale is an object type which keeps information regarding the country and language.

# Is the return type part of the signature of a method ?

NO.

# Can we have two classes with the same name in multiple packages ?

Yes, we can. However, we can't import both classes in the same file using two import statements. We will have to fully qualify one of the class names if you really need to reference both of them.

# Can you change the access level of an overridden method in Java ?

Yes, we can, but the access level cannot be made more restrictive (the idea is to be able to use the subclass in place of the superclass).

# How can we use a specific Locale in Java ?

We need to create a Locale object with the desired language and region, and then pass the Locale object to the appropriate methods that support localization.

# Can we inherit a Constructor ?

NO.

# Is it possible to mark an interface method as static ?

Starting from Java 8 we can have default and static methods.

# What is the difference between "byte" and "char" data types in Java?

In Java, byte is a signed 8-bit type that can hold values from -128 to 127, while char is an unsigned 16-bit type (because Java uses the Unicode). You can assign a value to char, but that value (seen as a Unicode code) will be converted to a char.

# What is a "covariant return type" in Java ?

A covariant return type in Java is the ability of a subclass method to override a superclass method and return a more specific type (a SubType) than the return type of the overridden method.

# Are Pointers supported in Java ?

Pointers are not supported in Java to improve security and reduce the risk of memory-related errors.

# Why Integer class is final in Java ?

We don't need to change the behaviour of the Integer class.

# Can a constructor be private in Java?

Yes, we can have a private Constructor.

# What is a POJO in Java ?

POJO (Plain Old Java Object) is a simple Java object without rules/restrictions. Ideally, it should not implement any interface, extend any classes or contain annotations.

# Can you import a class from a package in a different project in Java ?

Yes, we can, but that the class must be available on our classpath.

# What is a transitive dependency in Maven ?

A transitive dependency in Maven is a dependency of a dependency and is automatically included in a project.

# Annotations vs Marker Interfaces ?

Annotations are more flexible -> you can add more information.

# What is a Static Class in Java ?

A Static Class is a class that only contains static members. This class cannot be instantiated. This class could be an inner class.

# static vs dynamic binding

  • Static binding (early binding) occurs at compile-time when the types of objects are determined.
  • Dynamic binding (late binding) occurs at runtime when the types of some objects are determined.

# Can an abstract class have a constructor in Java ?

Yes.

# Can an interface have a constructor in Java ?

NO.

# java.lang package

java.lang package contains classes and interfaces that are essential to the Java programming language (String, Integer, System, Math).

# Why it is not a good practice to create static variables in Java ?

Creating static variables in Java can lead to race conditions because they are not thread-safe by default.

# Anonymous classes

Anonymous classes = inner classes with no name

Example:
Employee p = new Employee(){  
     void doSomething(){
       // Some code
     }  
}; 

Internally, Anonymous classes do have a name.

# Internationalization vs localization

Both support multiple languages, regions, and cultures.

Internationalization should be implemented during the design and development phase to support multi Locales.

Localization used to adapt an existing software to multiple languages, regions, and cultures (Locale).

# JTA vs Transaction Manager vs Resource Manager

JTA (Java Transaction API) -> specification

Transaction Manager(Atomikos) --(calls)--> Resource Managers #1, #2, ... #n (database, JMS)

Transaction Manager, Resource Manager -> concepts

Atomikos -> implementation

# FileSystemResource & ClassPathResource classes

FileSystemResource - provides methods to interact with resources from the file system.

ClassPathResource - with resources that are bundled with the application, such as configuration files, templates, or other static files (can be loaded into the application context in Spring).

# Where are the classes located after Maven compilation ?

./target/classes

# What is a Maven artifact?

It is the file which is generated and will be stored in a repository (groupId, artifactId, version are used to identify an artifact).

# How can we run Maven in debug mode ?

Using the -X option.

# Are class & jar files binary files ?

Yes, class, zip and jar (Java ARchive) files are considered binary files (but technically any file is binary).

# Which are the events provided by Spring framework for ApplicationContext ?

  • ContextStartedEvent is fired when the ApplicationContext is started
  • ContextStoppedEvent is fired when the ApplicationContext is stopped
  • ContextRefreshedEvent is fired when the ApplicationContext is initialized or refreshed

# Optional dependencies in Maven

You can mark a dependency as optional in the dependency declaration. In this case, this dependency is not included in the jar file, and generally it is a transitive dependency.

# What is a MOJO in Maven ?

MOJO (Maven Old Java Object) is a Java class that represents a goal that our plugin will execute. A plugin contains one or more MOJOs.

# Which are the non-access modifiers in Java ?

final, static, abstract, synchronized

# How are the variables in Interfaces ?

In Java, an interface variable is implicitly public, static, and final.

# Memory Leak

A Memory Leak is a situation where there are objects are in the HEAP, but these are no longer used, and the garbage collector is unable to remove them from memory. There are tool which monitor the memory or/and save the content of memory and analyze it.

# Starvation

Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress.

# Which are the stereotype annotations ?

The stereotype annotations are @Component, @Repository, @Service and @Controller.

# Which Java version introduce the "var" variable declaration ?

Java 10.

# Java Records (Java 16+)

From Java 16+.

record Point(int x, int y) { }
Point p = new Point(1, 2); // Compact constructor
int x = p.x();

Records are a new kind of class for keeping immutable data.

The main purpose is to hold and transfer data.

# Sealed Classes (Java 17+)

Java 17+

A sealed class specifies a limited set of classes that can extend it.

public sealed class Animal permits Dog, Cat, Bird {
    // Class definition
}

# Virtual Threads (Java 17+)

Java 17+

Virtual Threads are lightweight, low-cost threads that are managed by the JVM.

Runnable runnable = () -> {
    for(int i=1; i<=5; i++) {
        System.out.println("Hello from Virtual Thread #" + i);
    }
};

Thread vThread = Thread.ofVirtual().start(runnable);

// We can define an unstarted thread
Thread vThreadUnstarted = Thread.ofVirtual().unstarted(runnable);

// And we can start it later
vThreadUnstarted.start();

# Sequenced collection interfaces (Java 21+)

Java 21 -> New interfaces SequencedCollection, SequencedMap and SequencedSet.

interface SequencedCollection<E> extends Collection<E> {

    // New Method
    SequencedCollection<E> reversed();

    // Methods from Deque<E>
    void addFirst(E);
    void addLast(E);

    E getFirst();
    E getLast();

    E removeFirst();
    E removeLast();
}

ArrayList, LinkedList implements SequencedCollection.

# Structured concurrency (Java 21 - Preview)

In an unstructured concurrency programming each thread could succeed or fail independently.

Using StructuredTaskScope class, we can define a scope for some concurrent thread. The current thread is the owner of "sub-threads". If we use a try-with-resources block, we don't have to handle closing the scope when we're finished.

TrafficResponse retrieveData() throws ExecutionException, InterruptedException {

  // CREATE A NEW SCOPE
  try (var scope = new StructuredTaskScope.ShutdownOnFailure) {

      // FORK RELATED SUBTASKS
      Supplier<TrafficData> highwaySubtask = scope.fork(this::retrieveHighwayData);
      Supplier<TrafficData> localSubtask = scope.fork(this::retrieveLocalData);

      // JOIN ALL TASKS IN THE SCOPE
      scope.join()
           .throwIfFailed();  // AND PROPAGATE ERRORS

      // GET THE RESULTS
      return new TrafficResponse(highwaySubtask.get(),
                                 localTraffic.get());
    }
}

Note: This example was taken from here.

# Scoped values (Java 21 - Preview)

Scoped values are values which are "visible" inside that scope. Values are efficiently shared to methods (inside that scope) without using method parameters. They are preferred to thread-local variables, especially when using large numbers of virtual threads (Scoped values are working ONLY with virtual threads).

Scoped values are immutable.

Example:
private static final ScopedValue<String> CONTEXT = ScopedValue.newInstance();

ScopedValue.runWhere(CONTEXT, "Value for CONTEXT", () -> {

runThread1();

try (var scope = new StructuredTaskScope<String>()) {

    scope.fork(() -> runThread2());
    scope.fork(() -> runThread3());

    scope.join();
}
});

In this example we can access CONTEXT scoped value in all those 3 threads (thread 1, thread 2, thread 3).

# Unnamed Classes and Instance Main Methods (Java 21 - Preview)

The main class is much simpler starting from Java 21.

Instead

Before Java 21
package com.demo.app;

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello, World!");
  }
}

in Java 21 we have :

Java 21+
void main() { 
  System.out.println("Hello, World!");
}

However, the file name HelloWorld.java will give the name of the class.

# Java 22 - Main new features

  • unnamed variables : the variable must exist for the syntax to be valid, but not used in the code -> in this case we can use underscore "_".
  • we can create/ define intermediate operations in streams using Gatherers.
  • we can add code before this() or super() constructors.

# Which are the phases of releasing a new Java feature ?

  • JEP : Java Enhancement Proposal
  • Incubator : the non-final features is put in the hands of developers, while the APIs/tools progress towards either finalization or removal in a future release.
  • Preview : the feature is fully specified, fully implemented, but still could change. It is available in a JDK feature release to provoke developer feedback based on real world use; this may lead to it becoming permanent in a future Java SE Platform.
  • Standard : the feature become permanent.