Friday, 31 March 2017

AutoBoxing and UnBoxing in Java

From Java 5 two new features were added Autoboxing and Unboxing where Autoboxing automates the wrapping of primitive data types into the wrapper class for that particular data type when an object instead of primitive type is needed, Unboxing does the exact opposite that is it gets the value out of a wrapped object automatically.

As example –

Before this features autoboxing was added wrapping a primitive int to its corresponding wrapper class Integer would have looked like –

int num = 25;
Integer i = Integer.valueOf(num);

Now with this feature you can directly assign value to a wrapper class –

Integer i = 25;

Now valueOf() method call will be done by the compiler behind the scene.

Same way for auto unboxing if unboxing; a wrapped object previously meant calling the method intValue(), longValue(), doubleValue() based on the type

Integer i = new Integer(10);
int num = i.intValue();

Now it can be done directly –

Integer i = new Integer(10);
int num = i;

Or for float type

Float f = new Float(56.78);
float fNum = f;

Benefits of Autoboxing and Unboxing

As you have already seen with this feature you don’t need to wrap primitive types or unwrap them manually. That is a great help with the other feature generics also added in Java 5. Since generics work only with object so having the auto facility to box and unbox greatly simplifies the coding.

As the Collection classes also work only with objects so it makes working with collections easy too.

As example –

List<Integer> li = new ArrayList<>();
for (int i = 1; i < 10; i++){
    li.add(i);
}

Even though you have a List which stores objects of type Integer you can still add primitive int directly to List because of Autoboxing. Earlier when the primitive ints were added to the list, behind the scene those values were wrapped into the Integer objects and then added to the ArrayList.

Same way unboxing will also happen automatically.

int elem = li.get(0);
System.out.println("elem " + elem);

When you are trying to get the first element out of the list and assigned it to an int variable, then Integer is unboxed to get the int value out of the wrapped Integer class and that value is assigned to an int variable elem.

More examples of autoboxing and unboxing

We have already seen few examples of assignments where primitive types are autoboxed into wrapper classes and the boxed objects are automatically unboxed to get the primitive values. But that’s not the only place you can see autoboxing and unboxing.

  • You can see it in methods.
  • You can see it in expressions.
  • Due to Autoboxing and unboxing a wrapper class can be used in a switch statement.

Autoboxing in method parameters

When an argument is passed to a method or a value is returned from a method autoboxing/unboxing can happen, if required.

Example code

Here the method calcValue takes Double object as a parameter but primitive value double is passed while calling the method thus the double value is autoboxed to a Double type object.

Then there is an expression also which has a mix of Double object and double value -

dOb = dNum + 13.4;

And it is again assigned to a Double type.

Again the return type of the method is double and the returned value is assigned to a Double object.

public class BoxDemo {

 public static void main(String[] args) {
  BoxDemo bd = new BoxDemo();
  
  Double dVal = bd.calcValue(15.6);
  System.out.println("Value " + dVal);

 }
 
 public double calcValue(Double dNum){
  Double dOb;
  dOb = dNum + 13.4;
  return dOb;
 }
}

Use in switch statement

Due to unboxing Integer object can be used in a switch statement too. With in the switch statement object is unboxed and the int value is used for the conditions.

Integer iVal = 7;
switch(iVal) {
 case 1: System.out.println("First step");
 break;
 case 2: System.out.println("Second step");
 break;
 default: System.out.println("There is some error");
}

AutoBoxing and Unboxing overhead

There is some overhead involved in the process of autoboxing/unboxing so make sure you don’t start using objects exclusively thinking autoboxing/unboxing will happen anyway behind the scenes. It will happen but don’t forget the involved overhead thus making the code a little less efficient.

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


Related Topics

  1. Enum Type in Java
  2. Comparing Enum to String - Java Program
  3. covariant return type in Java
  4. Wildcard in Java Generics
  5. varargs in Java

You may also like -

>>>Go to Java advance topics page

Wednesday, 29 March 2017

TypeWrapper Classes in Java

As explained in the post primitive data types in Java there are eight primitive data types and most of the time you will use the primitive types in your code as it reduces the object creation overhead making it more efficient to use primitive types.

But there are scenarios when you would want to use objects in place of primitives, and the Java platform provides wrapper classes for each of the 8 primitive data types. These classes "wrap" the primitive in an object thus the name wrapper classes.

Eight wrapper classes used to wrap primitive data types are as given below -

Primitive TypeType Wrapper class
booleanBoolean
charCharacter
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble

Note that 6 of these are numeric and numeric wrapper classes are subclasses of the abstract class Number:

When do we need wrapper classes

You need to use wrapper classes when you want an object holding primitive data, some of the scenarios where you will need wrapper classes are –

  1. You want to add primitive value in an Object[] array.
  2. You want to add primitive type to any collection like ArrayList, HashMap as you can add only objects to collection classes.
  3. You want to use any of the utility function provided by the wrapper classes for converting values to and from other primitive types, for converting to and from strings, and for converting between number systems (decimal, octal, hexadecimal, binary).

Example code

  1. If you want to convert int to a float number.

    In Integer class there is a floatValue() method that can be used for the purpose.

    int num = 25;
    Integer i = new Integer(num);
    float fNum = i.floatValue();
    System.out.println("float Value " + fNum);
  2. If you want to convert double value to a string.
    double d = 25.67;
    String str = Double.toString(d);
    System.out.println("string " + str);
    
  3. If you want to know the min and max range of any type, like for integer
    System.out.println("Integer min value " + Integer.MIN_VALUE);
    System.out.println("Integer max value " + Integer.MAX_VALUE);
    

    Output

    Integer min value -2147483648
    Integer max value 2147483647
    

    For double

    System.out.println("Double min value " + Double.MIN_VALUE);
    System.out.println("Double max value " + Double.MAX_VALUE);
    

    Output

    Double min value 4.9E-324
    Double max value 1.7976931348623157E308
    

Autoboxing and unboxing

Here autoboxing and unboxing should get an honorable mention; autoboxing and unboxing feature was added in Java 5 and it converts primitive into object and object into primitive automatically. In many cases now you don’t need to convert using utility methods as it will happen automatically.

As example you can directly assign int value to an Integer object –

Integer i = 25;

Now conversion and method call (valueOf()) in this case will be done by compiler.

Equivalent code if you were converting yourself –
int num = 25;
Integer i = Integer.valueOf(num);

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


Related Topics

  1. Primitive Data Types in Java
  2. Object creation using new operator in Java
  3. Access modifiers in Java
  4. Why main method static in Java
  5. this in Java

You may also like -

>>>Go to Java Basics page

Tuesday, 28 March 2017

Converting String to enum type - Java Program

There may be a scenario where a string is passed in your code and you have to convert it into the enum type. For that you can use valueOf() method which is implicitly created for all enums.

public static T valueOf(String str) – This method is used to map from a String str to the corresponding enum constant. The name must match exactly an identifier used to declare an enum constant in this type.

If no constant with in the enum is found that matches the string passed IllegalArgumentException is thrown.

So the string passed should match one of the predefined constants in the enum. Actually it is not conversion in a true sense but you are searching for the enum type with the same name as the passed string, value returned is of type enum though.

Example code

 
enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
} 
public class EnumDemo {

 public static void main(String[] args) {
  EnumDemo ed = new EnumDemo();
  ed.lookUp("tuesday");
  
 }
 
 // method to lookup ennum constants
 public void lookUp(String str){
  Day day = Day.valueOf(str.toUpperCase());
  System.out.println("Found enum " + day );
 }

}

Output

Found enum TUESDAY

Here you can see that a string “Tuesday” is passed and using valueOf() method you get the corresponding enum constant. Make sure the name is same (that is why converted string to uppercase) not even extraneous whitespace are permitted. Use trim() method if you think there may be extraneous white spaces in the string passed.

That's all for this topic Converting String to enum type - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Comparing Enum to String - Java Program
  2. Converting string to int - Java Program
  3. Converting string to bytearray - Java Program
  4. Converting float to string - Java Program

You may also like -

>>>Go to Java Programs page

Monday, 27 March 2017

Comparing Enum to String - Java Program

Sometimes you may have the scenarion where you want to compare String to enumeration constants.

Like you may have an enum with product codes an you want to check that the passed produce code is one of the predefined product codes or not.

Here one thing to note is directly comparing enum value with a string won't work as they both will be of different types. As example notice in the code snippet given below where enum type d is directly compared with the String, it won't give any output as they will never be equal.

enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

public class EnumDemo {

 public static void main(String[] args) {
  EnumDemo ed = new EnumDemo();
  ed.checkDay("TUESDAY");  
 }
 
 private void checkDay(String str){
  Days[] allDays = Days.values();
  for(Days d : allDays){
   if(d.equals(str)){
    System.out.println(d + " " + d.getDay());
   }
  }
  
 }

}

Using toString() or name() methods

What you should do in such scenario is to convert enum to string for that you can use toString() method with the enum as toString() method returns the name of this enum constant, as contained in the declaration.

With toString() method

 
enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

public class EnumDemo {

 public static void main(String[] args) {
  EnumDemo ed = new EnumDemo();
  ed.checkDay("TUESDAY");
   
 }
 
 private void checkDay(String str){
  Days[] allDays = Days.values();
  for(Days d : allDays){
   if(d.toString().equals(str)){
    System.out.println(d + " " + d.getDay());
   }
  } 
 }
}

That will work as desired and give you the output - TUESDAY 3

Using name() method

Enum class also has a name() method that returns the name of this enum constant, exactly as declared in its enum declaration. Though a word of caution here according to Java docs -

"Most programmers should use the toString() method in preference to this one, as the toString method may return a more user-friendly name. This method is designed primarily for use in specialized situations where correctness depends on getting the exact name, which will not vary from release to release."

Example code

 
enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

public class EnumDemo {

 public static void main(String[] args) {
  EnumDemo ed = new EnumDemo();
  ed.checkDay("TUESDAY");
   
 }
 
 private void checkDay(String str){
  Days[] allDays = Days.values();
  for(Days d : allDays){
   if(d.name().equals(str)){
    System.out.println(d + " " + d.getDay());
   }
  }
  
 }
}

Using name() method also gives the desired output - TUESDAY 3

That's all for this topic Comparing Enum to String - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Enum Type in Java
  2. Converting String to enum type - Java Program
  3. Converting string to int - Java Program
  4. Converting string to bytearray - Java Program
  5. Converting float to string - Java Program

You may also like -

>>>Go to Java Programs page

Thursday, 23 March 2017

Producer consumer Java Program using volatile

Producer-consumer problem using multiple threads is a frequently asked multi-threading interview question. Though there are many ways to do it like -

But a simple way to do it, if you are using one writer thread and one or more reader thread, is to use volatile keyword.

Producer consumer using volatile

Here logic is to use a boolean flag which steers the logic and makes sure that value is put in the queue only after the previous value is consumed. Here two threads are created one calls the produce method and another consume. In consume method flag is assigned the value false, that is the trigger for the thread calling the produce method to come out of sleep and put another value.

In consume method busy spinning thread is used which loops continuously until the condition is met.

First let’s see what will happen if volatile keyword is not used with the boolean variable flag. In that case it may happen that producer thread sets the flag as true but that value is cached locally and current value of the flag variable is not visible to another thread. That will result in consumer thread getting in end less busy spinning causing deadlock.

ProducerConsumer class

 
public class ProducerConsumer {
     private int value = 0;
     private boolean flag = false;
     public void produce(Queue<Integer> sharedListObj) {
         // while flag is true put thread to sleep
         while (flag) {
           try {
             Thread.sleep(500);
           } catch (InterruptedException e) {
             e.printStackTrace();
           }
         }
         
         sharedListObj.add(++value);
         System.out.println("Thread " + Thread.currentThread().getName() + 
        " putting " + value);
         flag = true;
     }
     public int consume(Queue<Integer> sharedListObj) {
         int j = 0;
         while (!flag) j++;
        
         System.out.println("Getting from queue ");
         int value = sharedListObj.remove();
         flag = false;
         System.out.println("Thread " + Thread.currentThread().getName() + 
        " Consuming " + value);
         return value;
     }
}

ProducerConsumerDemo

 
import java.util.LinkedList;
import java.util.Queue;

public class ProducerConsumerDemo {

    public static void main(String[] args) {
         Queue<Integer> sharedListObj = new LinkedList<Integer>();
         ProducerConsumer producerConsumer = new ProducerConsumer();
         new Thread(new Runnable() {
               
           @Override
           public void run() {
               for(int i = 0; i < 5; i++){
                   producerConsumer.produce(sharedListObj);
               }
           }
         }, "ProducerThread").start();
         
         new Thread(()-> {
             for(int i = 0; i < 5; i++){
                 producerConsumer.consume(sharedListObj);
             }
    
        }, "ConsumerThread").start();        
    }
}

Output

Thread ProducerThread putting 1
Getting from queue 
Thread ConsumerThread Consuming 1
Thread ProducerThread putting 2

When I execute it, I get a deadlock after producing and consuming the first value.

Changing to volatile

Changing flag variable to volatile does the trick, now it is ensured that value of flag won’t be cached locally. It is always read from the main memory.

public class ProducerConsumer {
     private int value = 0;
     private volatile boolean flag = false;
     public void produce(Queue<Integer> sharedListObj) {
         // while flag is true put thread to sleep
         while (flag) {
           try {
             Thread.sleep(500);
           } catch (InterruptedException e) {
             e.printStackTrace();
           }
         }
         
         sharedListObj.add(++value);
         System.out.println("Thread " + Thread.currentThread().getName() + 
         " putting " + value);
         flag = true;
     }
     public int consume(Queue<Integer> sharedListObj) {
         int j = 0;
         while (!flag) j++;
        
         System.out.println("Getting from queue ");
         int value = sharedListObj.remove();
         flag = false;
         System.out.println("Thread " + Thread.currentThread().getName() + 
         " Consuming " + value);
         return value;
     }
}

Output

Thread ProducerThread putting 1
Getting from queue 
Thread ConsumerThread Consuming 1
Thread ProducerThread putting 2
Getting from queue 
Thread ConsumerThread Consuming 2
Thread ProducerThread putting 3
Getting from queue 
Thread ConsumerThread Consuming 3
Thread ProducerThread putting 4
Getting from queue 
Thread ConsumerThread Consuming 4
Thread ProducerThread putting 5
Getting from queue 
Thread ConsumerThread Consuming 5

That's all for this topic Producer consumer Java Program using volatile. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Volatile in Java
  2. Race condition in Java multi-threading
  3. Setting and getting thread name and thread ID - Java Program
  4. Print odd-even numbers using threads and semaphore
  5. How to run threads in sequence - Java Program

You may also like -

>>>Go to Java Programs page

Tuesday, 21 March 2017

Enum Type in Java

An enum type is a special data type that helps you to define a list of predefined constants which can be accessed using a variable. An enumeration is created using the enum keyword.

As example, if you want to declare a enum Day that has all the days as predefined constants.

enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

Since enum is a data type so you can declare a variable of that type.

Day d;
d = Day.FRIDAY;
System.out.println("Day of the week " + d);

Output

Day of the week FRIDAY

Note: You do not instantiate an enum using new operator, even though enumeration defines a class type. You declare an enumeration variable as you will declare a varibale of primitive data types.

Enumeration was added in Java 1.5 along with generics, varargs, autoboxing and other features.

When to use Enumeration

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system, days of the weeks and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

Example code

Here we have a complete code where enum is created for days of the week and then we loop through that enum values and print all the constants defined in the enum.

enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

public class EnumDemo {

 public static void main(String[] args) {
   Day[] allDays = Day.values();
   for(Day day : allDays){
   System.out.println(day);
   }
 }
}

Benefits & Usage of enum

Apart from the obvious benefit of using enum when you need to represent a fixed set of constants there are many benefits and usages of enum.

  1. Provides type safety – If you use private static final constants you can always assign any random value to a variable instead of these predefined constants.

    As example – If I have constants like below I can still assign dayOfTheWeek as “Funday”.

    private static final String SUNDAY = "Sunday";
    private static final String MONDAY = "Monday";
    private static final String TUESDAY = "Tuesday";
       
    final String dayOfTheWeek;
    dayOfTheWeek = "Funday";
    

    With enums it is not possible. If you have an enum like this -

    enum Day {
        SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
        THURSDAY, FRIDAY, SATURDAY 
    }
    

    How much ever you want your day to be a funday you can’t do it now.

    Day day = Day.FUNDAY; // Compile-time error
    
  2. Enums have their own name space – Enums have their own name space. So a enum Day as created above will be created in its own name space and has its own type. You are not permitted to use any value other than the one specified as predefined constants with in the enum.
  3. Comparison using == operator - Two enumeration constants can be compared for equality by using the = = relational operator. As example, this statement compares the value in day variable with the TUESDAY constant:
    Day day = Day.FRIDAY;
       
    if(day == Day.TUESDAY){
     System.out.println("Days are equal");
    }else{
     System.out.println("Days are not equal");
    }
    
  4. Used in switch statement - An enumeration value can also be used in a switch statement. All case statements have to use the constants from the enum that is used in the switch statement.

    As example -

    Day day = Day.FRIDAY;
     
     switch(day){
      case MONDAY: 
       System.out.println("Week started");
       break;
      case TUESDAY: case WEDNESDAY: case THURSDAY:
       System.out.println("Keep toiling");
       break;
      case FRIDAY:
       System.out.println("Countdown begins");
       break;
      case SATURDAY: case SUNDAY:
       System.out.println("Weekend !!!");
       break;
    }
    

enum declaration defines a class

Java enumeration is a class type, enum can have constructors, instance variables, methods. Enum can even implement interfaces.

As example – Here I have created an enum Days which defines constants, a constructor, a variable day, a method getDay() and even main method so you can run this enum as any other Java class.

public enum Days {
 SUNDAY(1), 
 MONDAY(2), 
 TUESDAY(3), 
 WEDNESDAY(4),
 THURSDAY(5), 
 FRIDAY(6), 
 SATURDAY(7);
 private int  day;
 private Days(int day){
  this.day = day;
 }
 
 
 int getDay(){
   return day;
 }
 public static void main(String[] args) {
  Days[] allDays = Days.values();
  for(Days d : allDays){
   System.out.println(d + " " + d.getDay());
  }
 }
}

Output

SUNDAY 1
MONDAY 2
TUESDAY 3
WEDNESDAY 4
THURSDAY 5
FRIDAY 6
SATURDAY 7

Some important points to note here

  1. Java requires that the constants be defined first, prior to any fields or methods. So you can’t have code like below where field day is declared first, as it will result in error.
    public enum Days {
     private int day;
     SUNDAY(1), 
     MONDAY(2), 
     TUESDAY(3), 
     WEDNESDAY(4),
     THURSDAY(5), 
     FRIDAY(6), 
     SATURDAY(7);
     ...
     ...
    }
    
  2. Each enumeration constant is an object of its enumeration type. When you create an object of any class its constructor is called for initialization same way constructor is called when each enumeration constant is created.

    If you have noticed constructor of the Days enum takes one int parameter and all the constants have an integer associated with them i.e. SUNDAY(1), MONDAY(2).

    When these constants are created constructor is called and day gets its value from the integer.
  3. Same like any other object each enumeration constant has its own copy of instance variables defined by the enumeration.

    That’s why d.getDay() gives the correct day of the week for every constant.

  4. The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.
  5. All enums implicitly extend java.lang.Enum. Because a class can only extend one parent in Java an enum cannot extend anything else.
  6. An enum can implement one or more interfaces.

values() and valueOf() methods

In the above example code I have already used values() method to iterate over the values of an enum type.

These two methods values() and valueOf() are implicitly declared for all enumerations.

General form of values() and valueOf() methods

public static T valueOf(String)

public static T[] values()

Here T is the enum type whose constant is to be returned

The values() method returns an array of the enumeration constants.

The valueOf() method returns the constant whose value corresponds to the string passed in String argument.

Example code

enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

public class EnumDemo {

 public static void main(String[] args) {
  
  // Using values method
   Day[] allDays = Day.values();
   for(Day day : allDays){
   System.out.println(day);
   }
   // Using valueOf() method
   Day day = Day.valueOf("TUESDAY");
   System.out.println("Day - " + day);  
 }
}

Points to remember

  1. Java enumeration is a class type.
  2. Enumerations can have Constructors, instance Variables, methods and can even implement Interfaces.
  3. You do not instantiate an enum using new operator, even though enumeration defines a class type.
  4. All Enumerations by default inherit java.lang.Enum class. So they can’t extend any other class.
  5. Enum constants are implicitly static and final and can not be changed once created.

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


Related Topics

  1. Comparing Enum to String - Java Program
  2. Converting String to enum type - Java Program
  3. covariant return type in Java
  4. Wildcard in Java Generics
  5. static import in Java

You may also like -

>>>Go to Java advance topics page

Monday, 20 March 2017

Volatile in Java

If volatile is to be defined in simple terms, it can be defined as “the volatile keyword is an indication that the variable marked as volatile can change its value between different accesses”.

In order to understand volatile better we need to have a little background on how memory works, though its natural to think that a variable’s value will be stored some where in the memory (RAM) which is true also. The catch is, in order to boost performance processor may store the value in its cache (L1, L2, L3 cache, you might have read about it in your class or seen it in advertisements of laptops or desktops).

In that case any change to the value is written back to the main memory only when the synchronization between the cache and the memory happens.

Volatile keyword

Now when we have some background on what actually happens with the variables and how main memory may be inconsistent with the current value of the variable in the processor’s cache, let’s see how volatile helps.

When a variable is declared as volatile, the compiler (even runtime) seeing the keyword volatile knows that this variable is shared. So the volatile variables are not cached in registers and read operation on a volatile variable always returns the most recent write by any thread.

Let’s see it with an example - In a multi-threaded application running on multi-processor may have different threads running on different processors. Also, note that shared field (a variable shared among many threads) will be stored in main memory, but as we know now, due to the caching by the processors even the shared field will have different copies in the cache of different processors. For example there is a shared int variable var1 which is not declared as volatile, this scenario can be diagrammatically portrayed as below -

Here you can see that when thread-2 in processor-2 tries to read the value of variable var1 from main memory it gets a stale value, where as thread-1 has already updated the value of variable var1 but that updated value is still stored in the cache of processor-1.

In this type of scenario declaring variable var1 as volatile will ensure that any change to volatile variable var1 will be visible to other threads.

Thus using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads.

What is Happens-before Order

Two actions can be ordered by a happens-before relationship. If one action happens-before another, then the first is visible to and ordered before the second.

Volatile example code

The most common use for volatile variables is to use it as a completion, interruption, or status flag. So let’s see an example where we have a status flag.

Here we have a class called TestVolatile which starts two threads, one of these threads prints “Printing Value“ five thousand times and then sets the flag as true. Where as the second thread is waiting for the flag to become true. When flag becomes true second thread prints “Job Done” once. Here note that the second thread loops continuously waiting for the first thread to complete its task and signal it to start, this is an example of busy spinning in multi-threading.

Also note that first time Runnable is implemented as an anonymous class, where as second time runnable is implemented as a lambda expression.

public class TestVolatile {
    private static  boolean flag = false;
    public static void main(String[] args) {
        // implemented as anonymous inner class
        new Thread(new Runnable(){
            
            @Override
            public void run() {
                for (int i = 1; i <= 5000; i++){
                    System.out.println("printing value " + i);
                }
                flag = true;
            }
            
        }).start();
        
        // Implemented as lambda expression
        new Thread(()-> {
            int i = 1;
            while (!flag) i++;
            System.out.println("Job Done " + i);    
        }).start();
    }
}

On executing this code you may get the first thread printing “printing value 1” to “printing value 5000” but after that second thread won’t start and the program will never terminate. Because the second thread never gets the updated value of flag and code execution goes into a deadlock. In this case having the boolean variable flag as volatile will help. That will guarantee that the change done to the shared variable by one thread is visible to other threads.

private static volatile boolean flag = false;

happens-before extended guarantee

Since Java 5, happens-before does not only mean that a thread reading a volatile variable sees the latest change to the volatile variable, but also the side effects of the code that led up the change.

So if there are two threads thread-1 and thread-2 and thread-1 changes any other variables (even non-volatile) before changing the volatile variable. Then, thread-2 when reading the volatile variable will also get the changed value of the other variables changed in thread-1 before updating the volatile variable.

As example, if there is a class Shared with 3 int variables

public class Shared {
    public int var1;
    public int var2;
    public volatile int var3;
}

Now let's say there is an object shared of the class Shared which is used by both thread-1 and thread-2, in thread-1 you assign values to the variables.

shared.var1 = 1;
shared.var2 = 2;
shared.var3 = 3;
And in thread-2 you print those variables
System.out.println("printing value " + shared.getVar1());
System.out.println("printing value " + shared.getVar2());
System.out.println("printing value " + shared.getVar3());

Here var3 being volatile ensures that all the actions of thread-1 prior to the write to the volatile variable var3 are guaranteed to be visible to the thread (thread-2 in this case) that has read the updated value of var3. Here it means that it is guaranteed by the Java memory model that the updated values of variables var1 and var2 will also be visible in thread-2 as they were updated before updating the value of volatile variable var3.

Volatile won’t stop race condition

One of the important point you should remember about volatile is it just guarantees visibility, atomicity is not guaranteed by the volatile. Thus a code where shared resource is used by many threads and each thread is updating/reading the shared resource is not an ideal place to rely on volatile as it may lead to race condition.

Example code

Here we have an example where a shared class is used to increment and get a counter, which is declared as volatile too. Then 6 threads are spawned that increment and use the counter. Some delay is also introduced to simulate a production environment as you generally have many users accessing an application where one request is pre-empted to cater to other request.

public class VolatileDemo {

 public static void main(String[] args) {
  Data data = new Data();
  // Starting 6 threads
  ExecutorService ex = Executors.newFixedThreadPool(6);
  ex.execute(new VTask(data));
  ex.execute(new VTask(data));
  ex.execute(new VTask(data));
  ex.execute(new VTask(data));
  ex.execute(new VTask(data));
  ex.execute(new VTask(data));
  //shutting down the executor service
  ex.shutdown();
 }

}

// shared class
class Data{
 public volatile int counter = 0;

 public int getCounter() {
  return counter;
 }

 public void incrementCounter() {
  try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
  ++counter;
 }
 
}

// Thread 
class VTask implements Runnable{
 private Data data;
 public VTask(Data data){
  this.data = data;
 }
 
 @Override
 public void run() {
  System.out.println("Value for Thread " + Thread.currentThread().getName() + " Before increment " + data.getCounter());
  data.incrementCounter();
        System.out.println("Value for Thread " + Thread.currentThread().getName() + " After increment " + data.getCounter());
  
 }
 
}

Output

Value for Thread pool-1-thread-1 Before increment 0
Value for Thread pool-1-thread-3 Before increment 0
Value for Thread pool-1-thread-2 Before increment 0
Value for Thread pool-1-thread-4 Before increment 0
Value for Thread pool-1-thread-5 Before increment 0
Value for Thread pool-1-thread-6 Before increment 0
Value for Thread pool-1-thread-2 After increment 1
Value for Thread pool-1-thread-5 After increment 2
Value for Thread pool-1-thread-3 After increment 1
Value for Thread pool-1-thread-6 After increment 3
Value for Thread pool-1-thread-1 After increment 5
Value for Thread pool-1-thread-4 After increment 4 

As you see values are not as expected because every thread is updating the value not only reading it.

Points to remember

  1. volatile keyword can only be used with variables, not with methods and classes.
  2. volatile variables are not cached and read operation on a volatile variable always returns the most recent write by any thread.
  3. volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.
  4. From Java 5 Happens before guarantees that all the other variables updated before writing to the volatile variable by one thread are visible to other threads when reading the volatile variable.
  5. volatile just guarantees visibility, atomicity is not guaranteed by the volatile.
  6. volatile won't block threads as synchronized does.

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


Related Topics

  1. Synchronization in Java multithreading
  2. Race condition in Java multi-threading
  3. Difference between sleep and wait
  4. Deadlock in Java multi-threading
  5. AtomicInteger in Java Concurrency
  6. Java Multi-threading interview questions

You may also like -

>>>Go to Java advance topics page

Thursday, 16 March 2017

Literals in Java

When you initialize a variable of a primitive data type in Java, you don’t use the new keyword. It is because primitive types are special types built into the language, they are not the objects created from a class.

A literal doesn’t require any computation and it is possible to assign a literal to a variable of a primitive type.

As example –

Short s = 100;
int num = 9000;
Boolean flag = true;

Literals can be classified into 3 types –

  • Integer Literals
  • Floating-point Literals
  • Character and String Literals
  • Boolean literals

Integer Literals

Literal assigned to a type byte, short, int or long is called an integer literal. Make sure when you assign a literal value to a byte or short it is within the range of that particular type.

An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int. It is recommended that you use the upper case letter L because the lower case letter l is hard to distinguish from the digit 1.

You will generally use a base 10 number i.e. decimal as an integer literal. But integer literals can be expressed by Binary (base two) and hexadecimal (base 16) number system also. Integer literals can be expressed by these number systems:

  • Decimal: Base 10, whose digits consists of the numbers 0 through 9; this is the number system you use every day.
  • Hexadecimal: Base 16, whose digits consist of the numbers 0 through 9 and the letters A through F.
  • Binary: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary literals in Java SE 7 and later).

As example if you want to write 50 using hexadecimal –

int hNum = 0x32;
System.out.println("" + hNum);

Same way, if you want to use binary system to assign literal 50 –

int bnum = 0b110010;
System.out.println("" + bnum);

Note - The prefix 0x indicates hexadecimal and 0b indicates binary.

Floating-point Literals

Literal assigned to a type float or double is called floating-point literal. A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double in that case it can end with the letter D or d but that is optional.

Floating-point literal can also be expressed using E or e (for scientific notation).

As example

double dNum1 = 156.7;
// same value as d1, but in scientific notation
double dNum2 = 1.567e2;
float fNum  = 34.8f;

Character and String Literals

Literals of types char and String may contain any Unicode (UTF-16) characters. Always use 'single quotes' for char literals and "double quotes" for String literals. The Java programming language also supports a few special escape sequences for char and String literals: \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote), \' (single quote), and \\ (backslash).

As example if you want to assign single quote (‘) itself to a char variable you need escape sequence in that case.

char c ='\'';
System.out.println(c);

That will give as output.

Boolean literal

Boolean literal can have only one of two values true and false. A Boolean literal can only be assigned to a variable of type boolean. It can also be used be used with conditions which evaluate to a boolean value.

As example

int num1 = 9;
int num2 = 7;
if(num1 > num2 == true){
 System.out.println(" num1 is greater than num2");
}

Here if condition num1 > num2 evaluates to either true or false. Though it can be expressed implicitly also (preferred)

int num1 = 9;
int num2 = 7;
if(num1 > num2){
 System.out.println(" num1 is greater than num2");
}

Here you can see with if only expression is used (num1 > num2) as it will evaluate to true or false anyway.

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


Related Topics

  1. Kinds of Variables in Java
  2. Primitive Data Types in Java
  3. Type Casting in Java
  4. instanceof Operator in Java
  5. String in Java

You may also like -

>>>Go to Java Basics page

Wednesday, 15 March 2017

Kinds of Variables in Java

As mentioned in the post object in Java, object is an instance of the class, which gets its state and related behavior from the class. At the same time an object stores its state in variables.

So in this post we’ll see what all types of variables are there in Java, what are the scopes for those variables and their visibility.

We’ll also see what is meant by declaring a variable and what is meant by initialization of the variable.

Declaring and Initializing a variable

In Java it is mandatory that a variable should be declared before it is used. Declaring a variable means telling what type of a variable it is. Variable may be of primitive data type (int, float, char), or having class or interface as type.

As exp.

int age, number;

double amount;

Person person;

As you see here in the first statement two variables of type int are declared. Note here that you can declare two or variable of same type as a comma separated list.

In the second statement a variable amount of type double is declared. Where as in third statement a variable person is declared which is of type Person. Here Person is a class.

Initialization

Initialization means providing initial value of the variable. Generally, both declaration and initialization are done in a single statement.

 
int age = 30;

char a = ‘A’;

But that is not necessary you may declare a variable first and initialize it later.

 
int age;

...... 
......
age = 50;

An expression can also be used to initialize a variable -

 
double amount;

amount = 67/9;

Here amount will have the value of 67 divided by 9.

Types of variables

The Java programming language defines the following kinds of variables:

  1. Instance Variables (Non-Static Fields) – As already mentioned object is an instance of the class and there can be many objects of the same class. Every object has its own state for the non-static fields which is unique for each instance (object). That is why the fields of each object are referred as instance variables as they are unique for each instance.

    As example – If you have a class Person and two objects of it person1 and person2 then the instance variables of these two objects will have independent values.

    public class Person {
     private String firstName;
     private String lastName;
     private int age;
     private char gender;
     public Person(String firstName, String lastName, int age, char gender){
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
      this.gender = gender;
     }
     
     public String getFirstName() {
      return firstName;
     }
    
     public String getLastName() {
      return lastName;
     }
    
     public int getAge() {
      return age;
     }
     public char getGender() {
      return gender;
     }
    }
    
    public class InstanceDemo {
    
     public static void main(String[] args) {
      Person person1 = new Person("Ram", "Mishra", 23, 'M');
      Person person2 = new Person("Amita", "Chopra", 21, 'F');
      
      System.out.println("Values in object person1 - " + 
        person1.getAge() + " " + person1.getFirstName() + " " + 
        person1.getLastName()+ " " + person1.getGender());
      System.out.println("Values in object person2 - " + 
        person2.getAge() + " " + person2.getFirstName() + " " + 
        person2.getLastName()+ " " + person2.getGender());
    
     }
    
    }
    

    Output

    Values in object person1 - 23 Ram Mishra M
    Values in object person2 - 21 Amita Chopra F
    

    Here you can see how using the constructor of the class, variables are initialized for both the objects and output shows that each instance of the class has its own values for the fields.

  2. Class Variables (Static Fields) - A class variable is any field declared with the static modifier. As the name suggests class variable is at the class level and there will be exactly one copy of this variable in existence. Doesn’t matter how many instances (objects) of the class you have the class variable will have the same value, moreover you don’t even need the object to refer to the class variable.

    As example - One common use of static fields is to create a constant value that's at a class level and applicable to all created objects.

    public class Employee {
     int empId;
     String name;
     String dept;
     // static constant
     static final String COMPANY_NAME = "XYZ";
     Employee(int empId, String name, String dept){
      this.empId = empId;
      this.name = name;
      this.dept = dept;
     }
     
     public void displayData(){
      System.out.println("EmpId = " + empId + " name= " + name + " dept = " + 
      dept + " company = " + COMPANY_NAME);
     }
     public static void main(String args[]){  
      Employee emp1 = new Employee(1, "Ram", "IT");
      Employee emp2 = new Employee(2, "Krishna", "IT");
      emp1.displayData();
      emp2.displayData();
     }
    }
    

    Output

    EmpId = 1 name= Ram dept = IT company = XYZ
    EmpId = 2 name= Krishna dept = IT company = XYZ
    
  3. Local Variables – Similar to how object store its state in fields, a method will store its temporary state in local variables. Scope of local variable is in between the start and closing curly braces of a method. There is also a nested scope, suppose with in a method you have a if condition with its own starting and closing curly braces, then that block of code with in the if condition creates a nested scope. One more thing to note is you can have a local variable with the same name as class level variable with in the method and with in the method the local variable will take priority.

    As example

    public class InstanceDemo {
     // class level variable
     int x = 8;
     public static void main(String[] args) {
      
      InstanceDemo id = new InstanceDemo();
      
      id.display();
      System.out.println("value of class level variable x " + id.x);
     }
     
     public void display(){
      int x = 5;
      boolean flag = true;
      System.out.println("value of local variable x " + x);
      if (flag){
       int y = 10;
       System.out.println("value of local variable y inside if " + y);
      }
      // This will cause compile-time error
      //System.out.println("value of local variable y inside if " + y); 
     }
     
    }
    

    Output

    value of local variable x 5
    value of local variable y inside if 10
    value of class level variable x 8
    

    Here you see there is a class level variable and again it the method display() there is a variable with the same name x. When in the method value of local variable x takes priority and that is printed. Once out of method x that is recognized is the class level variable x.

    Another thing to note is the nested scope created by the if condition with in the display() method. Scope of variable y is in between the starting and closing braces of the if condition. Once you are out of if condition y won’t be recognized. Any attempt to print value of y outside the if condition scope will result in compile-time error.

  4. Parameters - Variables passed to any method are known as parameter. Any changes made to the primitive types parameter won’t change the original value.

    As example

    public class InstanceDemo {
     public static void main(String[] args) {
      
      InstanceDemo id = new InstanceDemo();
      int x = 10;
      id.display(x);
      System.out.println("value of x after method call " + x);
     }
     
     public void display(int x){
      
      x++;
      System.out.println("value of local variable x " + x);
     }
     
    }
    

    Output

    value of local variable x 11
    value of x after method call 10
    

    Here you have a variable x that is passed to display method as an int parameter. With in the method display() value of x is changed. But that change is local only and doesn’t change the original value of x. This is because copy of a variable is passed as a method parameter.

    If an object is passed as a parameter and any of that object’s field is changed, that change will be visible in other scopes too.

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


Related Topics

  1. Primitive Data Types in Java
  2. Access modifiers in Java
  3. What are JVM, JRE and JDK in Java
  4. Object creation using new operator in Java
  5. Ternary operator in Java

You may also like -

>>>Go to Java Basics page

Thursday, 9 March 2017

Primitive Data Types in Java

The Java programming language is statically-typed meaning all variables should first be declared before they can be used. So you need to state variable's type and name, as example

int test = 1;

Doing so tells your program that a field named "test" exists, holding numerical data and has an initial value of "1".

A variable's data type determines the values it may contain, plus the operations that may be performed on it. The Java programming language supports eight primitive data types.

A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are:

  1. byte
  2. short
  3. int
  4. long
  5. float
  6. double
  7. boolean
  8. char

These primitive data types can be classified into 4 groups -

  1. Integer types – byte, short, int, long
  2. Floating-point types – float, double
  3. Characters – char
  4. Booleans - boolean

byte

The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters.

Though you may be tempted to use it at the places where you know value won’t go beyond the byte’s range but the fact is using byte in an expression will result in an automatic type promotion of byte to int when expression is evaluated.

Short

The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, you can use a short to save memory in large arrays, in situations where the memory savings actually matters.

Also the same automatic type promotion from short to int will happen in case of short too.

int

The int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1, which means a range of -2,147,483,648 to 2,147,483,647.

Note from Java 8 there are some unsigned int methods provided to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1.

An example of unsigned int method is Integer.parseUnsignedInt.

long

The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1 which means a range of -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

In most of the cases int would be sufficient but long will be useful in scenarios where an int type is not large enough to hold the value.

float

float data type belongs to the floating-point type group along with double. The float data type is a single-precision value requiring 32-bit (4 byte) of storage. This data type should never be used for precise values where round-off errors may cause problems.

As example System.out.println(1-.56); will print 0.43999999999999995 instead of 0.44.

You have to use suffix F (or f) with floating data type numbers, not providing suffix ‘F’ means number would be considered double.

As example – If you declare a float variable as below :

float f = 1.1; 

You will get a compile-time error - Type mismatch: cannot convert from double to float

As there is no suffix F so number will be considered double. If you want float data type correct way to write the above statement is - float f = 1.1F;

double

The double data type is a double-precision value requiring 64-bit (8 byte) of storage. For decimal values, this data type is generally the default choice. Just like float this data type should never be used for precise values.

boolean

The boolean data type has only two possible values: true and false. The boolean data type is generally used as simple flag to track true/false conditions.

char

char data type is used to store characters. In Java, the char data type is a single 16-bit Unicode character. The range of a char is 0 to 65,536. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

You can either use the character enclosed in single quote to define a char or you can also provide the unicode of the character (hexadecimal form which has \u prefix).

char a = 'A';

Default values for primitive types

You don't need to always assign a value when a field is declared. Fields that are declared but not initialized will be set to a default value by the compiler. Generally speaking, this default will be zero or null, depending on the data type.

The following table summarizes the default values for the above data types.

Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object)   null
boolean false

In addition to the above mentioned eight primitive data types, the Java programming language also provides special support for character strings via the java.lang.String class. The String class is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such.

String object (non-primitive data type) can be defined in the same way as primitive data types.

String s = "this is a string"

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


Related Topics

  1. Ternary operator in Java
  2. instanceof Operator in Java
  3. Switch-Case statement in Java
  4. Object creation using new operator in Java
  5. Type Casting in Java

You may also like -

>>>Go to Java Basics page

Tuesday, 7 March 2017

Type Casting in Java

Whenever you try to assign data of one type to variable of another type conversion happens, it may be a -

  • Widening primitive conversions
  • Widening reference conversions
  • Narrowing primitive conversions
  • Narrowing reference conversions

Widening primitive conversions

If a type to which you are converting is larger than the source type you are widening your source and that will happen with out problem and automatically.

As example -

int i = 10;
float f = i;

i which is an int can safely be assigned to float variable as float is compatible with int and also wider than int.

Widening reference conversions

Same way you can have a widening reference conversion. That is applicable in an inheritance scenario where a parent-child relationship exists.

As example -

If there is a class A and a child class B that extends class A then reference type A can safely hold reference type of class B.

A a;
B b = new B();
a = b; // Widening conversion from sub type to super type

Type casting

Though automatic conversion is convenient and helpful, it may not always be possible. Especially in case of narrowing conversions. Again, narrowing conversion can be of two types -

  • Narrowing primitive conversions
  • Narrowing reference conversions

Narrowing primitive conversions

As the name suggests if you try to fit a value into a source that is narrower than the original type of the value then it is a narrowing conversion.

As example – If we do the exact opposite of what we did in the example of widening conversion and try to assign a float value to an int.

int i;
float f = 19.6f;
i = f; // Compile-time error (Type mismatch: cannot convert from float to int)

As you see, you get a compile-time error if you try to assign a float value to an int as it is a narrowing conversion. In case of narrowing conversion you need to explicitly cast it to make it work.

General form of cast

(type) value;

Here type is the type to which the value has to be converted.

So in the above example we have to add an explicit cast to int.

int i;
float f = 19.6f;
i = (int)f;
System.out.println("value " + i); 

Output

value 19

Here you can see that the fractional part is truncated.

Narrowing reference conversions

A super type can hold reference to an object of itself or the sub-types. But doing the opposite, when you want a conversion from super-type to sub-type, you will need type casting.

Since the conversion is from super-type to sub-type it is called narrowing reference conversion.

One important thing to always remember is; 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 (run-time).

As example -

If we take the same example as used in widening reference conversion where there is a class A and a child class B that extends class A then reference type A can safely hold reference type of class B. But now we’ll try the opposite too.

A a;
B b = new B()
a = b; // OK widening conversion
b = a; // Compile-time error as it is a narrowing conversion

What you will have to do is to avoid compile-time error is -

b = (B) a;

Why type casting

You may have a scenario where child class has methods of its own apart from inheriting methods from the super class or overriding methods of the super class.

Being a good programmer and always trying to achieve polymorphism you will make sure that the reference of the sub-class is held by the super-class object. But one problem is, then you can’t call those methods which are exclusive to sub-class.

In order to call those methods you need casting to the type. Let’s try to understand it with an example.

Example code

Here I have a class hierarchy where Payment is an interface and there are two classes CashPayment and CardPayment implementing the Payment interface.

Payment interface

public interface Payment {
 public boolean proceessPayment(double amount);
}

CashPayment class

import org.netjs.examples.interfaces.Payment;

public class CashPayment implements Payment {
 @Override
 public boolean proceessPayment(double amount) {
  System.out.println("Cash payment done for Rs. " + amount);
  return true;
 }
}

CardPayment class

import org.netjs.examples.interfaces.Payment;

public class CardPayment implements Payment {

 @Override
 public boolean proceessPayment(double amount) {
  System.out.println("Card Payment done for Rs. " + amount);
  return true;
 }
 
 public void printSlip(){
  System.out.println("Printing slip for payment" );
 }
}

In CardPayment class, note that, there is an extra method printSlip() which is exclusive to this class.

Now when you do some payments using the class as given below -

import org.netjs.examples.interfaces.Payment;

public class PaymentDemo {

 public static void main(String[] args) {
  PaymentDemo pd = new PaymentDemo();
  Payment payment = new CashPayment();
  pd.doPayment(payment, 100);
  payment = new CardPayment();
  pd.doPayment(payment, 300);
  //int i = 10;
  //float f = i;
  
  int i;
  float f = 19.6f;
  i = (int)f;
  System.out.println("value " + i);
 }
 
 public void doPayment(Payment pd, int amt){
  pd.proceessPayment(amt);
  pd.printSlip();
 }
}

This method call pd.printSlip(); will give compile-time error as the Payment object has no idea of the printSlip() method, thus the error -

The method printSlip() is undefined for the type Payment

If you want to call printSlip() method you need a cast back to CardPayment class type. Beware that there are two child classes and you don’t need that casting for CashPayment class object. Which means you need to use instanceof operator in conjunction with the casting.

With these corrections the code will now look like -

import org.netjs.examples.interfaces.Payment;

public class PaymentDemo {

 public static void main(String[] args) {
  PaymentDemo pd = new PaymentDemo();
  Payment payment = new CashPayment();
  pd.doPayment(payment, 100);
  payment = new CardPayment();
  pd.doPayment(payment, 300);
  //int i = 10;
  //float f = i;
  
  int i;
  float f = 19.6f;
  i = (int)f;
  System.out.println("value " + i);
 }
 
 public void doPayment(Payment pd, int amt){
  pd.proceessPayment(amt);
  
  if (pd instanceof CardPayment){
   CardPayment cardPay = (CardPayment)pd;
   cardPay.printSlip();
  }
 }
}

Output

Cash payment done for Rs. 100.0
Card Payment done for Rs. 300.0
Printing slip for payment
value 19

Here you can see how instanceof operator is used to make sure that the object is indeed of type CardPayment and then casting is done to the CardPayment type, which makes it possible to call the printSlip() method.

Reference: https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html

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


Related Topics

  1. Switch-Case statement in Java
  2. Access modifiers in Java
  3. Array in Java
  4. Overview of Exception handling in Java
  5. Java pass by value or pass by reference

You may also like -

>>>Go to Java Basics page

Monday, 6 March 2017

instanceof Operator in Java

In your application sometimes you have a situation when you would like to know the type of an object during run time. It is evidently important when you have a parent-child relationship, an inheritance hierarchy with a parent class and more than one child classes.

A super type can hold reference to an object of itself or the sub-types. But doing the opposite, when you want a conversion from super-type to sub-type, you will need type casting.

As example, if there is class A and two child classes class B and class C, then object of type A can refer to object of type B or to an object of type C.

A a;
B b = new B();
C c = new C();
a = b; 
b = a; // results in compile-time error (Type mismatch)

This (a = b) can be done with out any need of casting.
But doing the opposite (b = a;) will need casting. What you will have to do is -

b = (B) a;
a = c;

and for class C object c = (C)a;

Now, in your application if you have a hierarchy where there are many child classes, type casting may cause problem as you may not be knowing the actual type of the object. In this case you need instanceof operator to check the type of the object before doing the casting.

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 (run-time).

In order to avoid that error it is better to check whether the object can be cast to that type safely or not. For that you can use instanceof operator.

General form of the instanceof operator

obj instanceof type;

Here obj is refrence to an object and type is a class type. This check will return true if obj is of the class type given on the right hand side of the instanceof operator or can be cast into that type safely.

Example using instanceof operator

Here I have a class hierarchy where Payment is an interface and there are two classes CashPayment and CardPayment implementing the Payment interface.

Payment interface

public interface Payment {
 public boolean proceessPayment(double amount);
}

CashPayment class

import org.netjs.examples.interfaces.Payment;

public class CashPayment implements Payment {
 @Override
 public boolean proceessPayment(double amount) {
  System.out.println("Cash payment done for Rs. " + amount);
  return true;
 }
}

CardPayment class

import org.netjs.examples.interfaces.Payment;

public class CardPayment implements Payment {

 @Override
 public boolean proceessPayment(double amount) {
  System.out.println("Card Payment done for Rs. " + amount);
  return true;
 }
 
 public void printSlip(){
  System.out.println("Printing slip for payment" );
 }
}

In CardPayment class, note that, there is an extra method printSlip().

As a good programmer you are trying to write a good, object-oriented principles following code and want to have proper polymorphism. In order to achieve that you will refer the instances of child classes CardPayment and CashPayment through the super type instance Payment. Something similar to what is written below.

import org.netjs.examples.interfaces.Payment;

public class PaymentDemo {

 public static void main(String[] args) {
  PaymentDemo pd = new PaymentDemo();
  Payment payment = new CashPayment();
  pd.doPayment(payment, 100);
  payment = new CardPayment();
  pd.doPayment(payment, 300);
 }
 
 public void doPayment(Payment pd, int amt){
  pd.proceessPayment(amt);
  CardPayment cardPay = (CardPayment)pd;
  cardPay.printSlip();
 }
}

But running this will throw ClassCastException at run time -

Cash payment done for Rs. 100.0
Exception in thread "main" java.lang.ClassCastException: org.netjs.examples.impl.CashPayment cannot be cast to org.netjs.examples.impl.CardPayment
 at org.netjs.examples.impl.PaymentDemo.doPayment(PaymentDemo.java:17)
 at org.netjs.examples.impl.PaymentDemo.main(PaymentDemo.java:10)

What went wrong here is that you want to call printSlip() method only if the instance is of type CardPayment. But doPayment() method of the PaymentDemo class is having Payment (Super class) as the argument which can refer to instances of CardPayment as well as CashPayment.

Here you can use instanceof operator to check if passed reference is actually of type CardPayment, if yes, then only call the printSlip() method.

Code after including instanceof operator

public class PaymentDemo {

 public static void main(String[] args) {
  PaymentDemo pd = new PaymentDemo();
  Payment payment = new CashPayment();
  pd.doPayment(payment, 100);
  payment = new CardPayment();
  pd.doPayment(payment, 300);
 }
 
 public void doPayment(Payment pd, int amt){
  pd.proceessPayment(amt);
  if (pd instanceof CardPayment){
   CardPayment cardPay = (CardPayment)pd;
   cardPay.printSlip();
  }
 }
}

Output

Cash payment done for Rs. 100.0
Card Payment done for Rs. 300.0
Printing slip for payment

Here note how instanceof operator is used to check the type and if appropriate type is there then only condition gets fulfilled.

Points to remember

  1. An object can only be cast to its own class or one of its super-type.
  2. instanceof operator provides you a way to get run time information about the type of the object.
  3. instanceof operator, if used, should be used sporadically. If you are compelled to use instanceof operator a lot that would mean some inherent flaw in the design of your application.
  4. A use case where use of instanceof operator makes sense is trying to write a generalized logic for a class hierarchy, so that your logic can work for any object of the class hierarchy.

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


Related Topics

  1. Package in Java
  2. Access modifiers in Java
  3. Encapsulation in Java
  4. Polymorphism in Java
  5. Ternary operator in Java

You may also like -

>>>Go to Java Basics page