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.
| 51. |
Synchronization with respect to Java multi-threading |
|
Answer» Multiple THREADS can manage their access to a shared resource USING SYNCHRONIZATION where only one thread accesses the resource at a time. There are two types of thread synchronization in Java. These are given as follows:
A program of thread synchronization is given as follows: class Demo { synchronized void display(int n) { for(int i=1;i<=5;i++) { System.out.println(n); try { Thread.sleep(400); }catch(Exception e){System.out.println(e);} } } } class Thread1 extends Thread { Demo obj; Thread1(Demo obj) { this.obj=obj; } public void run() { obj.display(8); } } class Thread2 extends Thread { Demo obj; Thread2(Demo obj) { this.obj=obj; } public void run() { obj.display(3); } } public class SynchronizationDemo { public static void main(String args[]) { Demo obj1 = new Demo(); Thread1 thr1 = new Thread1(obj1); Thread2 thr2 = new Thread2(obj1); thr1.start(); thr2.start(); } }The output of the above program is as follows: 8 8 8 8 8 3 3 3 3 3 |
|
| 52. |
Compare sleep() and wait() methods in Java |
||||||||||||
|
Answer» The execution of a thread can be paused in a multithreading environment in Java using the sleep() or wait() methods. The thread is paused for the required time using sleep() while the thread goes into a wait state using wait() and can only be revived by calling NOTIFY() or NOTIFYALL(). Some of the differences between sleep() and wait() are given as follows:
An example of sleep() is given as follows: synchronized(LOCK) { Thread.sleep(1000); }An example of wait() is given as follows: synchronized(LOCK) { LOCK.wait(); } |
|||||||||||||
| 53. |
Check for underflow in Java |
|
Answer» When a value is assigned to a variable that is less than the minimum allowed value for that variable, then underflow occurs. There is no exception THROWN by the JVM if an underflow occurs and it is the responsibility of the programmer to HANDLE the underflow condition. A program that checks for underflow in Java is given as follows: public class Demo { public static void main(String[] ARGS) { int num1 = -2147483648; int num2 = -1; System.out.println("Number 1: " + num1); System.out.println("Number 2: " + num2); long sum = (long)num1 + (long)num2; if (sum < Integer.MIN_VALUE) { throw new ArithmeticException("Underflow occurred!"); } System.out.println("The sum of two numbers is: " + (int)sum); } }The output of the above program is as follows: Number 1: -2147483648 Number 2: -1 Exception in thread "main" java.lang.ArithmeticException: Underflow occurred! at Demo.main(Demo.java:15) |
|
| 54. |
Check if two strings are anagrams of each other in Java |
|
Answer» An anagram of a STRING is a string that has the same characters with the same frequency. Only the character order can be different. An EXAMPLE of a anagram is given as follows: String = silent Anagram = listenA program that checks if two strings are anagrams of each other in Java is given as follows: import java.io.*; import java.util.*; public class Demo { STATIC boolean checkAnagram(char s1[], char s2[]) { int alphaCount1[] = NEW int [256]; Arrays.fill(alphaCount1, 0); int alphaCount2[] = new int [256]; Arrays.fill(alphaCount2, 0); int i; for (i = 0; i <s1.length && i < s2.length ; i++) { alphaCount1[s1[i]]++; alphaCount2[s2[i]]++; } if (s1.length != s2.length) return false; for (i = 0; i < 256; i++) { if (alphaCount1[i] != alphaCount2[i]) return false; } return true; } public static void main(String args[]) { String str1 = "triangle"; String str2 = "integral"; char s1[] = str1.toCharArray(); char s2[] = str2.toCharArray(); System.out.println("String 1: " + str1 ); System.out.println("String 2: " + str2 ); if ( checkAnagram(s1, s2) ) System.out.println("The two strings are anagram of each other"); else System.out.println("The two strings are not anagram of each other"); } }The output of the above program is as follows: String 1: triangle String 2: integral The two strings are anagram of each other |
|
| 55. |
New features in Java 10 |
|
Answer» Java 10 is the fastest release of a Java version till date. It has many important features with multiple changes that have a far-reaching impact. Some of the new features of Java 10 are given as follows: 1. Experimental Java Based JIT Compiler (JEP 317) A new Java based JIT compiler is introduced by this JEP that is the basis of an experimental AOT(Ahead of Time) compiler. 2. Time-Based Release Versioning (JEP 322) The version STRING scheme of the JDK and the Java SE platform can be revised using this JEP. 3. Remove the Native Header Generation Tool (JEP 313) There is no separate tool in Java 10 to generate header files when compiling the JNI code. This was done as the above process can already be performed using javac. 4. Garbage Collector Interface (JEP 304) The code isolation of different garbage collectors is increased and a clean interface is introduced by this JEP. 5. Parallel Full GC for G1 (JEP 307) The full GC algorithm is parallelized with the JEP 307. This is done so that the same number of threads can be used in the event of a G1 full GC as are used in the concurrent collections. 6. Heap Allocation on Alternative Memory Devices (JEP 316) The Java object heap is allocated by the HOTSPOT VM on an alternate memory device that is specified by the user. 7. CONSOLIDATE the JDK Forest into a Single Repository (JEP 296) The multiple repositories of the JDK forest are combined into a single repository using this JEP. 8. Root CERTIFICATES (JEP 319) A default SET of root certification authority is provided by the JEP 319 that makes openJDK builds more attractive for developers. 9. Local Variable Type Inference (JEP 286) Some of the strict type declaration is removed to improve the developer experience. This means that the compiler can infer the type using only var. |
|
| 56. |
When to use ArrayList and LinkedList in Java? |
|
Answer» The List interface is implemented using the ArrayList and the LinkedList. The ArrayList implements a dynamically RESIZED array while the LinkedList implements a doubly linked list. So ArrayList or LinkedList in Java should be SELECTED ACCORDING to the implementations required. Also the differences between both of these are provided to make the selection easily. Some of the differences between Arraylist and LinkedList are given as follows:
|
|
| 57. |
Constructor chaining with this keyword |
|
Answer» Constructor chaining in JAVA is the process of calling one constructor with the help of another while considering the current object. It can be done in 2 ways –
Here we will take a look at how constructor chaining is done with this keyword public class Example { Example() { this(10); System.out.println("Default constructor"); } Example(int x) { this(7, 9); System.out.println("Parameterized Constructor having parameter :"+x); } Example(int a, int b) { this(10,3,4); System.out.println("Parameterized Constructor having parameters :"+a+","+b); } Example(int a, int b, int c) { System.out.println("Parameterized Constructor having parameters :"+a+","+b+","+c); } public STATIC void MAIN(String args[]) { NEW Example(); } }The output is as follows: $javac Example.java $java Example Parameterized Constructor having parameters :10,3,4 Parameterized Constructor having parameters :7,9 Parameterized Constructor having parameter :10 Default constructor |
|
| 58. |
Execute a Java Program without main() method |
|
Answer» A JAVA program can be compiled and executed without MAIN method if we use the static block having System.exit(0); statement at the end which terminates the program before JVM starts looking for main method. However, this is only possible upto Java 6 . Let us see how to execute a Java program without the main() method public class Example { static { System.out.println("HELLO World"); System.exit(0); } }Upto Java 6, the output would be as follows: $javac Example.java $java Example Hello WorldJava 7 onwards, the program gets compiled but will not get executed and will show an error message as. |
|
| 59. |
Convert an UNSIGNED byte to Java type |
|
Answer» When a byte is converted to another data type, it is always considered to be signed. In ORDER for unsigned byte conversion, we must mask it to Java and cast it to an integer. Firstly, we declare three byte values b1, b2 and b3 and assign them values in the range of -128 to 127. Then we cast the value to an integer and use a logical & operator with 0xFF which represents the HEXADECIMAL number having integer value 255 or has binary representation as 00000000000000000000000011111111 (under the 32-bit integer) and it along with the bitwise effectively masks the VARIABLE leaving its values in the last 8 bits and ignores the other values as the other bits become 0.Thus & 0xff is used for masking variables. Let us see how an unsigned byte is converted to a Java type: import java.util.*; public class Example { public static void main(String[] args) { byte b1 = 127; byte b2 = -128; byte b3 = -1; System.out.print(b1+" : "); System.out.println((int) b1 & 0xFF); System.out.print(b2+" : "); System.out.println((int) b2 & 0xFF); System.out.print(b3+" : "); System.out.println((int) b3 & 0xFF); } }The output is as follows: $javac Example.java $java Example 127 : 127 -128 : 128 -1 : 255 |
|
| 60. |
CompletableFuture API enhancements in Java 9 |
|
Answer» In Java 9, the CompletableFuture API has been further developed. Some of the changes done to the API are:
Support for timeouts and delays public CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit)This METHOD COMPLETES the CompletableFuture with the provided value. If not, it completes it before the GIVEN timeout. Improved support for subclassing public Executor DEFAULTEXECUTOR() It returns the default Executor used for async methods that do not show an Executor. This method may be OVERRIDDEN in subclasses to return an Executor to give at least one independent thread public <U> CompletableFuture<U> newIncompleteFuture()It returns a new incomplete CompletableFuture of the specification to be returned by a CompletionStage method. New factory Methods public static <U> CompletableFuture<U> completedFuture(U value)This factory method returns a new CompletableFuture which is already accomplished with the provided value. public static <U> CompletionStage<U> completedStage(U value)This factory method returns a new CompletionStage which is accomplished beforehand with the provided value and is compatible with only those methods available in interface CompletionStage. |
|
| 61. |
Java 9 collection Factory Methods |
|
Answer» Before Java 9, we had to ADD DATA to Set and List separately and then Map them. Java 9 added methods to List, Set and Map along with their overloaded counterparts. Some of the Collection Objects have the FOLLOWING factory methods: static <E> List<T> of(T l1, T l2, T l3); static <E> Set<T> of(T s1, T s2, T s3); static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3); static <K,V> Map<K,V> ofEntries(Map.Entry<? extends K,? extends V>... entries)The of(...) method is overloaded to have 0-10 parameters and one with variable var args parameter for Set and Map interfaces and is overloaded to have 0-10 parameters for Map interface. When there are more than 10 parameters for a Map Interface, ofEntries() method is used to accept var args parameter. Let us see an example showing the USE of Collection Factory Methods: import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class Example { public static void main(String []args) { Set<String> set = Set.of("S", "E", "T"); System.out.println(set); List<String> list = List.of("L", "I", "S","T"); System.out.println(list); Map<String, String> map = Map.of("M","m","A","a","P","p"); System.out.println(map); } }The output is as FOLLOWS [S, E , T] [L, I, S, T] {M=m, A=a, P=p |
|
| 62. |
Java 9 Inner Class Diamond Operator |
|
Answer» The PURPOSE of the diamond operator was to increase reusability of code, avoid redundant code which was ACHIEVED by leaving the generic type on the right SIDE of the expression. There was a certain problem with the diamond operator as it couldn’t be used with anonymous inner classes. Java 9 enhanced the diamond operator so that it could be used with anonymous inner classes. Let us look at an example of diamond operator with anonymous inner class abstract class ABC<T> { abstract T dif(T t1, T t2); } public class Example { public static void main(String[] args) { MyClass<Integer> obj = new MyClass<>() { Integer dif(Integer a, Integer b) { return a-b; } }; Integer dif = obj.dif(10,90); System.out.println(dif); } }The output is as FOLLOWS: $javac Example.java $java Example -80 |
|
| 63. |
Can Java static methods be overridden? |
|
Answer» JAVA STATIC METHODS cannot be OVERRIDDEN. |
|
| 64. |
Stream API improvements in Java 9 |
|
Answer» When Java 9 burst onto the scene, it BROUGHT with it some improvements in STREAM API. Quite a few methods were added to the Stream Interface. Let us have a look at some of them.
takewhile() method accepts all VALUES until the predicate RETURNS false. If a stream is ordered, takewhile() returns a stream consisting the longest prefix of elements taken from this stream that match the predicate. If the stream is unordered, the method returns a stream consisting of a subset of elements extracted from this stream that match the given predicate. The syntax: default Stream<T> takeWhile(Predicate<? super T> predicate)Let us see an example of the takeWhile() method: import java.util.stream.Stream; public class Example { public static void main(String[] args) { Stream.of("y","a","m","","u","f").takeWhile(o->!o.isEmpty()).forEach(System.out::print); } }The takeWhile() method accepts all y, a, and m and then once it finds the String to be empty, it stops its execution. The output is as follows: $javac Example.java $java Example yam
The dropWhile() method drops all the value until it matches with the predicate. After that, it starts to accept values. The dropWhile() method returns the remaining stream after matching the predicate if the stream is ordered. When the stream is unordered , it returns a stream consisting of the remaining elements of this stream after dropping a subset of elements that match the given predicate. The syntax: default Stream <T> dropWhile(Predicate<? super T> predicate)Let us see a program showing the use of the dropWhile() method: import java.util.stream.Stream; public class Example { public static void main(String[] args) { Stream.of("y","a","m","","u","f").dropWhile(o->!o.isEmpty()).forEach(System.out::print); Stream.of("y","","m","","u","f").dropWhile(o->!o.isEmpty()).forEach(System.out::print); } }dropWhile() method for the first SEQUENCE drops y,a,m values, then once string is empty, it takes all the values. dropWhile() method for the first sequence drops y values, then once string is empty, it takes all the values. $javac Example.java $java Example uf muf
The iterate() method has hasNext predicate as argument which terminates the loop once hasNext predicate returns false. It takes three arguments, seed, hasNext and next. The syntax: static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext,UnaryOperator<T>next)Let us see an example of the iterator method: import java.util.stream.Stream; public class Example { public static void main(String[] args) { Stream.iterate(1, i -> i <= 10, i -> i*2).forEach(System.out::println); } }The output is as follows: $javac Example.java $java Example 1 2 4 8 10
The ofNullable prevents Null pointer exceptions and prevents null checks for streams. It returns a sequential stream that contains a single element, if non-null. Otherwise, it returns an empty stream. The syntax: static <T> Stream<T> ofNullable(T t) |
|
| 65. |
Private Interface Methods in Java 9 |
|
Answer» Java 9 introduced private methods and private STATIC methods. An interface can now have six features. The features are as follows:
The private methods increase reusability of code within interfaces. Their scope is limited to the interface itself and cannot be CALLED or accessed outside the interface. An example to show private methods in interfaces is as follows: public interface MethodInterface { public abstract void m1(); public default void M2() { m4(); //private method inside default method m5(); //static method inside other non-static method System.out.println("This is a default method"); } public static void m3() { System.out.println("This is a static method"); } private void m4() { System.out.println("This is a private method"); } private static void m5() { System.out.println("This is a private static method"); } } public class Example implements MethodInterface { @Override public void m1() { System.out.println("This is an abstract method"); } public static void main(String[] args) { MethodInterface OBJ = NEW Example(); obj.m1(); obj.m2(); MethodInterface.m3(); }The output is as follows: This is an abstract method This is a private method This is a private static method This is a default method This is a static method |
|
| 66. |
Create a module in Java 9 |
|
Answer» A self-explanatory COLLECTION of code and resources is called a MODULE. It adds a higher level of hierarchy above packages. A module is basically a uniquely named, RECLAIMABLE group of related packages, as well as resources (such as images and XML FILES) and a module descriptor. Without further ado, let us go on and see the Steps to create a module in Java 9. Let the name of our module be examplemodule. C:\>Java\src The same folder is visible here: Create a folder named examplemodule inside the src folder: C:\Java\src\examplemoduleThe screenshot displays the same path: Step 2: Create a module-info.java file in the C:\>Java\src\examplemodule folder with following code: module examplemodule{ }The screenshot: Step 3: Create a file Example.java in the C:\Java\src\examplemodule folder. The file has the following SOURCE code: package examplemodule; public class Example { public static void main(String[] args) { System.out.println("Welcome to Java 9"); } }Step 4: Create a folder C:\Java\mods. Create a folder name examplemodule in the mods folder. This is the same as the name of the module we have created. Now compile the module to mods directory C:\Java> javac -d mods/examplemodule src/examplemodule/module-info.java src/examplemodule/Example.javaStep 5: Let us run the module by running the following command C:\Java>java --module-path mods -m examplemodule/examplemodule.Example The module-path provides the module location as mods and -m signifies the main module. The following is the output: |
|
| 67. |
Inbuilt encoder and decoder for Base64 encoding in Java 8 |
|
Answer» The BASE64 class consist of static methods for obtaining encoders and decoders for Base64 encoding. JAVA 8 allows us to use three types of encoding:
The declaration of the Base64 class is as follows: public class Base64 EXTENDS ObjectLet us see an example of basic Base64 encoding and decoding: import java.util.Base64; public class Example { public static void main(String[] args) { String enc = Base64.getEncoder().encodeToString("Encoding in Base64".getBytes()); System.out.println("Encoder Output : " + enc); byte[] dec = Base64.getDecoder().decode(enc); System.out.println("Decoder Output : " + new String(dec)); } }The output is as follows: $javac Example.java $java -Xmx128M -Xms16M Example Encoder Output : RW5jb2RpbmcgaW4gQmFzZTY0 Decoder Output : Encoding in Base64 |
|
| 68. |
Are functions in Java virtual by default? |
| Answer» | |
| 69. |
Optional Class in Java 8 |
|
Answer» Optional is a container object which might not contain a non-null value. If a value is AVAILABLE, isPresent() will RETURN true and get() will return the value. Supplementary methods that rely on the availability of a contained value are provided, like orElse() methods (return a default value if value not present) and ifPresent()(execute a block of code if the value is present). Syntax for optional class public final class Optional<T> extends ObjectOptional class is a value based class. Operations pertaining to identity including reference equality (==), identity hash code, or synchronization on objects of the class may have unprecedented outcomes and should be avoided. Let us see an example where the isPresent() method of the optional class is used: import JAVA.util.Optional; public class Example { public static void main(String[] ARGS) { String s1 = new String("Hello"); String s2 = null; Optional<String> obj1 = Optional.ofNullable(s1); Optional<String> obj2 = Optional.ofNullable(s2); if (obj1.isPresent()) // checks if String object is present { System.out.println(s1.toUpperCase()); } else System.out.println("s1 is a Null string"); if(obj2.isPresent()) // checks if String object is present { System.out.println(s1.toUpperCase()); } else System.out.println("s2 is a Null string"); } }The OUTPUT is as follows: $javac Example.java $java Example HELLO s2 is a Null string |
|
| 70. |
New Date/Time API in Java 8 |
|
Answer» Java 8 introduced a new Date/Time Application Program Interface(API) as the previous Date/Time API w drawbacks.
Let us see an EXAMPLE of the Local class with the new Date/Time API: import java.time.LocalDate; import java.time.LocalTime; import java.time.LocalDateTime; import java.time.Month; public class Example { public void checkDate() { LocalDateTime currentTime = LocalDateTime.now(); // computing local Date/Time System.out.println("Present DateTime: " + currentTime); LocalDate date = currentTime.toLocalDate(); // computing local Data System.out.println("Present Local Date : " + date); // computing current local time in hours, minutes and seconds int second = currentTime.getSecond(); int minute =currentTime.getMinute(); int hour=currentTime.getHour(); System.out.println("Hour: " + hour +"|Minute: " + minute +"|seconds: " + second); } public STATIC void main(String args[]) { Example obj = new Example(); obj.checkDate(); } }The output is as follows: $javac Example.java $java Example Present DateTime: 2018-12-13T18:39:24.730 Present Local Date : 2018-12-13 Hour: 18|Minute: 39|seconds: 24Now, let us see an example of the Zoned class with the new Date/Time API: import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class Example { public static void Zone() { LocalDateTime dt = LocalDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern(" HH:mm:ss dd-MM-YYYY"); String fcd = dt.format(format); // stores the formatted current date System.out.println("Present formatted Time and Date: "+fcd); ZonedDateTime zone = ZonedDateTime.now(); System.out.println("The Present zone is "+zone.getZone()); } public static void main(String[] args) { Zone(); } }The output is as follows: $javac Example.java $java Example Present formatted Time and Date: 19:24:52 13-12-2018 The Present zone is Etc/UTC |
|
| 71. |
Predicate in Java 8 |
|
Answer» Predicate is a FUNCTIONAL interface defined in java.util.Function package. It helps in improving the control of the code. It can be used as an assignment target in lambda expressions and functional interfaces. Functional interfaces are those interfaces that have only ONE abstract method. Here is the declaration @FunctionalInterface public interface Predicate <T>Methods: boolean test(T t)The test() method evaluates the predicate BASED on the given argument. default Predicate<T> and(Predicate<? super T> other)The and() method returns a formulated predicate by short circuited logical AND of this predicate and the other. If the other is null, it throws a NullPointerException. If this predicate is false, the other is not evaluated. default Predicate<T> negate()The negate() method returns a predicate that REPRESENTS the logical NOT of this predicate. default Predicate<T> or(Predicate<? super T> other)The or() method returns a formulated predicated by short circuited OR of this predicate and the other. If this predicate is true, the other is not evaluated. static <T> Predicate<T> isEqual(Object targetRef)The isEqual() method returns a predicate that tests if two arguments are equal according to Objects.equals(Object, Object). Here is a SAMPLE program for Predicates in Java : import java.util.function.Predicate; public class Example { public static void main(String[] args) { Predicate<Integer> a = n-> (n%3==0); // Creating predicate with lambda expression System.out.println(a.test(36)); // Calling Predicate method test(Object) } }The output is as follows: $javac Example.java $java Example true |
|
| 72. |
Daemon Threads in Java |
|
Answer» Daemon Thread are a specific kind of thread in JAVA that has the lowest priority while multithreading. All the User Threads have higher priority than the Daemon Thread. It cannot STOP the JVM from exiting while rest of the threads have finished executing. JVM doesn’t depend on the execution of the daemon threads. The Daemon thread performs background TASKS like Garbage collection but is terminated as soon as the User Threads complete their execution. JVM doesn’t take into consideration whether the Daemon Thread is STILL running or not. It terminates the threads and then shuts itself down. Daemon thread in java is a service provider thread that provides services to the user thread. There are many automatic daemon threads like gc and finalizer. Methods for the Daemon thread include: public void setDaemon(boolean status)The void setDaemon(boolean status) labels the current thread as a Daemon thread or an User Thread public boolean isDaemon()The boolean isDaemon() checks whether the thread is a Daemon thread or not. Let us see the execution of Daemon Threads along with User Threads public class Example extends Thread { public Example(String thread_name) { super(thread_name); } public void run() { if(Thread.currentThread().isDaemon()) { System.out.println(getName() + " is just a Daemon thread "); } else { System.out.println(getName() + " is an User thread!!!!"); } } public static void main(String[] args) { Example t1 = new Example("t1"); Example t2 = new Example("t2"); Example t3 = new Example("t3"); Example t4 = new Example("t4"); t1.setDaemon(true); // making t1 as Daemon t1.start(); t2.setDaemon(true); // making t2 as Daemon t2.start(); t3.start(); // t3 is a user thread t4.setDaemon(true); // making t4 as Daemon } }The OUTPUT is as follows: $javac Example.java $java Example t1 is just a Daemon thread t2 is just a Daemon thread t3 is an User thread!!!!We can notice that after the execution of the User Thread t3 has completed, the Daemon Thread t4 terminates and is not checked for being a Daemon Thread. |
|
| 73. |
Does Java support Remote Method Invocation (RMI)? |
|
Answer» The Remote Method Invocation is an API in Java which manages the creation of a distributed application by ALLOWING an object to invoke a method on another object that may be on the same machine or another remote machine but is on another address space. The communication between the CLIENT and server in RMI is done by using the stub object and the skeleton object that are on the client SIDE and server side respectively. Details about the stub object and the skeleton object are provided along with the FOLLOWING DIAGRAM:
The steps to create a Remote Method Invocation program are given as follows:
|
|
| 74. |
Nashorn in Java 8 |
|
Answer» The JAVASCRIPT engine in Java SE 8 which replaces the erstwhile Rhino engine is called NASHORN. It is 2-10 times better in performance than Rhino, as it compiles the source code in the system memory directly and sends it in the form of bytecode to the JVM. JAVA 8 provides a new command for Nashorn namely, jjs which runs JAVASCRIPTS codes at command window (Command Prompt for Windows and Terminal for Linux operating systems). RUNNING js file using jjs Create and save JavaScript file example.js in the C:\Java Folder The example.js has the following command: print(‘Welcome to NASHORN’);The screenshot showing the location of the example.js file: Open Command Prompt in Windows and type C:\Java>jjs example.js Running jjs in Interactive mode Type jjs in the console window and type a print command. For exiting, type quit(): Now, quit: |
|
| 75. |
JShell in Java 9 |
|
Answer» JShell is a FEATURE introduced in Java 9. JShell provides Java with REPL ability. REPL STANDS for Read-Eval-Print-LOOP. With REPL, we can test java based logic and expressions without any requirement of compiling. REPl is acts as an immediate feedback loop and can have a great effect on productivity in that particular language. Now let us play around with JShell for a bit. Running JShell on Windows Step 1: Setup the JDK path Go to Control Panel > System > Advanced System Settings > Advanced tab > Environment Variables. Under System Variable, click Path, then New and add the following JDK path, C:\Program Files\Java\jdk-11.0.1\binStep 2: Now open Command Prompt and type jshell. Step 3: Viewing the JShell commands Step 4: Running jshell commands Type /imports in the jshell command window for obtaining the packages imported by jshell Step 5: Performing CALCULATIONS in jshell Try simple arithmetic calculations with jshell Step 6: Creating functions in jshell You can create functions and use them in jshell Step 7: Exiting jshell To exit jshell, type /exit |
|
| 76. |
Java Memory Model |
|
Answer» The Java Memory Model helps to understand the way the Java Virtual Machine works with the computer memory. The internal Java memory model divides the memory into thread stacks that are used by individual threads and the heap that is used by the entire APPLICATION. A diagram that demonstrates the internal Java memory model is given as follows: Details about the thread stack and Heap in the internal Java memory model are given as follows: Thread StackThe Thread 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. HeapThe heap space in Java is used to allocate memory to the Objects and the JRE CLASSES by the Java runtime. All the objects in the application are created in the heap space. The objects in the heap space are globally accessible from any place in the application and so they have a lifetime for the whole application execution. The memory model of the heap space is divided into parts KNOWN as generations. Details about these are given as follows:
All the new objects are allocated in the young generation and they age here. When this place fills up, then minor garbage collection occurs.
All the longer existing objects are stored in the old generation. When objects in the young generation reach a certain age THRESHOLD, they are moved to the old generation.
The Java metadata for runtime classes is stored in the permanent generation. |
|
| 77. |
What is cloning? What is the difference between shallow cloning and deep cloning? |
|
Answer» Cloning means creating a copy of an object or creating a duplicate object - the state of them should be the same. An object may be composed of SEVERAL other OBJECTS. Shallow cloning creates a new object and assigns its field values to the corresponding fields of the new object. As the fields contain only the references of the objects which reside in the HEAP, fields of the new object also point to the same component instances. Shallow cloning is fast but has a serious downside in that if any of the component objects is changed, it REFLECTS in the cloned object as well, because both of them holds the references of the same objects. Deep Cloning, on the other side, doesn’t copy the references from the fields, it creates a duplicate of the component objects as well. As in Deep cloning, all the component objects are cloned it’s comparatively slow but creates a true duplicate of the actual object. |
|
| 78. |
Is String an immutable class? Why String has been defined as immutable? |
|
Answer» Yes, String is an immutable class. String is WIDELY used in different situations like sharing as a parameter of a method, loading a class by its name, returning as a value. So, there would be a huge possibility that a String object could be changed without any knowledge of its other users and result in creating difficult to catch bugs in the system. String has been a POPULAR choice as a key in the HASHMAP or HashTable. A good candidate for a key in the HashMap should be immutable. If String had been mutable and changes its state, it might result in retrieving the wrong value for the same key or not finding it at all. String LITERALS are fetched from the String pool instead of creating it every time. Had the String been mutable, this would not be possible as it could not identify whether the value exists in the pool after any CHANGE in its state. |
|
| 79. |
What is a HashSet? How is it implemented? |
|
Answer» A SET is a collection of UNORDERED and UNIQUE elements. While adding an element a HashSet uses the hashCode() and equals() method to determine if the element already exists in the Set. If it doesn’t exist, it adds the element into the set. A HashSet uses a HashMap internally which uses the element as the key and keeps a fixed item as the VALUE. If the element exists in the HashMap as a key, it simply returns with a boolean value false denoting it already exists in the set, otherwise puts the element in the map and returns TRUE. |
|
| 80. |
What is the difference between the stack and heap memory? Why a stack is used for the purpose of storing the local variables? |
|
Answer» STACK memory is used to create the local variables and object references while executing a method by a thread. This means each thread has a SEPARATE stack and set of local variables. Stack doesn’t contain the actual objects - it only contains the references. The memory space for the actual objects is allocated in the heap memory. Heap memory is composed of a number of parts - young generation (EDEN and Survivor space) and old generation. For each method CALL JVM creates a new stack frame containing the local variables. Maintaining them as a stack helps to retrieve the most recent stack frame i.e., the set of variables of the caller method easily when a method returns. |
|
| 81. |
What is a default method? Why this design change has been done? |
|
Answer» In the earlier versions of Java (up to 1.7), the interface was DESIGNED to have only method signatures. From Java 8 the interface is now able to CONTAIN method implementation as well. These methods should be marked with default keyword and are called default methods of an interface. This means it is not mandatory to override the default methods in the implementing classes. When an interface is widely used by many applications, it was very DIFFICULT to add a new method in the same, because, it can break the code. The implementers need to change their code in many places. To overcome this COMPLEXITY and make interfaces backward compatible this change has been introduced. public interface SHAPE { default double area() { return 0.0; } default double volume() { return 0.0; } } |
|
| 82. |
What do you mean by an immutable class? How can we make a class immutable? |
|
Answer» An immutable class doesn’t allow to change the state of its objects after creation. If we need to change that state of an object it will create a new object. One of the most popular examples of an immutable class is String. We need to TAKE care of several things to make a TYPE immutable.
|
|
| 83. |
What is the String pool in java? |
|
Answer» Strings are immutable in Java. When we make changes in a String, it creates a new String OBJECT. Our PROGRAMS create a LOT of String objects in the runtime. To offer optimum performance, JVM minimizes the String object creation maintaining a pool of String literals in the heap memory (Java 7 onwards). So, when it is required to create a String literal, it first checks in the pool, whether it exists there. If found, it returns the reference of that object. Otherwise, it creates the object and reserves it in the pool for REUSING it in a later phase. |
|
| 84. |
May I override a public method with a protected method? Why is it so? |
|
Answer» We cannot override a public method by a protected method. The ACCESS modifiers of the method in the child class cannot limit the scope of the method of the parent class while overriding. This is because we call the method through a SUPERCLASS reference which overrides the parent implementation by the child implementation. As the type of reference is of Parent class, the client code knows the API with the broader scope (public) and is prepared BASED on the parent API. So, it doesn’t make any sense to limit the scope in the overriding (child) method, but the opposite is possible, of course. |
|
| 85. |
Compare two dates in Java |
|
Answer» Two dates in Java can be compared using the compareTo() method. The syntax for this is given as follows: date1.compareTo(date2)This method returns 0 if both the dates are equal, it returns a value greater than 0 if date1 is after date2 and it returns a value less than 0 if date1 is before date2. A PROGRAM that compares two dates in Java is given as follows: import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Demo { public static void main(String[] args) THROWS ParseException { SimpleDateFormat dformat = NEW SimpleDateFormat("yyyy-MM-dd"); Date D1 = dformat.parse("2018-12-05"); Date d2 = dformat.parse("2018-08-07"); System.out.println("The date 1 is: " + dformat.format(d1)); System.out.println("The date 2 is: " + dformat.format(d2)); if (d1.compareTo(d2) > 0) { System.out.println("Date 1 occurs after Date 2"); } else if (d1.compareTo(d2) < 0) { System.out.println("Date 1 occurs before Date 2"); } else if (d1.compareTo(d2) == 0) { System.out.println("Both the dates are equal"); } } }The output of the above program is as follows: The date 1 is: 2018-12-05 The date 2 is: 2018-08-07 Date 1 occurs after Date 2 |
|
| 86. |
Compare two Java arrays |
|
Answer» Two arrays in Java are SAID to be equal if they have the same number of elements and all the corresponding elements are also the same. So, the two arrays can be compared in Java by using the Arrays.equals() method. A program that demonstrates this method is given as follows: import java.util.Arrays; PUBLIC class DEMO { public static void MAIN (STRING[] args) { int arr1[] = {5, 2, 9, 7, 1}; int arr2[] = {5, 2, 9, 7, 1}; int i; System.out.print("Array 1: "); for (i=0; i<5; i++) System.out.print(arr1[i] + " "); System.out.print("\nArray 2: "); for (i=0; i<5; i++) System.out.print(arr2[i] + " "); if (Arrays.equals(arr1, arr2)) System.out.println("\nThe above two arrays are the same"); else System.out.println("\nThe above two arrays are not the same"); } }The output of the above program is as follows: Array 1: 5 2 9 7 1 Array 2: 5 2 9 7 1 The above two arrays are the same |
|
| 87. |
Can the overloaded method be overridden in Java? |
|
Answer» YES, we can OVERRIDE the OVERLOADED METHOD in JAVA. |
|
| 88. |
Check for Overflow in Java |
|
Answer» When a value is assigned to a variable that is more than the MAXIMUM allowed value for that variable, then overflow occurs. There is no exception thrown by the JVM if an overflow occurs and it is the RESPONSIBILITY of the programmer to handle the overflow condition. A program that checks for overflow in JAVA is given as follows: public class Demo { public static void main(String[] args) { int num1 = 2147483647; int num2 = 1; System.out.println("Number 1: " + num1); System.out.println("Number 2: " + num2); long sum = (long)num1 + (long)num2; if (sum > Integer.MAX_VALUE) { throw new ArithmeticException("Overflow occurred!"); } System.out.println("The sum of TWO numbers is: " + (int)sum); } }The OUTPUT of the above program is as follows: Number 1: 2147483647 Number 2: 1 Exception in thread "main" java.lang.ArithmeticException: Overflow occurred! at Demo.main(Demo.java:14) |
|
| 89. |
Heap vs Stack Memory in Java |
|
Answer» DETAILS about the heap space and stack memory in Java as well as their differences is given as follows: Heap Space in JavaThe heap space in Java is allocated the memory to the Objects and the JRE classes by the Java runtime. All the objects in the application are created in the heap space. The objects in the heap space are globally accessible from any place in the application and so they have a lifetime for the whole application execution. The memory model of the heap space is divided into parts known as generations. The three generations are young generation, old generation and PERMANENT generation. Stack Memory in JavaThe 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. Differences between Heap Space and Stack MemorySome of the differences between stack memory and heap memory are given as follows:
|
|
| 90. |
Reverse an Integer in Java |
|
Answer» Reversing an integer involves reversing all of its DIGITS. An example of this is given as follows: Integer = 123 Reverse of the integer = 321A program that demonstrates reversing an integer in Java is given as follows: public class Demo { public static void main(String args[]) { int num = 2413, rev = 0; System.out.println("The number is " + num); while(num != 0) { rev = rev * 10; rev = rev + num % 10; num = num / 10; } System.out.println("Reverse of the above number is " + rev); } }The OUTPUT of the above program is as follows: The number is 2413 Reverse of the above number is 3142In the above program, the number 2413 is REVERSED using a while loop and the result is stored in rev which is then DISPLAYED. |
|
| 91. |
Determine day of week for a given date in Java |
|
Answer» The Calendar.DAY_OF_WEEK constant is used in Java to get the day number of week. The EXAMPLE DISPLAYS the same: import java.util.Calendar; public class Example { public static void main(String[] args) { Calendar c = Calendar.getInstance(); System.out.println(c.getTime().toString()); System.out.println("Day = " + c.get(Calendar.DAY_OF_WEEK)); } }The example displays the day number of the week: Sun Dec 16 21:32:34 UTC 2018 Day = 1 |
|
| 92. |
When a class file gets created in Java? |
|
Answer» The JAVA CLASS file has a .class extension and contains the Java bytecode. This class file can be executed by the Java Virtual Machine. The Java class file is created as a result of successful compilation by the Java compiler from the .java file. Each class in the .java file is compiled into a separate class file if the .java file has more than one class. A program that demonstrates the creation of a class file in Java is given as FOLLOWS: class A { A() { System.out.println("This is class A"); } } class B { B() { System.out.println("This is class B"); } } public class Demo { public static void main(String[] args) { A obj1 = new A(); B OBJ2 = new B(); } }The output of the above program is as follows: This is class A This is class BAfter the above program is compiled successfully, there are 3 class files created in the corresponding folder as there are 3 CLASSES in the .java file. These class files are A.class, B.class and Demo.class. |
|
| 93. |
Role of ClassLoader in Java |
|
Answer» The Java Class is stored in the form of byte code in a .class file after it is compiled. The ClassLoader loads the Class of the Java program into memory when it is required. The ClassLoader is hierarchical and so if there is a request to load a class, it is DELEGATED to the parent class loader. The uniqueness in the Java Runtime ENVIRONMENT is maintained using this method. The types of build-in ClassLoader in Java are given as follows:
A program that demonstrates ClassLoader in Java is given as follows: public class Demo { public static void MAIN(STRING[] ARGS) { System.out.println("class loader for this class: " + Demo.class.getClassLoader()); System.out.println("class loader for DNSNameService: " + sun.net.spi.nameservice.dns.DNSNameService.class.getClassLoader()); System.out.println("class loader for HashMap: " + java.util.HashMap.class.getClassLoader()); } }The output of the above program is as follows: class loader for this class: sun.misc.Launcher$AppClassLoader@4e0e2f2a class loader for DNSNameService: sun.misc.Launcher$ExtClassLoader@5c647e05 class loader for HashMap: null |
|
| 94. |
What is a Nested Top-level class in Java |
|
Answer» Nested classes in Java is declared inside a CLASS or interface. Non-STATIC nested classes are known as inner class in Java as there are two types of nested classes i.e. static and non-static. 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 method |
|
| 95. |
Benefit of Generics in Collections Framework? |
|
Answer» Generics were introduced to deal with type-safe objects in J2SE 5. Only specific TYPES of objects can be stored in Collections as forced by Generics. Some of the benefits of Generics in Java are given as FOLLOWS: Elimination of type casting Type casting is not required after the advent of generics. An example that demonstrates this is as follows: Before generics type casting was required. List l = new ArrayList(); l.add("apple"); String str = (String) list.get(0); // type casting After generics type casting was no longer needed. List<String> l = new ArrayList<String>(); list.add("apple"); String str = list.get(0); // no type castingChecking at COMPILE time Compile time checking is PROVIDED so that there is no problem at run time as it is much better to handle a problem at compile time than at run time. An example that demonstrates this is as follows: List<String> l = new ArrayList<String>(); l.add("apple"); l.add("MANGO"); l.add(98); // This will lead to a Compile Time ErrorType-Safety Generics result in type safety as only a single type of object can be held in them. This means that other types of objects are not allowed. |
|
| 96. |
How to set JDK path in Java |
|
Answer» GO to “Start” and type “Environment Variables”. Then you will reach a window “”. System Properties Now, click on “Environment Variables”: Now click on “Path” in the user variables drop down list. Click on “New” and ENTER the following path. We are setting path here for Java 11: C:\PROGRAM Files\Java\jdk-11.0.1\binAfter adding the path above, click “OK”. Click “OK” again. Click “OK”. For verification, go to command prompt (cmd) and type: java -versionThe above shows that we have successfully set the path. |
|
| 97. |
Compare Characters in Java |
|
Answer» The Java provides compareTo() method to COMPARE two characters. Now let us compare them: public class Example { public static VOID main(String []ARGS) { Character c1 = new Character('s'); Character c2 = new Character('p'); if ((c1.compareTo(c2)) == 0) { System.out.println("Equal!"); } else if ((c1.compareTo(c2)) < 0) { System.out.println("c1 is less than c2"); } else if ((c1.compareTo(c2)) > 0) { System.out.println("c1 is less than c2"); } } }The OUTPUT: c1 is less than c2 |
|
| 98. |
Overload main() method in Java |
|
Answer» It is quite possible to overload the main() method in Java as it is not an extra-terrestrial method. The main() method is like any other method and can be overloaded too like other methods. As public static void main(STRING [] args) serves as the method signature of the main method, JVM calls its first. public static void main(String [] args) acts as the entry point for the Java program. We can overload the main method in Java. SINCE the program doesn’t execute the overloaded main method when the program executes, we need to call the overloaded main method from the ACTUAL main method which has the method signature. Let us see an EXAMPLE of overloading of the main method in Java public class Example { public static void main(String x) { System.out.println(x+" World"); } public static void main(String a, int b) { System.out.println(a+","+b); } public static void main(String []args) { System.out.println("Hello from public static void main(String []args)!"); main("Hello"); main("Hello",2); } }The output is as FOLLOWS: $javac Example.java $java -Xmx128M -Xms16M Example Hello from public static void main(String []args)! Hello World Hello,2 |
|
| 99. |
How to compare two strings in Java |
|
Answer» Using compare methods Compare two strings in Java using the compareTo() and compareToIgnoreCase() methods. The compareTo() method is used to compare two strings lexicographically or in dictionary order. Each CHARACTER is translated into a Unicode VALUE for comparison. If both the strings are equal, it returns 0 otherwise it returns positive or negative values. The compareTo() method returns a positive value if the first string is lexicographically greater than the second string and it returns a negative value if the first string is lexicographically lesser than the second string. The compareToIgnoreCase() method compares two strings lexicographically irrespective of their cases. Let us SEE an example where compareTo() and compareToIgnoreCase() methods are used to compare two strings: public class Example { public static void MAIN(String args[]) { String s1 = "Same string"; String s2 = "same string"; int a1= s1.compareTo(s2); int a2=s1.compareToIgnoreCase(s2); if(a1<0) System.out.println("String s2 is greater"); else if(a1>0) System.out.println("String s1 is greater"); else System.out.println("String s1 is equal to String s2"); if(a2==0) System.out.println("After Ignoring the case, s1 and s2 are equal"); else System.out.println("Even after ignoring the case, s1 and s2 are not equal"); } }The output is as follows: $javac Example.java $java Example String s2 is greater After Ignoring the case, s1 and s2 are equalUsing equals() and equalsIgnoreCase() The equals() method compares the string to a specific object. It returns a boolean value either true or false. It returns true when argument is not NULL and the string matches the characters of the object. The equalsIgnoreCase() does the same operation but does not take into account the case of the string and the sequence of characters of the object. Let us see an example where equals() and equalsIgnoreCase() are used to compare two strings. public class Example { public static void main(String []args) { String s1 = "Same String"; String s2 = "same string"; System.out.println(s1.equals(s2)); System.out.println(s1.equalsIgnoreCase(s2)); } }The output is as follows: $javac Example.java $java Example false trueUsing the == operator We can use the == operator to compare two strings. This operator acts like the equals() method and returns a boolean value as the result. Let us see the application of == operator for comparison of two strings: public class Example { public static void main(String []args) { String s1 = "Same String"; String s2 = "same string"; String s3 = "Same String"; System.out.println(s1==s2); System.out.println(s1==s3); } }The output is as follows: $javac Example.java $java Example false true |
|
| 100. |
Can we increase the size of a Java array after its declaration? |
|
Answer» The size of a primitive array cannot be increased in Java as it is fixed. If we try to increase the size of the primitive array, it would lead to an ArrayIndexOutOfBoundsException. import java.util.*; public class EXAMPLE { public static void main(String args[]) { int size=10; int arr[]=new int[size]; for(int i=0;i<10;i++) // initializing the array with values from 0 to 9 { arr[i]=i; } size++; // trying to increase the size and then initialize the 11th element present at 10TH index arr[size-1]=2; } }The OUTPUT is as follows: $javac Example.java $java Example Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at Example.main(Example.java:14)The code generates an java.lang.ArrayIndexOutOfBoundsException exception. To increase the size of an array, we need to copy it and increase its size dynamically. The java.util.Arrays class provides Arrays.copyOf() METHOD which helps us to create a new array with an increased size and copy the values of the elements of the original array simultaneously. The syntax: Arrays.copyOf(original_array,new_size);Let us see an example where we copy an array and increase its size: import java.util.Arrays; public class Example { public static void main(String[] args) { int[] arr = {1,2,3,4,5,6,7,8}; // array arr has 8 elements System.out.println("Inital array size: "+arr.length); // copying the array arr and increasing its size to 10 int[] crr = Arrays.copyOf(arr, 10); System.out.println("Final array size: "+crr.length); } }The output is as follows: $javac Example.java $java Example Inital array size: 8 Final array size: 10We can use the ArrayList class to create a dynamic array list but that would occupy a lot more memory. Thus we use the Arrays.copyOf() method. |
|