Wednesday, 31 August 2016

Difference between Runnable and Callable in Java

Differences between Callable and Runnable is a frequently asked Java concurrency interview question and that is the topic of this post.

Runnable interface is around from JDK 1.0 where as Callable was added much later in Java 5 along with many other concurrent features like ConcurrentHashMap, BlockingQueue, ExecutorService.

If you see basic functionality both Callable and Runnable interfaces are implemented by any class whose instances are to be executed by another thread. Since Callable is added later so it is obvious that it would have some extra features which were not there in Runnable. Some of the added features in Callable are -

  • It can return value
  • It can throw exception

Which are not there in Runnable. These features make Callable an excellent choice if you have to run a task that involves extensive computation of a value that can be returned later.

Runnable Vs Callable

  1. Though both Callable and Runnable are interfaces and both have a single method but that method and its signature is different.

    Callable interface

    public interface Callable<V> { 
        V call() throws Exception;
    }
    

    Runnable interface

    public interface Runnable {
        public abstract void run();
    }
    
  2. Callable interface is part of the java.util.concurrent package where as Runnable interface is part of the java.lang package.
  3. If you have noticed the signature of call method in the Callable interface you can see that call method can return value
    V call() throws Exception
    
    Here V is the computed result. Callable is a generic interface and type is provided at the time of creating an instance of Callable implementation.

    As example

    Callable<Integer> callableObj = new Callable<Integer>() {
       @Override
       public Integer call() throws Exception {
        return 5;
      }
    };
    

    run() method of the Runnable interface doesn't return any value, return type for the run method is void.

  4. Another difference that can be noticed from the signatures of the call() and run() method is that you can not give a checked exception with a throws clause in run method.

    This statement will give compile time error -

    public void run() throws InterruptedException
    
    With call method checked exception can be given with throws clause.

    This statement is valid -

    public Integer call() throws InterruptedException
    
  5. In order to run a runnable task options are -
    • Thread class has a constructor that takes Runnable as parameter.
    • Executor interface has execute method which takes Runnable as parameter.
    • ExecutorService has submit method which takes Runnable as parameter.
    For Callable
    • Thread class doesn't have any constructor that takes Callable as parameter.
    • ExecutorService has submit method which takes Callable as parameter.
    • ExecutorService also has invokeAll and invokeAny methods that take Callable as parameter.
    • Executors class has callable method that can convert Runnable to Callable.
      Callable callable = Executors.callable(Runnable task); 
      

That's all for this topic Difference between Runnable and Callable in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Executor and ExecutorService in Java concurrency
  2. Callable and Future in Java concurrency
  3. Non-blocking algorithms
  4. What if run() method called directly instead of start() method
  5. Java Concurrency interview questions

You may also like -

Monday, 29 August 2016

StampedLock in Java

From Java 5 in Concurrency util package ReentrantReadWriteLock class is provided which has separate read and write locks thus providing non-exclusive (shared) and exclusive locks respectively.

In Java 8 a new kind of lock StampedLock is added which apart from providing separate read and write locks also has a feature for optimistic locking for read operations. StampedLock also provide method to upgrade read lock to write lock which is not there in ReentrantReadWriteLock.

The locking methods of StampedLock return a stamp represented by a long value. You can use these stamps to either release a lock, to check if the lock is still valid, to convert a lock.

So, if you want to use a StampedLock for acquiring a write lock it can be done as -

StampedLock sl = new StampedLock();
//acquiring writelock
long stamp =  sl.writeLock();
try{
 ...
 ...
}finally {
 //releasing lock
 sl.unlockWrite(stamp);
}

Modes in StampedLock

As already mentioned StampedLock has an extra mode optimistic reading apart from reading and writing.

  • Writing mode – When you try to acquire a write lock. It can be done using Method writeLock() which exclusively acquires the lock, blocking if necessary until available. This method retruns a stamp that can be used in method unlockWrite(long)to release the lock or in conversion of the lock.
    Untimed and timed versions of tryWriteLock are also provided. This method won’t block and return stamp as zero if the lock is not immediately available (or with in the given in case of timed version). When the lock is held in write mode, no read locks may be obtained, and all optimistic read validations will fail.
  • Reading Mode – When you try to acquire a read lock. It can be done using method readLock() which non-exclusively acquires the lock, blocking if necessary until available returning a stamp that can be used to unlock or convert mode. Untimed and timed versions of tryReadLock are also provided.
  • Optimistic Reading – That is the new mode added in StampedLock. Method tryOptimisticRead() is used to read in optimistic mode. This method returns a non-zero stamp only if the lock is not currently held in write mode.
    Method validate(long) is used to validate if the values read optimistically are correct or not. Validate() method returns true if the lock has not been acquired in write mode since obtaining a given stamp.

Lock conversion

StampedLock class also supports methods that conditionally provide conversions across the three modes. The forms of these methods are designed to help reduce some of the code bloat that otherwise occurs in retry-based designs.

For example, method tryConvertToWriteLock(long)attempts to "upgrade" a mode, returning a valid write stamp if

(1) already in writing mode 
(2) in reading mode and there are no other readers or 
(3) in optimistic mode and the lock is available. 
  • tryConvertToWriteLock(long stamp) - If the lock state matches the given stamp, performs one of the following actions. If the stamp represents holding a write lock, returns it. Or, if a read lock, if the write lock is available, releases the read lock and returns a write stamp. Or, if an optimistic read, returns a write stamp only if immediately available. This method returns zero in all other cases.
  • tryConvertToReadLock(long stamp) - If the lock state matches the given stamp, performs one of the following actions. If the stamp represents holding a write lock, releases it and obtains a read lock. Or, if a read lock, returns it. Or, if an optimistic read, acquires a read lock and returns a read stamp only if immediately available. This method returns zero in all other cases.
  • tryConvertToOptimisticRead(long stamp) - If the lock state matches the given stamp then, if the stamp represents holding a lock, releases it and returns an observation stamp. Or, if an optimistic read, returns it if validated. This method returns zero in all other cases, and so may be useful as a form of "tryUnlock".

Is there any acquisition preference

The scheduling policy of StampedLock does not consistently prefer readers over writers or vice versa. All "try" methods are best-effort and do not necessarily conform to any scheduling or fairness policy.

StampedLocks are not reentrant

Unlike ReentrantLocks, StampedLocks are not reentrant, so locked bodies should not call other unknown methods that may try to re-acquire locks (although you may pass a stamp to other methods that can use or convert it).

Example code

Let’s see some examples in order to get a better understanding of the StampedLock.

Using the read/write lock

This example uses the write lock in order to get an exclusive lock for a counter and there is also a read lock which tries to read the value of the counter.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.StampedLock;

public class CounterST {
    int c = 0;
    public static void main(String[] args) {
        StampedLock sl = new StampedLock();
        ExecutorService executor = Executors.newFixedThreadPool(2);
        CounterST cst = new CounterST();
        
        
        // Runnable as lambda - read
        Runnable readTask = ()->{
            long stamp = sl.readLock();
            try{
                System.out.println("value " + cst.getValue());
                
            }finally{
                sl.unlockRead(stamp);
            }
        };
        
        // Runnable as lambda - Write lock
        Runnable writeTask = ()->{
            long stamp = sl.writeLock();
            try {
                cst.increment();
            }finally{
                sl.unlockWrite(stamp);
            }
        };
        
        // 3 write tasks
        executor.submit(writeTask);
        executor.submit(writeTask);
        executor.submit(writeTask);
        // 1 read task
        executor.submit(readTask);
        executor.shutdown();

    }
    public  void increment() {     
        c++;
        System.out.println("in increment " + c);
    }

    public  int getValue() {
        return c;
    }

}

Output

in increment 1
in increment 2
value 2
in increment 3

Using tryOptimisticRead method

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.StampedLock;

public class StampedLockDemo {

    public static void main(String[] args) {
        StampedLock sl = new StampedLock();
        ExecutorService executor = Executors.newFixedThreadPool(2);
        // Runnable as lambda - optimistic read
        Runnable r1 = ()->{
            long stamp = sl.tryOptimisticRead();
            try{
                System.out.println("In optimistic lock " + sl.validate(stamp));
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("In optimistic lock " + sl.validate(stamp));
                
            }finally{
                sl.unlock(stamp);
            }
        };
        
        // Runnable as lambda - Write lock
        Runnable r2 = ()->{
            System.out.println("about to get write lock");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            long stamp = sl.writeLock();
            try{
                System.out.println("After getting write lock ");
                
            }finally{
                sl.unlock(stamp);
            }
        };
        
        executor.submit(r2);
        // Optimistic read
        executor.submit(r1);
        executor.submit(r2);
        
        executor.shutdown();
    }

}

Output

about to get write lock
In optimistic lock true
After getting write lock 
about to get write lock
After getting write lock 
In optimistic lock false

Here it can be seen when write lock is acquired at that time validate method returns false for optimistic read.

Since optimistic read mode is a new feature provided by StampedLock so let’s see one more example which is provided in Javadocs.

double distanceFromOrigin() { // A read-only method
     long stamp = sl.tryOptimisticRead();
     double currentX = x, currentY = y;
     if (!sl.validate(stamp)) {
        stamp = sl.readLock();
        try {
          currentX = x;
          currentY = y;
        } finally {
           sl.unlockRead(stamp);
        }
     }
     return Math.sqrt(currentX * currentX + currentY * currentY);
}

In this method you can notice that initially values are assigned to variables currentX and currentY after getting the optimistic lock. Then validate method is used to check if the lock has not been exclusively acquired since issuance of the given stamp. In case validate method returns false (which means write lock is acquired by some thread after optimistic lock is acquired) then read lock method is acquired and values are assigned again. Here note that read lock may block if there is any write lock. So that is the benefit of optimistic lock you can acquire it and read the values and then check if there is any change in the values, if there is then only you need to go through the blocking read lock.

Example using tryConvertToWriteLock method

void moveIfAtOrigin(double newX, double newY) { // upgrade
     // Could instead start with optimistic, not read mode
     long stamp = sl.readLock();
     try {
       while (x == 0.0 && y == 0.0) {
         long ws = sl.tryConvertToWriteLock(stamp);
         if (ws != 0L) {
           stamp = ws;
           x = newX;
           y = newY;
           break;
         }
         else {
           sl.unlockRead(stamp);
           stamp = sl.writeLock();
         }
       }
     } finally {
       sl.unlock(stamp);
     }
}

Here it can be seen that initially read lock is acquired and then some condition is checked if it satisfies then only an attempt is made to convert the read lock to write lock. If returned stamp is not zero that means conversion was successful otherwise go through the procedure of releasing the read lock and acquiring a write lock.

That's all for this topic StampedLock in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Source: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/StampedLock.html


Related Topics

  1. ReentrantLock in Java concurrency
  2. Difference between ReentrantLock and Synchronized
  3. Lock Striping in Java Concurrency
  4. Non-blocking algorithms
  5. Java Concurrency interview questions

You may also like -

Thursday, 25 August 2016

Lambda Expression Callable example

Since Callable is a functional interface, starting Java 8 it can also be implemented as a lambda expression.

In this post we’ll see how to implement Callable as a lambda expression. Suppose you want to have a callable where string is passed and it returns the length of the string.
In this Java code a thread pool of 2 threads is created and then submit method is called with callable object as parameter.

Java Code

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableLambda {
    public static void main(String args[]){
        ExecutorService es = Executors.newFixedThreadPool(2);
        getLength(es, "executor");
        getLength(es, "executor service");
        getLength(es, "Scheduled executor service");
        getLength(es, "executors");
        getLength(es, "fork join");
        getLength(es, "callable");    
    }
    
    public static void getLength(ExecutorService es, final String str){
        // callable implemented as lambda expression
        Callable<String> callableObj = () -> {
            StringBuffer sb = new StringBuffer();
            return (sb.append("Length of string ").append(str).append(" is ").
                    append(str.length())).toString();
        };
        
        // submit method
        Future<String> f = es.submit(callableObj);
        
        try {
            System.out.println("" + f.get());
        } catch (InterruptedException | ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

Output

Length of string executor is 8
Length of string executor service is 16
Length of string Scheduled executor service is 26
Length of string executors is 9
Length of string fork join is 9
Length of string callable is 8

Also, if you noticed the  try-catch block in the code,  multi catch statement from Java 7 is used here.

That's all for this topic Lambda Expression Callable example. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Lambda Expression Runnable example
  2. Lambda Expression Comparator example
  3. Functional interface annotation in Java 8
  4. Lambda expression examples in Java 8
  5. Java Concurrency interview questions

You may also like -

>>>Go to Java Programs page

Wednesday, 24 August 2016

Ternary operator in Java

Java includes a conditional operator known as ternary operator (?:), which can be thought of as a shorthand for an if-else statement. This operator is known as the ternary operator because it uses three operands.

General form of ternary operator

boolean-exp ? expression2 : expression3

If boolean expression evaluates to true then expression2 is evaluated and its value becomes the result of the operator; otherwise (boolean expression is false), expression3 is evaluated and its value becomes the result of the operator.

Note that both expression2 and expression 3 should return the value of same (or compatible) type.

As example if you have this statement -

int result = someCondition ? value1 : value2;

This operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."

Usage of ternary operator

Though switch-case statement provides performance improvement over if-else statement there is no performance improvement if ternary operator is used over an if-else statement but it makes the code more readable and terse.

As example -

int val = (i > 10) ? i * 5 : i * 10;

Here val is assigned the value (i * 5) if i is greater than 10 otherwise val is assigned the value (i * 10).

Writing the same thing using if-else will be a multiple line affair.

 
 if(i > 10){
    val = i * 5;
}else{
    val = i * 10;
}

If you were to write a method where value is returned using the same logic, with ternary operator the method will look like -

 
public int getValue(int i){
 return (i > 10) ? i * 5 : i * 10;
}

In this case if-else statement can also be made more compact -

 
public static int getValue(int i){
    if(i > 10)
        return i * 5;
    return i * 10;
}

Not its up to you to decide what looks more readable. I feel once you get a grip over ternary operator it will always be more readable.

Another example – This example uses String expression and prints a message based on the value of the string.

 
String day = "saturday";
System.out.println(((day.equalsIgnoreCase("saturday") || day.equalsIgnoreCase("sunday"))
    ? "weekend! time to party!" : "Working day"));

Output

weekend! time to party!

Nested ternary operator

Ternary operator can be nested but doing that considerably decreases the readability.

As example if you have the logic that number of transactions in a week is-

upto 5 means ok, 
more than 5 and less than 10 means notify the user 
more than 10 means alarm!!

Then you can use the nested ternary operator

String noOfTransactions = (i < 5) ? "ok" : (i > 5 && i < 10) ? "notify" : "alarm";

Generally it is not advisable to use nested ternary operator as it defeats the purpose of making the code more readable in contrast it makes it look more complex and confusing in most of the cases.

That's all for this topic Ternary operator in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. String in Java
  2. Switch-Case statement in Java
  3. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

Monday, 22 August 2016

String Vs StringBuffer Vs StringBuilder in Java

String in Java has many characteristics like being immutable, thread safety, declared as final that sets it apart. But, being immutable also means that any modification to String object will result in a creation of new string even if you use operations like converting to lowercase, uppercase. Thus concatenation of many strings will result in creation of many objects making it less memory efficient in that case.

Enters StringBuffer which is mutable and has an append() method which can append to the original StringBuffer and doesn’t result in creation of many objects. StringBuffer is also thread safe but here thread safety comes from the fact that all of its methods are synchronized. This synchronization makes it a little slow.

Enters StringBuilder class which provides the same methods as StringBuffer but it is not thread safe. Which makes it faster, as it performs no synchronization.

In this post we’ll go through these difference among the String, StringBuffer and StringBuilder classes which is a very important String interview question too.

Difference among String, StringBuffer and StringBuilder

String StringBuffer StringBuilder
Creation Apart from creating strings using new operator, String object can also be created like primitive data types are created as example String str = "test"; When String is created this way it is stored in a common string pool. StringBuffer object can only be created using new operator. StringBuffer object is stored in Heap. StringBuilder object can only be created using new operator. StringBuilder object is stored in Heap.
Modifiability Once you create a String object the content of that string cannot be modified i.e. String objects are immutable. Here being immutable means whenever you perform any operation on string which alters its content a new string object is created which contains the modified string. Original string is left as it is. StringBuffer is a mutable(modifiable) sequence of characters. Thus in case of StringBuffer length and content of the sequence can be changed through certain method calls. StringBuilder is a mutable(modifiable) sequence of characters. Thus in case of StringBuilder length and content of the sequence can be changed through certain method calls.
Appending If you have to append a lot of strings it will take more memory. Since string is immutable so concatenation of strings will result in creation of a lot of intermediary strings. StringBuffer class is mutable so appending to it using append() method will not result in creation of intermediary objects. That way less memory is used. StringBuilder class is mutable so appending to it using append() method will not result in creation of intermediary objects. That way less memory is used.
Thread-safety As string objects are immutable so they are thread safe. StringBuffer is thread safe so String buffers are safe for use by multiple threads. Each method in StringBuffer is synchronized making it thread safe. StringBuilder is not thread-safe.
Performance String class is fast. All the methods in StringBuffer class are synchronized which makes it a little slow. If you don't have to bother about thread safety then use StringBuilder class as it supports all of the same operations as StringBuffer but it is faster, as it performs no synchronization.

That's all for this topic String Vs StringBuffer Vs StringBuilder in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. String charAt() and subString() methods in Java
  2. Searching within a String using indexOf(), lastIndexOf() and contains() methods
  3. Splitting a String using split() method in Java
  4. String join() method in Java 8
  5. Java String interview questions

You may also like -

>>>Go to Java Basics page

Friday, 19 August 2016

Switch-Case statement in Java

Switch case statement is Java's decision statement which can have a number of possible execution paths. It provides an easy and more readable way to execute a set of code based on the value of the expression.

General form of switch-case statement

switch (expression) {
 case value1:
  // statement
  break;
 case value2:
  // statement
  break;
 .
 .
 .
 case valueN :
  // statement
  break;
 default:
  // default statement
}

Switch works with byte,short, char, and int primitive data types and their wrapper classes Character,  Byte, Short, and Integer. Starting Java 7 it also works with String in Java.

Execution path of switch-case statement

When a value is passed in the switch expression it is compared with the value of each case statement, if match is found the code following that case statement is executed. Code execution with in the case statement is terminated when the break statement is encountered. As soon as the break statement is encountered no other case statement is executed and control comes out of the switch case statement.

If none of the values in the case statement matches the value of the expression then the default statement is executed. Note that default statement is not mandatory though. If none of the values in the case statement matches the value of the expression and default statement is also not there then control will come out of the switch-case statement executing nothing.

It is not mandatory to have break statement in every case statement, in case break statement is omitted in any case statement, next case statement will also be executed though it doesn't match the value of the expression. That can be used to group a set of case statements but omission due to negligence will result in execution of several case statements in place of a single matching one. See example for more clarity.

Also note that the type of each value must be compatible with the type of expression.

Switch-case statement example

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 7;
  switch(month){
   case 1: System.out.println("Month is January"); 
   break;
   case 2: System.out.println("Month is February"); 
   break;
   case 3: System.out.println("Month is March"); 
   break;
   case 4: System.out.println("Month is April"); 
   break;
   case 5: System.out.println("Month is May"); 
   break;
   case 6: System.out.println("Month is June"); 
   break;
   case 7: System.out.println("Month is July"); 
   break;
   case 8: System.out.println("Month is August"); 
   break;
   case 9: System.out.println("Month is September"); 
   break;
   case 10: System.out.println("Month is October"); 
   break;
   case 11: System.out.println("Month is November"); 
   break;
   case 12: System.out.println("Month is Decmber"); 
   break;
  }

 }

}

Output

Month is July

Here month expression has the value 7 so it will go to the case statement which has value 7 and execute the statements with in that case statement and then break out.

Note that default statement is not used this code.

Let us change this example to pass month as 13 and have a default statement to encounter such cases.

Java code

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 13;
  switch(month){
   case 1: System.out.println("Month is January"); 
   break;
   case 2: System.out.println("Month is February"); 
   break;
   case 3: System.out.println("Month is March"); 
   break;
   case 4: System.out.println("Month is April"); 
   break;
   case 5: System.out.println("Month is May"); 
   break;
   case 6: System.out.println("Month is June"); 
   break;
   case 7: System.out.println("Month is July"); 
   break;
   case 8: System.out.println("Month is August"); 
   break;
   case 9: System.out.println("Month is September"); 
   break;
   case 10: System.out.println("Month is October"); 
   break;
   case 11: System.out.println("Month is November"); 
   break;
   case 12: System.out.println("Month is Decmber"); 
   break;
   default: System.out.println("Invalid month value passed");
  }
 }
}

Output

Invalid month value passed

Example omitting break statement

As stated above break statement is not mandatory but it will result in execution of the next case statement.

Java code

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 7;
  
  switch(month){
   case 1: System.out.println("Month is January");
   
   case 2: System.out.println("Month is February"); 
   
   case 3: System.out.println("Month is March"); 
   
   case 4: System.out.println("Month is April"); 
   
   case 5: System.out.println("Month is May"); 
   
   case 6: System.out.println("Month is June"); 
   
   case 7: System.out.println("Month is July"); 
   
   case 8: System.out.println("Month is August"); 
   
   case 9: System.out.println("Month is September"); 
   
   case 10: System.out.println("Month is October"); 
   
   case 11: System.out.println("Month is November"); 
   
   case 12: System.out.println("Month is Decmber"); 
   
   default: System.out.println("Invalid month value passed");
  }

 }

}

Output

Month is July
Month is August
Month is September
Month is October
Month is November
Month is Decmber
Invalid month value passed

In the above switch case statement break is not used with any case statement. Since month passed is 7 so control will go to the case statement having value 7 and start executing the code with in that case statement but it won't know when to break so all the following case statements (even default) are executed.

Case statements can be grouped by omitting the break statement. As example if you want to display the quarter passed month falls into then you can group three case statements where break statement is used with only the last one in the group.

Java Code

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 5;
  
  switch(month){
   case 1: 
   
   case 2: 
   
   case 3: System.out.println("Quarter 1"); 
     break;
   
   case 4: 
   
   case 5:  
   
   case 6: System.out.println("Quarter 2"); 
     break;
   
   case 7:
   
   case 8:
   
   case 9: System.out.println("Quarter 3"); 
     break;
   
   case 10:  
   
   case 11: 
   
   case 12: System.out.println("Quarter 4"); 
      break;
   
   default: System.out.println("Invalid month value passed");
  }

 }

}

Output

Quarter 2

Using Strings in switch Statements

In Java SE 7 and later, you can use a  String object in the switch statement's expression.

 
public class StringSwitchDemo {

 public static void main(String[] args) {
  String dept = "Human Resources";
  String deptCd = null;
  switch(dept.toLowerCase()){
   case "account": 
    deptCd = "acct";
    break;
   case "human resources": 
    deptCd = "hr";
    break;
   case "administration":
    deptCd = "admin";
    break;
   default: System.out.println("Invalid deprtment");
  }
  
  System.out.println("Department - " + deptCd);
 }

}

Output

Department – hr

Nested switch statements

You can have nested switch-case statement with in the outer switch statement.

switch(month){
 case 1:
 switch(week){
  case 1: .....
         break;
  case 2 : ....

  ...
  ...
 }
 break;
}

Switch-case statement efficiency

If you have to make a choice between sequence of if-else stateemnt and switch-case statement opt for switch case as it will run faster.

Reason being when the Java compiler compiles a swith-case statement it will go through all the case statement values (which are constants) and make a jump table. The value on which the switch is being performed is used as an index into the jump table to directly go to that case statement. In the case of switch-case statemnt it can be done as compiler knows that case values are all of sane type and switch expression can only be used for equality test with case values.

Points to note

  1. Value of the case statement can only be a constant expression.
  2. Switch case statement can only be used for equality test. No other boolean expression like greater than, not equal to etc. can be used with switch statement.
  3. Duplicate case values are not allowed, each case statement should have a unique value.
  4. default statement is not mandatory.
  5. break statement is also not mandatory. Leaving break statement with in a case statement will result in the execution of the next case statement.
  6. From Java 7 string class can also be used with switch case.

That's all for this topic Switch-case statement in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. String in Java
  2. Ternary operator in Java
  3. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

Monday, 15 August 2016

String interview questions

  1. What is String in Java?

    In Java String class represents character strings which means; Strings in Java are objects and all strings are instances of the String class. Internally in String class Strings are stored as character array.

    Read more about String in Java here.

  2. In how many ways String object can be created?

    Since strings are objects so strings can of course be created using new operator. String class has more than 10 constructors to create Strings which ranges from taking nothing as parameter to taking char array, StringBuffer, StringBuilder, another String as argument.
    Another and more preferred way to create Strings is to assign String literal directly to a String reference as you will do for any primitive type. For every string literal Java will automatically constructs a String object.

    As example - String str = “abc”; 
    

    Read more about String in Java here.

  3. If String can be created using String str = “test” then String is a primitive data type.Yes/No?

    No. For every string literal Java automatically constructs a String object.


  4. What is String pool? Where is it created in memory?

    When String literals are created they are stored in a String pool and that is a common pool; which means if there are two strings literals having the same content then those string will share the space in the pool.
    When String object is created by assigning a string literal, pool will be checked to verify if there is any existing object with the same content if there is then that existing reference is used, no new object is created in that case. If no object is found with the same content then this new literal will be added in the pool.
    String pool is stored in the heap.

    Read more about String in Java here.

  5. What is immutable object? Is String object immutable?

    An immutable object is an object that would not be able to change its state after creation. Thus immutable object can only be in one state and that state can not be changed after creation of the object.
    Yes String object is immutable. Once you create a String object the content of that string cannot be modified.


  6. Why is String class immutable?

    Since Java maintains a string pool where String references are shared thus changing content of any of the String will also affect the other strings sharing the same references that’s one reason why string is immutable.


  7. Why is String class final in Java?

    Since String is immutable, whenever you perform any operation on string which alters its content a new string object is created containing the modified string. Which means all the methods of the String class that modify the content in any way return a new String object with the modified content.
    Now, What if you can override the method of the String class so that it modifies and return the original string reference itself? In that case all the other strings having the same data in the string pool will also get affected as the reference is shared for the String literals having the same content.
    To avoid these kind of scenarios String class is declared as final and it can’t be overridden.


  8. Which operator is overloaded for String?

    ‘+’ operator is overloaded in Java for String. It is used for concatenating two strings.


  9. How many objects will be created if two Strings are created this way?

    String s1 = “test”; 
    String s2 =  “test”;
    

    Since s1 and s2 are string literals and having the same content object reference will be shared by them in the string pool. Therefore only one object is created.


  10. How many objects will be created if two Strings are created this way?

    String s1 = “test”;
    String s2 =  new String(“test”);
    

    In this case string literal goes to string pool and s2 is another object created using new. So, in this case two objects are created even if content is same.


  11. How many objects will be created if two Strings are created this way?

    String s1 = new String(“test”);
    String s2 =  new String(“test”);
    

    Two separate objects are created.
    If you check it using the following code

    if(s1 == s2){
       System.out.println("s1 and s2 are same");
    }else{
       System.out.println("s1 and s2 are not same");
    }
    
    s1 and s2 are not same will be displayed.


  12. How many object will be created if Strings are created this way?

    String s1 = “test”;
    String s2 =  new String(“test”);
    String s3 = new String(“test”).intern();
    

    s1 will go to string pool, for s2 new object is created. S3, though created using new will still search in the string pool for any reference having the same content as intern() method is used. So two objects will be created.


  13. What is intern() method in String?

    Using intern() method you can still get string object from the pool (if it exists) even if new operator is used to create a string.
    When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

    Read more about String in Java here.

  14. Is String thread safe in Java?

    Yes string is thread safe in Java as String is immutable.

    Read more about String and thread safety in Java here.

  15. What is StringBuffer in Java?

    StringBuffer class is the companion class of String. StringBuffer is a mutable(modifiable) sequence of characters which is in contrast to String class which is an immutable sequence of characters. Thus in case of StringBuffer length and content of the sequence can be changed through certain method calls.
    Since StringBuffer is mutable a new String object is not created every time string is modified, which in turn results in less memory consumptions and not having lots of intermediate String object for garbage collection.

    Read more about StringBuffer in Java here.

  16. What is StringBuilder in Java?

    StringBuilder class (Added in Java 5),just like StringBuffer, is a mutable(modifiable) sequence of characters which is in contrast to String class which is an immutable sequence of characters. Thus in case of StringBuilder length and content of the sequence can be changed through certain method calls.

    Read more about StringBuilder in Java here.

  17. Differences among String, StringBuffer and StringBuilder in Java?

    String is immutable where as both StringBuffer and StringBuilder are mutable.
    String and StringBuffer are thread safe where as StringBuilder is not thread safe.

    Read more about String Vs StringBuffer Vs StringBuilder in Java here.

  18. Is StringBuffer class also immutable in Java?

    No, StringBuffer is not immutable.

    Read more about StringBuffer in Java here.

  19. Is StringBuffer class also final in Java?

    Yes, StringBuffer class is final in Java.


  20. Is StringBuffer class thread safe?

    Yes StringBuffer class is thread safe. Methods in StringBuffer class are synchronized.


  21. Is StringBuilder class thread safe?

    No StringBuilder class is not thread safe. That makes it faster than StringBuffer.


  22. Is StringBuilder class also final in Java?

    Yes StringBuilder class is final in Java.

    Read more about StringBuilder in Java here.

  23. How to compare two strings in Java?

    equals() method can be used for comparing two strings in Java. If you want to ignore case then you can use equalsIgnoreCase(String anotherString) method.
    There are also compareTo() and compareToIgnoreCase() methods for comparing two strings lexicographically. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.
    You can also use matches() method where you can pass a regular expression for matching strings.

    Read more about String comparison in Java here.

  24. What will happen if “==” operator is used to compare two strings in Java?

    “==” operator will compare the references of the strings not the content.

    String str1 = "abc";
    String str4 = new String("abc");
    
    Comparing these two strings using “==” operator
     if(str1 == str4)
    
    will return false as the references are different.


  25. How to get characters and substrings by index with in a String?

    You can get the character at a particular index within a string by invoking the charAt() accessor method.

    String str = "Example String";
    char resChar = str.charAt(3);
    
    Will give char ‘m’. If you want to get more than one consecutive character from a string, you can use the substring method. The substring method has two versions -
    • String substring(int beginIndex, int endIndex) - Returns a new string that is a substring of this string.
    • String substring(int beginIndex) - Returns a new string that is a substring of this string.

    Read more about String charAt() and subString() methods in Java here.
  26. How can you find characters or substrings within a string?

    To find characters or substrings with in a string indexOf() and lastIndexOf() methods can be used.
    You can also use contains() method
    public boolean contains(CharSequence s) - Returns true if and only if this string contains the specified sequence of char values. Otherwise it returns false.

    Read more about charAt() and subString() methods in Java here.
  27. How can you split a string in Java?

    String provides a split method in order to split the string into one or more substring based on the given  regular expression.
    As example If you have a string where one (or more) spaces are used and you want to split it around those spaces.

    String str1 = "split example    program";
    String[] strArray = str1.split("\\s+");
    

    Read more about Splitting a String using split() method in Java here.
  28. How can you join strings in Java?

    With Java 8 join() method has been added in the String class which makes it very easy to join the multiple strings.
    join method has two overloaded versions -

    • public static String join(CharSequence delimiter, CharSequence... elements) - Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
    • public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) – Here elements is an Iterable that will have its elements joined together and delimiter is a sequence of characters that is used to separate each of the elements in the resulting String.

    Read more about String join() method in Java 8 here.
  29. Can we use String in switch case statement?

    Yes from Java 7 string can be used in switch case statement.


Related Topics

  1. Java OOP interview questions
  2. Core Java basics interview questions
  3. Java Collections interview questions
  4. Java Multi-threading interview questions
  5. Java Concurrency interview questions
  6. Java Exception Handling interview questions

Tuesday, 9 August 2016

Java basics interview questions

  1. What are JVM, JRE and JDK?

    JVM

    JVM meaning Java Virtual Machine is an abstract layer between a Java program and the platform that Java Program is running on.
    JVM is platform dependent and different implementations of JVMs are available for specific platforms.

    JRE

    JRE meaning Java Runtime Environment provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language.

    JDK

    JDK meaning Java Development Kit is a superset of the JRE, and contains everything that is in the JRE, plus development tools such as the compilers and debuggers necessary for developing applets and applications.

    Read more about JVM, JRE and JDK here

  2. What is bytecode in Java or Why java is called platform independent?

    Java programs are both compiled and interpreted which means -
    When we do javac javaprogram, the java source code is compiled into a .class file which is actually a bytecode. The generated bytecode is portable and it's format is same across platforms.
    After compilation, the interpreter reads the generated byte code & transforms it according to the native platform.
    The compiled bytecode doesn't run on CPU directly, JVM sits in between and interpret the bytecode into readable machine language for the CPU. So Java program is platform independent but JVM is platform dependent and different implementations of JVMs are available for specific platforms.


  3. Java is pass by value or pass by reference?

    Java is pass by value for both primitive types as well as for objects.

    Read more about Java pass by value or pass by reference here

  4. What is package in Java?

    A package is a namespace that organizes a set of related classes and interfaces. Packages also help in  preventing naming conflicts.
    Packages also provide visibility control mechanism. You can define classes and class members inside a package that are not visible to the classes in other packages.

    Read more about Package in Java here

  5. What are access modifiers in Java?

    Access level modifiers are used to control the visibility of the class or the members of the class i.e. fields and methods.
    Types of Access Modifiers

    • private - private modifier specifies that the member can only be accessed in its own class.
    • default (or package-private) - If no specifier is used (which is known as default access) member is visible only within its own package.
    • protected - protected modifier specifies that the member can only be accessed within its own package and by a subclass of its class in another package.
    • public - public modifier specifies that member is visible to all classes everywhere.

    Read more about Access Modifiers here

  6. What all access modifiers can be used with a class?

    At the class level only two of the modifiers can be used, public or default.
    If a class is declared with the modifier public, that class is visible to all classes everywhere.
    If a class has no modifier (the default), it is visible only within its own package.

    Read more about Access Modifiers here

  7. What all access modifiers can be used with class fields?

    All the four types of access modifiers - public, protected, default, private can be used with variables declared in the class.

    • If a field is declared as public then it is visible to all classes in the same package or other packages.
    • If a fields is declared with no access specifier (default) then it can be accessed by any class in the same package.
    • If a field is defined as protected then it is accessible to any class in the same package or to any subclass (of the class where field is declared) in different package.
    • If a field is defined private then that field can only be accessed in its own class.


  8. What all access modifiers can be used with class methods?

    All the four types of access modifiers - public, protected, default, private can be used with methods of the class and access modifier for the methods work the same way as for the fields.


  9. What all access modifiers can be used with constructors?

    All the four types of access modifiers - public, protected, default, private can be used with constructors of the class.

    • In case constructor of the class is private then the object of that class can be created by that class only.
    • In case constructor is marked as protected then a subclass in different package can access the protected constructor.
    • If a constructor is declared with no access specifier (default) then it can be accessed by any class in the same package.
    • If a constructor is declared as public then it is visible to all classes in the same package or other packages.


  10. What is automatic numeric promotion in Java?

    In Java numeric promotion happens in case of primitive types when those primitives are used in an expression.
    As exp.

    byte a = 100;
    byte b = 50;
    int i = a * b;
    
    In the above code a * b will exceed the range of its byte operand (range of byte is -128 to 127). In these types of situations Java will automatically promote the byte, short or char to int when evaluating an expression.

    Read more about automatic numeric promotion here

  11. What is constructor?

    In Java there is a special method provided to initialize objects when they are created. This special method which is used for automatic initialization is called Constructor.
    Constructor has the same name as the class in which it is created and defined just like a method, that is, constructor's syntax is similar to a method

    Read more about constructor here.

  12. What is default constructor in Java?

    When a constructor is not explicitly defined for a class, then Java creates a default no-arg constructor for a class that is called default constructor.

    Read more about constructor here.

  13. What is Parameterized Constructor in Java?

    If we want our object's fields to be initialized with specific values, we can do it by adding parameters to the constructor.

    Read more about constructor here.

  14. What is constructor chaining in Java?

    In case when we have a hierarchy of classes (inheritance) the constructors of the classes are invoked in an order. That order is known as constructor chaining.
    For Exp - If class A is super-class and there is Class B which is subclass of A. In that case if a new instance of class B is created, order in which constructors of Class A and Class B are executed is from super-class to subclass.

    Read more about constructor chaining here.

  15. What is constructor overloading in Java?

    Like method overloading there is also an option to have multiple constructors within the same class where the constructors differ in number and/or types of parameters, that process is known as Constructor overloading.

    Read more about constructor overloading here.

  16. Are constructors from the super class inherited in the sub-class?

    No constructors are not inherited in Java.


  17. What is this in java?

    this in java is a reference to the current object on which the method or constructor was invoked. this can be used inside any method or constructor to refer to the current object.

    Read more about this here

  18. What is super in java?

    The super keyword in java is essentially a reference variable that can be used to refer to its immediate parent class.
    Usage of super -

    • Invoke the constructor of the super class.
    • Accessing the variables and methods of parent class.

    Read more about super here

  19. If there is a parent class A and two child classes class B and class C, can object of type A refer to object of type B or to an object of type C?

    Yes Parent class object can refer to child class object.

    A a;
    B b = new B();
    C c = new C();
    a = b;
    a = c; 
    
    is permissible.

  20. In the above case can child class object hold parent class reference?

    No that will result in compile time error without type casting.

    A a;
    B b = new B();
    b = a;
    

    This will result in error. You will have to typecast it.

    b = (B) a; 
    
    Read more about type casting in Java here

  21. What is instanceof operator?

    An object can only be cast to its own class or one of its super-type, if you try to cast to any other object you may either get a compile-time error or a class-cast exception.

    You can use instanceof operator to check whether the object can be cast to that type safely or not.

    Read more about instanceof operator here

  22. What is interface in Java?

    Interfaces help in achieving full abstraction in Java, as using interface, you can specify what a class should do, but how class does it is not specified.
    Interfaces look syntactically similar to classes, but they differ in many ways -

    • Interfaces don't have instance variables.
    • In interfaces methods are declared with out any body. They end with a semicolon.
    • Interface can't be instantiated.
    • Interfaces don't have constructors.
    • An interface is implemented by a class not extended.
    • An interface can extend multiple interfaces.

    Read more about interfaces here.

  23. Can an Interface be final?

    No, interface can't be final. The whole idea of having an interface is to inherit it and implement it. Having it as final means it can't be subclassed.

    Read more about interfaces here.

  24. Is it possible to declare an interface method static?

    Not before Java 8, from Java 8 it is possible to have interface static methods.

    Read more about interface here and interface static method here.

  25. What are interface default/defender methods?

    With the release of Java 8, it is now possible to add default method in interfaces. With the addition of default method to an interface, addition of new method, to even an interface will not break the pre-existing code.
    An interface default method is defined the same way a method will be defined in a class. One difference is that in interface default method is preceded by the keyword default
    As Exp.

    public interface MyInterface {
     int method1();
     // default method, providing default implementation
     default String displayGreeting(){
      return "Hello from MyInterface";
     }
    }
    

    Read more about interface default method here.

  26. Can an Interface implement another Interface?

    No, an interface can't implement another interface. Though, interface can extend another interface.

    Read more about extending interface here.

  27. Can an Interface extend another Interface?

    Yes,interface can extend another interface.

    Read more about extending interface here.

  28. Is it possible to have final method in an interface?

    No, whole idea of interface is to have abstract methods for which implementation is provided by the implementing classes. Making a method as final in interface will mean it can't be overridden which will mean implementing class can't provide an implementation for that mthod.

    Read more about interfaces here.

  29. Is it possible to define a class inside an interface?

    Yes.An interface can have an inner class. That class will be accessed by using interfaceName.ClassName.


  30. What is a nested interface?

    An interface or a class can have another interface. Such an interface is known as nested interface or a member interface.When a nested interface is used outside, it must be used as a fully qualified name i.e. must be qualified by the name of the class or interface of which it is a member.

    Read more about nested interface here.

  31. What is a marker interface?

    A marker interface is an interface that has no method declarations or fields in it. It is used as a tag to let the compiler know it needs to add some special behavior to the class implementing marker interface. That is why marker interface is also known as tag interface.

    Read more about marker interfaces here.

  32. What is an abstract class?

    An abstract class is a class that is declared using the abstract keyword. An abstract class may contain methods without any implementation, called abstract methods.

    Read more about abstract class here.

  33. Is it possible to have abstract method in a class that is not abstract?

    No. If there is even a single abstract method in a class that class has to be declared as abstract.

    Read more about abstract class here.

  34. Is it possible to instantiate an abstract class?

    No. An abstract class can not be instantiated on its own, but abstract class can be used to create object references.

    Read more about abstract class here.

  35. Is it possible to have an abstract class without any abstract method?

    Yes. Even if there are no abstract methods in a class that class can still be declared as abstract. That abstract class still can not be instantiated.

    Read more about abstract class here.

  36. Can you use abstract and final both with a method?

    No. The whole idea of having a abstract method in a class is that it would be implemented by the inheriting class. Whereas making a method final means it can't be overridden thus can't be provided implementation in inheriting class. So using both of them is not possible.

    Read more about abstract class here and about final here

  37. What are the differences between abstract class and interface?

    Abstract Class Interface
    Methods Abstract class can have both abstract and non-abstract methods. Interface can have abstract methods only.
    Note: From Java 8 interfaces can have default methods and static methods.
    Access Modifiers Abstract class methods can have public, protected, private and default modifier apart from abstarct methods. In interface methods are by default public abstract only.
    Variables Abstract class fields can be non-static or non-final. In interface all the fields are by default public, static, final.
    Implementation Abstract class may have some methods with implementation and some methods as abstract. In interface all the methods are by default abstract, where only method signature is provided. Note: From Java 8 interfaces can have default methods and static methods.
    Constructor Abstract class have a constructor, it may be user supplied or default in case no constructor is written by a user. Interface can't have a constructor.
    Multiple Inheritance Abstract class can extend at most one class and implement one or more interfaces. Interface can only extend one or more interfaces.
    Abstraction Abstract class can provide both partial or full abstraction. Interface provides full abstraction as no implementation is provided for any of the method.
    Extends/Implements Abstract class are extended by the sub-classes. Sub-classes need to provide implementation for all the abstract methods of the extended abstract class or be declared as abstract itself. Interface is implemented by a class and the implementing class needs to provide implementation for all the methods declared in an interface. If a class does not implement all the methods of interface then that class must be declared as abstract.
    Easy to evolve Abstract class was considered easy to evolve as abstract classes could add new methods and provide default implementation to those methods. Interface was not considered easy to evolve as, in the case of adding new method to an interface, all the implementing classes had to be changed to provide implementation for the new method. With Java 8 even interfaces can have default methods so that issue has been addresses.


  38. Why multiple inheritance not supported through Java?

    Multiple inheritance by extending several classes is one feature omitted in the Java language as the designers of the Java language opined that multiple inheritance is a confusing feature and it causes more problems than it solves.

    Read more about why multiple inheritance is not supported in Java here.

  39. Why multiple inheritance not supported through Java?

    Multiple inheritance by extending several classes is one feature omitted in the Java language as the designers of the Java language opined that multiple inheritance is a confusing feature and it causes more problems than it solves.

    One of the reason given for omitting multiple inheritance is to avoid “diamond problem” which is one of the classic multiple inheritance problem.

    Read more about why multiple inheritance is not supported in Java here.

  40. What is diamond problem in Java?

    Refer http://netjs.blogspot.com/2017/06/why-no-multiple-inheritance-in-java-diamond-problem.html to read about diamond problem in Java.


  41. Can we implement more than one interfaces in Java?

    Yes in Java you can implement more than one interface.


  42. What is Static variable in Java?

    A variable declared as static is associated with the class rather than with any object. When objects of its class are created, copy of static variable is not created per object. All objects of the class share the same static variable.

    Read more about static keyword here.

  43. What is static method in Java?

    A static method is associated with the class rather than objects of the class. Static method can be called directly with the class name ClassName.static_method() rather than with the object of the class.

    Read more about static method here.

  44. What is static block in Java?

    A static block in a class is executed only once, when the class is first loaded, even before the main method.

    Example of static block

    public class StaticDemo {
    // static blank final variable
     static final int i;
     static int b;
    static {
      System.out.println("in static block");
      i = 5;
      b = i * 5;
      System.out.println("Values " + i + " " +  b);
     }
    }
    
    Read more about static block here.

  45. Can we have static variable inside a method?

    No. Since static variables belong to a class where as variables declared inside a method are local variables and belong to that method. So variables inside a method can be declared as final, but not static, public, protected or private.

    Read more about static keyword here.

  46. Why can't we access non-static variable from static method?
    OR
    Why non-static variable can not be accessed from main method in Java?

    Static methods or fields can be accessed without even creating an instance of the class, we just need to qualify the static member with the class name and access it. But non-static members need instance of the class to be created to come into existence. That is the reason why non-static field or method can not be called from the static context.

    Read more about Static reference to the non-static method or field error here.

  47. Can we overload static method?

    Static methods can be overloaded just as 'instance methods'. So it is possible to have two or more static methods having the same name, but the parameters are different in types or number.

    Read more about static overloading here.

  48. Can we override static method?

    Static methods can not be overridden in Java. Though it is possible to have a static method with same signature in sub-class but in that case sub-class method hides the super class method rather than overriding it.

    Read more about static method overriding here.

  49. Why main method is static in Java?

    When a class is loaded JVM needs an entry point (main method). JVM needs to access that main method with out creating an instance of the class, that is why main method is static.
    If it is not declared as static then instance of the main class has to be created which may cause ambiguity.

    public class A {
     private int i;
     A(int i){
      this.i = i;
     }
     public static void main(String args[]){
     }
    }
    

    Here in the class there is a constructor with one argument i. Now in order to create an object of the class what should be passed as i? To avoid these types of ambiguities it doesn't make sense for the JVM to have to create an object of the class before the entry point (main method) is called. That's why main method is static.

    Read more about Why main method is static here.

  50. What is static import in Java?

    In order to access any static member (static field or method) of the class, it is necessary to qualify references with the class they came from.
    As exp. - ClassName.static_method()

    With static import feature of Java 5, members defined in a class as public static can be used without qualifying it with the class name, in any Java class which does a static import. This shortens the syntax required to use a static member.

    Read more about static import in Java here.

  51. What is final in Java?

    final keyword in java has its usage in preventing the user from modifying a field, method or class.

    • final field - A variable declared as final prevents the content of that variable being modified.
    • final method - A method declared as final prevents the user from overriding that method.
    • final class - A class declared as final can not be extended thus prevents inheritance.

    Read more about final keyword here.

  52. What is a final blank variable?

    A final variable can be initialized only once but it can be done in two ways.

    • Value is assigned when the variable is declared.
    • Value is assigned with in a constructor.
    A final variable that has not been assigned a value while declaring a variable is called blank final variable, in that case it forces the constructor to initialize it.

    Read more about final keyword here.

  53. What if a list is declared as final, is it possible to add or remove values from that list?

    When an object reference variable is declared as final, object fields can still be changed but the reference can't be changed.
    So yes it is possible to add or remove values from the list even if the list is declared as final.

    But we can't change the reference of that list.
    As Exp.

    final List tempList = new Arraylist();
    tempList.add("1"); // permitted
    tempList = new ArrayList()// This will result in an error as we are trying to change the reference
    

  54. What is a final method?

    A method can be declared as final in order to avoid method overriding. Method declared as final in super class cannot be overridden in subclass.

    Read more about final method here.

  55. What is a final class?

    A class declared as final can't be extended thus avoiding inheritance altogether.
    If creator of the class is sure that the class has all the required functionality and should be used as it is with out extending it then it should be declared as final.

    Read more about final class here.

  56. What is finalize method in Java?

    If an object need to perform some action before it is garbage collected that can be done using finalize method. In finalize method we can provide the actions to release the resources before the object is destroyed.

    finalize method is provided as a protected method in the Object class.

    protected void finalize() throws Throwable
    
    Read more about finalize method here.

  57. When is finalize method called?

    The finalize method is called by the garbage collector when it determines no more references to the object exist.

    Read more about finalize method here.

  58. Can we use the finalize method provided by the Object class?

    The finalize method of class Object performs no special action; it simply returns normally.

    Subclasses of Object class should override finalize method and provide the required implementation.

    Read more about Object class here.

  59. What are the best practices for overriding finalize method?

    If overriding finalize() it is a good programming practice to use a try-catch-finally statement and to always call super.finalize().

    Read more about finalize method here.

  60. What is covariant return type?

    Before Java 5, when you override a superclass method in a subclass the method signature had to be exactly same, i.e., the name, argument types and return type of the overriding method in the sub-class had to be exactly same as that of the super-class method.

    This is relaxed a bit in Java 5 in case of return type. The sub-class method's return type may be different from super-class method's return type but the return type of the subclass should be a subtype of return type of super class method. Which means, if method in the super-class has return type R1 and the overriding method in the subclass has return type R2 then R2 must be the subtype of R1. That is known as covariant return type.

    Read more about covariant return type here.

  61. What is strictfp in Java?

    strictfp is a keyword in Java that restricts floating-point calculations to ensure portability. Prior to JVM 1.2, floating-point calculations were strict; which meant, all intermediate floating-point results were represented as IEEE single or double precisions only. As a consequence, errors of calculation (round-off errors), overflows and underflows would occur with greater frequency than in architectures which did intermediate calculations in greater precision.

    Since JVM 1.2, intermediate computations are not limited to the standard 32 bit and 64 bit precisions. On platforms that can handle other representations e.g. 80-bit double extended on x86 or x86-64 platforms, those representations can be used, helping to prevent round-off errors and overflows, thereby increasing precision.

    Read more about strictfp in Java here.

  62. What is serialization and deserialization in Java?

    Object serialization is the mechanism of converting object into byte stream. Where as the reverse process of constituting the object from those bytes is known as deserialization.

    Read more about serialization in Java here.

  63. What are the benefits of serialization?

    Once an object is converted to a byte stream those bytes can be -

    • Transmitted from one JVM to another where the object can be reconstituted using those bytes and used in further processing.
    • Stored on a disk/DB for further use.
    Read more about serialization in Java here.

  64. When a serialized object is transmitted across the network where different operating system is used will it work?

    Yes serialization offers that portability. When a serialized object is transmitted across the network the serialization mechanism will take into account the differences in operating systems. Thus an object converted into byte streams in Windows OS can be transmitted across the network and deserialized into an object in the Unix operating system.

    Read more about serialization in Java here.

  65. What is Serializable interface in Java?

    Serializable interface is a marker interface and does not have any field or method. It is part of java.io package.
    Any class whose object has to be serialized should implement Serializable interface.

    Read more about marker interface here.

  66. Suppose I have a Person class in which Address class object is referred. Person class implements Serializable interface but Address class doesn't. Will you be able to serialize a Person object in that case?

    No, in this case you will get exception (java.io.NotSerializableException) when you try to serialize the Person class object.
    All the classes which are to be serialized should be implementing Serializable interface. Since in this case Address class whose object is used in Person class doesn't implement Serializable interface an exception will be thrown.


  67. What is ObjectOutputStream class?

    An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. This class provides writeObject method which is used to write an object to the stream.

    Read more about ObjectOutputStream class here.

  68. What is ObjectInputStream class?

    An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream. This class provides readObject method which is used to read an object from the stream.

    Read more about ObjectInputStream class here.

  69. What if you provide your own writeObject() and readObject() methods?

    If you want to have some control over the process of serialization and deserialization rather than using the default serialization mechanism which for us, as end user, is automatic then you can add your own implementation of writeObject() and readObject() methods.

    If you add methods writeObject() and readObject(), these methods will be called automatically when the object is serialized and deserialized respectively and provide the serialization mechanism rather than using the default mechanism.


  70. What is transient keyword in Java?

    If you want to exclude any object field from getting serialized you can use transient keyword along with that field. Note that you cannot use transient keyword with methods or local variables it can only be used with member variables.

    Read more about transient here.

  71. What is Externalizable interface in Java?

    Externalizable interface extends the Serializable interface and adds two methods writeExternal() and readExternal(). When you use Externalizable for your serialization, you will implement Externalizable interface and implement writeExternal() and readExternal() methods. These two methods will be called while serializing and deserializing respectively.

    Read more about Externalizable interface here.

  72. How is the class object serialized if it implements Externalizable interface?

    An object which is to be serialized is tested for the Externalizable interface. If the object supports Externalizable, the writeExternal method is called. If the object does not support Externalizable and does implement Serializable, the object is saved using ObjectOutputStream.

    When an Externalizable object is reconstructed, an instance is created using the public no-arg constructor, then the readExternal method called. Serializable objects are restored by reading them from an ObjectInputStream.

    Read more about Externalizable interface here.

  73. What are the conditions when class implements Externalizable interface?

    A default no-arg constructor has to be there in the class while using externalizable as object is created using no-arg constructor while deserializing and then the object is initialized using the logic in readExternal() method.

    Order that is used in writeExternal() method for writing the fields should be maintained in readExternal() method.

    Read more about Externalizable interface here.

  74. What is serialVersionUID?

    The serialVersionUID helps in versioning in a Serializable class. serialVersionUID is declared as a private static final long field in the serializable class.
    Suppose you have some class which is serialized and it changes before it is deserialized. If serialVersionUID was generated for the class when serializing it then the generated serialVersionUID while deserializing will differ as the class has changed.

    Read more about serialVersionUID and how it helps with version control here.

  75. How is serialVersionUID generated?

    The stream-unique identifier is a 64-bit hash of the class name, interface class names, methods, and fields. If you are using IDE like eclipse that will give you an option to add generated serialVersionUID or to add default serialVersionUID.
    If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class.

    Read more about serialVersionUID and how it helps with version control here.

  76. What is Serialization Proxy pattern?

    Its a way of designing your class where proxy pattern defines its serialization mechanism. Rather than serializing the original class you provide functionality to serialize the proxy class instead. For the class which has to be serialized a proxy class is also created which is then serialized instead of the original class.
    In serialization Proxy pattern writeReplace() method and readResolve() methods are used for serialization.

    Read more about Serialization Proxy pattern here.

  77. What is writeReplace() method?

    Serializable classes that use an alternative object (proxy object) when writing an object to the stream should implement writeReplace() method with the exact signature:

    ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException;
    
    This writeReplace() method is invoked by serialization if the method exists and this method is defined within the original class whose object is serialized.

    Read more about Serialization Proxy pattern here.

  78. What is readResolve() method?

    Using serialization proxy pattern you serialize the proxy class instead of the original class. At the time of deserializing it should create the original class object. Thus the classes that need to provide a replacement object when the serialized object is read from the stream should implement readResolve() method with the exact signature.

    ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;
    

    Read more about Serialization Proxy pattern here.

  79. How does Serialization Proxy pattern work?

    Rather than serializing the original class you provide functionality using the writeReplace() method to serialize the proxy class instead. writeReplace() method is implemented in the original class.

    At the time of deserialization proxy object is deserialized and then the readResolve() method is called. That’s where you will have to provide the functionality to create the original class object regular way. readResolve() method is implemented in the proxy class.

    Read more about Serialization Proxy pattern here.

  80. What is cloning process?

    If you want to quickly create an object using the existing object in such a way that you get a new instance (where the reference between the objects is not shared) with the same content for the fields in the new object as in existing object. Then you can clone the existing object to create an exact copy.


  81. How is cloning of the object done in Java?

    In Java you can use clone() method to create an exact copy of the existing object.
    clone() method is defined as protected in the Object class which you must override as public in any derived classes that you want to clone.
    Signature of clone method in Object class - protected native Object clone() throws CloneNotSupportedException;

    Read more about Object cloning in Java here.

  82. What is Cloneable interface?

    Your class, whose object you want to clone, must implement Cloneable interface which is part of java.lang package. Not implementing Cloneable interface will result in CloneNotSupportedException exception being thrown when clone method is called.

    Read more about Object cloning in Java here.

  83. What all methods are there in Cloneable interface?

    Cloneable interface is a marker interface and defines no members of its own.

    Read more about marker interface here.

  84. What are the steps in cloning process?

    There are two required steps if you want to clone any object.

    • You need to call clone() method of the Object class or provide your own implementation by overriding the clone() method in your class.
    • Your class, whose object you want to clone, must implement Cloneable interface.

    Read more about Object cloning in Java here.

  85. What are the advantages of cloning?

    If you have an object, creation of which using the usual way is costly; as example if you have to call DB in order to get data to create and initialize your object. In that scenario rather than hitting DB every time to create your object you can cache it, clone it when object is needed and update it in DB only when needed.


  86. What is Shallow copy?

    If the class whose object you want to clone has reference to other class objects then those reference are shared.
    When you clone an object all the values for the fields are copied to the cloned object. Since Java is pass by value, if the field value is a reference to an object (a memory address) it copies that reference to the field of the cloned object. In that case referenced field is shared between both objects and any change made to the referenced field will be reflected in the other object too.
    This process of cloning when the field values are copied to the new object is known as shallow copy.

    Read more about Shallow copy here.

  87. What is deep copy?

    If you don’t want references of object being copied during the cloning process then option is deep copy. When a deep copy is done objects referenced by the cloned object are distinct from those referenced by original object, and independent.
    Deep copies are more expensive, as you need to create additional objects, and can be substantially more complicated, due to references possibly forming a complicated graph.

    Read more about deep copy here.

Related Topics

  1. Java OOP interview questions
  2. Java String interview questions
  3. Java Exception Handling interview questions
  4. Java Multi-threading interview questions
  5. Java Collections interview questions
  6. Java Concurrency interview questions