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.
| 101. |
Lambda Expressions in Java 8 |
|
Answer» Lambda expressions in JAVA are expressions which implement functional interfaces. Functional interfaces are those interfaces that have only one abstract method. These expressions were created to reduce the unwieldy overhead code of an anonymous class. An anonymous class is a local class devoid of a name and is declared and instantiated at the same time. Until Java 8, even for the simplest of operations, additional syntactical code was written with anonymous classes . Lambda expressions were introduced to remove this shortcoming. The syntax: lambda operator->bodylambda operator is an parameter LIST can have 0, 1 or multiple PARAMETERS. Zero parameter: ()->System.out.println(“I have no argument”);One parameter: (arg)->System.out.println(“I have one argument”+arg)Multiple parameters: (arg1,arg2)->System.out.println(“I have many arguments”+arg1+“ ”+arg2)Let us use lambda expression to print even integers from a list: import java.util.*; public class Example { public static void main(String args[]) { List<Integer> list = new ArrayList<Integer>(); for(int i=1;i<=10;i++) // ADDING 1 to 10 in the integer ArrayList { list.add(i); } // printing even elements in list using lambda expression list.forEach(arg -> { if (arg%2 == 0) System.out.println(arg); }); } }The output is as follows: $javac Example.java $java Example 2 4 6 8 10 |
|
| 102. |
Java Annotations |
||||||||||||||
|
Answer» Annotations in Java are a form syntactic metadata which are used to CONVEY additional information about a program’s ELEMENTS like constructors, methods, instance variables and classes. They always start with @ symbol. Annotations have no direct effect in the compilation of the program. On the other side, annotations do not completely act like comments as they can transform the compiler’s perspective about the program. Let us see an example where annotations effect the output of a program. We are trying to override a private method . This will generate an error. class Parent { private void display() { System.out.println("Super class"); } } public class Example extends Parent { //using the Override annotation @Override void display() // trying to override display() { System.out.println("Sub class"); } public static void main(String[] args) { Parent obj = new Example(); obj.display(); } }The output is as follows: $javac Example.java Example.java:11: error: method does not override or IMPLEMENT a method from a supertype @Override ^ Example.java:19: error: display() has private access in Parent obj.display(); ^ 2 errorsBasically, Annotations are divided into three categories
Marker Annotations: They are used to point out at declaration. These annotations do not have any parameters. For example: @ExampleAnnotation()@Override is an example of a marker annotation. Full Annotations: These annotations consist of multiple variables’ name,value, pairs. For example: @ExampleAnnotation(name=”Program”, value=”Java”)Single value Annotations: These annotations consist only a single member with a shorthand value. For example: @ExampleAnnotation(“running”)There are a few built-in/ primitive annotations in Java. 3 of the built-in annotations are INCLUDED in the java.lang package. They are as follows
4 of them are imported the java.lang.annotation class, namely:
|
|||||||||||||||
| 103. |
Multi-catch block in Java |
|
Answer» Before Java 7 when we needed to handle more than one exception, we required multiple catch blocks to handle those exceptions. Let us see an example: import java.util.*; public class Example { public STATIC void main(String args[]) { Scanner SC = new Scanner(System.in); try { int n=INTEGER.parseInt(sc.next()); System.out.println(n/0); } catch (ArithmeticException ex) { System.out.println("Exception caught " + ex); } catch (NumberFormatException ex) { System.out.println("Exception caught " + ex); } } }The output here depends on the input. When we input an integer it will generate an arithmetic exception. For the following input: 3The output would be as follows: $javac Example.java $java ExampleException caught java.lang.ArithmeticException: / by zeroFor a String or character input, the output would be different. For the following input: HelloThe output would is as follows: $javac Example.java $java Example Exception caught java.lang.NumberFormatException: For input string: "Hello"From Java 7, the multi-catch block was INTRODUCED in Java A single catch block could catch multiple exceptions which are separated | symbol. Let us see an example for the multi-catch block: import java.util.*; public class Example { public static void main(String args[]) { Scanner sc = new Scanner(System.in); try { int n=Integer.parseInt(sc.next()); System.out.println(n/0); } catch (NumberFormatException | ArithmeticException ex) { System.out.println("Exception caught " + ex); } } }When we input an integer it will generate an arithmetic exception. For the following input: 3The output would be as follows: $javac Example.java $java Example Exception caught java.lang.ArithmeticException: / by zeroFor a String or character input, the output would be different. For the following input: HelloThe output would is as follows: $javac Example.java $java Example Exception caught java.lang.NumberFormatException: For input string: "Hello" |
|
| 104. |
Can we override private methods in Java? |
|
Answer» No, PRIVATE methods cannot be overridden in JAVA. The private keyword limits the scope of the method, variable or class with which it is declared. Private methods in Java are not visible to any other class which limits their scope to the class in which they are declared. Let us see what happens when we TRY to override a private method: class Parent { private void display() { System.out.println("Super class"); } } public class Example EXTENDS Parent { void display() // trying to override display() { System.out.println("Sub class"); } public static void MAIN(String[] args) { Parent obj = new Example(); obj.display(); } }The output is as follows: $javac Example.java Example.java:17: error: display() has private access in Parent obj.method(); ^ 1 errorThe program gives a compile time error showing that display() has private access in Parent class and hence cannot be overridden in the subclass Example. |
|
| 105. |
Serialize and Deserialize an Object in Java |
|
Answer» Serialization is the process of CHANGING the state of an object into the byte stream so that the byte stream can return back into a copy of the object In Java, an object is SAID to be serializable if its class or parent classes IMPLEMENT either the Serializable interface or the Externalizable interface. Deserialization is CONVERTING the serialized object back into a copy of the object. 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. Serialization of an object is done through the FileOutputStream and ObjectOutputStream. Suppose we create an object obj of class Example: Example obj = new Example();It is serialized as follows: FileOutputStream fos = new FileOutputStream("file_name.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(obj);The serialized object is deserialized using FileInputStream and ObjectInputStream. The byte stream reverts back to the copy of the object i.e. x FileInputStream fis = new FileInputStream("file_name.txt"); ObjectInputStream ois = new ObjectInputStream(fis); Example x = (Example)ois.readObject();Let us see an program for serialization along with deserialization of an object named obj : import java.io.*; public class Example implements Serializable { int a = 1, b = 2; // instance variable transient int c = 3; // transient variable public static void main(String[] args) throws Exception { Example obj = new Example(); // serialization FileOutputStream fos = new FileOutputStream("example_file.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(obj); // de-serialization FileInputStream fis = new FileInputStream("example_file.txt"); ObjectInputStream ois = new ObjectInputStream(fis); Example x = (Example)ois.readObject(); System.out.println("a = " + x.a); System.out.println("b = " + x.b); System.out.println("c = " + x.c); } }The output is as follows: $javac Example.java $java Example a = 1 b = 2 c = 0 |
|
| 106. |
Avoid Deadlock in Java? |
|
Answer» A deadlock is a situation that usually occurs in multi-threading or multi-tasking. It means that two or more THREADS are waiting indefinitely on each other to release the resources they require to complete their EXECUTION. DEADLOCKS can be avoided in Java by trying to avoid the possibilities that give rise to them. These possibilities cannot be completely erased but they can definitely be lessened. Some of the ways to avoid deadlocks in Java are given as follows:
Using unnecessary locks can lead to deadlock so only those members should be locked that are ACTUALLY required.
Nested locks to multiple threads are the main reason for deadlocks. So, locks to multiple threads should be avoided if one thread has already been locked.
If one thread is waiting for another then deadlock occurs. So, Thread.join can be used if the deadlock condition appears for the maximum time required for the execution. |
|
| 107. |
How Java Threads communicate with each other? |
|
Answer» Inter-thread communication involves the communication of Java threads with each other. The three methods are Java that are used to IMPLEMENT inter-thread communication are given as follows:
This method causes the CURRENT thread to release the lock. This is done until a specific amount of time has passed or another thread calls the notify() or notifyAll() method for this OBJECT.
This method wakes a SINGLE thread out of multiple threads on the current object’s monitor. The choice of thread is arbitrary.
This method wakes up all the threads that are on the current object’s monitor. A program that demonstrates inter-thread communication in Java is given as follows: class BankCustomer { int balAmount = 10000; synchronized void withdrawMoney(int amount) { System.out.println("Withdrawing money"); balAmount -= amount; System.out.println("The balance amount is: " + balAmount); } synchronized void depositMoney(int amount) { System.out.println("Depositing money"); balAmount += amount; System.out.println("The balance amount is: " + balAmount); notify(); } } public class Demo { public static void main(String args[]) { final BankCustomer cust = new BankCustomer(); new Thread() { public void run() { cust.withdrawMoney(5000); } }.start(); new Thread() { public void run() { cust.depositMoney(2000); } }.start(); } }The output of the above program is as follows: Withdrawing money The balance amount is: 5000 Depositing money The balance amount is: 7000 |
|
| 108. |
Java vs Python |
||||||||||||||||||
|
Answer» Both Java and Python are HIGH level languages. Some of the differences between these languages are given as follows:
|
|||||||||||||||||||
| 109. |
Why Strings in Java are Immutable? |
|
Answer» Strings in Java are immutable. This means that they are unchangeable or unmodifiable. There are several reasons for this. Some of these are given below:
Synchronization issues are solved by making strings in Java as immutable. This is because they automatically become thread safe if they are immutable.
Class Loading has string arguments. If Strings were MUTABLE, then wrong classes could be loaded as mutable objects change their state.
Network connections, urls, DATABASE connections, usernames/passwords etc. have parameters that are represented as String. These parameters could be easily changed if the Strings were mutable and that WOULD be a security breach. A program that demonstrates Strings is given as FOLLOWS: public class Demo { public static void main(String args[]) { String str = "Snow"; str.concat("White"); System.out.println(str); } }The output of the above program is as follows: SnowIn the above program, only Snow is printed as Strings are immutable objects. |
|
| 110. |
Difference between declaring a variable and defining a variable in Java |
|
Answer» Declaring a variable implies giving a DATA type to the variable such as int, float, char etc. An example of this is given as follows: int val;Defining a variable implies assigning a value to the declared variable. This value is stored in the variable. An example of this is given as follows: val = 5;A program that demonstrates declaring a variable and defining a variable in Java is given as follows: public class Demo { public static void main(STRING[] ARGS) { int val; //declaring a variable val = 5; //defining a variable System.out.println("val = " + val); } }The OUTPUT of the above program is as follows: val = 5 |
|
| 111. |
Difference between inner class and nested class in Java? |
|
Answer» A nested class in Java is declared inside a class or interface. There are two types of nested CLASSES i.e. static and non-static. The non-static nested classes are known as inner class in Java whereas the static nested classes are merely known as nested class. A program that demonstrates an inner class in Java is GIVEN as follows: class Outer { class Inner { public void display() { System.out.println("Inside the inner class METHOD"); } } } public class Main { public static void main(String[] args) { Outer.Inner OBJ = new Outer().new Inner(); obj.display(); } }The output of the above program is as follows: Inside the inner class methodA program that demonstrates the nested class in Java is given as follows: class Outer { static int num = 67; static class Inner { public void display() { System.out.println("The number is: " + num); } } } public class Main { public static void main(String[] args) { Outer.Inner obj = new Outer.Inner(); obj.display(); } }The output of the above program is as follows: The number is: 67 |
|
| 112. |
Stop a Thread in Java |
|
Answer» Stopping a thread in Java can be a little complicated as there is no working stop method. This is quite DIFFERENT than starting a thread in Java as there is a start() method available. When Java was first released, there was a stop() method in Thread class, but that has since been deprecated. A program that demonstrates how to stop a thread in Java using a personal stop() method is given as FOLLOWS: import static java.lang.Thread.currentThread; import java.util.concurrent.TimeUnit; public class Demo { public static VOID main(String args[]) throws InterruptedException { Server ser = new Server(); Thread thread = new Thread(ser, "T1"); thread.start(); System.out.println(currentThread().getName() + " is stopping Server thread"); ser.stop(); TimeUnit.MILLISECONDS.sleep(200); System.out.println(currentThread().getName() + " is finished now"); } } class Server implements RUNNABLE { private volatile boolean exit = false; public void run() { while(!exit) { System.out.println("The Server is running"); } System.out.println("The Server is now stopped"); } public void stop() { exit = true; } }The OUTPUT of the above program is as follows: main is stopping Server thread The Server is running The Server is now stopped main is finished now |
|
| 113. |
Serialization vs Deserialization in Java |
|
Answer» Serialization in JAVA involves writing the object state into a byte stream so that it can be SENT to a database or a disk. Deserialization is the reverse PROCESS wherein the stream is converted into the object. The java.io.Serializable interface is implemented by default by the String class as well as all the wrapper classes. The functionality to serialize the objects is provided by the writeObject() method of ObjectOutputStream class. Deserialization of objects and primitive data is done using ObjectInputStream. A program that demonstrates serialization and deserialization in Java is given as follows: import java.io.*; class EMPLOYEE implements Serializable { int empID; String name; Employee(int e, String n) { this.empID = e; this.name = n; } } public class Demo { public static void MAIN(String[] args) { Employee emp1 = new Employee(251,"Jason Scott"); FileOutputStream f = new FileOutputStream("file.txt"); ObjectOutputStream o = new ObjectOutputStream(f); o.writeObject(emp1); o.flush(); ObjectInputStream i = new ObjectInputStream(new FileInputStream("file.txt")); Employee emp2 = (Employee)i.readObject(); System.out.println(emp2.empID + " " + emp2.name); i.close(); } }The output of the above program is as follows: 251 Jason Scott |
|
| 114. |
super vs this in Java |
|
Answer» Both super and this are keywords in JAVA. Details about these are GIVEN as follows: The super keywordThe super keyword is a reserved keyword in Java that is used to refer to the immediate parent class. The super keyword can also invoke the method and constructor of the immediate parent class. A program that demonstrates the super keyword is given as follows: class A { int x = 26; static int y = 15; } public class B EXTENDS A { void display() { System.out.println(super.x); System.out.println(super.y); } public static void main(String[] args) { B obj = new B(); obj.display(); } }The OUTPUT of the above program is as follows: 26 15The this keywordThe this keyword is a reserved keyword in Java that is used to refer to the current class instance variable. The this keyword can also invoke the method and constructor of the current class. It can also be passed as an argument in the method or constructor call. A program that demonstrates the super keyword is given as follows: public class Demo { int x = 25; static int y = 12; void display() { this.x = 250; System.out.println(x); this.y = 120; System.out.println(y); } public static void main(String[] args) { Demo obj = new Demo(); obj.display(); } }The output of the above program is as follows: 250 120 |
|
| 115. |
ArrayList vs Vectors in Java |
||||||||||||
|
Answer» The list interface in Java can be maintained using both ARRAYLIST and Vector and both of them use dynamically resizable arrays as their internal DATA structure. So, the major DIFFERENCES between these are given as follows:
|
|||||||||||||
| 116. |
Memory Management in Java |
|
Answer» Memory Management is a vital part of Java and it is very important to understand it. The memory in Java is divided into two MAIN parts, the stack and the heap. A diagram that demonstrates this is given as follows: Details about the stack and the heap memory in Java is given as follows: Stack Memory in JavaThe Stack memory in Java is used for thread execution. Specific values are stored in the thread stack that are available for a short time. Also, stack memory may contain DATA references to objects GETTING referred from the method that are in the heap memory. The order in Thread Stack memory is Last In First Out (LIFO). A block is created in the stack memory for all the primitive values and references to other objects in a method when that method is invoked. After the end of the method, the memory block in the stack memory is free and can be used by another method. Heap Memory in JavaThe heap memory in Java is memory allocated to the Objects and the JRE CLASSES by the Java runtime. All the objects in the application are created in the heap memory. The objects in the heap memory are globally accessible from any place in the application and so they have a lifetime for the whole application execution. |
|
| 117. |
Thread Priority in Java |
|
Answer» In multithreading, each thread is assigned a PRIORITY. The processor is assigned to the thread by the scheduler based on its priority i.e. the highest priority thread is assigned the processor FIRST and so on. The three STATIC values defined in the Thread class for the priority of a thread are given as follows:
This is the maximum thread priority with value 10.
This is the default thread priority with value 5.
This is the minimum thread priority with value 1. A program that demonstrates thread priority in Java is given as follows: import java.lang.*; public class ThreadPriorityDemo extends Thread { public static VOID main(String[]args) { ThreadPriorityDemo thread1 = new ThreadPriorityDemo(); ThreadPriorityDemo thread2 = new ThreadPriorityDemo(); ThreadPriorityDemo thread3 = new ThreadPriorityDemo(); System.out.println("Default thread priority of thread1: " + thread1.getPriority()); System.out.println("Default thread priority of thread2: " + thread2.getPriority()); System.out.println("Default thread priority of thread3: " + thread3.getPriority()); thread1.setPriority(8); thread2.setPriority(3); thread3.setPriority(6); System.out.println("New thread priority of thread1: " + thread1.getPriority()); System.out.println("New thread priority of thread2: " + thread2.getPriority()); System.out.println("New thread priority of thread3: " + thread3.getPriority()); } }The OUTPUT of the above program is as follows: Default thread priority of thread1: 5 Default thread priority of thread2: 5 Default thread priority of thread3: 5 New thread priority of thread1: 8 New thread priority of thread2: 3 New thread priority of thread3: 6 |
|
| 118. |
Need of Thread in Java |
|
Answer» Threads in Java help to achieve parallelism in a program. This means that multiple operations can be performed at the same time using multithreading. The most IMPORTANT usage of threads can be achieved using multithreading. This means that multiple tasks can be done simultaneously using multithreading. Some of the major uses of multithreading in Java are given as follows:
The response time for a particular problem can be reduced by dividing it into smaller CHUNKS and assigning each of these chunks to a thread. This means that multiple threads can be used to solve the problem in a relatively lesser time.
Multiple tasks can run in parallel using multithreading. An example of this is event handling or drawing which can be performed at the same time using multiple threads. Also, multiple threads are REQUIRED in a Graphical User Interface as a thread is performing a particular function, other threads are required for more user tasks as the GUI cannot be frozen.
In a client server application, many clients can connect to the server using multiple threads. This means that a client does not have to wait until the request of the previous client has been serviced by the server.
Threads can be used to utilize the full CPU power and INCREASE the throughput of the system. If there are multiple cores to the CPU, then multiple threads are required to run in parallel across these cores to optimize the system performance. |
|
| 119. |
Composition in Java |
|
Answer» The two entities in composition are quite dependent on each other i.e. one ENTITY cannot exist without the other. Basically, composition is a restricted form of aggregation. A program that demonstrates composition in Java is given as follows: import java.io.*; import java.util.*; class DEPARTMENT { public STRING name; Department(String name) { this.name = name; } } class College { private final List<Department> departments; College (List<Department> departments) { this.departments = departments; } public List<Department> getDepartments() { return departments; } } public class Demo { public static void main (String[] args) { Department d1 = new Department("Computer Science"); Department d2 = new Department("Electrical"); Department D3 = new Department("Mechanical"); Department d4 = new Department("INFORMATION Technology"); Department d5 = new Department("Civil"); List<Department> departments = new ArrayList<Department>(); departments.add(d1); departments.add(d2); departments.add(d3); departments.add(d4); departments.add(d5); College c = new College(departments); List<Department> dpt = c.getDepartments(); System.out.println("The different departments in college are: "); for(Department d : dpt) { System.out.println(d.name); } } }The output of the above program is as follows: The different departments in college are: Computer Science Electrical Mechanical Information Technology CivilThe above program is an example of composition as the departments and college are dependent on each other. There would be no departments without a college. |
|
| 120. |
Priority Queue in Java |
|
Answer» The priority queue is a data structure in which elements are handled based on their priority. The priority heap is the basis of the priority queue. Also, priority queues are unbound queues and they do not allow NULL pointers. A program that demonstrates priority queue in Java is GIVEN as follows: import java.util.*; public CLASS Demo { public STATIC void main(String args[]) { PriorityQueue<String> p = new PriorityQueue<String>(); p.add("Apple"); p.add("Mango"); p.add("Orange"); p.add("Peach"); p.add("Guava"); System.out.println("The priority queue elements are:"); Iterator I1 = p.iterator(); while (i1.hasNext()) { System.out.println(i1.next()); } System.out.println("\nThe ELEMENT with highest priority is: " + p.peek()); p.poll(); System.out.println("\nThe priority queue elements after removing an element with poll function are:"); Iterator<String> i2 = p.iterator(); while (i2.hasNext()) { System.out.println(i2.next()); } } }The output of the above program is as follows: The priority queue elements are: Apple Guava Orange Peach Mango The element with highest priority is: Apple The priority queue elements after removing an element with poll function are: Guava Mango Orange Peach |
|
| 121. |
Anonymous Inner Class in Java |
|
Answer» An anonymous class is an inner class that does not have any name in Java. Only a single object of this class is created. An instance of an object can be created with more features such as OVERLOADING methods of a class by using the anonymous inner class. This can be done without having to subclass a class. A PROGRAM that demonstrates the anonymous inner class in Java is given as follows: interface Num { int num = 50; void getNum(); } public class Demo { public static void main(STRING[] args) { Num obj = new Num() { @Override public void getNum() { System.out.print("The number is: " + num); } }; obj.getNum(); } }In the above example an anonymous inner class is used and the object of that is created as WELL as copied in the class code. |
|
| 122. |
Comparable vs Comparator interface in Java |
|
Answer» There are two interfaces to sort the objects using the class data members. These are comparable interface and comparator interface. Details about these are given as FOLLOWS: Comparable InterfaceThe comparable interface provides a single SORTING sequence. This means that a single element of the collection can be used as the basis for the sorting. The compareTo() method is used by the comparable interface to sort the elements. The java.lang package contains the comparable interface. A program that demonstrates the comparable interface is given as follows: import java.io.*; import java.util.*; class Student implements Comparable<Student> { private int rollNumber;; private String name; private double MARKS; public int compareTo(Student s) { return this.rollNumber - s.rollNumber; } public Student(int rno, String n, double m) { this.rollNumber = rno; this.name = n; this.marks = m; } public int getRNo() { return rollNumber; } public String getName() { return name; } public double getMarks() { return marks; } } public class Demo { public static void main(String[] args) { ArrayList<Student> list = new ArrayList<Student>(); list.add(new Student(23, "Harry", 87.5)); list.add(new Student(1, "AMY", 85.5)); list.add(new Student(15, "John", 55.0)); list.add(new Student(45, "James", 95.0)); list.add(new Student(7, "Sally", 78.0)); System.out.println("Original Student List: "); for (Student s: list) { System.out.println(s.getRNo() + " " + s.getName() + " " + s.getMarks()); } Collections.sort(list); System.out.println("\nStudent List after sorting according to their Roll Number: "); for (Student s: list) { System.out.println(s.getRNo() + " " + s.getName() + " " + s.getMarks()); } } }The output of the above program is as follows: Original Student List: 23 Harry 87.5 1 Amy 85.5 15 John 55.0 45 James 95.0 7 Sally 78.0 Student List after sorting according to their Roll Number: 1 Amy 85.5 7 Sally 78.0 15 John 55.0 23 Harry 87.5 45 James 95.0Comparator InterfaceThe comparator interface provides multiple sorting sequences. This means that multiple elements of the collection can be used as the basis for the sorting. The compare() method is used by the comparator interface to sort the elements. The java.util package contains the comparator interface. A program that demonstrates the comparator interface is given as follows: import java.io.*; import java.util.*; class Student implements Comparable<Student> { private int rollNumber;; private String name; private double marks; public int compareTo(Student s) { return this.rollNumber - s.rollNumber; } public Student(int rno, String n, double m) { this.rollNumber = rno; this.name = n; this.marks = m; } public int getRNo() { return rollNumber; } public String getName() { return name; } public double getMarks() { return marks; } } class MarksCompare implements Comparator<Student> { public int compare(Student s1, Student s2) { if (s1.getMarks() < s2.getMarks()) return -1; if (s1.getMarks() > s2.getMarks()) return 1; else return 0; } } class NameCompare implements Comparator<Student> { public int compare(Student s1, Student s2) { return s1.getName().compareTo(s2.getName()); } } public class Main { public static void main(String[] args) { ArrayList<Student> list = new ArrayList<Student>(); list.add(new Student(23, "Harry", 87.5)); list.add(new Student(1, "Amy", 85.5)); list.add(new Student(15, "John", 55.0)); list.add(new Student(45, "James", 95.0)); list.add(new Student(7, "Sally", 78.0)); System.out.println("Original Student List: "); for (Student s: list) { System.out.println(s.getRNo() + " " + s.getName() + " " + s.getMarks()); } Collections.sort(list); System.out.println("\nStudent List sorted by Roll Number: "); for (Student s: list) { System.out.println(s.getRNo() + " " + s.getName() + " " + s.getMarks()); } System.out.println("\nStudent List sorted by Marks: "); MarksCompare mc = new MarksCompare(); Collections.sort(list, mc); for (Student s: list) { System.out.println(s.getRNo() + " " + s.getName() + " " + s.getMarks()); } System.out.println("\nStudent List sorted by Name: "); NameCompare nc = new NameCompare(); Collections.sort(list, nc); for (Student s: list) { System.out.println(s.getRNo() + " " + s.getName() + " " + s.getMarks()); } } }The output of the above program is as follows: Original Student List: 23 Harry 87.5 1 Amy 85.5 15 John 55.0 45 James 95.0 7 Sally 78.0 Student List sorted by Roll Number: 1 Amy 85.5 7 Sally 78.0 15 John 55.0 23 Harry 87.5 45 James 95.0 Student List sorted by Marks: 15 John 55.0 7 Sally 78.0 1 Amy 85.5 23 Harry 87.5 45 James 95.0 Student List sorted by Name: 1 Amy 85.5 23 Harry 87.5 45 James 95.0 15 John 55.0 7 Sally 78.0 |
|
| 123. |
Convert string to date in Java |
|
Answer» The compare() method is USED in JAVA to compare two doubles. The output: Value 1 is greater than Value 2 |
|
| 124. |
Best Practices of Exception Handling in Java |
|
Answer» Exception handling is the process that deals with the occurrence of exceptions during computation. Some of the best practices of exception handling in Java are given as follows:
There are many resources that are used in a TRY block that need to be closed afterwards. HOWEVER, these resources should not be closed in the end of the try block as it may never be reached if any exception is thrown. So, all the cleanup code should be in the finally block for better results.
The superclass of all the exceptions and errors is throwable. It should never be used in a catch clause as it will catch all exceptions and errors, some of which may be outside the control of the APPLICATION and so unable to be handled.
Descriptive messages should be provided with exceptions that help to understand why the exception was reported to the monitoring tool or the log file. The descriptive messages should be precise and describe the exceptional event problem as clearly as possible.
All the exceptions that are specified in the method signature should also be documented in the Javadoc. This is quite useful as it provides the caller with more information that helps to handle or avoid the exception as required.
Never ignore an exception under the assumption that it will never occur. This is faulty as the code may change in unforeseen ways in the future and the exceptions thought not required as a particular event would never occur might just occur.
The most specific exception class should be catched first and the less specific catch blocks should be provided later as the first catch block that matches an exception gets executed. So, if the less specific exception catch block is given first, then the control may never REACH the more specific exception catch block.
It is better to have as specific exceptions as possible as they make the API easier to understand. This means that the class which is the best fit for the exceptional event should be used and unspecified exceptions should be avoided.
Do not log and rethrow exceptions as it leads to multiple error messages for the same exception. These additional error messages are quite useless as they do not provide any extra information. If any additional information is required, the exception should be caught and wrapped in a custom one. |
|
| 125. |
Marker Interface in Java |
|
Answer» An empty interface that contains no fields or methods is known as a marker interface. Realistic examples of a marker interface are Serializable interface, Cloneable interface and Remote interface. Details about these interfaces are given as follows: Serializable InterfaceThe serializable interface makes an object eligible to save its state in a file. This interface is stored in the java.io package. The CLASSES in which the serializable interface is not implemented do not have their states SERIALIZED or deserialized. Cloneable InterfaceThe cloneable interface is implemented by a class that indicates it is allowed for a clone() method in the Object class to MAKE field-to field COPY of the class instances. The java.lang package contains the cloneable interface. The exception CloneNotSupportedException is thrown if the clone() method is invoked for a class that has no implementation of the cloneable interface. The classes that have an implementation of this interface usually override the Object.clone() method by convention. Remote InterfaceAn object that is stored on a machine and can be accessed from another machine is known as a remote object. The remote interface is required to flag an object and convert it into a remote object. The java.rmi package contains the remote interface. The interfaces whose methods can be invoked using a non-local virtual machine can also be identified by the remote interface. Also, the Remote Method Invocation (RMI) has some convenience class that can be extended using the remote object implementations and these facilitate the creation of the remote objects. |
|
| 126. |
Collections API in Java |
|
Answer» A group of objects can be STORED and manipulated using an architecture that is provided by the Collections API in Java. All the possible operations in Java such as searching, sorting, deletion, insertion etc. can be performed using the Java Collections. A HIERARCHY of collections in Java is given as follows: Some of the characteristics of the Collections API in Java are given as follows:
|
|
| 127. |
ArrayList vs LinkedList in Java |
|
Answer» ArrayList and LinkedList are very important lists in Java. While the ArrayList implements a DYNAMIC array, the LinkedList implements a doubly linked list. Some of the differences between Arraylist and LinkedList are given as follows:
A program that demonstrates ArrayList in Java is given as follows: import java.util.ArrayList; public class ArrayListDemo { public static void main(String[] args) { ArrayList<String> al= new ArrayList<String>(); al.add("Apple"); al.add("Orange"); al.add("Guava"); al.add("MANGO"); al.add("Peach"); System.out.println(al); al.remove(2); System.out.println(al); if (al.contains("Apple")) System.out.println("Apple found in ArrayList"); else System.out.println("Apple not found in ArrayList"); } }The output of the above program is as follows: [Apple, Orange, Guava, Mango, Peach] [Apple, Orange, Mango, Peach] Apple found in ArrayListA program that demonstrates LinkedList in Java is given as follows: import java.util.LinkedList; public class LinkedListDemo { public static void main(String[] args) { LinkedList l = new LinkedList(); l.add("Apple"); l.add("Orange"); l.add("Guava"); l.add("Mango"); l.add("Peach"); System.out.println(l); l.remove(0); System.out.println(l); if (l.contains("Apple")) System.out.println("Apple found in LinkedList"); else System.out.println("Apple not found in LinkedList"); } }The output of the above program is as follows: [Apple, Orange, Guava, Mango, Peach] [Orange, Guava, Mango, Peach] Apple not found in LinkedList |
|
| 128. |
Role of Java Sockets |
|
Answer» The Java Sockets are USED for communication between two computers using the TCP PROTOCOL. The communication between the client and server occurs when they read from and write to the sockets as required. The class java.net.Socket provides a representation for sockets in Java and the class java.net.ServerSocket allows the server programs to listen for clients and create connections with them. The steps to create a TCP connection between two computers using sockets is given as follows:
The communication can occur using the Output stream and INPUT stream after the connections are established. |
|
| 129. |
Explain JRE (Java Runtime Environment) |
|
Answer» The Java RUNTIME Environment consists of the Java Virtual Machine, supporting files and core classes. This is basically the minimum requirements to execute a Java application. The JRE is actually a component of the JDK but it can be downloaded separately from the rest. Some of the components of the JRE are given as follows:
The Java programs are executed by the Java Virtual Machine which is a running software system. The Java Runtime Environment on the other hand, is a on-disk system that starts the JVM to execute the Java code by combining it with the required libraries. In short, the software and libraries that are necessary to run the Java programs are CONTAINED in the Java Runtime Environment. A diagram that demonstrates that the JRE contains the JVM is given as follows: Installing the JREThe Java Runtime Environment is essentially a software that is installed on the computer that runs the Java programs. Normally, Java is installed on the computer and the JRE is included. HOWEVER, if anytime it is required to install or upgrade the JRE manually, it can be done by downloading the current JRE VERSION from Oracle. |
|
| 130. |
Default vs Protected access specifiers in Java |
|
Answer» The access specifiers in Java specify the scope of the data members, constructors, methods etc. of the class. Details about the DEFAULT and protected access specifiers are given as follows: Default Access SpecifierThe default access specifier is used when no access specifier is clearly provided by the PROGRAMMER. The data members, constructors, methods etc. that have the default access specifier are only accessible in the same package. A program that demonstrates the default access specifier in Java is given as follows: package pack1; class C1 { void print() { System.out.println("This is in package p1"); } } package pack2; IMPORT pack1.*; class C2 { public static void main(String args[]) { C1 obj = new C1(); obj.print(); } }Execution of the above program results in compile time error as the access specifier of class C1 and print() is default and so they cannot be accessed from outside the package pack1. Protected Access SpecifierThe protected access specifier can be used on the class data members or methods with the protected keyword. This MEANS that the data members are accessible INSIDE the package and in other packages using inheritance. The protected access specifier cannot be directly applied on a class but it can be applied on a data member, constructor or method. A program that demonstrates the protected access specifier in Java is given as follows: package pack1; public class C1 { protected void print() { System.out.println("This is in package p1"); } }Another package: package pack2; import pack1.*; class C2 extends C1 { public static void main(String args[]) { C1 obj = new C1(); obj.print(); } }The output of the above program is as follows: This is in package p1 |
|
| 131. |
Role of default constructor in Java |
|
Answer» A default constructor is a constructor without PARAMETERS that is automatically created if there is no constructor written by the programmer. All the DATA MEMBERS in a class are initialized by the default constructor to their default values. The default values of numeric data types is 0, of references is null, of floating point numbers is 0.0 and of booleans is false. A program that demonstrates a default constructor in Java is given as follows: class Student { INT rollNumber; String name; float MARKS; } public class Demo { public static void main(String args[]) { Student s = new Student(); System.out.println(s.rollNumber); System.out.println(s.name); System.out.println(s.marks); } }The output of the above program is as follows: 0 null 0.0In the above program, the default constructor is called when an object s of class Student is created. Then the default values of the data members of class Student are printed. |
|
| 132. |
Role of throw and throws keyword in Java |
|
Answer» Both the throw and throws keywords in Java are related to exception handling. Details about these are given as follows: The throw keywordAn exception can be thrown explicitly from a METHOD or a code block using the throw keyword. Mainly custom exceptions are thrown using this keyword. ALSO, throw can be used to throw checked or unchecked exceptions. A PROGRAM that demonstrates throw keyword in Java is given as follows: public class Demo { static void checkMarks(int marks) { if(marks < 40) throw new ArithmeticException("You failed"); else System.out.println("Congratulations! You passed"); } public static void main(String args[]) { System.out.println("Test Report"); checkMarks(29); } }The output of the above program is as follows: Test Report Exception in thread "main" java.lang.ArithmeticException: You failed at Demo.checkMarks(Demo.java:6) at Demo.main(Demo.java:16)The throws keywordThe signature of a method can CONTAIN the throws keyword to signify that the specified method can throw any one of the listed type exceptions. The exception can be handled using a try catch block by the caller of the method. A program that demonstrates throws keyword in Java is given as follows: public class Demo { public static void main(String[] args)throws InterruptedException { Thread.sleep(1000); System.out.println("Demonstration of throws keyword"); } }The output of the above program is as follows: Demonstration of throws keyword |
|
| 133. |
BigInteger negate value |
|
Answer» Use the BigInteger negate() METHOD to nagate a BigInteger VALUE in Java. Let us see a simple example: import java.math.*; PUBLIC CLASS Example { public static void main(String[] args) { BigInteger b1, b2; b1 = new BigInteger("35"); b2 = b1.negate(); System.out.println("Negated = " +b2); } }The output: Negated = -35 |
|
| 134. |
States of a Thread in Java |
|
Answer» The thread LIFE cycle in Java CONTAINS 5 states. This means that the thread can be in any of these 5 states. The 5 states in a thread life cycle are DEMONSTRATED with the help of a diagram as follows: 1. New When an instance of the thread class has been created but the start() method is not invoked, then the thread is in the new state. 2. RUNNABLE When the start() method has been invoked but the thread scheduler has not selected the thread for execution, then the thread is in the runnable state. 3. Running If the thread scheduler has selected a thread and it is currently running, then it is in the running state. 4. Blocked (Non-runnable) When a thread is not eligible to RUN but still alive, then it is in the blocked state. 5. Terminated When the run() method of a thread exits, then it is in the terminated state. |
|
| 135. |
Java Stack Memory |
|
Answer» The Stack memory in Java is used for thread execution. Specific values are stored in the stack memory that are available for a short time. Also, stack memory may contain data references to objects getting referred from the method that are in the heap memory. The order in Stack memory is Last In First Out (LIFO). A block is created in the stack memory for all the primitive values and references to other objects in a method when that method is invoked. After the end of the method, the memory block in the stack memory is free and can be used by another method. In general, the size of the stack memory is quite less as COMPARED to the heap memory. Some of the important FEATURES of Java Stack Memory are given as follows:
Some of the DIFFERENCES between stack memory and heap memory are given as follows:
|
|
| 136. |
Which Java operator has the highest precedence? |
|||||||||||||||||||||||||||||||||||||||||||||
|
Answer» The operator PRECEDENCE in JAVA determines the order of evaluation for the operators in an expression. The Java operator that has the highest precedence can be seen from the table given below:
As is obvious from the above table, the postfix operators (++ --) have the highest precedence in Java. |
||||||||||||||||||||||||||||||||||||||||||||||
| 137. |
Aggregation in Java |
|
Answer» Aggregation is a type of weak association that specifies a HAS-A relationship. Both the objects of a class in an aggregation can EXIST individually. Also, aggregation is a one-way relationship. For example - A class in a school has STUDENTS but the opposite is not true. A program that demonstrates aggregation in Java is given as FOLLOWS: class School { private String name; School(String name) { this.name = name; } public String retClassName() { return this.name; } } class Student { private int rno; private String name; Student(int rno, String name) { this.rno = rno; this.name = name; } public String retStudentName() { return this.name; } } public class AssociationDemo { public static void main (String[] args) { School c = new School("XII B"); Student s1 = new Student(1, "John"); Student s2 = new Student(2, "Susan"); Student s3 = new Student(3, "Mary"); Student s4 = new Student(4, "ADAM"); Student s5 = new Student(5, "Lucy"); System.out.println("The students in school class " + c.retClassName() + " are:") ; System.out.println(s1.retStudentName()); System.out.println(s2.retStudentName()); System.out.println(s3.retStudentName()); System.out.println(s4.retStudentName()); System.out.println(s5.retStudentName()); } }The output of the above program is as follows: The students in school class XII B are: John Susan Mary Adam LucyIn the above program, there is a HAS-A relationship between School class and student as a class in a school has multiple students. |
|
| 138. |
Association in Java |
|
Answer» A RELATIONSHIP between two CLASSES that can be ESTABLISHED using their OBJECTS is known as association in Java. The two forms of association are Composition and Aggregation. The types of association can be one-to-one, many-to-one, one-to-many, many-to-many etc. A program that demonstrates association in Java is given as follows: class Teacher { private String name; private int age; private String subject; Teacher(String name, int age, String subject) { this.name = name; this.age = age; this.subject = subject; } public String retTeacherName() { return this.name; } public String retTeacherSubject() { return this.subject; } } class Student { private int rno; private String name; Student(int rno, String name) { this.rno = rno; this.name = name; } public String retStudentName() { return this.name; } } public class Association { public static void main (String[] args) { Teacher t = new Teacher("Amy", 25, "Maths"); Student s1 = new Student(12, "John"); Student s2 = new Student(15, "Susan"); System.out.println(t.retTeacherName() + " teaches " + t.retTeacherSubject() + " to students " + s1.retStudentName() + " and " + s2.retStudentName()) ; } }The output of the above program is as follows: Amy teaches Maths to students John and SusanIn the above program, the two classes Teacher and Student are associated as a teacher may teach multiple students. This is a one-to-many relationship. |
|
| 139. |
Big Decimal negate value |
|
Answer» Use the Big Decimal NEGATE() method to negate a BigDecimal value in Java. The OUTPUT: Negated = -879879 |
|
| 140. |
What are the types of variables a class can have? |
|
Answer» The different types of variables in Java are local variables, INSTANCE variables and class variables. Details about these are given as follows: Local VariablesLocal variables in Java are those declared locally in methods, code blocks, constructors etc. When the program control enters the methods, code blocks, constructors etc. then the local variables are created and when the program control leaves the methods, code blocks, constructors etc. then the local variables are destroyed. A program that demonstrates local variables in Java is given as follows: public class Demo { public void func() { int num = 50; System.out.println("The number is : " + num); } public static void main(String args[]) { Demo obj = new Demo(); obj.func(); } }The output of the above program is as follows: The number is : 50Instance VariablesInstance variables in Java are those variables that are declared OUTSIDE a block, method, constructor etc. but inside a class. These variables are created when the class object is created and similarly, they are destroyed when the class object is destroyed. A program that demonstrates instance variables in Java is given as follows: public class Demo { int num; Demo(int N) { num = n; } public void display() { System.out.println("The number is: " + num); } public static void main(String args[]) { Demo obj = new Demo(20); obj.display(); } }The output of the above program is as follows: The number is: 20Class VariablesClass variables or Static variables are defined using the static keyword. These variables are declared inside a class but outside a method, code block etc. Class variables last for the program lifetime i.e. they are created at the START of the program and destroyed at the end of the program. A program that demonstrates class variables in Java is given as follows: public class Demo { int num; static int count; Demo(int n) { num = n; count ++; } public void display() { System.out.println("The number is: " + num); } public static void main(String args[]) { Demo obj1 = new Demo(20); obj1.display(); Demo obj2 = new Demo(50); obj2.display(); System.out.println("The total objects of class Demo are: " + count); } }The output of the above program is as follows: The number is: 20 The number is: 50 The total objects of class Demo are: 2 |
|
| 141. |
Default value of local variable in Java? |
|
Answer» Local variables in Java are those declared locally in methods, code blocks, constructors etc. When the program control enters the methods, code blocks, constructors etc. then the local variables are created and when the program control leaves the methods, code blocks, constructors etc. then the local variables are destroyed. The local variables do not have any default values in Java. This means that they should be declared and ASSIGNED a value before the variables are used for the first time. Other the compiler THROWS an error. A program that demonstrates local variables in Java is given as follows: public class Demo { public void func() { int num; System.out.println("The NUMBER is : " + num); } public STATIC void main(String args[]) { Demo OBJ = new Demo(); obj.func(); } }The above program contains a local variable num. It leads to an error “variable num might not have been initialized” The correct version of the above program is given as follows: public class Demo { public void func() { int num = 50; System.out.println("The number is : " + num); } public static void main(String args[]) { Demo obj = new Demo(); obj.func(); } }The output of the above program is as follows: The number is : 50 |
|
| 142. |
Why Java doesn’t support multiple inheritance? |
|
Answer» An important part of object-oriented programming is MULTIPLE INHERITANCE. This means that a class INHERITS the properties of multiple classes. However, multiple inheritance may lead to many problems. Some of these are:
The above problems are one of the reasons that Java doesn't support multiple inheritance. A program that demonstrates the diamond problem in Java is given as follows: public class A { void display() { System.out.println("This is class A"); } } public class B extends A { void display() { System.out.println("This is class B"); } } public class C extends A { void display() { System.out.println("This is class C"); } } public class D extends B, C { public static void main(String args[]) { D obj = new D(); D.display(); } }The above program leads to an error as multiple inheritance is not allowed Java. |
|
| 143. |
Advantages of Packages in Java |
|
Answer» A package in Java is a group of different sub-packages, interfaces, classes etc. that are of a similar type. The two types of packages are build-in packages and user defined packages. Some of the build-in packages are awt, swing, lang, util. javax, SQL etc. Some of the advantages of packages in Java are given as follows:
A PROGRAM that demonstrates a package in Java is given as follows: package packageExample; public class Demo { public static VOID main(String args[]) { System.out.println("This is a package example"); } }The OUTPUT of the above program is as follows: This is a package example |
|
| 144. |
C++ vs Java |
||||||||||||||||||||||||||||
|
Answer» C++ and Java are programming languages with many differences and similarities. C++ supports both procedural as well as object-oriented programming language while Java is purely an object oriented programming language. The major differences between C++ and Java are GIVEN as follows:
|
|||||||||||||||||||||||||||||
| 145. |
Check if a string ends with a specific substring |
|
Answer» The endsWith() method is used to check whether a string ends with a specific string or not. Here, we are checking whether the given string ends with the substring “one”: PUBLIC class Example { public STATIC VOID MAIN(String[] args) { String s = "Mobile Phone"; if(s.endsWith("one")) { System.out.println("Ends with the specified word!"); } ELSE { System.out.println("Does not end with the specified word!"); } } }The output: Ends with the specified word! |
|
| 146. |
Check if a string begins with a specific substring |
|
Answer» The startsWith() METHOD is used to check WHETHER a string begins with a specific string or not. Here, we are checking whether the given string begins with the substring “one”: public class Example { public STATIC void main(String[] ARGS) { String s = "OneAndOnly"; if(s.startsWith("one")) { System.out.println("Begins with the specified word!"); } ELSE { System.out.println("Does not begin with the specified word!"); } } }The output: Begins with the specified word! |
|
| 147. |
Display last two digits of the current year in Java |
|
Answer» To DISPLAY the last two digits of the current year, use the date character y as shown in the below example: import java.util.Date; public CLASS Example { public STATIC void main(String[] ARGS) throws Exception { Date date = new Date(); System.out.printf("Two-digit Year = %ty\n",date); } }The output display 18 for the current year 2018: Two-digit Year = 18 |
|
| 148. |
Does Java use Pointers? |
|
Answer» No, Java doesn’t exactly use pointers. Pointers are variables which store the exact address of another variable in their memory. Due to its feature of security and robustness, Java shimmies away from this concept of pointers which forms a major PART of C and C++ in memory addressing. If we know the address of a variable, we can access and modify it from anywhere EVEN if it is private which is self-contradictory and hence Java doesn’t use pointers. INSTEAD of using a pointer, Java sticks to a safer option called references. A REFERENCE is an address that shows the location of storage of the object’s variables and methods. We never actually use objects or copies of objects when we assign objects to variables or methods. Instead we use references to those objects. References though,
|
|
| 149. |
New features in Java 11 |
|
Answer» Some of the new features of Java 11 are given as follows: 1. LOCAL-Variable Syntax for Lambda Parameters The Local-Variable Type Inference was introduced by JDK 10 that simplified the code as the type of the local variable did not need to be EXPLICITLY STATED. This syntax is extended by JEP 32 for use to the parameters of Lambda expressions. 2. Single-File Source-Code Programs Java is criticized as quite a complex language. However, JEP 330 simplifies this a little bit by eliminating the need to compile a single file application. 3. HTTP Client (Standard) The Java SE 11 standard contains the HTTP client API as its part. A new module and package is introduced i.e. java.net.http. Some of the main types defined in this are as follows:
4. Remove the Java EE and CORBA Modules There are 6 modules INCLUDED in the java.se.ee meta-module that are not a part of the Java SE 11 standard. The modules that are affected are:
5. New APIs There are a lot of APA’s that are included in the JDK 11 result. There are available as the HTTP is a part of the standard and also because the Flight Recorder is included. |
|
| 150. |
Throw vs Throws keyword in Java |
||||||||||||
|
Answer» Both the throw and throws keywords in Java are related to exception handling. DIFFERENCES between these two keywords are given as follows:
A program that demonstrates throw keyword in Java is given as follows: public class Demo { STATIC void checkMarks(INT marks) { if(marks < 40) throw new ArithmeticException("You failed"); else System.out.println("Congratulations! You passed"); } public static void main(String args[]) { System.out.println("Test Report"); checkMarks(29); } }The output of the above program is as follows: Test Report Exception in thread "main" java.lang.ArithmeticException: You failed at Demo.checkMarks(Demo.java:6) at Demo.main(Demo.java:16)A program that demonstrates throws keyword in Java is given as follows: public class Demo { public static void main(String[] args) throws InterruptedException { Thread.sleep(1000); System.out.println("Demonstration of throws keyword"); } }The output of the above program is as follows: Demonstration of throws keyword |
|||||||||||||