QA Interview: Top 100: Java Interview Questions for QA (51:100)

 Other useful Links:



51. What is the final blank variable?
  • Final variable is a variable that is declared as final and is not initialized.

52. Can you declare the main() method as final?
  • yes, public static final void main(String[] args){}

53. Can you declare the interface method as static?

  • No. Because methods of interfaces are abstract by default and we can't use static and abstract together.


54. Can we override the main() method?
  • No, because the main() method is also a static method.

55. Final vs Static

Final

Static

This modifier is only applicable to inner classes, methods, and variables.

This modifier is applicable to both outer and inner classes, variables, methods, and blocks.

The final variable does not need to be initialised at the moment of declaration.

The static variable must be initialised at the moment of its declaration.

Final variable cannot be reinitialized.

Static variables can be reinitialized.


Final method can’t be inherited.

Static methods have access to the class's static members and can only be called by static methods.

No class can inherit from the final one.

It is not possible to build a static class object, as it only contains static members.

No block for initialization of final variables is supported by the final keyword.

The static variables are initialised using the static block.


56. Can we modify the 'throws' clause of superclass method while overriding it in subclass?
  • Yes. But -
  • If a superclass doesn't declare an exception, a subclass overridden method cannot declare checked exceptions, but can only declare checked exceptions.
  • If superclass declares an exception, then subclass cannot declare parent exception of exception declared by superclass.

57. Can we declare the interface as final?

  • No. You cannot declare an interface as final because the interface must be implemented by some class to provide its definition.
  • Therefore, there is no sense to make it final. However if you try to do so it will throw a compile time error.


58. What is a Java instance of operator?

The instanceOf operator in java is also known as type comparison operator because it compares instance with type.
class Simple{
public static void main(String[] args){
Simple s = new Simple();
                System.out. println(s instanceOf sample)
        }
}

59. Can we achieve runtime polymorphism by data members?

  • No, we can override member functions but not data members.


60. What is an abstract class?
  • Abstract classes are those that are declared abstract.
  • It requires extension and implementation of its method..
  • It cannot be instantiated.
  • It can have abstract, non-abstract, static methods and constructors.
  • It can also have a final method which will force subclass not to change the body of the method.

61. Is it possible to have an abstract method without an abstract class?

  • No. If there is no abstract method in a class, the class must be abstract.


62. Can you use both abstract and final with a method at same time?

  • No. We can't override the final method since we need to override the abstract method to provide its implementation.


63. How many ways can we create string objects?

  • String literal
    • String s1 = “welcome”;
  • New keyword
    • String s1 = new String(“welcome”);



64. How many objects are created?

String s1 = “India”;

String s2 = “India”;

String s3 = “India”;

  • Only one


65. How many objects are created?

String s1 = new String("India");
  • Two - one in string constant pool and other in non-pool (Heap memory).

66. Why are strings immutable in Java?
  • String in Java is immutable, which ensures that the string value does not change. String literals are frequently exchanged among several clients.
  • If the value of the string changes (from “ABC” to “abc”), it will affect all reference variables and cause severe discrepancies.
  • Hence, strings are immutable in Java. Making a string immutable improves the application's security, caching, synchronisation, and performance.

67. What is the difference between equals() method and  (==) in Java?

equals() method
  • It's used to make that two objects specified by business logic have the same contents.
  • The Object class provides a public boolean equals(Object o) function.
double equal operator (==)
  • It is a binary operator in Java.
  • It examines if both objects are pointing to the same memory location by comparing addresses (or references).
  • Default implementation uses a double equal operator == to compare two objects.

68. How Object is unreferenced? 

  • By Nulling
    • s1=null;
  • By assigning it to another reference.
    • s1=s2;
  • By anonymous object.
    • New A();


69. String vs StringBuffer

String

StringBuffer

The String class is immutable.

The StringBuffer class is mutable

When you concatenate too many strings, the String becomes slow and requires more memory since it creates a new instance each time.

The StringBuffer is fast and consumes less memory when you concat many strings.

The String class overrides the Object's equals() method.

The StringBuffer class doesn’t override the equals() method of Object class.


70. StringBuffer vs StringBuilder

StringBuffer

StringBuilder

StringBuffer is synchronized

StringBuilder is not synchronized

Thread Safe

Not thread Safe

Less efficient than StringBuilder

More efficient than StringBuffer


71. How can we create immutable classes in java?

  • By making the class and all its members final.


72. Why is charArray better than String for password storage?

  • Until the garbage is cleared, string stays in the string pool. If we store the password into the string then it stays in memory over long periods of time and anyone having access to the memory dump can extract the password as clear text.
  • On the other hand, using char array allows us to set it to blank whenever we are done with the password. It avoids the security threats and enables us to save memory.


73. What is garbage collection?

  • Garbage collection is the process of reclaiming the unused runtime objects. It is performed for memory management.
  • In other words, we can say that garbage collection is a process of removing unused objects from memory to free up space and make this space available for JVM.


74. What is the System.gc() method?

  • The System.gc() method is used to invoke a garbage collector. The System and Runtime classes both have this method.


75. What are the advantages of Exception handling?

The advantages are as follows:
  • If an exception is handled, the execution flow will not be interrupted.
  • Using the catch declaration, we can pinpoint the issue.

76. What are the Exception handling keywords in Java?

try:
  • When a try block surrounds a potentially dangerous code. A catch block catches an exception that occurs in the try block.
  • Try can be followed by catch or finally or both. However, any one of the blocks is required.
catch:
  • This is followed by a try block. Exceptions are caught here.
finally:
  • finally is followed either by try block or catch block. 
  • This block gets executed regardless of an exception. So generally clean up codes are provided in this block.

77. Explain the 'throw' keyword in Java.

The ‘throw’ keyword is used to explicitly throw an exception from a method or any block of code.

class Test{
static void fun(){
try{
throw new NullPointerException("Demo");
}catch(NullPointerException e){
System.out.println("Inside catch");
throw e;
}
}
public static void main(String[] args){
try{
fun();
}catch(NullPointerException e){
System.out.println("Caught in Main");
}
}
}

78. Explain ‘throws’ keyword in java?

  • The ‘throws’ is used to declare an exception. It notifies the programmer that an exception is possible.
  • Exception handling is mainly used to handle checked exceptions. Throws keyword is required only for checked exceptions and usage of throws keyword for unchecked exceptions is meaningless.
  • By the help of throws keyword provide information to the caller method about the exception.

        class Test{
        static void methodA(char arr) throws IndexOutOfBoundsException{
        System.out.println(arr[6]);
        }
        public static void main(String[] args){
    try{
char arr[] = new char[5];
methodA(arr);
    }catch(ArithmeticException e){
    System.out.println(e+ "Exception Handled");
    }
        }
        }

79. throw vs throws

throw

throws

‘throw’ keyword is used to throw an exception explicitly in a program inside a function.

‘throws’ keyword is used in method signature to declare an exception which might get thrown by a function while executing the code.

We cannot throw multiple exceptions with the throw keyword.

We can declare multiple exceptions that could get thrown by function using throws keyword.

throw keyword is followed by an instance of exception.

throws keyword is followed by class name of exception to be thrown.


80. final vs finally vs finalize


final

finally

finalize

final is a keyword

finally is a block

finalize is a method.

Final is used to apply restrictions on variables, methods and class.

finally is used to execute important code. i.e. close file, close DB connection.

finalize() is used to perform cleanup processing just before an object is garbage collected.


81. How many .class files will be created?


class Test{

class Test1{ // code}

        static class Test2{ // code}

        void run(){

    Helper t = new Helper(){

Int helpMethod(){

return 5;

}

};

    }

}

  • This will produce class files
    • Test.class
    • Test $Test1.class
    • Test $Test2.class
    • Test $1.class (for the implementation of the Helper interface)


82. What is the meaning of Collections in Java?

  • Collection is a framework for storing objects and manipulating the design in order to store them.
  • Collections are used to perform the following operations:
    • Searching
    • Sorting
    • Manipulation
    • Insertion
    • Deletion
  • A group of objects is known as collections. All the classes and interfaces for collecting are available in the Java util package.


83. What are all the Classes and Interfaces that are available in the collections?

Interfaces:

  • Collection
  • List
  • Set
  • Map
  • Sorted Set
  • Sorted Map
  • Queue
Classes:
Lists:
  • Array List
  • Vector
  • Linked List
Sets:
  • Hash set
  • LinkedHashSet
  • Tree Set
Maps:
  • Hash Map
  • TreeMap
  • LinkedHashMap
Queue:
  • Priority Queue

84. Iterator vs ListIterator

Iterator

ListIterator

It can traverse elements present in the collection only in forward direction.

It can traverse elements present in the collection in forward and backward direction.

Helps to traverse list, map and set.

Helps to traverse only lists.

Index of elements cannot be found using an iterator.

Index of elements can be found using an iterator.

Cannot modify or replace elements.

Can modify or replace elements.

Cannot add elements.

Can add elements easily.


85. ArrayList vs Vector

ArrayList

Vector

ArrayList is not synchronized.

Vector is synchronized.

ArrayList is not a legacy class.

Vector is a legacy class.

ArrayList is fast.

Vector is slow.

ArrayList uses an iterator to traverse elements.

Vector uses an iterator and enumeration to traverse elements.

ArrayList increases the size by 50% if it exceeds its capacity.

Vector increases the size by 100% if it exceeds its capacity.


86. ArrayList vs LinkedList 

ArrayList

LinkedList

ArrayList uses dynamic arrays.

LinkedList uses a doubly linked list.

ArrayList is not preferred for manipulation.

LinkedList is preferred for manipulation.

ArrayList provides random access.

LinkedList does not provide random access.

ArrayList stores only objects hence it takes less overhead of memory.

LinkedList stores objects as well as addresses of objects, hence it takes extra overhead of memory.

This class implements List interface hence it can act as a list.

LinkedList implements list and DeQueue interface, hence it can act as list and queue.


87. HashMap vs HashTable

HashMap

HashTable

HashMap is not synchronized.

HashTable is synchronized.

It is not thread safe, hence cant be shared between many threads.

It is thread safe, and can be shared between many threads.

HashMap is fast.

HashTable is slow.

HashMap allows for one null key and numerous null values.

HashTable doesn’t allow any null key or value.

HashMap is a new class implemented in JDK1.2

HashTable is a legacy class.

HashMap is traversed by Iterator.

HashTable is traversed by Iterator and Enumerator.

HashMap inherits AbstractMap class.

HashTable inherits Dictionary class.

88. HashMap vs HashSet

HashMap

HashSet

HashMap implements Map interface.

HashSet implements Set interface.

In HashMap we can store key-value pairs.

In HashSet we can store Objects.

HashMap is fast.

HashSet is slow.

Duplicate keys are not permitted in HashMap, although duplicate values are permitted.

HashSet does not allow duplicate values.

HashMap allows for one null key and numerous null values.

HashSet allows one null value.

HashMap is faster than HashSet.

HashSet is slower than HashMap. 

HashMap uses put() methods to add elements.

HashSet uses add() method to add elements


89. HashSet vs TreeSet


HashSet 

TreeSet

It is implemented through a hash table.

TreeSet is a SortedSet implementation that stores data in trees.

It permits the null object.

It does not allow the null object.

It outperforms TreeSet in terms of search, insert, and delete operations.

For these actions, it is slower than HashSet.

It does not keep elements in a logical arrangement.

The elements are sorted.

It compares two objects using the equals() method.

It compares two objects using the compareTo() method.

It does not permit a heterogenous object.

It permits a heterogenous object.


90. Array vs ArrayList


Array

ArrayList

Cannot contain values of different data types.

Can contain values of different data types.

At the time of declaration, the size must be specified.

Size can be dynamically changed.

To add data, you must first define the index.

No need to specify the index.

Arrays are not type parameterized.

Arraylists are type.

Arrays can contain primitive data types as well as objects.

Arraylists can contain only objects, no primitive data types are allowed.



91. How to initialize a map with key as a string and value as integer?

  • HashMap<String, Integer> map = new HashMap<String,Integer>();


92. How to add and remove elements from HashMap?

  • Add Elements:
    • map.put(“Piyush”,10);
    • map.put(“Rahul”,20);
    • map.put(“Ujwal”,30);
    • map.put(“Shubham”,40);

  • Remove Elements:
    • map.remove(“Shubham”,40);


93. How to iterate through HashMap?


for(Map.Entry<String,Integer> e:map.entrySet()){

System.out.println(“key”+e.getKey()+ ” value”+e.getValue());

}


94. Does HashMap maintain insertion order?

  • No. TreeMap and LinkedHashMap maintain insertion order.


95. What are some of the important Java 8 features?
  • forEach() method in iterable interface
  • Lambda expressions and functional interfaces
  • Static and default methods in interfaces
  • Java time API
  • Stream API for bulk data operations on collections
  • Concurrency API improvements
  • Collection API improvements
  • Java IO improvements
  • Core API improvements

96. What is the output?

class Test{
public static void main(String[] args){
Test t1 = new Test();
Test t2 = new Test();
System.out.println(t1.equals(t2));
System.out.println(t1 == t2);
}
}

Output:
false
false

97. What is the output?

void methodA(){
try{
System.out.println("In try block");
}catch(Exception e){
System.out.println("In catch-1 block");
}catch(ArithmeticException e){
System.out.println("In catch-2 block");
}
}

Output:
Compile-time error (unreachable code at second catch block)

98. What is the output?

class Test {
static void methodA(String str)
char arr[] = str.toCharArray();
}
public static void main(String[] args){
Test.methodA();
}
}

Output:
No compile time error but NullPointerException at runtime.

99. What is the output?

class Test {
static void methodA(String str)
System.out.println(str);
}
public static void main(String[] args){
Test.methodA(null);
}
}

Output:
null

100. Can we write return statement after finally?

Yes.
int method_Test(){
try{
// code
}catch(Exception e){
// code
}finally{
System.gc();
}
return 0;
}

Greetings, reader! Your input is highly important to us. Please share your thoughts in the comments section below.


Contact:

Email:  piyushagrawal.automation@gmail.com

Follow on LinkedIn: Piyush Agrawal - LinkedIn

Follow on YouTube: Piyush Agrawal - Youtube

Happy to Help You !!

No comments:

Post a Comment