Explore topic-wise InterviewSolutions in .

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:

  • New

When an instance of the thread class has been created but the start() method is not invoked, then the thread is in the new state.

  • Runnable

When the start() method has been invoked but the thread scheduler has not selected the thread for execution, then the thread is in the runnable state.

  • Running

If the thread scheduler has selected a thread and it is CURRENTLY running, then it is in the running state.

  • Blocked (Non-runnable)

When a thread is not ELIGIBLE to run but still ALIVE, then it is in the blocked state.

  • Terminated

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 false

A 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:

  1. The reference variable to the object is reassigned.
  2. The reference variable to the object is set is null.
  3. An island of isolation
  4. An object is created inside a method.

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:

  1. The Runtime.getRuntime().gc() method can be called to run the garbage collector by requesting the Java Virtual Machine.
  2. The System.gc() method can be called to run the garbage collector by requesting the Java Virtual Machine.

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:

Process
Thread
A process is a program that is currently executing.
A thread is a subpart of the process.
A process is also KNOWN as a heavyweight task.
A thread is also known as a lightweight task.
Communication between TWO processes is quite complicated and expensive.
Communication between two threads is comparatively less expensive.
All the processes have a separate address space as they are individual entities.
The threads of a single process share the address space of the process as they are a PART of the process.
Context switching between two processes is quite expensive.
Context switching between two threads is less expensive than that between processes.
An individual process has its own global variables, address space, files, accounting information etc.
A thread has its own stack, register and program counter. The rest of the components are shared by all the threads of a process.
A computer SYSTEM can run multiple processes concurrently in process multitasking.
A computer system can run multiple threads of a program concurrently in thread multitasking.
Java does not CONTROL process multitasking.
Java does controls thread multitasking.
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:

  1. The heap space contains the young generation, old generation and the permanent generation.
  2. The stack memory is faster than the heap space in Java.
  3. The error java.lang.OutOfMemoryError is thrown if the heap space is full.
  4. The heap space is not thread safe. It needs SYNCHRONIZATION methods for safety purposes

Some of the differences between stack memory and heap memory are given as follows:

  1. Stack memory is faster than heap memory as its memory allocation procedure is much more simple.
  2. The stack memory is only used by a thread whereas the heap memory is required by all the application parts.
  3. The stack memory is only accessible by the individual thread but the heap memory objects can be accessed globally.
  4. The stack memory is comparatively SHORT LIVED while the heap memory exists for the whole execution of the application.
  5. The stack memory management is done using LIFO but it is more complicated for heap memory as that is used by the whole application.
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:

  1. The current class object can be pointed to by using the this keyword.
  2. The this keyword can be used in a constructor call as an argument.
  3. The current class constructor can be invoked using this().
  4. The current class method can be invoked implicitly using this keyword.
  5. The this keyword can be used in a method call as an argument.

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:

  1. The diamond problem occurs when 2 classes (B and C) inherit from a single class(A) and then a class(D) inherits these 2 classes(B and C) using multiple inheritance. This leads to multiple copies of class members of class A in class D which can create problems.
  2. The ambiguity problem occurs if a class inherits from 2 classes that contain the same NAME for a class member. Then there is ambiguity in the inherited class when that class member is required.

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:

TypeDefault ValueSize (in bits)Description
booleanfalse1This signifies true or false
byte08Two’s complement integer
char\u000016Unicode Character
short016Two’s complement integer
int032Two’s complement integer
long064Two’s complement integer
float0.032IEEE 754 floating point
double0.064IEEE 754 floating point

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:

Static Variables
Non-static variables
The static keywords are defined using the keyword static.
The non-static keywords do not contain the keyword static.
Static variables can be accessed using a class reference as there is only a SINGLE copy of them.
Non-static variables can be accessed using only an object reference.
The memory for static variables is allocated when the class is loaded.
The memory for non-static variables is allocated when an object of the class is CREATED.
Every object of the class shares the static variable i.e. it is common for every object.
All objects of the class have their own copy of a non-static variable i.e the non-static variables are specific for objects.
The memory for static variables is allocated only one time.
The memory for non-static variables is allocated whenever a new object of the class is created.
Static variables can also be called class variables as memory for static variables is allocated when the class is loaded.
Non-static variables can also be called instance variables as memory for non-static variables is allocated whenever a new instance of the class is created.
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:

  1. pack200 - This is a JAR compression tool.
  2. appletviewer - This runs and debugs the Java applets without using a web browser.
  3. javah - This is used to write the native methods and is a stub generator as well as C header.
  4. JConsole - This is a graphic management tool.
  5. jstack -This prints the stack traces of java threads
Java Runtime ENVIRONMENT (JRE)

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:

  1. Java Virtual Machine and Server Virtual Machines.
  2. User Interface Toolkits such as Java 2D, AWT, Sound, Swing etc.
  3. Base LIBRARIES such as I/O, Beans, JNI, Networking etc.
  4. Lang and Util base libraries such as Zip, Collections, Versioning etc.
  5. Deployment techniques
Java Virtual Machine (JVM)

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:

  1. The code can be loaded and executed by the Java Virtual Machine.
  2. The JVM also provides the runtime environment.
  3. The code is verified by using the JVM.
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.

  • FileInputStream consists of input bytes from a file.
  • ByteArrayInputStream reads the next byte of data from the input STREAM.
  • FilterInputStream returns the APPROXIMATE number of bytes that can be read from the input stream. It consists of the DataInputStream, BufferedInputStream and PushBackInputStream classes.
  • PipedInputStream can be used to read data and is PIPED with PipedOutputStream. A pipe is said to be a link between TWO threads running in JVM simultaneously.
  • ObjectInputStream is used to deserialize primitive data types and objects previously written by the ObjectOutputStream.

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.

  • FileOutputStream is a output stream used for writing data into a file.
  • ByteArrayOutputStream allows us to seize data written to a stream in an array.
  • FilterOutputStream is the parent class of all those classes which filter output streams. It is extended by many subclasses including DataOutputStream, BufferedOutputStream and PrintStream.
  • PipedOutputStream is piped with the PipedInputStream.
  • ObjectOutputStream writes primitive objects, data types and graphs to the OutputStream.
165.

Implement Runnable vs Extend Thread in Java

Answer»

We have the ability to define a Thread in two ways:

  1. By extending the Thread class
  2. By implementing the Interface

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 running

Let 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, Serializable

The Locale class uses the following constructors:

  • Locale(String L) : Initializes locale from the language code passed as an argument .   
  • Locale(String L, String C) : Initializes locale from the  language, country code passed as ARGUMENTS.                
  • Locale(String L, String C, String V) : Initializes locale from the  language, country, variant passed as arguments.

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 Exception

Here 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’.
Let US see an EXAMPLE:

public class Example {     public static void main(String []args) {        char C = 'B';        if (C >= 'A' &AMP;& C &LT;= 'Z') {          System.out.println("Uppercase!");        } else {          System.out.println("Lowecase!");        }     } }

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:

Checked ExceptionUnchecked Exception
Checked Exceptions are checked by the compiler.Unchecked exceptions are not checked by the compiler.
It is a subclass of Exception classIt is the subclass of RuntimeException class
They are required to be handled by the try catch block or be rethrown by a method using the throws keywordThey are not restricted
Checked Exceptions are GENERATED for errors that cannot be DIRECTLY prevented  from occuringUnchecked Exceptions are generated for errors that can be directly prevented from occuring

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 error

Now, 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

Data typeDefault size
char2 bytes
byte1 byte
short2 byte
int4 bytes
long8 bytes
float4 bytes
double8 bytes
boolean1 bit

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 remote

To 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):

12345example

To 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 Chairs

And 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 following is an EXAMPLE:

public class Demo {   public static void main( String args[] )   {       // hexadecimal string       String STR = "298";       // hex to decimal       System.out.println("Decimal = "+Integer.parseInt(str, 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.

Basis
ClassNotFoundException
NoClassDefFoundError
Parent class
ClassNotFoundException is a child class of java.lang.Exception
NoClassDefFoundError is a child class of java.lang.Error
Occurrence
It occurs when an application tries to load a class during runtime which is not UPDATED in the CLASSPATH
It occurs when the system doesn’t find the class definition during runtime which was present during compile time.
Thrown by
It is thrown by the application (program). Some methods like Class.forName(), loadClass() and findSystemClass() cause this exception.
It is thrown by the Java Runtime System.
Condition
It occurs when the classpath is not updated in accordance to the Java Archive files
It occurs when class definition is missing during runtime.
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.

Basis
StringBuffer
StringBuilder
Introduction
StringBuffer in Java was introduced in JDK 1.0.
StringBuilder in Java was introduced in JDK 1.5.
Synchronization
Every method present in StringBuffer class is synchronized.
Every method present in StringBuilder class is not synchronized.
Performance
Performance is low
Performance is relatively high
Thread Safe
StringBuffer Object is thread safe.
StringBuilder Object is not thread safe.
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 in Java is a part of the collection class in the java.util package. It is based on Maps and is used for storage of data in Key and Value pairs.

HashMap extends the AbstractMap class and ALSO implements the Cloneable and Serializable interface.

  • Hashtable in Java was an original part of the java.util package and was implementation of a Dictionary. It was updated by JDK 1.2 and implemented the Map Interface. Currently, it is a part of the collections framework. It also stores data in Key and Value pairs.

Despite of the similarities, HashMap and HashTable have few differences. Let us have a look at them.

BasisHashMapHashtable
Null keys/valuesNull key/values are allowed in HashMap. It allows one null key and MULTIPLE null values.Null key/values are not allowed in Hashtable
SynchronizationHashMap is not synchronized and is not thread safe. It can’t be shared amongst multiple threads without appropriate synchronization.Hashtable is synchronized and thread safe.
Nature of iteratorHashMap iterator is FAIL FAST in nature.Hashtable iterator is fail safe in nature.
IntroductionHashMap was introduced in JDK 1.2Hashtable is a legacy class.
PerformanceHashMap is fast.Hashtable is slower than HashMap
Parent ClassAbstractMap is the parent class for HashMapDictionary is the parent class for Hashtable
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:

  • public : This is the access specifier/access modifier of the main method. It should be public to allow the CLASS to access it. In case of violation of the same, the program will show an error.
  • static : At the start of the runtime, the class is devoid of any object. Thus, the main method needs to be static so that the Java Virtual Machine can set the class to the memory and CALL the main method. If the main method is not static then the JVM won’t be able to call it due to the absence of an object.
  • void : It is the return TYPE of the main method. Each and every method in Java must have a return type.The main method doesn’t return any value that can be accessed by the other methods as the main method can’t be called in any other method. As soon as the main method finishes its execution the program terminates. Hence it wouldn’t be of any use to return a value. If any value is returned then the compiler will show an unexpected return value error.
  • main: It is the name of the main method. This name is already set and can’t be changed. If any changes are made to the main keyword then the compiler tells that the main method couldn’t be found.
  • String args[]:  The main method can accept a single argument which is of the String type. They are also called command line arguments. They can be used and manipulated as normal arguments in the code written in the main method. They are written along with the execution statement.

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.

  • CLASSLOADER: Classloader is a subsystem of JVM and a part of the Java Runtime Environment which dynamically loads class in the JVM.
  • Method Area: Method Area is common across all threads. It consists of per-class elements such as constant pool, FIELDS, method data and code and constructor codes. This area gets created during the JVM start-up. If the memory isn’t sufficient then it gives an OutOfMemoryError.
  • Heap: Variables ASSIGNED with this memory structure can be administered during runtime. This leads to dynamic memory allocation.
  • Stack: If the amount of memory required is known beforehand, memory is allocated using stacks.
  • Program Counter Register: It contains the address of the Java virtual machine instruction currently being executed. Programs are a set of instructions given to a computer for performing few specific tasks. The Program Counter Register carries the address of the forthcoming instructions.
  • Native Method Stack: It is a collection of all the native methods used in the application.
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:

Basis
HashSet
TreeSet
Performance
HashSet in Java offers faster performance than TreeSet
TreeSet in Java is slower than HashSet for most of the generic operations like add, remove and search.
Underlying data structure
HashSet has hashtable as its underlying data structure.
TreeSet has a red black tree as its underlying data structure.
NULL element
HashSet does allow one null element
TreeSet doesn’t allow any null element to be present
Implementation
It is implemented by HashMap
It is implemented by TreeMap
Interface
HashSet implements the Set interface.
TreeSet implements the SortedSet interface. SortedSet interface extends the Set interface.
Sorting
HashSet is not in sorted order
TreeSet is sorted in ascending order
COMPARISON
HashSet applies the equals() method for comparison
TreeSet applies the compareTo() method for comparison.
193.

What type of parameter passing does Java support?

Answer»

There are basically TWO types of parameter passing:

  • Pass by value
  • Pass by reference

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:

  • The original variable type is primitive: If the original variable type is primitive, then a copy is created in the stack memory and is further passed to the method.
  • The original variable type is non-primitive: If the original variable type is non-primitive, then a new reference is formed in the stack memory which points to the actual parameters and this new reference is sent to the method.
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:

Basis
Iterator
Enumeration
Introduction
Iterator interface was introduced in JDK 1.2
Enumeration interface existed since JDK 1.0
Functions
Iterator can be used for traversal as well as to remove an element from a given Collection object.
Enumeration can only perform traversal through the collection object.
Nature
Iterator is fail-fast is nature. It throws a ConcurrentModificationException if any modification other than the remove() method  is done to the collection while iteration.
Enumeration is fail-safe in nature. It does not throw any exceptions during modification of the Collection Object during an iteration.
Legacy
Classes like ArrayList, HASHSET and HashMap in the collection framework are traversed by Iterator
Traversal of legacy classes like Vector and Stack is done through Enumeration
Safety
Iterator is safer and more robust than Enumeration
Enumeration is more vulnerable due to its fail-safe nature.
Methods
hasNext()  
next()
remove()
hasMoreElements()
NEXTELEMENT()
-
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:

  • Using the java.util.Random class
  • Using the java.util.Math.random() method
  • Using the java.util.concurrent.ThreadLocalRandom class

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 23

The 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.7534013549366972

The 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:

Basis
Vector
ArrayList
Threads
Vector thread is thread safe as only one thread is allowed to work at a time
ArrayList is not thread safe as multiple threads are allowed to work at a time
Synchronization
Every method available in Vector is Synchronized
Every method available in ArrayList is not Synchronized
Performance
Threads are required to hold-up on Vector object and hence their performance is low as compared to ArrayList.
Threads are not required to hold-up on ArrayList object and hence their performance is high as compared to Vector
Growth
Doubles its size when it grows
Grows by half of its size
Application
Multi user application
Single user application
Legacy class
Vector is a legacy class, INTRODUCED in JDK 1.0
ArrayList is a non legacy class, introduced in JDK 1.2
Traversal
Uses enumeration for traversal.
Uses Iterator/ListIterator for traversal.
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 True

Here 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 False

The 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