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 is a shared int variable var1 which is not declared as volatile, this scenario can be diagrammatically portrayed as below -

volatile in Java

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