CORE Flashcards
In Java, does the finally block get executed if we insert a return statement
inside the try block of a try-catch-finally?
Yes, it will get executed.
Note that there are some cases in which the finally block will not get executed, such as the following:
- If the virtual machine exits during try/ catch block execution.
- If the thread which is executing during the try/ catch block gets killed.
What is the difference between final, finally, and finalize?
To speak in very general terms, final is used to control whether a variable, method, or class is “changeable:’ The finally keyword is used in a try/ catch block to ensure that a segment of code is always
executed. The finalize() method is called by the garbage collector once it determines that no more
references exist.
Explain the differences between TreeMap, HashMap, and
LinkedHashMap. Provide an example of when each one would be best.
All offer a key->value map and a way to iterate through the keys. The most important distinction between
these classes is the time guarantees and the ordering of the keys.
- HashMap offers 0(1) lookup and insertion. If you iterate through the keys, though, the ordering of the
keys is essentially arbitrary. It is implemented by an array of linked lists.
• TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you need to iterate through
the keys in sorted order, you can. This means that keys must implement the Comparable interface.
TreeMap is implemented by a Red-Black Tree.
-LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by their insertion order. It is
implemented by doubly-linked buckets.
What structure would you use in following scenario: Suppose you were creating a mapping of names to Person objects. You might want to periodically
output the people in alphabetical order by name.
TreeMap
What structure would you use in the following scenario: you need the ordering of keys to match the ordering of insertion. This might be useful in a caching situation, when you want to delete the oldest item.
LinkedHashMap
What structure would you use in the following scenario: you need to get key,value pairs data in alphabetical order
TreeMap
Explain what object reflection is in Java and why it is useful.
Object Reflection is a feature in Java that provides a way to get reflective information about Java classes and
objects, and perform operations such as:
[1] Getting information about the methods and fields present inside the class at runtime.
[2] Creating a new instance of a class.
[3] Getting and setting the object fields directly by getting field reference, regardless of what the access
modifier is.
Is java pass by value or by reference?
https://www.baeldung.com/java-pass-by-value-or-pass-by-reference
The fundamental concepts in any programming language are “values” and “references”. In Java, Primitive variables store the actual values, whereas Non-Primitives store the reference variables which point to the addresses of the objects they’re referring to.
Both values and references are stored in the stack memory.In case of primitives, the value is simply copied inside stack memory which is then passed to the callee method; in case of non-primitives, a reference in stack memory points to the actual data which resides in the heap. When we pass an object, the reference in stack memory is copied and the new reference is passed to the method.
Describe what happen when Passing Primitive Types to methods?
https://www.baeldung.com/java-pass-by-value-or-pass-by-reference
The Java Programming Language features eight primitive data types. Primitive variables are directly stored in stack memory. Whenever any variable of primitive data type is passed as an argument, the actual parameters are copied to formal arguments and these formal arguments accumulate their own space in stack memory.
The lifespan of these formal parameters lasts only as long as that method is running, and upon returning, these formal arguments are cleared away from the stack and are discarded.
Describe what happen when passing Object references to method?
https://www.baeldung.com/java-pass-by-value-or-pass-by-reference
In Java, all objects are dynamically stored in Heap space under the hood. These objects are referred from references called reference variables.
A Java object, in contrast to Primitives, is stored in two stages. The reference variables are stored in stack memory and the object that they’re referring to, are stored in a Heap memory.
Whenever an object is passed as an argument, an exact copy of the reference variable is created which points to the same location of the object in heap memory as the original reference variable.
As a result of this, whenever we make any change in the same object in the method, that change is reflected in the original object. However, if we allocate a new object to the passed reference variable, then it won’t be reflected in the original object.
What could happen when parameters would be pass by reference?
https://www.baeldung.com/java-pass-by-value-or-pass-by-reference
When a parameter is pass-by-reference, the caller and the callee operate on the same object.
It means that when a variable is pass-by-reference, the unique identifier of the object is sent to the method. Any changes to the parameter’s instance members will result in that change being made to the original value.
What happens exactly in below code:
baeldung.com/java-pass-by-value-or-pass-by-reference
public class PrimitivesUnitTest {
@Test public void whenModifyingPrimitives_thenOriginalValuesNotModified() { int x = 1; int y = 2; // Before Modification assertEquals(x, 1); assertEquals(y, 2); modify(x, y); // After Modification assertEquals(x, 1); assertEquals(y, 2); } public static void modify(int x1, int y1) { x1 = 5; y1 = 10; } }
Let’s try to understand the assertions in the above program by analyzing how these values are stored in memory:
The variables “x” and “y” in the main method are primitive types and their values are directly stored in the stack memory
When we call method modify(), an exact copy for each of these variables is created and stored at a different location in the stack memory
Any modification to these copies affects only them and leaves the original variables unaltered
What heppen in this piece of code:
baeldung.com/java-pass-by-value-or-pass-by-reference
public class NonPrimitivesUnitTest {
@Test public void whenModifyingObjects_thenOriginalObjectChanged() { Foo a = new Foo(1); Foo b = new Foo(1); // Before Modification assertEquals(a.num, 1); assertEquals(b.num, 1); modify(a, b); // After Modification assertEquals(a.num, 2); assertEquals(b.num, 1); } public static void modify(Foo a1, Foo b1) { a1.num++; b1 = new Foo(1); b1.num++; } }
class Foo {
public int num;
public Foo(int num) { this.num = num; } }
a) Let’s analyze the assertions in the above program. We have passed objects a and b in modify() method that has the same value 1. Initially, these object references are pointing to two distinct object locations in a heap space
b) When these references a and b are passed in the modify() method, it creates mirror copies of those references a1 and b1 which point to the same old objects
c) In the modify() method, when we modify reference a1, it changes the original object. However, for a reference b1, we have assigned a new object. So it’s now pointing to a new object in heap memory.
Any change made to b1 will not reflect anything in the original object:
What happen in below code:
educative.io/courses/java-interview-handbook/NEX9nXBGzBp
public class SuperList {
// Constructor public SuperList(int n) { 1. List superList; 2. allocate(superList, n); } // Method that does initialization void allocate(List list, int n) { 3. list = new ArrayList<>(n); } }
When the program control returns to line 2, superList is still null because it was never passed in and assigned the ArrayList object.
In Java, we are copying the reference or the address the reference data type variable holds and passing it, and not the actual variable.
What value will be printed from the following snippet?
educative.io/courses/java-interview-handbook/NEX9nXBGzBp
String[] students = new String[10]; String studentName = "You are an awesome developer"; students[0] = studentName; studentName = null; System.out.println(students[0]);
You are an awesome developer
How does method overloading match work in Java?
https://www.educative.io/courses/java-interview-handbook/xlxWYp8YvyJ
Question # 2
How does method overloading match work in Java?
Methods of a class can be overloaded in Java by:
Changing the number of parameters
Changing the type of the parameters passed into the methods
Note that methods can’t be overloaded by changing the return types of the methods, as it may cause ambiguity. While overloading has nothing to do with polymorphism, Java programmers also refer to method overloading as Compile Time Polymorphism because the method that is going to get called will be decided at compile time.
The compiler uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable. There may be more than one such method, in which case the most specific one is chosen. Typically, varargs methods are the last chosen, if they compete with other candidate methods because they are considered less specific than the ones receiving the same parameter type.
Can the main method be overloaded?
https://www.educative.io/courses/java-interview-handbook/xlxWYp8YvyJ
Yes, the static main method can be overloaded. But only public static void main(String[] args) will be used when your class is launched by the JVM even if you specify one or two command-line arguments. However, programmatically one can invoke the overloaded versions of the main method.
Consider the following overloaded methods and determine which method will be invoked for the call myOverloadedMethod(5)?
https://www.educative.io/courses/java-interview-handbook/xlxWYp8YvyJ
void myOverloadedMethod(long arg) { System.out.println("Method with long invoked"); } void myOverloadedMethod(int arg) { System.out.println("Method with int invoked"); }
Method with int invoked
List the access modifiers in Java?
https://www.educative.io/courses/java-interview-handbook/RMjBvpKEmOz
There are four accessibility levels in Java. They are listed below in order of increasing restrictiveness:
public
package private
protected
private
Explain the protected access modifier?
https://www.educative.io/courses/java-interview-handbook/RMjBvpKEmOz
The protected modifier specifies that a member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another or the same package.
Explain the private modifier?
https://www.educative.io/courses/java-interview-handbook/RMjBvpKEmOz
The private modifier specifies that the member can only be accessed in its own class. Note that top level classes can’t be marked private or protected but nested ones can be.
What is the Object class?
The Object class is the superclass directly or indirectly of every other class in Java. The Object class itself doesn’t have any superclass. In the absence of any other explicit superclass, every class is implicitly a subclass of Object.
Implicit Object Superclass
// Class is implicity a derived class
// of the Object class
public class ObjectSubclass {
}
(new ObjectSubclass()) instanceof Object // Prints true
What are the methods defined in the Object class?
The methods defined in the Object class include:
clone()
equals()
hashCode()
finalize()
getClass()
toString()
What is the output of the below snippet?
String obj1 = new String("abc"); String obj2 = new String("abc"); System.out.println(obj1 == obj2);
ANSWER: false
The equals() method provided in the Object class uses the identity operator == to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. The equals() method provided by Object tests whether the object references are equal — that is, if the object references are pointing to the same address in memory. This is the reason the statement new Integer(5) == new Integer(5) will output false because the two integer objects have different memory addresses even though their values are the same.
The case of String class is a little tricky. Compiler optimization can cause string literals to point to a single string object if the same literal is repeated many times in the code. Therefore, a snippet like below can result in true or false depending on how the program is compiled.
String myStr = “abc”;
System.out.println(myStr == “abc”);
Always use the equals() method when comparing strings!