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!
What is wrong with the BadCloneExample class shown below?
public class BadCloneExample {
List seen = new ArrayList<>(); int current = -1; public void add(int newCurrent) { seen.add(current); current = newCurrent; } public void clearHistory() { seen.clear(); } public BadCloneExample clone() { BadCloneExample clone = new BadCloneExample(); clone.current = current; clone.seen = seen; return clone; } }
The Object class’s clone() method can be overridden by classes in Java. However, the most common mistake is to copy reference variables. In the given code snippet, the clone method copies the reference to the list field seen. This makes two objects point to the same list field. Look at the snippet below:
BadCloneExample bce = new BadCloneExample(); bce.add(5); bce.add(6); BadCloneExample prev = bce.clone(); // will print [-1, 5] System.out.println(prev.seen); // clears out the list field bce.clearHistory(); // user sees [] but expects [-1,5] System.out.println(prev.seen); The two objects point to the same field and operations by the original object cascade to the clone.
Answer the question based on the following snippet:
public class Employees {
List list = new ArrayList<>(); public Employees() { } public void add(String name) { list.add(new Person(name)); } public Employees clone() { Employees clone = new Employees(); for (Person person : list) { clone.list.add(person); } return clone; } }
class Person {
String name; public Person(String name) { this.name = name; } }
What will be the output of the following snippet?
Employees apple = new Employees(); apple.add("Tim Cook"); Employees microsoft = apple.clone(); microsoft.list.get(0).name = "Satya Nadella"; System.out.println(apple.list.get(0).name);
ANSWER: )
Satya Nadella
The purpose of the above question is to drive home the fact that correct implementation of the clone method, requires appropriately copying nested reference variables.
Answer the question based on the following setup:
public class Celebrity {
String name; int age; public Celebrity(String name, int age) { this.name = name; this.age = age; } public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Celebrity) || obj == null) return false; Celebrity otherCeleb = (Celebrity) obj; return name.equals(otherCeleb.name); } }
What will be the output of the below snippet:
Celebrity realKardashian = new Celebrity("Kim", 17); Celebrity kardashianClone = new Celebrity("Kim", 17); System.out.println(realKardashian.equals(kardashianClone));
ANSWER:
The above questions explain why one needs to override the hashCode() method whenever we override the equals() method for a class. The vice-versa is not necessary that is if you override the hashCode method it is not a must to override the equals method. Let’s try to understand why that is so. Whenever, we use a hash-based collection, it uses:
hashCode() method to find the right bucket
equals() method to match the object we are looking for
In the example snippet in the quiz above, the two celebrity objects are equal but when we search for the second object in the hash set we are unable to find it because it has a different hashcode than the first celebrity object that has been added to the set. The value returned by hashCode() is the object’s hash code, which is the object’s memory address in hexadecimal. By definition, if two objects are equal, their hash code must also be equal. If you override the equals() method, you change the way two objects are equated and Object’s implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well.
What will be the output of the programme:
import java.util.HashSet;
class Demonstration {
@SuppressWarnings("unchecked") public static void main( String args[] ) { HashSet set = new HashSet(); Celebrity realKardashian = new Celebrity("Kim", 17); Celebrity kardashianClone = new Celebrity("Kim", 17); set.add(realKardashian); if (set.contains(kardashianClone)) { System.out.println("Kim is a celebrity"); } else { System.out.println("Can't find Kim"); } System.out.println(realKardashian.equals(kardashianClone)); System.out.println(realKardashian.hashCode() + " " +kardashianClone.hashCode()); } }
class Celebrity {
String name; int age; public Celebrity(String name, int age) { this.name = name; this.age = age; } public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Celebrity) || obj == null) return false; Celebrity otherCeleb = (Celebrity) obj; return name.equals(otherCeleb.name); } }
ANSWER: Can’t find Kim
true
685325104 460141958
The above questions explain why one needs to override the hashCode() method whenever we override the equals() method for a class. The vice-versa is not necessary that is if you override the hashCode method it is not a must to override the equals method. Let’s try to understand why that is so. Whenever, we use a hash-based collection, it uses:
hashCode() method to find the right bucket
equals() method to match the object we are looking for
In the example snippet in the quiz above, the two celebrity objects are equal but when we search for the second object in the hash set we are unable to find it because it has a different hashcode than the first celebrity object that has been added to the set. The value returned by hashCode() is the object’s hash code, which is the object’s memory address in hexadecimal. By definition, if two objects are equal, their hash code must also be equal. If you override the equals() method, you change the way two objects are equated and Object’s implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well.
Explain the finalize() method in the Object class?
The Object class provides a callback method, finalize(), that may be invoked on an object when it becomes garbage. Object’s implementation of finalize() does nothing — you can override finalize() to do cleanup, such as freeing up resources.
The finalize() method may be called automatically by the system, but when it is called, or even if it is called, is uncertain. Therefore, you should not rely on this method to do your cleanup for you. For example, if you don’t close file descriptors in your code after performing I/O and you expect finalize() to close them for you, you may run out of file descriptors.
Consider the snippet below:
void myMethod(Object input) { // Your awesome code here } myMethod("123") myMethod(new Integer(5)) Is there a way your method can find out if the object passed in is an integer or a string?
Yes, the getClass() method returns a Class object, which has methods you can use to get information about the class, such as its name getSimpleName(), its superclass getSuperclass(), and the interfaces it implements getInterfaces(). The getClass() method is final and can’t be overridden.
What will be the output of the following snippet of code? Can you explain the result?
Integer.valueOf(1).equals(Long.valueOf(1))
The output will be false. Even though the values are the same, i.e. one, but the objects are of different types. One is of type Integer and other is of type Long.
What will be printed on the console, if we create an object of the following class and invoke it’s print method?
public class SpecialPerson {
String fullName = init(); String name = "batman"; public SpecialPerson() { name = "superMan"; } private String init() { return name; } public void print() { System.out.println(fullName); } }
ANSWER: NULL
Can a class have a static constructor to initialize static fields?
ANSWER: NO
There’s no such thing as a static constructor in java. A constructor only exists in the context of creating a new instance or object of a class. Static fields of a class can be initialized in the static block.
Can we change the contents of a final array as in the code snippet below?
final int[] array = new int[5]; array[0] = 1;
It may appear counterintuitive, but we can actually change the contents of the array even though it is marked as final. The array variable points to a particular start location in the memory where the contents of the array are placed. The location or the memory address can’t be changed.
What are static initialization blocks?
A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. It can be used to initialize static fields of a class. A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
Static Initialization Block Example
public class EducativeCourse {
static String courseName; static String version; // We have two static initialization blocks static { version = "1.0"; } static { courseName = "Java Interview Bible"; } } The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
Can initialization block also be used to initialize instance fields?
Yes,
initialization blocks
final methods
can be used to initialize instance fields. Both of them are alternatives to using a constructor.
Initialization Using Final Method and Initialization Block
public class EducativeCourse {
String courseName = setCourseName(); String version; // initialization block { version = "1.0"; } // final method used for intialization private String setCourseName() { return "Java Interview Bible"; } } Note that we could have marked the setCourseName as non-final and not have a compile error. However, non-final methods used during initialization can cause problems as the object may not be fully constructed. Using a method for initialization may be useful if subclasses want to reuse the initialization method.
Explain the concept of class in Java?
A class in object orientated languages is the fundamental building block of any program. It can be thought of as a blueprint and its instance objects as manifestations of that blueprint. A class, in the context of Java, are templates that are used to create objects, and to define object data types and methods. Except for primitive types (int, double, float, char etc), all objects (String, Lists, Runnable, etc) in Java are instances of a class.