#
Review No. 2
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.
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.
It is not allowed to mark a method as transient in Java.
#
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
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.
A Member Inner class can access all the variables and methods of the outer class. A Local Inner class can only access final local variables.
- The methods & class definitions are stored in Method Area (a kind of internal heap, which is not garbage collected). The loading is executed of the start of the application.
- Metaspace, like the Perm Gen, is the implementation of the Method Area in the JVM specification (from Java 8). Now, Metaspace utilizes native memory (outside JVM heap).
#
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.
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
Info
ArrayDeque and ArrayList works similarly under the hood, excepting the resizing. ArrayDeque has a default size of 16 and is always resized to a power of 2 (32, 64, 128, 256,...).
#
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
// 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
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
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
Info
- ApplicationContext is a sub-interface of BeanFactory.
SpEL
= Spring Expression Language
#
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
public class StudentService {
private final Student student;
public StudentService(Student student) {
this.student = student;
}
}
Info
- Constructor Based DI is preferred over Property-Based DI because we can mark the variable
used in the class with
final
which is not possible when we use @Autowired. - the
private
modifier make the variable encapsulated in the class. @Autowired
is needed before a constructor if we have more constructor using DI (if we have only on Constructor with DI, the annotation is optional from Spring 4.3).
Info
This approach is a good approach because:
- it is thread-safe
- the validation of the dependencies is done when the Bean is created
- easier to test (allowing easy injection of mocks)
- Field or Property-Based DI
public class StudentService {
@Autowired
private final Student student;
}
- Setter Based DI
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.
Info
- In this case we are speaking about Runtime polymorphism, also known as dynamic polymorphism (or dynamic method dispatch).
- A virtual function (or a virtual method) is a member function that can be redefined in derived classes.
#
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.