#
Review No. 1
This page contains Java concepts (but not only) briefly explained.
#
convention-over-configuration concept
Some configurations are done automatically based on conventions. For instance, a data source bean could be created automatically when a JDBC driver is a dependency and the information needed for configuration are in the application.properties file.
#
JIT vs. AOT
JIT = Just in Time Compilation AOT = Ahead of Time Compilation
Java Code ---> javac compiler (the default) --> Bytecode (platform independent) --> JVM (contains JIT compiler) --> machine code (platform specific)
Java Code ---> Java AOT compiler ---> machine code
JIT : platform independent
AOT : faster, low memory print (works better for containers) - see GraalVM.
#
ClassLoader
The ClassLoader in Java is a subsystem of Java Virtual Machine, dedicated to loading class files when a program is executed.
#
public static void main
public static void main or static public void main ? Response: both are ok, because in Java the order of modifiers is not important.
#
String plus numbers
System.out.println(100 + 200 +"ABC"); => 300ABC
System.out.println("ABC" + 100 + 200); => ABC100200
#
Is Java Virtual Machine (JVM) written in Java ?
Today, the Java compiler is written in Java, while the JRE is written in C. The C language allows the JVM to interact directly with the underlying operating system and hardware.
#
Java = pure Object Oriented Language ?
No, because Java supports primitive data types (byte, boolean, char, short, int, float, long, and double).
#
Object based vs OOP programming languages
Object based programming languages (JavaScript, for instance) follow all the features of OOPs except Inheritance.
#
Why does Java not make use of pointers ?
Pointers are complicated and unsafe to use by beginner programmers. Java focuses on code simplicity, security.
#
Variables used in a switch statement
Variables used in a switch statement could be : int, enum, byte, short, char, String, Integer.
#
Class vs instance vs local variable
Class variables (static variables) : declared in a class, but outside a method or a constructor. Are accessible by all the class instances.
Instance variables : are accessible by all the methods in the class.
Local variables : created in a block, function, or constructor and can be accessed only inside them.
Info
- The instance variables, have default values: for an int variable is 0, for a boolean variable, it is false, and for a String variable, it is null.
- The local variables are not initialized to any default value, neither primitives nor object references (local variables must be initialized before they can be used, otherwise we will receive an error).
#
static blocks
It is used to initialize the static data members, and it is executed before main method at the time of classloading.
#
java.util.regex package
java.util.regex package is used for pattern matching with regular expressions. More information you can have here.
#
Are any Default values assigned to local variables in Java ?
No, in such a situation you receive "java: variable
#
Why is Java Architectural Neutral ?
Because Java Bytecode is platform independent.
#
What is a Class in Java ?
The class is the blueprint for creating the Java objects (created during the runtime).
#
Can we have multiple catch blocks under a single try block?
Yes, we can. Each catch block, define the code for a specific exception. "catch" block is optional.
#
3 steps for creating an Object ?
declared, instantiated and initialized
#
Which are the Access Modifiers ?
You can take a look here.
#
y = x++;
What is the result of the following code ?
int x = 1;
int y = x++;
System.out.println("x : " + x);
System.out.println("y : " + y);
int z = ++x;
System.out.println("z : " + z);
System.out.println("x : " + x);
Result :
x : 2
y : 1
z : 3
x : 3
By definition postfix increment/ decrement operator first returns the original value of the operand then increments the operand (= the higher precedence).
#
Integer.parseInt("9")
parseInt() is used to convert a string containing a number in an int type:
int x =Integer.parseInt("9");
The vice-versa is Integer.toString()
method.
#
Read system variables
String str1 = System.getProperty("java.home");
The system variables are here.
#
Vector class in Java
Vector implements a dynamic array (can grow or shrink as required). Like an array, it contains components that can be accessed using an integer index. It is synchronized. It is similar with ArrayList (which is not synchronized).
#
Object finalize() Method
Example:
@Override
protected void finalize()
{
System.out.println("finalize method called");
}
finalize() is a method that the Garbage Collector always calls just before the deletion/destroying the object which is eligible for Garbage Collection to perform clean-up activity. However, the use of the finalize() method is discouraged because it is not guaranteed to be called, and also because it could add significant overhead on the Garbage Collector.
#
Can we import a sub-package in Java ?
Yes, you can.
import com.package.subpackage.*;
#
Error vs Exception
Error
(class, extends Throwable(class)) -> hardware related (when the execution stops)
Exception
(class, extends Throwable(class))
- compilation exceptions (checked exception // Other exceptions ) : IOException, SQLException
- runtime exception (unchecked exception // Runtime exceptions) : NullPointerException
More information we have here.
#
throws vs throw
a method uses throws to tell that it could throw that error. throw - used in a method to throw an error. It comes from Throwable(class).
#
Polymorphism
In Java polymorphism is done using method overriding and method overloading.
#
How can we lock an object for exclusive use by a thread ?
Response:
- using synchronized keyword
- using java.util.concurrent.locks package
#
Packages in Java
Packages are used in Java in-order to :
- control the access
- prevent naming conflicts
- organize the classes, interfaces, enumerations and annotations, etc in our application/service.
#
Java applet
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application.
#
notifyAll() vs notify()
- notify() : wake up one specific thread ( wait() -> stops its execution of the thread)
- notifyAll() : wake up all the waiting threads (but they will not run necessarily immediately all together)
More information: Monitors in Java.
#
Comparable vs Comparator Interface
The objects of a class implementing the Comparable interface can be sorted. It is used to sort collections and arrays of objects using the sort() method. This is predefined.
Comparator Interface : allows you to define a custom sorting order for elements.
#
Why are the String object created immutable?
For better security and better performance.
#
JAR
JAR (Java Archive) files holds Java classes in a library. JAR files are built using ZIP file format.
#
Association vs Aggregation vs Composition vs Inheritage
- Association -> A person works with a car. There is a relationship between objects, but there is no ownership relation.
- Aggregation -> A class HAS-A student. When you destroy the class, the student still exists.
- Composition -> A house HAS-A main door. When you destroy the house, you destroy the main dor as well.
- Inheritance -> The dog IS-AN animal (inheritance / generalization).
#
Catch order for FileNotFoundException and IOException
FileNotFoundException is caught first. FileNotFoundException extends IOException.
#
List primitive Java types
Primitive Java types: boolean, int, byte, char, short, long, float, double.
#
Native methods is Java
A native method is a Java method (instance or class method) whose implementation is written in another programming language such as C/C++ (to access a system-specific functionality that is not available in Java).
#
process vs thread
1 process (java application instance) has :
- 1..n threads : share the HEAP
- 1..n system threads (memory management, IO)
#
Garbage Collection (GC) performance
Garbage Collection performance depends on:
- heap size
- the rate of object allocation and deallocation
- internal GC algorithm used (ex G1)
An object in Java becomes eligible for Garbage Collection when there are no more references to the object.
#
gc() method
The gc() method can be used to explicitly request that the Garbage Collector run. However, it is not guaranteed that the GC will actually run.
The System.gc() method and the Runtime.gc() method are equivalent.
#
Which number is denoted by leading zero in Java?
Octal literals. Example: 010.
#
Which number is denoted by leading 0x or 0X in Java?
Hexadecimal literals. Example: 0xA.
#
Which number is denoted by leading 0b or 0B in Java?
Binary literals. Example: 0b101.
#
static fields & serialization
The static fields are not part of the Class instance and are not serialized.
#
"$" symbol in a class name
If we can see a class named MyOuterClass$InnerChild.class, that means MyOuterClass has an inner class named InnerChild. MyOuterClass$InnerChild.class is generated under the hood.
#
Fully Qualified Class Name
com.example.package.ClassA : used generally when the "ClassA" class is imported from 2 different packages.
#
Reference types in Java
- Strong References: the normal references that are used in Java, and the objects that are referenced by strong references are not eligible for Garbage Collection.
- Soft References are references that are used to refer to objects that are still in use, but are not critical to the functioning of the application. Soft referenced objects are eligible for Garbage Collection when the JVM needs to reclaim memory.
- Weak References are references that are used to refer to objects that are weakly reachable, meaning that the objects are eligible for Garbage Collection as soon as there are no other strong or soft references to the objects.
- Phantom References are references that are used to track the lifecycle of an object (we can use it instead finalize() method which is not guaranteed to be run -> cleanup of resources).
#
hashCode() vs equals() methods in Java
hashCode()
: returns a unique identifier for an object based on its content OR memory address.
Initially, in the Object class this value is based on the memory address, but in other classes (String, Integer
for instance), the method is overridden.
equals()
: generally speaking returns "true" if the objects use the same memory address, but this is not true for the
String objects.
Info
- System.identityHashCode(obj1) is always based on memory address.
- When hashCode() is based on memory address,
obj1.hashCode() is equal to System.identityHashCode(obj1)
.
Take a look at the following example:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Demo1Application {
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
System.out.println("---------------------------");
String str1 = "ABC";
String str2 = new String("ABC");
System.out.println(str1.hashCode());
System.out.println(str2.hashCode());
System.out.println(str1.equals(str2));
System.out.println("---------------------------");
Object obj1 = new Object();
Object obj2 = new Object();
System.out.println(obj1.hashCode());
System.out.println(obj2.hashCode());
System.out.println(obj1.equals(obj2));
System.out.println("---------------------------");
}
}
When we run this we will get a result like this:
---------------------------
64578
64578
true <-- equals() for String is based on content
---------------------------
439232821
1933328958
false <-- equals() for Object is based on memory address
---------------------------
equals()
for String is based on content. equals()
for Object is based on memory address.
hashCode()
for String is based on content. hashCode()
for Object is based on memory address.
#
What is the reason for overriding equals() method (for Objects) ?
By default, the method is based on the memory address of the object (reference) and not on the content of the object.
#
What is a Fair lock in Java ?
A Fair lock is a locking mechanism based on the order in which the threads requested it (the priority of the threads is not important). This mechanism is used when notify() or notifyAll() methods are called (when using Monitors).
#
Convert a Map to a List in Java
Map<Integer, String> myMap = new HashMap<>();
ArrayList<Integer> keyList = new ArrayList<Integer>(myMap.keySet());
ArrayList<String> valueList = new ArrayList<String>(myMap.values());
Info
By default, the Maps has no duplicated keys, but there are libraries where we can do this.
#
ReadWriteLock interface
ReadWriteLock interface allows multiple threads to read at a time but only one thread can write at a time.
#
What is the purpose of static method in Java ?
Static methods in Java can be accessed without creating an instance of the class.