InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 201. |
Scope of Access Specifiers in Java |
||||||||||||||||||||||||||||||
|
Answer» A Java access specifier shows the capability to specific classes to access a given class and its components. They are also called access modifiers. They help limit the scope of the class, constructor, variables and methods.
The FOLLOWING table illustrates the visibility of the access specifiers
Let us see an example: class Scope { private int x=5; // a private variable can only be accessed in the same class protected int k=10; // a protected variable can be accessed in the subclass public void print() // a public method which can be accessed anywhere { System.out.println(x); } } public class Example extends Scope { public STATIC void main(String[] args) { Scope s=new Scope(); s.print(); System.out.println(s.k); } }The program gives the following output: $javac Example.java $java Example 5 10 |
|||||||||||||||||||||||||||||||
| 202. |
Can we have an empty catch block? |
|
Answer» Yes, we can have an empty catch block in Java. This is a bad practice though and shouldn’t be implemented. Generally, the try block has the code which is capable of producing exceptions. WHENEVER SOMETHING out of the blue or malicious is written in the try block, it generates an exception which is caught by the catch block. The catch block identifies(catches), handles the exceptions and usually prompts the user on what is wrong. If the catch block is empty then you will have no idea what went wrong with your code. Take for example, division by zero when HANDLED by an empty catch block public class Example { public static void MAIN(String[] args) { try { int a=4 ,b=0; int c=a/b; } catch(ArithmeticException E) { } } }The catch block catches the exception but doesn’t print anything. This makes the user think that there is no exception in the code. $javac Example.java $java Example But when the catch block is not empty, it gives a sense of awareness to the user about the exception. public class Example { public static void main(String[] args) { try { int a=4, b=0; int c=a/b; } catch(ArithmeticException e) { System.out.println("Division by zero is illegal"); } } }The output for the following is as follows $javac Example.java $java Example Division by zero is illegal |
|
| 203. |
What is the difference between final, finalize and finally? |
|
Answer» There are quite a few differences between final, finalize and finally.
The finalize, unlike final and finally is not a reserved keyword in Java. The finalize method can be invoked explicitly which leads to it being executed as a normal method call and wouldn’t lead to destruction of the object. Let us see a program which violates the use of the final keyword: public class Example { public STATIC void main(String[] args) { final int x=1; x++; } }The program will generate a compile time error as a final variable can’t be updated: $javac Example.java Example.java:6: error: cannot assign a value to final variable x x++;//Compile Time Error ^ 1 errorNow let us look at the use of finally keyword in Java: public class Example { public static void main(String[] args) { try { System.out.println("In try block"); int a=1/0; } catch(ArithmeticException e) { System.out.println("Exception Caught"); } finally { System.out.println("In finally block"); } } }The program will give the following output: $javac Example.java $java Example In try block Exception Caught In finally blockNow let us look at the overriding of finalize method in Java: public class Example { public static void main(String[] args) { String str = NEW String("Example"); str = null; System.gc(); // prompts the JVM to call the Garbage Collector System.out.println("End of main method"); } public void finalize() { System.out.println("This is the finalize method"); } }The output is as follows: $javac Example.java $java Example End of main method |
|
| 204. |
Working of JVM |
|
Answer» JVM STANDS for Java Virtual Machine. It is the driving force that provides the run time environment. It converts the Java ByteCode into machine code. It is an abstract machine that provides the specification for execution of a Java program during runtime. JVM loads the byte code and verifies it. It also runs the code and provides runtime environment. During compile time, the Java Compiler converts the Source Code into the ByteCode. The components REQUIRED to execute the bytecode are provided by the Java Virtual Machine, which invocates the processor to allot the needed resources. JVMs are BASED on stacks so they implement stacks to read and process the bytecode. In other words when we compile a .java file, files with nomenclature same to that of the class are created with the extension .class by the Java Compiler. These files contain the byte code. There are various STEPS involved when a .class file is executed. These steps provide a detailed account of the Java Virtual Machine. |
|
| 205. |
Can try statements be nested in Java? |
|
Answer» Yes, try statements can be nested in Java. A try block within a try block is called nested try block. The syntax for a nested try block is as follows: try // outer try block { statements; try // inner try block { statements; } CATCH(Exception e) // inner catch block { } } catch(Exception x) // outer catch block { }The following is an example for nested try block: public CLASS Example { public STATIC void main(String[] args) { int[] n={1,2,3,4,5,6}; int[] d={1,2,0,3}; for(int i=0;i<n.length;i++) { try { try { System.out.println(n[i]+"/"+d[i]+"="+n[i]/d[i]); } catch(ARITHMETICEXCEPTION e) { System.out.println("Division by zero not Possible"); } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array Index is out of bounds"); } } } }The output is: $javac Example.java $java Example 1/1 = 1 2/2 = 1 Division by zero not Possible 4/3 = 1 Array Index is out of bounds Array Index is out of bounds |
|
| 206. |
The yield method of the Thread Class |
|
Answer» The YIELD() method of the Thread class is used to TEMPORARILY stop the EXECUTION of the thread and carry out the execution. For the JAVA.lang.Thread class, the syntax for the yield method is as follows: public static void yield()Execution of a thread is prevented by three ways namely yield(), sleep(), join(). In certain situations where one thread is taking exceedingly more time to complete its execution, we need to find a solution to delay the execution of the thread which completes its execution quickly in between if something important is pending. The yield() provides an answer to this problem. For example, import java.lang.*; class ExampleThread EXTENDS Thread { public void run() { for (int i=0; i<2 ; i++) System.out.println(Thread.currentThread().getName() + " in control"); } } public class Example { public static void main(String[]args) { ExampleThread t = new ExampleThread(); t.start(); // this calls the run() method for (int i=0; i<2; i++) { Thread.yield(); System.out.println(Thread.currentThread().getName() + " in control"); } } }The output of the above program is: $javac Example.java $java Example Thread-0 in control Thread-0 in control main in control main in controlThe output may differ from system to system but the probability of execution of the yield() thread is more. |
|
| 207. |
How to differentiate between the size and capacity of a Vector in Java? |
|
Answer» Vectors in Java are dynamic data structures which can expand when a new element is added to them. They are synchronized and contain many methods that are not a PART of the Collections framework in Java. Vectors in Java have two methods call size() and capacity() which are in relation with the NUMBER of elements of the Vector. The size() returns the number of elements the vector is CURRENTLY holding. It increases or decreases whenever elements are inserted or deleted to/from a vector respectively. The capacity() returns the maximum number a elements a vector can hold. Since the vector is an expandable data STRUCTURE, its capacity is not fixed. We can set the initial value of the capacity. The Vector() constructor initializes the initial capacity of the vector to be 10. For example, import java.util.*; // Vector is a class of the java.util package public class Example { public static void main (String[] args) { Vector v = new Vector(); // creating new Vector object System.out.println("Vector Size: " + v.size()); // prints the current size of the Vector v.addElement(10); v.addElement(20); System.out.println("Vector Size: " + v.size()); v.addElement(5); System.out.println("Vector Size: " + v.size()); System.out.println("Vector Capacity: " + v.capacity()); //prints the capacity of the vector } }The output will be the following: $javac Example.java $java Example Vector Size: 0 Vector Size: 2 Vector Size: 3 Vector Capacity: 10 |
|
| 208. |
When is the constructor of a class invoked? |
|
Answer» The constructor of a class is invoked at the time of object creation. Each time an object is created USING the new keyword, the constructor gets invoked. The constructor initializes the data members of the same class. class Example { Example() // constructor { } } Example obj=new Example(); // invokes above constructorA constructor is used to initialize the state of the object. It contains a LIST of statements that are EXECUTED at the time of creation of an object. For example, public class Example { Example() // constructor of class Example { System.out.println("This is a constructor"); } public static void main(String []args) { Example e=new Example(); // constructor Example() is invoked by creation of new object e } }The OUTPUT of the above is as follows: $javac Example.java $java Example This is a constructor |
|
| 209. |
If I write System.exit(0); at the end of the try block, will the finally block still execute? |
|
Answer» No, the finally block will not EXECUTE. The System.exit() method is a predefined method of the java.lang package. It exits the current program by termination of the running of Java Virtual Machine. The System.exit() method has a status code represented by an integer value. Usually the status code is 0. A non-zero status code means UNUSUAL termination of the Java program. The syntax for the exit method in the java.lang package is as follows is as follows public static void exit(int status_code);The finally block in Java usually executes everything irrespective of what is written in the try and catch block. An aberration is made when the System.exit() function is written in the try block. For example, public class Example { public static void main(String[] args) { try { System.out.println("In try block"); System.exit(0); int a=1/0; } catch(ArithmeticException E) { System.out.println("EXCEPTION Caught"); } finally { System.out.println("In finally block"); } } }The output is as follows: $javac Example.java $java Example In try block |
|
| 210. |
String Pool in Java |
|
Answer» String Pool in Java is a pool or collection of Strings stored in the Java Heap Memory. When initialize a String using double quotes, it first SEARCHES for String with same value in the String pool. If it matches, it just RETURNS the reference otherwise, it generates a new String in the String pool and then it returns its reference. The possibility of the String Pool exists only DUE to the immutability of the String in Java. In CASE of the creation of String using the new operator, the String class is entitled to create a new String in the String Pool. For example, public class Example { public static void main(String[] args) { String s1 = "Hello"; String s2 = "Hello"; String s3 = new String("Hello"); System.out.println("Do s1 and s2 have the same address? "+ (s1==s2)); System.out.println("Do s1 and s2 have the same address? "+ (s1==s3)); } }The OUTPUT will show that s1 and s2 have the same address due to implementation of String Pool. String s3 though will have a different address due to the use of the new keyword. $javac Example.java $java Example Do s1 and s2 have the same address? true Do s1 and s2 have the same address? false |
|
| 211. |
Compile-time vs Runtime Polymorphism in Java |
|||||||||||||||||||||
|
Answer» The following is the COMPARISON:
An EXAMPLE for the implementation of compile time polymorphism using method overloading is given below: class Overload { public void display(char C) { System.out.println(c); } public void display(char c, int num) { System.out.println(c + " "+num); } } public class Example { public static void main(String args[]) { Overload obj = new Overload(); obj.display('s'); obj.display('s',12); } }The output of the above program is: $JAVAC Example.java $java Example s s 12An example for the implementation of run-time polymorphism using method overriding is given as follows: class SuperClass { void display() { System.out.println("SuperClass"); } } class SubClass extends SuperClass { void display() { System.out.println("Subclass"); } } public class Example { public static void main(String[] args) { SuperClass obj1 = new SuperClass(); obj1.display(); SuperClass obj2 = new SubClass(); obj2.display(); } }The output is as follows: $javac Example.java $java Example SuperClass Subclass |
||||||||||||||||||||||
| 212. |
Constructor vs Method |
||||||||||||||||||||||||
|
Answer» The following is the difference:
An example program to show the use of constructor and method is as follows: PUBLIC class Example { Example() { System.out.println("You are in a constructor"); } public void PRINT() { System.out.println("You are in a method"); } public static void main(String []args) { Example e = new Example(); e.print(); } }The output for the following is as follows: $javac Example.java $java Example You are in a constructor You are in a method |
|||||||||||||||||||||||||
| 213. |
ByteCode in Java |
|
Answer» During compile time, the Java Compiler CONVERTS the Source Code into the ByteCode. ByteCode is a highly developed set of instructions given to the Java Virtual Machine to generate the machine code. It is the machine code in the form of the .class file. Analogies can be made to the assembler in C++. It is CALLED ByteCode because each INSTRUCTION is of 1-2 bytes. One of the main features in Java which distinguishes it from other Object-Oriented Languages is that it is Platform Independent. This Platform Independence is achieved through the Java ByteCode. The COMPONENTS required to execute the bytecode are provided by the Java Virtual Machine, which invocates the processor to allot the needed resources. JVMs are based on stacks so they implement stacks to READ and process the bytecode. Some ByteCode instructions are as follows: 1: istore_1 2: iload_1 3: sipush 1000 6: if_icmpge 44 9: iconst_2 10: istore_2The Code Segment is the memory segment that holds the ByteCode. |
|
| 214. |
What does “static” mean in public static void main(String args[])? |
|
Answer» The public static void main(String args[]) is the main METHOD of the Java Program. It is the most important Java Method. It is the entry point of any Java Program. A Java Program cannot be executed without the main method. The static KEYWORD acts as an access modifier. When the Java Virtual Machine calls out to the main method, it has no object to call to. Hence, we use static to permit its call from the class. If we do not use static in public static void main(String args[]), then the compiler will GIVE an error message. public class Example { public void main(String args[]) { System.out.println("Hello"); } }The output window is as FOLLOWS $javac Example.java $java Example Error: Main method is not static in class Example, please define the main method as: public static void main(String[] args) |
|
| 215. |
Usage of Final keyword in Java |
|
Answer» The final KEYWORD is a type of modifier in Java. It is of the non-access type. It can only be applied to a variable, method or a class. Class that are final cannot be extended. Methods that are final cannot be used for method overriding in child class. The final variables have constant value which are not changeable throughout the program. This MEANS they need to be initialized along with their declaration, OTHERWISE they would be blank final variables, which can be later initialized only once. If a final variable is used as a reference to an object, it cannot be used as a reference to another object.
This program will generate a compile time error $javac Example.java Example.java:9: error: cannot assign a value to final variable x x= 5; ^ 1 error2. If we try to inherit a final class in a subclass, the compiler will show an error. final class Superclass { static int x=5; } public class Example extends Superclass { public static void main(String []args) { System.out.println(x); } }The error message is as follows: $javac Example.java Example.java:5: error: cannot inherit from final Superclass public class Example extends Superclass ^ 1 error3. If we try to override a final class, it will generate an error: class Superclass { int x=5; final void add() { int j=x+5; System.out.println(j); } } public class Example extends Superclass { void add() { int a=5,b=10; System.out.println(a+b); } public static void main(String []args) { Example e=new Example(); e.add(); } }The error generated is as follows $javac Example.java Example.java:12: error: add() in Example cannot override add() in Superclass void add() ^ overridden method is final 1 error |
|
| 216. |
Transient keyword in Java |
|
Answer» The transient keyword in Java is a variable modifier. It finds its application in serializiation. During serialization, if we don’t want to write the state of the particular variable in the byte stream, we use the transient keyword. When the JVM comes up to the transient keyword, it ignores the original state of the variable and stores a default value of that data type i.e. 0 for int, 0 for byte, 0.0 for float,etc. As static variables are ALSO ignored by the JVM, there is no use of writing transient with them though this won’t generate an error. As final variables are directly SERIALIZED by their values, there is no use of making them transient ALTHOUGH this would not give a COMPILE time error. The transient keyword is useful for security and data hiding. It is a good practice to use the transient keyword with private access specification. An example program where the effect of the transient keyword during serialization and deserialization is shown below: import java.io.*; public class Example implements Serializable { int a = 1, b = 2; // instance variables transient int c = 3; // transient variable // transient is rendered affectless with static and final transient final int d = 4; transient static int e = 5; public static void main(String[] args) throws Exception { Example input = new Example(); // serialization FileOutputStream fo = new FileOutputStream("example_file.txt"); ObjectOutputStream obj = new ObjectOutputStream(fo); obj.writeObject(input); // de-serialization FileInputStream fi = new FileInputStream("example_file.txt"); ObjectInputStream o = new ObjectInputStream(fi); Example x = (Example)o.readObject(); System.out.println("a = " + x.a); System.out.println("b = " + x.b); System.out.println("c = " + x.c); System.out.println("d = " + x.d); System.out.println("e = " + x.e); } }The output of the program is: $javac Example.java $java Example a = 1 b = 2 c = 0 d = 4 e = 5We can notice that the transient variable c has been set to its default value i.e. 0 while there is no CHANGE in the final, static and the instance variables. |
|
| 217. |
What is the difference between a=a+b and a+=b |
|
Answer» The a=a+b statement has an assignment operator = and a arithmetic operator + while a+=b has a arithmetic assignment operator +=. Apart from this there is only a slight difference between the two. For similar integer or byte or float data TYPES both the expressions would compile. But if one value(a) is byte and the other(b) is int, a=a+b will not compile as byte+int is not byte On the other HAND, a+=b will compile as the arithmetic assignment operator will do an implicit type casting. Take for example, public class Example { public static void main(String []args) { byte a=2; int b=3; a=a+b; // generates an error as byte+int=int System.out.println(a); } }The above program generates an error $javac Example.java Example.java:7: error: INCOMPATIBLE types: possible LOSSY conversion from int to byte a=a+b; ^ 1 errorBut if we take a+=b public class Example { public static void main(String []args) { byte a=2; int b=3; a+=b; // compiles System.out.println(a); } }This code is error free and will generate the following output: $javac Example.java $java Example 5 |
|
| 218. |
Exception vs Error in Java |
||||||||||||||||||
|
Answer» Errors in Java are a part of the java.lang.error CLASS. Exceptions in Java a part of the java.lang.Exception class. Both are a part of the java.lang.Throwable class.
|
|||||||||||||||||||
| 219. |
Default switch case in Java |
|
Answer» A switch statement is a DECISION making statement in Java. It is used to CHECK a variable’s equality against a list of values and their subsequent statements. It is a multiway branch statement. Each condition is called a case and the variable is checked for each case. Syntax for switch case: switch(EXPRESSION) { case value1 : // Statements break; // optional case value2 : // Statements break; // optional . . . . default : // This is the default switch case // Statements }The default statement is optional, and can appear anywhere inside the switch block. |
|
| 220. |
Create a custom exception in Java |
|
Answer» Custom Exceptions are nothing but user defined exceptions. Java custom exceptions are used to make and modify the exception according to the requirements of the user. Before CREATING a custom exception, let us look at its prerequisites
Let us now create a parent custom exception which generates an exception if a number is not divisible by 3: class CustomException extends Exception { CustomException(String errormsg) { super(errormsg); } } public class Example { static void validate(INT num)throws CustomException { if(num%3!=0) throw new CustomException("Not divisible by 3"); else System.out.println("Divisible by 3"); } public static void main(String args[]) { try { validate(10); } catch(Exception e) { System.out.println("Exception caught: "+e); } System.out.println("Outside the try-catch block"); } }The output for the above program is as follows: $javac Example.java $java Example Exception caught: CustomException: Not divisible by 3 Outside the try-catch block |
|
| 221. |
Method Overloading vs Overriding |
||||||||||||||||||||||||||||||||||||
|
Answer» In Method Overloading, the names of the methods in the same class are same but the arguments (TYPE and/or number) are DIFFERENT.
|
|||||||||||||||||||||||||||||||||||||
| 222. |
What is a WAR file in Java? |
|
Answer» WAR stands for Web Application RESOURCE or Web Application Archive. It finds its application in distribution of a collection of JAR(Java Archive) FILES, Java Server Pages, Java Servlets, Java Classes, XML files, tag libraries, static web pages, and other resources that constitute a web Application. WAR files have the file extension .war. These are extended from JAR files. So, a .war is a .jar, but it contains web application components and is laid out according to a specific structure. A .war is designed to be deployed to a web application server such as Tomcat or Jetty or a Java EE server such as JBoss or Glassfish. The primary advantage of a .war file is it combines all files into a single unit which reduces the transfer time from client to server. To create a war file, we need to use the jar tool of the Java Development Kit. Go inside the project directory of your project, then write the following command: jar -cvf yourproject.war *The -c switch is used to create file, -v is used to generate the verbose output and -f switch is used to specify the archive name of the file. During Java runtime, verbose OPTIONS can be used to tell the JVM which kind of information to see. JVM supports three verbose options out of the box. As the name suggests, verbose is for DISPLAYING the work done by JVM. |
|
| 223. |
Abstract Classes vs Interfaces |
||||||||||||||||||||||||
|
Answer» Abstract CLASS and Interface both are used for ABSTRACTION which is HIDING the background details and representing only the essential features. But there are major DIFFERENCES between abstract classes and interfaces. These are given as follows:
|
|||||||||||||||||||||||||
| 224. |
Local and Instance Variable in Java |
|
Answer» Local Variable in Java is a variable declared in a method body or a constructor or a block (for example for loop) and its scope lies within the method or constructor or the block. The scope of the local variables starts from its declaration and ENDS when the block or method body or the constructor ends by the closing curly brace. Access specifiers like public, private, PROTECTED can’t be used for declaring local variables. They are implemented at the stack level internally. Instance Variables in Java is a data member of a class and is DEFINED in a class. Each object can create its own COPY of the instance variable and access it separately. The instance variables are visible for all methods, constructors and block in the class. They can be accessed directly by calling the variable NAME inside the class. Any changes made to the instance variables in the methods reflect in the state or value of the variable outside the scope of the method for a particular object. The scope of the instance variable is created and destroyed when the objects are created and destroyed respectively. Default values are given to instance variables. The default value is 0 for integers, floats, doubles and bytes, it is false for Boolean and null for object references. They cannot be declared as static otherwise they’ll be classified as static variables. If instance and local variables have the same name then ‘this’ keyword is used to differentiate among them. An example program to illustrate the use of Local as well as Instance variables is given as follows. public class Example { int a=5; // a is an instance variable public void add(int n) { int sum = a + n; // sum is a local variable System.out.println(sum); //accessing local variable } public static void main(String[] args) { int k=11; Example obj= new Example(); // creating object for Example class System.out.println(obj.a); // accessing instance variable obj.add(k); } }The given program produces the following output: $javac Example.java $java Example 5 16Here, a is the instance variable while sum is the local variable. |
|
| 225. |
What are Wrapper Classes in Java? |
||||||||||||||||||
|
Answer» Wrapper classes are predefined classes in Java whose objects have primitive data types. They convert primitive data types into objects and vice versa. The Wrapper Classes provide a NEW angle to Java which helps it put a STRONG foot forward against its contemporaries. Data Structures in a collection framework can store only objects and not primitive data types. They provide SYNCHRONIZATION during multithreading. They are defined in the java.lang package. They are converted to primitive data types and vice versa by the process of boxing and unboxing. Typically, there are eight wrapper classes. They are linked to the primitive data types as follows:
Now let us discuss about the wrapper classes:
|
|||||||||||||||||||
| 226. |
What is public static void main(String args[]) in Java |
|
Answer» The public static void main(String ARGS[]) is the main method of the Java Program. It is the entry point of any Java Program. A Java program cannot be executed without the main method. The syntax of the main method is as follows: public static void main(String args[])Only the args can be changed to a different name but the rest of the method carries the same syntax. Let us analyze the main method by breaking it up:
|
|
| 227. |
How a value is retrieved from a HashMap? |
|
Answer» For retrieval or storing a value, a HashMap uses two methods of its KEY class - hashCode() and equals(). HashMap STORES its entries in a large collection of buckets which can be randomly accessed using an INDEX. To retrieve a value, first, the hashCode() method of the Key is invoked to get the hash value. This hash value is USED to identify the bucket where the value would be retrieved from. While storing an entry, there might be some scenario where the calculated hash value is the same for more than one keys. This results in to enter multiple key-value pairs in the same bucket. A bucket keeps its entries as a Linked List. So, while retrieving, after finding out the appropriate bucket, this linked list needs to be traversed to find the actual entry for the key. This time, the equals() method is used to compare the key of each entry in the list. Once it finds a key equal, the value from the entry is returned. There is a contract between these two methods which says if two objects are equal based on equals() method, their hashCode() value MUST be the same. So, if we plan to use objects of a class as the key of a HashMap, we should override both the methods - hashCode() and equals() so that this contract is maintained. |
|
| 228. |
What is the difference between a HashTable and a HashMap? |
|
Answer» HASHTABLE and HashMap both store key-value pairs and take a constant time to put or GET operations. HOWEVER, Hashtable is SYNCHRONIZED and can be shared to get modified by multiple threads while HashMap is not synchronized and performs better, but not suitable for the multithreaded environment as a shared object. HashTable doesn’t allow NULL keys or values, bur a HashMap allows a Null key and more than one Null values. |
|
| 229. |
What is the difference between an ArrayList and LinkedList? |
|
Answer» ArrayList and LinkedList both represent a list of numbers but differ in their internal implementation. ArrayList uses an array internally to store the elements added to it. When the number of elements is about to exceed the size of the array, it allocates a NEW array and copies the elements to the new location. It GIVES constant time access to add (if it doesn’t need to expand) and GET an element, but for deletion, it gives linear time COMPLEXITY as it needs to shift its elements to the left. LinkedList, on the other hand, MAINTAINS a sequence of linked nodes internally for storing the elements. So, retrieves an element in linear time whereas addition and deletion take a constant time to execute. |
|
| 230. |
What do you understand by a static member of a class? |
|
Answer» We declare a MEMBER as static if it doesn’t depend on any instance of the class, i.e., independent of any OBJECTS. These members are bound to the type and usually accessed USING the type name (rather than the OBJECT references). Static methods and fields are shared between all the objects of a class and can be accessed from any of them, whereas we cannot access the non-static members from a static method. As static methods are not bound to an object, they cannot be overridden. Static fields are initialized through a static block which is executed when a class is loaded by the class loader. Let’s see an example: public class Countable { private static int COUNT; private int x; static { count = 0; // initialize static member } public Countable(int x) { this.x = x; Count++; // non-static can access static member } public int getX() { return x; } public static int getCount() { return count; // only static can access static member } } Countable c1 = new Countable(10); Countable c2 = new Countable(20); System.out.println("Object count " + Countable.getCount()); // should print 2 |
|
| 231. |
Does Java support multiple inheritance? |
|
Answer» JAVA doesn’t support multiple inheritance completely as a CLASS can extend only ONE class. This is not supported as this can cause ambiguity in accessing inherited fields or methods if the same member EXISTS in the other PARENT class. However, the facility is provided partially through the interfaces. |
|
| 232. |
What is the difference between an interface and an abstract class? When we should prefer the interface over abstract class? |
|
Answer» A class can inherit from both an ABSTRACT class and an interface, but there are some differences. A class can extend only one abstract class while can implement multiple interfaces. An interface cannot have a constructor whereas the abstract class can have constructors which the child classes need to invoke in their constructors. An abstract class may contain fields which may be accessible by child classes to change its state. Interface, on the other hand, can contain only final variables. So, abstract class lets the child class to inherit the state and behavior while the interface is mainly used for implementing a SET of behaviors in a child class. An abstract class should be preferred where there is a direct IS-A relationship between the PARENT and the child. We use abstract class when the different implementations have most of the behaviors common and defined by the abstract class. An interface is preferred while exposing a public API to the CLIENT code and if a class can behave differently in different context. |
|
| 233. |
What is the difference between StringBuffer and StringBuilder? |
|
Answer» STRINGBUFFER and StringBuilder expose the same kind of APIs to build a String and both are mutable classes. There is a big difference in them, though. StringBuffer is thread-safe which means it can be used as a shared object among MULTIPLE THREADS. On the other hand, StringBuilder is not thread-safe and should not be allowed to be MODIFIED by multiple threads without proper synchronization techniques. That’s why StringBuilder is faster than StringBuffer. In the scenario where we NEED to build a String object local to a method or local to a particular thread, we should prefer StringBuilder over StringBuffer. |
|
| 234. |
What is runtime polymorphism? |
|
Answer» Polymorphism or static polymorphism decides which method needs to be invoked at the time of compilation and bind the method invocation with the call. HOWEVER, there are some situations where the static binding doesn’t work. As we know, a parent class reference can point to a parent object as WELL as a child object. Now, if there is a method which exists in both the parent class and the child class with the same signature and we invoke the method from parent class reference, the compiler cannot decide which method to bind with the call. This will depend on which type of object the reference is pointing to at the time of running. If the reference is pointing to a parent object, then the method in the parent class will be invoked. If the pointed object is an instance of the Child class, then the child-class implementation is invoked. That’s why this is called dynamic binding or runtime polymorphism and it is said that the child class method has OVERRIDDEN the parent class method. Let’s take an example of this: class Animal { public void makeSound() { System.out.println(“My sound varies based on my type”); } } class Dog extends Animal { @Override public void makeSound() { System.out.println(“I bark”); } } Animal a = new Animal(); a.makeSound(); a = new Dog(); a.makeSound();If we run the code snippet, we’ll find that a.makeSound() printing different messages based on the object-type pointed by reference. Please note that the Override annotation is REQUIRED in the child class to notify the compiler that this method is OVERRIDING the parent implementation. |
|
| 235. |
In how many ways an object can be created in Java? |
|
Answer» There are several ways we can create an object in JAVA. 1. A new object can be created using the new operator on the class calling ONE of its constructors. MyClass o = new MyClass(); 2. We can create an object using the Java reflection API - Class.newInstance() if the class has a default constructor. If the class has multiple constructors that take parameters, we can get the corresponding constructor using Class.getConstructor() method and invoke that to create a new object. MyClass o = MyClass.class.newInstance(); MyClass o = MyClass.class .getConstructor(int.class) .newInstance(10); 3. We can invoke clone method on an object to create a duplicate object. MyClass o = new MyClass(); MyClass b = (MyClass)o.clone(); 4. If a state of that object is AVAILABLE in a serialized form, we can DESERIALIZE it to create a new object having the same state. ObjectInputStream is = new ObjectInputStream(anIStream); MyClass o = (MyClass) is.readObject(); |
|
| 236. |
What is the purpose of a wrapper class? |
|
Answer» The WRAPPER classes wrap the primitive data types to introduce them as objects. The primitive values are not objects and the developer NEEDS to write many boilerplate codes to convert them to each other and using them in collections. To OVERCOME these problems, Java introduced wrapper classes. These classes provide with polymorphic APIS for data type conversions and the utility methods like hashCode() and equals(). These make the values very USEFUL members in the object-oriented environment. |
|
| 237. |
Is Java fully object-oriented? |
|
Answer» Java supports programming in the Object-Oriented PARADIGM, but it is not fully object-oriented. Java has a set of PRIMITIVE data types - byte, short, char, INT, long, float, DOUBLE, boolean. Any VARIABLE of this type is not an object. That’s why Java is not purely an object-oriented. |
|
| 238. |
What is JWebUnit and explain its advantages? |
|
Answer» JWebUnit is one of the extensions of JUnit and is a Java-based testing FRAMEWORK for web applications. It offers high-level API of Java used for the navigation of the web applications in addition to the set of ASSERTIONS for the verification of the authenticity of the application. The main function of JWebUnit is WRAPPING the existing frameworks for testing with a simple and unified testing INTERFACE to check for the credibility of the web applications. |
|
| 239. |
Please explain JUnit extensions? |
|
Answer» There are four extensions of Junit-
|
|
| 240. |
Explain the difference between JUnit and TestNG? |
| Answer» | |
| 241. |
How do you test exceptions in JUnit? |
| Answer» | |
| 242. |
Which is better JUnit or TestNG? |
||||||||||||||||||
Answer»
|
|||||||||||||||||||
| 243. |
How do I run a JUnit test from the command line? |
| Answer» | |
| 244. |
Why do we use JUnit testing? |
|
Answer» The multiple ESSENTIAL features of JUnit testing are the answer to the above question. Some of them are as follows-
|
|
| 245. |
What is Junit testing? |
|
Answer» Junit testing is a framework written in Java for providing a standard way of organizing, writing, and RUNNING the tests. An ACCURATE logic of the test can be written following a simple rule. Here, Junit means UNIT testing which implies the meaning as of checking the individual parts of a software SYSTEM WITHOUT the implementation of the entire system from end to end. |
|
| 246. |
What is the purpose of the @AfterClass annotation in JUnit? |
|
Answer» In CASE of the ALLOCATION of the expensive external resources in a BeforeClass method, then there is the requirement of releasing them after the running of the tests completes. For this, the annotation of the @AfterClass method, a public static void method is required to be run after all the class’s tests have been run. It is because of the feature of the method such as it guarantees the test is running even in the SITUATION of an EXCEPTION thrown by BeforeClass. It is one of the methods to be declared in the superclass and run after the running process of the current class ends. Also, it is called once per test class. 6. What are JUnit annotations?The SPECIAL form of the syntactic meta-data that can be used for the improved code readability and structure in the source code. The examples of the entities that can be annotated are parameters, methods, variables, classes, and methods in the Java source code. JUnit annotations are Before, After, AfterClass, Ignore, BeforeClass, RunWith, and Test. |
|
| 247. |
How do you assert exceptions in JUnit? |
| Answer» | |
| 248. |
What are the essential features of JUnit? |
Answer»
Junit Interview Questions can be learned easily with us on this online LEARNING platform. |
|
| 249. |
Explain the difference between dependency and plugin in Maven? |
||||||||||||
Answer»
|
|||||||||||||
| 250. |
Explain the difference between Maven build and Maven install? |
|||||||||
Answer»
|
||||||||||