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.
| 151. |
Display Java Runtime Environment (JRE) version |
|
Answer» To GET the JRE version in Java, USE the predefined System.property() and include the key as “java.version” as shown below: public class EXAMPLE { public STATIC void main(String[] args) { System.out.println(System.getProperty("java.version")); } }The output displays the version: 1.8.0_141 |
|
| 152. |
Thread Life Cycle 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. A diagram to understand the states in the thread life cycle is GIVEN below: The 5 states in a thread life cycle are:
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.
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.
If the thread scheduler has selected a thread and it is CURRENTLY running, then it is in the running state.
When a thread is not ELIGIBLE to run but still ALIVE, then it is in the blocked state.
When the run() method of a thread exits, then it is in the terminated state. |
|
| 153. |
Java equals() method vs == operator |
|
Answer» The equals() method and the == operator in JAVA are both used to find if TWO objects are equal. However, while equals() is a method, == is an operator. Also, equals() compares the object values while == checks if the objects point to the same memory location. A program that demonstrates the == operator is given as follows: public class DEMO { public static void main(String[] args) { System.out.println(67 == 67); System.out.println('u' == 'v'); System.out.println('A' == 65.0); System.out.println(false == true); } }The output of the above program is as follows: true false true falseA program that demonstrates the equals() method is given as follows: public class Demo { public static void main(String[] args) { String str1 = NEW String("apple"); String str2 = new String("apple"); String str3 = new String("mango"); System.out.println(str1.equals(str2)); System.out.println(str1.equals(str3)); } }The output of the above program is as follows: true false |
|
| 154. |
Garbage Collection in Java |
|
Answer» The Garbage collection in Java DESTROYS all those objects that are not in use any more. So basically, garbage collection helps free the heap memory by removing the unreachable objects i.e. the objects that don’t have any REFERENCE to them. The different ways that an object is made eligible for garbage collection by the programmer is given as follows:
After an object is eligible for garbage collection, the garbage COLLECTOR can be run by requesting the Java Virtual Machine. This can be done using the following methods:
A PROGRAM that demonstrates running the garbage collector by requesting the Java Virtual Machine is given as follows: public class Demo { public static void main(String[] args) throws InterruptedException { Demo obj = new Demo(); obj = null; System.gc(); } @Override protected void finalize() throws Throwable { System.out.println("The garbage collector is called..."); System.out.println("The object that is garbage collected is: " + this); } }The OUTPUT of the above program is as follows: The garbage collector is called... The object that is garbage collected is: Demo@7978f9b4 |
|
| 155. |
Process vs Thread in Java |
||||||||||||||||||
|
Answer» The terms process and thread are often used in multithreading in Java. A major difference between a process and a thread is that a process is a program that is currently executing while a thread is a subpart of the process. The differences between a process and a thread in detail are given as follows:
|
|||||||||||||||||||
| 156. |
Copy Constructor in Java |
|
Answer» The main usage of the copy CONSTRUCTOR is to create an object of a class by initializing it with another object of the same class. A copy constructor in Java is not available by default like in C++, but needs to be explicitly created. A program that DEMONSTRATES a copy constructor in Java is GIVEN as follows: class Employee { int empNo; String name; int salary; Employee(int eNo, String n, int sal) { empNo = eNo; name = n; salary = sal; } Employee( Employee e) { empNo = e.empNo; name = e.name; salary = e.salary; } void print() { System.out.println("Employee Number = " + empNo); System.out.println("Name = " + name); System.out.println("Salary = " + salary); } } public class Demo { public static void main(String args[]) { Employee emp1 = new Employee(1, "John", 25000); Employee emp2 = new Employee(emp1); emp1.print(); emp2.print(); } }The output of the above program is as follows: Employee Number = 1 Name = John Salary = 25000 Employee Number = 1 Name = John Salary = 25000 |
|
| 157. |
Heap Space in Java |
|
Answer» The 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. Details about these are given as follows: 1. Young Generation All the new objects are allocated in the young generation and they age here. When this place fills up, then minor garbage collection occurs. 2. Old Generation 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. 3. Permanent Generation The Java metadata for runtime classes is stored in the permanent generation,. Some of the important features of Heap space in Java are given as follows:
Some of the differences between stack memory and heap memory are given as follows:
|
|
| 158. |
Check if a given string is a palindrome in Java |
|
Answer» A string is said to be PALINDROME if it is read the same forwards and backwards. An example of this is given as follows: String = madam The above string is palindrome.A program that checks if a string is palindrome in JAVA is given as follows: public class Example { public static void main(String args[]) { String str = "madam"; String strrev = ""; int N = str.length(); System.out.println("String: " + str); for(int i = n - 1; i >= 0; i--) { strrev = strrev + str.charAt(i); } if(str.equalsIgnoreCase(strrev)) { System.out.println("The above string is palindrome."); } else { System.out.println("The above string is not palindrome."); } } }The OUTPUT of the above program is as follows: String: madam The above string is palindrome. |
|
| 159. |
This keyword in Java |
|
Answer» The this keyword in Java refers to the CURRENT object and so is a reference variable. Some of the uses of the this keyword is GIVEN as follows:
A program that demonstrates this keyword in Java is given as follows: class Employee{ int empNo; String name; int SALARY; Employee(int empNo, String name, int salary) { this.empNo = empNo; this.name = name; this.salary = salary; } void print() { System.out.println("Employee Number = " + empNo); System.out.println("Name = " + name); System.out.println("Salary = " + salary); } } public class Demo { public STATIC void main(String args[]) { Employee emp1 = new Employee(1, "Amy", 20000); Employee emp2 = new Employee(2, "Harry", 15000); Employee emp3 = new Employee(3, "Peter", 50000); emp1.print(); emp2.print(); emp3.print(); } }The output of the above program is as follows: Employee Number = 1 Name = Amy Salary = 20000 Employee Number = 2 Name = Harry Salary = 15000 Employee Number = 3 Name = Peter Salary = 50000 |
|
| 160. |
Why multiple inheritance is not supported in Java? |
|
Answer» A key 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. |
|
| 161. |
Primitive types in Java |
||||||||||||||||||||||||||||||||||||
|
Answer» The primitive data types in JAVA are BOOLEAN, byte, char, short, int, long, float and double. These data types have no special capabilities and are only single values. A table that demonstrates all the primitive types in Java is as follows:
A program that demonstrates all the primitive types in Java is given as follows: public class Demo { public static void main(String []args) { boolean var1 = true; byte var2 = 127; char var3 = 'A'; short var4 = -2000; int var5 = 5000; long var6 = 10000; float var7 = 75.8756f; double var8 = 28.84642387; System.out.println("boolean: " + var1); System.out.println("byte: " + var2); System.out.println("char: " + var3); System.out.println("short: " + var4); System.out.println("int: " + var5); System.out.println("long: " + var6); System.out.println("float: " + var7); System.out.println("double: " + var8); } }The output of the above program is as follows: boolean: true byte: 127 char: A short: -2000 int: 5000 long: 10000 float: 75.8756 double: 28.84642387 |
|||||||||||||||||||||||||||||||||||||
| 162. |
Difference between static and non-static variables in Java |
||||||||||||||
|
Answer» Any variable is a class in Java can either be STATIC or non-static. Some of the DIFFERENCES between static and non-static VARIABLES in Java is given as following:
|
|||||||||||||||
| 163. |
Role of JDK, JRE and JVM |
|
Answer» Details about JDK, JRE and JVM in Java are given as follows: Java Development Kit (JDK)The Java SE, Jakarta EE or the Java Me are platforms whose implementation is done by the Java Development Kit. The basic contents of the JDK are resources for a Java application and the JVM. A LIST of some of the JDK programming tools is given as follows:
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 Virtual Machine allows a computer to run Java programs. It can also run programs in other languages that are beforehand compiled to Java bytecode. The JVM is a virtual machine. Some of the OPERATIONS performed by the JVM are given as follows:
|
|
| 164. |
Hierarchy of InputStream and OutputStream in Java |
|
Answer» The InputStream is an abstract class of the java.io package. It is the PARENT class of all the subclasses related to input in the form of sequence of bytes.
The OutputStream is an abstract class of the java.io package. It is the parent all the subclasses related to input in the form of sequence of bytes.
|
|
| 165. |
Implement Runnable vs Extend Thread in Java |
|
Answer» We have the ability to define a Thread in two ways:
By the first technique, the Thread class is extended. Since Java doesn’t support MULTIPLE inheritance, we can’t extend any other class. This is a shortcoming as the benefits of inheritance can’t be completely exploited. By the second technique, the Runnable interface is implemented. We can extend any other class and use the ADVANTAGES of inheritance completely. Let us see a program where we extend the Thread class: public class Example EXTENDS Thread // any other class can’t be extended { public void run() { System.out.println("Thread running"); } public static void main(STRING[] args) { Example obj = new Example(); obj.start(); // it CALLS the run() method System.out.println("Thread starting"); } }The output is as follows: $javac Example.java $java Example Thread starting Thread runningLet us now see the implementation of the Runnable interface class Parent { public static void method() { System.out.println("This is an extended class"); } } // since Runnable is a interface, class Example can extend class Parent public class Example extends Parent implements Runnable { public void run() { System.out.println("Thread running"); } public static void main(String[] args) { Example obj = new Example(); obj.method(); Thread t = new Thread(obj); // creating a new thread t t.start(); // calls the run() method System.out.println("Thread starting"); } }The output is as follows: $javac Example.java $java Example This is an extended class Thread starting Thread running |
|
| 166. |
How Java achieves Platform Independence? |
|
Answer» Java is a platform independent programming language. It can operate on any platform i.e. operating system with LITTLE or no change. The Java Virtual Machine plays a pivotal role in making Java a platform independent language. When the Java program is compiled, a .class file is created by the Java compiler. This .class file contains nothing but Java BYTECODE. The Java ByteCode is a highly developed set of instructions given to the Java Virtual Machine to generate the machine code. It is the machine code in the form of the .class file . ByteCode is independent on the version of JVM. JVM is dependent on the system. So when the .class file is ported to the other system, that system’s JVM runs the bytecode and converts it into a machine level code which the system can UNDERSTAND. Thus Java ACHIEVES platform independence. An important point to be taken in consideration is that the Java Virtual Machine does not have any knowledge in regard to the programming language. It only is AWARE of the binary format of the ByteCode and confirm that the .class file is as per Java ByteCode specification thus eliminating errors of running bad Java ByteCodes: |
|
| 167. |
What is meant by Ordered and Sorted in Java collections? |
|
Answer» Ordered in Java Collection An ordered collection in Java mean that the elements of the collection have a definite order. The order of the elements is unconstrained by their value. In other words, the order of the elements in the ordered collection does not depend on their value. An example for an ordered Java collection is a LIST. List in Java are interface that extend the Collection interface. Java List allows us to exercise control over the index for insertion of elements. List allows searching and access of elements by their index. Duplicate elements can be stored in a List. Instances of the list can be created by the new KEYWORD along with the ArrayList, LinkedList, Vector and Stack classes. List arrayListObj = new ArrayList(); List stackObj = new Stack(); List linkedListObj = new LinkedList(); List vectorObj = new Vector();After JDK 1.5, we can limit the type of object we want in the List, List<Obj> list = new List<Obj>();Let us see an example of a List in Java: import java.util.*; public class Example { public static void main(String[] ARGS) { List<Integer> list = new ArrayList<Integer>(); list.add(0,6); // adds element 6 at index 0 list.add(1,3); // adds element 3 at index 1 list.add(2,9); // adds element 9 at index 2 System.out.println(list); list.remove(1); // removes element at index = 1 System.out.println(list); }The OUTPUT is as follows $javac Example.java $java Example [6, 3, 9] [6, 9]Sorted in Java Collection A sorted collection in Java is a collection whose elements have a definite order and the order is constrained by the values of the elements. In other words, the order of the elements is dependent on the values of the elements. An example for a sorted collection in Java is a SORTEDSET. SortedSet is an interface which extends the Set interface in Java. All the components in SortedSet are bound to implement the Comparator interface in Java. Let us see an example of a SortedSet: import java.util.*; public class Example { public static void main(String[] args) { SortedSet set = new TreeSet(); // creating a SortedSet object set set.add(10); // adding 10 to the SortedSet set.add(1); // adding 1 to the SortedSet set.add(4); // adding 4 to the SortedSet Iterator i = set.iterator(); // creating an iterator // iterating through the SortedSet by checking for the presence of next element while (i.hasNext()) { Object obj = i.next(); // acquiring the element System.out.println(obj); } } }The output is as follows: $javac Example.java $java Example 1 4 10 |
|
| 168. |
Get the cause of an exception in Java |
|
Answer» In Java, we use the getCause() method which returns the cause of the exception or returns null if the cause of the exception is not known. The declaration of the java.lang.THROWABLE.getCause() is public Throwable getCause()The getCause() method doesn’t accept any arguments and doesn’t throw an exception. It returns the cause that was provided by one of its constructors or that was determined by FORMATION of the initCause(Throwable) method. Let us see an example on the working of the getCause() method as we try to compile a program with ArrayIndexOutOfBoundsException: public class Example { public static void main(String[] args) throws Exception { try { myException(); } catch(Exception e) { System.err.println("Cause = " + e.getCause()); } } public static void myException() throws Exception { int arr[]={1,3,5}; try { System.out.println(arr[8]); // generates an ArrayIndexOutOfBoundsException } catch(ArrayIndexOutOfBoundsException aie) { Exception e = new Exception(); // creating Exception class OBJECT throw (Exception) // throwing the exception to be caught by catch BLOCK in main() e.initCause(aie); // supplies the cause to getCause() } } }The output is as follows: $JAVAC Example.java $java Example Cause = java.lang.ArrayIndexOutOfBoundsException: 8 |
|
| 169. |
Hierarchy of Java Exception Classes |
|
Answer» Exceptions in Java are a part of the java.lang.Exception CLASS. It is an issue that arises during the EXECUTION of a program. All Exception classes in Java are subordinates of the java.lang.Exception class. The java.lang.Exception class is a child class of the Throwable class. Another subclass of the Throwable class is the java.lang.Error class. Errors are anomalous conditions that occur in a Java program DUE to many failures. They cannot be handled by the Java program. Usually, programs can’t recuperate from errors. |
|
| 170. |
How to make a class Singleton |
|
Answer» SINGLETON class is a class which has only a single object. This means you can instantiate the class only once.When we declare the constructor of the class as private, it will limit the scope of the creation of the object.If we return an INSTANCE of the object to a static METHOD, we can handle the object creation inside the class itself. We create a static block for the creation of an object. For example, PUBLIC class Example { private static Example obj; static { obj = new Example(); // creation of object in a static block } private Example() { } // declaring the constructor as private public static Example getObject() { return obj; } public void print() { System.out.println("Just for checking"); } public static void main(String[] args) { Example e = getObject(); e.print(); } } |
|
| 171. |
What is the Locale Class in Java |
|
Answer» A Locale Class is used to perform locale operations and supply locale information to the client or user. Locale is defined as a set of parameters that represents a geographical location or place where some operation occurs. The locale class is declared as follows: public final class Locale extends Object implements Cloneable, SerializableThe Locale class uses the following constructors:
The following program is an example for the implementation of the locale class: import java.text.SimpleDateFormat; import java.util.Locale; public class Example { public static void main(String[] args) { Locale arr[] = SimpleDateFormat.getAvailableLocales(); for (int i = 1; i <=15; i++) { System.out.printf("\N%s (%s) " ,arr[i].getDisplayName(), arr[i].toString()); } } }The output of the following is as follows javac Example.java $java Example Arabic (United Arab Emirates) (ar_AE) Arabic (Jordan) (ar_JO) Arabic (Syria) (ar_SY) Croatian (Croatia) (hr_HR) French (BELGIUM) (fr_BE) Spanish (Panama) (es_PA) Maltese (Malta) (mt_MT) Spanish (Venezuela) (es_VE) Bulgarian (bg) Chinese (Taiwan) (zh_TW) Italian (it) Korean (ko) UKRAINIAN (uk) Latvian (LV) Danish (Denmark) (da_DK) |
|
| 172. |
Unsupported Operation Exception in Java |
|
Answer» Unsupported Operation Exception is an exception THROWN by Java during the time of EXECUTION of the Java program. It is included in the java.lang package. Unsupported Operation Exception is a PART of the Collections framework in Java. It is a subclass of the Runtime Exception class which is a subclass of the Exception class which, in turn extends the THROWABLE class. The class definition is as follows: public class Unsupported Operation Exception extends Runtime ExceptionHere is a sample program for Unsupported Operation Exception: import java.util.*; public class Example { public static void main(String[] args) { List aList = new ArrayList(); aList.add('a'); aList.add('b'); List newList = Collections.unmodifiableList(aList); newList.add('c'); } }The output displays an error: $javac Example.java. $java Example Exception in THREAD "main" java.lang.Unsupported Operation Exception at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055) at Example.main(Example.java:10) |
|
| 173. |
Check whether a value is uppercase or not |
|
Answer» To check for uppercase, you need to test the value from ‘A’ to ‘Z’. The output: Uppercase! |
|
| 174. |
Checked Exception vs Unchecked Exception with examples |
||||||||||
|
Answer» The exceptions which are checked during compile time are called checked exceptions. When method throws checked exceptions, they must either be handled by the try-catch block or must declare the exception using the throws keyword. In case of violation, it will show a compile time error. Unchecked exceptions are the exceptions that are not checked during compile time. If the code throws an unchecked exception and even if it is not handled, it will not generate a compile time error. This is dangerous as unchecked exceptions generally generate runtime errors. All unchecked exceptions are a child class of RuntimeException Class:
Example of a Checked Exception by reading a file which is not created: import java.io.File; import java.io.FileReader; PUBLIC class Example { public static void main(String args[]) { File f = new File("D://abc.txt"); // file abc is not created, it generates a FileNotFoundException FileReader obj= new FileReader(f); } }The exception generated is as follows $javac Example.java Example.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown FileReader obj= new FileReader(f); ^ 1 errorNow, let us see an example of an unchecked exception: public class Example { public static void main(String args[]) { int val1=10; int val2=0; int ANS=val1/val2; System.out.println(ans); } }The output is as follows: $javac Example.java $java Example Exception in thread "main" java.lang.ArithmeticException: / by zero at Example.main(Example.java:7) |
|||||||||||
| 175. |
Does size of operator exist in Java? |
||||||||||||||||||
|
Answer» No, sizeof operator doesn’t exist in Java. All PRIMITIVE data types in Java such as int, char, float, double, long, short have a predefined size in Java. Hence there is no SPECIFIC requirement of the sizeof operator. Also, in Java, size of the primitive data types is independent of the platform i.e. Windows, Linux. An int variable will take 4 bytes in both 32 and 64 bit and in both Windows and Linux operating systems. The size of boolean is not fixed and depends on the JVM. Different JVMs might have different boolean size. Mostly the size of boolean is 1 bit. Here are a few primitive data types with their fixed sizes
Since Java 8, all primitive wrapper classes provide a SIZE constant in bits. Since 1 byte= 8 bits, we divide the constant by 8 to obtain the size of the wrapper class in bytes. public class Example { public static void MAIN (STRING[] args) { System.out.println(" char: " + (Character.SIZE/8) + " bytes"); System.out.println(" byte: " + (Byte.SIZE/8) + " bytes"); System.out.println(" short: " + (Short.SIZE/8) + " bytes"); System.out.println(" int: " + (Integer.SIZE/8) + " bytes"); System.out.println(" long: " + (Long.SIZE/8) + " bytes"); System.out.println(" float: " + (Float.SIZE/8) + " bytes"); System.out.println(" double: " + (Double.SIZE/8) + " bytes"); } }The output of the program is as follows: $javac Example.java $java Example char: 2 bytes byte: 1 bytes short: 2 bytes int: 4 bytes long: 8 bytes float: 4 bytes double: 8 bytes |
|||||||||||||||||||
| 176. |
How to split String with Comma (,) in Java |
|
Answer» The split() method is used to split a string on the basis of regular expression. The first PARAMETER is the same regular expression, whereas if the second parameter is zero, it RETURNS all the strings matching the Regular Expression. Our sample string: The TV, and the remoteTo split the string with comma, the following is the EXAMPLE: public class Example { public static void main(String[] args) { String s = "The TV, and the remote"; System.out.println("Initial String = "+s); String[] str = s.split("[,]", 0); System.out.println("\nSplitted string: "); for(String val: str){ System.out.println(val); } } }The OUTPUT: Initial String = The TV, and the remote Splitted string: The TV and the remote |
|
| 177. |
Get all digits from a string in Java |
|
Answer» To DISPLAY the digits from a STRING, use Regular Expression. The string (with digits): 12345exampleTo get the digits use the \\D flag and the replaceAll(): replaceAll("\\D", ""))The example: PUBLIC class Example { public static void main(String[] args) { // string with digits String s = "12345example"; System.out.println("Our String = "+s); // display digits System.out.println("Get digits from the string = "+s.replaceAll("\\D", "")); } }The output displays only the digits: Our String = 12345example Get digits from the string = 12345 |
|
| 178. |
How to add leading zeros in Java? |
|
Answer» We can add leading zeros to a number in JAVA. LET us see how: The number we are taking as an example: 15 We will add 6 leading zeros to the above number using the following code. Here, we are working on the String.format() method to achieve the same: import java.util.Formatter; PUBLIC CLASS Example { public static VOID main(String args[]) { int a = 15; System.out.println("Value = "+a); // adding leading zeros String res = String.format("%08d", a); System.out.println("Updated = " + res); } }The output: Value = 15 Updated = 00000015 |
|
| 179. |
How to replace every occurrence of a character in Java? |
|
Answer» To replace every occurrence of a character, use the replace() method in Java. Let’s say the following is the string: TABLES and ChairsAnd for every occurrence of “a”, you NEED to replace it with “z”. The following is the example that would replace every occurrence of “a” with “z”: public class Example { public STATIC void main(String[] args) { // Initial string String STR = "Tables and Chairs"; System.out.println("Initial String = "+str); // REPLACING character String res = str.replace('a', 'z'); // displaying the new string System.out.println("New string = "+res); } }The output: Initial String = Tables and Chairs New string = Tzbles znd Chzirs |
|
| 180. |
How can we subtract hours from current time in Java? |
|
Answer» To subtract hours, you need to USE the HOUR_OF_DAY constant. Within that, INCLUDE the number with the negative sign. This WOULD be the hours you want to REDUCE. All this is done under the Calendar add() method. The following is an example: import java.util.Calendar; public class Example { public static void main(String[] args) { Calendar c = Calendar.getInstance(); System.out.println("Date : " + c.getTime()); // 2 hours subtracted c.add(Calendar.HOUR_OF_DAY, -2); System.out.println("After subtracting 2 hrs : " + c.getTime()); } }Here is the output: Date : Sun Dec 16 16:28:53 UTC 2018 After subtracting 2 hrs : Sun Dec 16 14:28:53 UTC 2018 |
|
| 181. |
Convert hexadecimal number to decimal number in Java |
|
Answer» The parseInt() METHOD converts hexadecimal to decimal. It can even convert octal to decimal. You just NEED to set the radix. For hexadecimal, the radix is 16. The output: Decimal = 664 |
|
| 182. |
How to sort a Short array in Java |
|
Answer» The Arrays.sort() method is PROVIDED in Java to sort Short array. Let us see an example: import java.util.*; PUBLIC class Example { public static void main(String []args){ short[] shortArr = new short[] { 35, 25, 18, 45, 77, 21, 3 }; System.out.println("Unsorted:"); for (short a : shortArr) { System.out.print(a+" "); } System.out.println("\nSorted Array = "); // sort array Arrays.sort(shortArr); for (short a : shortArr) { System.out.print(a+" "); } System.out.println(); } }The output: Unsorted: 35 25 18 45 77 21 3 Sorted Array = 3 18 21 25 35 45 77 |
|
| 183. |
Print stack trace information in Java |
|
Answer» A stack TRACE is a characterization of a call stack at a particular instant, with each element depicting a method call statement. The stack trace contains all the call statements from the START of a thread until the POINT of generation of exception. When the stack trace is printed, the point of generation is exception is printed first, followed by method call statements, which help us identify the root cause of failure. Here is an example of printing the stack trace in Java: PUBLIC class Example { public STATIC void main (String args[]) { int arr[] = {1,2,3,4}; int num1=10, num2=0; int ans; try { System.out.println("The output is..."); ans = num1/num2; System.out.println("The result is " +ans); } catch (ArithmeticException ex) { ex.printStackTrace(); } } }The output is as follows: $javac Example.java $java Example The output is... java.lang.ArithmeticException: / by zero at Example.main(Example.java:11) |
|
| 184. |
Difference between a ClassNotFoundException and NoClassDefFoundError? |
|||||||||||||||
|
Answer» ClassNotFoundException and NoClassDefFoundError both OCCUR when a class is not found during runtime. ClassNotFoundException is an exception that is thrown when we try to load a class while EXECUTION of a Java program. NoClassDefFoundError is an error which is thrown when a class marks it presence during COMPILE time but isn’t available during runtime. Despite their similarity of a missing class during runtime, there are a quite a few differences between ClassNotFoundException and NoClassDefFoundError.
|
||||||||||||||||
| 185. |
StringBuffer vs StringBuilder in Java |
|||||||||||||||
|
Answer» StringBuffer class which is related to class STRING that GIVES most of the usage of strings. StringBuffer is a mutable, expandable and WRITABLE SEQUENCE of characters. StringBuilder is a class whose objects are similar to String objects barring that they can be CHANGED. The size and matter of the sequence of characters can be modified through method calling statements.
|
||||||||||||||||
| 186. |
NumberFormatException in Java |
|
Answer» A NumberFormatException in Java is an exception of the java.lang package which is thrown when we try to convert a String into a numeric DATA TYPE such as int, float, double, long and short. This happens when the String does not have an appropriate format. Take for example, we try to PARSE a String which is not of numeric type into an integer: public class Example { public static void main(String[] args) { String str = "Number"; int intVal = Integer.parseInt(str); System.out.println(intVal); } }The above CODE will throw a NumberFormatException: $javac Example.java $java -Xmx128M -Xms16M Example Exception in thread "main" java.lang.NumberFormatException: For input string: "Number" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at Example.main(Example.java:8)But if the String is of numeric type, it will successfully parse it to an integer public class Example { public static void main(String[] args) { String str = "12"; int intVal = Integer.parseInt(str); System.out.println(intVal); } }The OUTPUT is the following: $javac Example.java $java -Xmx128M -Xms16M Example 12 |
|
| 187. |
HashMap vs Hashtable in Java |
|||||||||||||||||||||
Answer»
HashMap extends the AbstractMap class and ALSO implements the Cloneable and Serializable interface.
Despite of the similarities, HashMap and HashTable have few differences. Let us have a look at them.
|
||||||||||||||||||||||
| 188. |
What is JIT compiler? |
|
Answer» JIT STANDS for Just In Time. JIT compiler is a program which CONVERTS the Java BYTECODE into processor level instructions. The JIT compiler runs after the program has begun and COMPILES the bytecode while the program is running into a quicker and more local processor level directive set. After you've completed writing a Java program, the SOURCE code are compiled by the Java compiler into bytecode. Then the bytecode is converted into processor level instructions by the JIT compiler. Thus the JIT compiler acts as a second compiler. The JIT compiler runs simultaneously with the execution of the program. It compiles the bytecode into platform-specific executable code that is instantly executed. Once the code is re-compiled by the JIT compiler, it runs relatively quickly on the system. |
|
| 189. |
A Java program begins with a call to which function? |
|
Answer» When a JAVA program begins, the public static void main(String []args) method is called. When the Java program needs to be executed, the system looks for the main entry point in the program. This is provided through the main method, The public static void main(String args[]) is the main method of the Java Program. It is the most important Java Method. It is the entry point of any Java Program. A Java Program cannot be executed without the main method. Only the args can be changed to a different name but the rest of the method carries the same syntax. Let us analyze the main method by breaking it up:
The following program will illustrate that the main method is run at first: public class Example { void display() { System.out.println("This is the display method"); } public static void main(String[] args) // the main method { System.out.println("This is the main method"); Example obj = new Example(); obj.display(); // invokes display method } }The output is as follows: $javac Example.java $java Example This is the main method This is the display method |
|
| 190. |
Purpose of finalize() in Java |
|
Answer» The finalize() is a method which is used to clean up the processing before the garbage COLLECTION in java. It is called by the garbage collector of an object when there are no further references to that object. finalize() is overridden by a child class to get rid of the system resources or to conduct other cleanup. The exception raised by this method is called the THROWABLE exception. The java.lang.Object.finalize() method does not take any parameters and does not return a value. Now let us look at the overriding of finalize() method in Java, public class Example { public static void main(String[] args) { String STR = new String("Example"); str = NULL; System.gc(); // prompts the JVM to call the Garbage Collector System.out.println("End of main method"); } public void finalize() { System.out.println("This is the finalize method"); } }The output is as follows $JAVAC Example.java $java Example End of main method |
|
| 191. |
Types of memory areas allocated by JVM |
|
Answer» JVM stands for Java Virtual Machine. It is the driving force that provides the run time environment. It converts the Java ByteCode into machine code. It is an ABSTRACT machine that provides the specification for execution of a Java program during runtime. When we compile a .java file, files with nomenclature same to that of the class are created with the extension .class by the Java Compiler. These files contain the byte code. There are various steps involved when a .class file is executed. These steps provide a detailed account of the Java Virtual Machine. There are typically 6 types of memory areas ALLOCATED in JVM.
|
|
| 192. |
HashSet vs TreeSet in Java |
||||||||||||||||||||||||
|
Answer» The HashSet class implements the Set interface, supported by a Hashtable. Due to the implementation of the Set Interface, duplicate VALUES are not ALLOWED. The underlying data structure for a HashSet is a Hashtable. The TREESET class implements the SortedSet interface, which in turn extends the Set interface. Objects are stored in a sorted ascending order. The underlying data structure for TreeSet is a tree. Here are a few notable differences between a HashSet and a TreeSet:
|
|||||||||||||||||||||||||
| 193. |
What type of parameter passing does Java support? |
|
Answer» There are basically TWO types of parameter passing:
JAVA supports Pass by value. Passing by value means that when a method is called, a copy of the parameters is SENT to the memory. When we are using the parameters inside the method or the block, the actual arguments aren’t used but the copy of those arguments (formal parameters) are worked with. There is no change in the actual parameters. Passing by reference means that the changes in the parameters will be reflected in the original value . This occurs because the method RECEIVES the memory address of the parameters i.e. the address of the parameters. What Java does is that it passes the reference of the object by value. In Java, arguments are always passed by value irrespective of their original VARIABLE type. Each time a method is called, a copy is created in the stack memory and its version is passed to the method. There are two situations which arise:
|
|
| 194. |
Local Inner Class in Java |
|
Answer» A class created in a block( method body or a loop or conditional clauses) is called as a LOCAL inner class. They are not a member of the class they are enclosed in. They rather, associate themselves to the block they are defined in. Local inner class can be declared as final or abstract. They cannot be instantiated out of their SCOPE i.e. the block they are created in. We can say that they are a form of non-static nested classes. For example, PUBLIC class Example { final int y=12; void disp() { class Inner { void print() { System.out.println(y); } } Inner i=new Inner(); i.print(); } public static void main(String args[]) { Example obj=new Example(); obj.disp(); } }The output is as follows $javac Example.JAVA $java Example 12 |
|
| 195. |
Iterator vs Enumeration in Java |
|||||||||||||||||||||
|
Answer» Both Iterator and Enumeration are interfaces BELONGING to the java.util package. They are used for traversal of collection objects. Although Iterator and Enumeration have the same functionality of traversal, there are quite a few DIFFERENCES between them. Some of the differences are given below:
|
||||||||||||||||||||||
| 196. |
Jagged Arrays in Java |
|
Answer» Jagged arrays in Java are multidimensional arrays in which each element itself is an array of varying size as well as dimensions. Thus, they’re often referred to as array of arrays. Syntax for a two-dimensional jagged array for FIXED rows and variable columns, data_type array_name[][]= new data_type [array_size][]; (OR) data_type[][] array_name=new data_type[array_size][];Take for example a JAGGER integer array of size 4: int arr[][] = new int[4][];This row has 4 rows and each row has varying amount of columns which might later be specified. We can either declare the array and initialize the elements directly: arr[0] = new int[] {13, 42}; arr[1] = new int[] {34, 43, 95}; arr[2] = new int[] {69, 71, 83, 29}; arr[3] = new int[] {10,11};or, we can just declare the array elements without initializing them. arr[0] = new int[2]; arr[1] = new int[3]; arr[2] = new int[4]; arr [3] = new int[2];For example, PUBLIC class Example { public static void main(String[] args) { int arr[][] = new int[4][]; // creating a Jagged Array of 4 rows arr[0] = new int[]{1,2,3,4}; // the first row has 4 columns arr[1] = new int[]{5,6,7}; // the second row has 3 columns arr[2] = new int[]{10,20,30}; // the third row has 3 columns arr[3] = new int[]{2,4,2,4}; // the fourth row has 4 columns System.out.println("The elements of the Jagged Array are..."); for (int i=0; i<arr.length; i++) { for (int j=0; j<arr[i].length; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } }The OUTPUT is the following: $javac Example.java $java Example The elements of the Jagged Array are... 1 2 3 4 5 6 7 10 20 30 2 4 2 4 |
|
| 197. |
Generate Random Numbers in Java |
|
Answer» Java imparts us with three WAYS to generate random NUMBERS. The three ways are:
The java.util.Random class We create an object of this class and call predefined methods such as nextInt() and nextDouble() using this object. Random numbers of several data types can be produced by this method. Suppose If we pass an argument x to nextInt() then we would get any random integer from 0 to x-1. For EXAMPLE, import java.util.Random; public class Example { public static void main(String args[]) { Random r= new Random(); int r1 = r.nextInt(20); // generates random integers from 0 to 19 int r2 = r.nextInt(100); // generates random integers from 0 to 99 System.out.println("The first random number generated is: "+r1); System.out.println("The second random number generated is "+r2); } }The SUBSEQUENT output is as follows: $javac Example.java $java Example The first random number generated is: 2 The second random number generated is 23The Math.random() method The Math.random() is a method of the java.util.Math class. It returns a positive double VALUE between 0.0 (inclusive) and 1.0 (exclusive). import java.util.*; public class Example { public static void main(String args[]) { double x=Math.random(); System.out.println("Random number between 0.0 and 1.0 is "+x); } }The random output for the following is as follows: $javac Example.java $java Example Random number between 0.0 and 1.0 is 0.7534013549366972The ThreadLocalRandom Class This is a relatively new feature introduced in JDK 1.7. The ThreadLocalRandom gives random values for integers, doubles, floats and booleans. For example, import java.util.concurrent.ThreadLocalRandom; public class Example { public static void main(String args[]) { int intVal = ThreadLocalRandom.current().nextInt(); System.out.println("A random integer : " + intVal); double doubVal = ThreadLocalRandom.current().nextDouble(); System.out.println("A random double number : "+doubVal); } }The output is as follows: $javac Example.java $java Example A random integer : 1700060375 A random double number : 0.24593329857940383 |
|
| 198. |
ArrayList vs Vector in Java |
||||||||||||||||||||||||
|
Answer» The java.util.ArrayList class extends the AbstractList class. It is a part of the collection framework. The ArrayList is initialized a size which is capable of INCREASING or decreasing its size when OBJECTS are separated from the collection. The java.util.Vector class represents DYNAMIC data structures which can expand when a new element is added to them. Vectors are synchronized and contain MANY methods that are not a part of the Collections framework in Java. Here are a few key differences between Vectors and ArrayList:
|
|||||||||||||||||||||||||
| 199. |
Java instanceOf operator |
|
Answer» Java uses the instanceOf operator to check the type of object during the time of execution of a Java program. The instanceOf operator is used to check whether a particular object is an instance of a parent class, child class or an interface. The instanceOf operator returns a boolean value, either TRUE or false. It is used as a type comparison operator because it compares the object with its type. If APPLIED to a variable having a null value, the operator will always return a false value. For example, public class Example { public static void main(String args[]) { Example obj=new Example(); System.out.println(obj instanceof Example); } }The OUTPUT is as follows: $javac Example.java $java Example TrueHere is another example when instanceOf operator is used against a instance having null value public class Example { public static void main(String args[]) { Example obj=null; System.out.println(obj instanceof Example); } }The output is as follows $javac Example.java $java Example FalseThe instanceOf operator is also useful in downcasting. Downcasting is the process when the child class type refers to the object of the parent class. If Downcasting is performed directly, a ClassCastException is generated. The instanceOf operator PROVIDES the means for downcasting. This can be done via typecasting: class Parent { // empty class } public class Example extends Parent { static void downcast(Parent p) { if(p instanceof Example) { Example d = (Example)p; System.out.println("Downcasting SUCCESSFUL"); } } public static void main (String [] args) { Parent obj=new Example(); Example.downcast(obj); } }The output is as follows: $javac Example.java $java Example Downcasting successful |
|
| 200. |
Java Example to check if a string is empty or not |
|
Answer» To check whether a string is empty or not is an easy TASK since Java comes with a function isEmpty () for this. Let us see an example: public CLASS Example { public STATIC void main(String[] args) { String s = ""; System.out.println("Is the string empty? "+s.isEmpty()); } }The output: Is the string empty? TRUE |
|