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

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. covariant return type in Java
  2. Wildcard in Java Generics
  3. static import in Java
  4. interface default methods in Java 8
  5. Optional class in Java 8

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

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