Wednesday, 27 March 2013

Static Keyword in Java

The static keyword can be used in 3 scenarios -
  • static variables
  • static methods
  • static blocks

static keyword in General

There are some things that must immediately come to our mind when we speak of static keyword. First of all a resource defined as static belongs to class as a whole rather that individual objects of the class. These resources are loaded when the class is loaded by the JVM unlike non-static case where memory is allocated only when we create an object of the class.

static variables

  •  Java instance variables are given separate memory for storage. If there is a need for a variable to be common to all the objects of a single java class, then the static modifier should be used in the variable declaration.
  • It is a variable which belongs to the class and not to object(instance).
  • Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables.
  • A single copy to be shared by all instances of the class.
  •  A static variable can be accessed directly by the class name and doesn’t need any object.
  • Syntax : <class-name>.<variable-name>
  • Any java object that belongs to that class can modify its static variables.

static methods

  • It is a method which belongs to the class and not to the object(instance).  
  • A static method can access only static data. It can not access non-static data (instance variables)
  • A static method can call only other static methods and can not call a non-static method from it
  • A static method can be accessed directly by the class name and doesn’t need any object.
  • Syntax : <class-name>.<method-name>.
  • A static method cannot refer to “this” or “super” keywords in anyway.

Example code on static variables and methods

Code for class  StaticDemo.java -

package greetings;

public class StaticDemo {

    private int a;// initialized to zero
    static int b;// initialized to zero only when class is loaded not for each
                    // object created.

    public StaticDemo() {
        b++;// Constructor incrementing static variable b
    }

    public void displayData() {
        System.out.println("Value of a = " + a);
        System.out.println("Value of b = " + b);

    }

}
Code for class TestStaticDemo.java -
package greetings;

public class TestStaticDemo {

    public static void main(String args[]) {
        System.out
                .println("Value of the static variable b before object creation is "
                        + StaticDemo.b);

        StaticDemo s1 = new StaticDemo();
        System.out.println("Printing data on object creation \n");
        s1.displayData();
    }
}


Output



Understanding the code

       Let understand our StaticDemo class first. We have defined two variables a and b. a is static while b is non static which means a belongs to the whole StaticDemo class as a whole. It is initialized to 0 (default value) right when the class is loaded by the JVM. Hence in the output we can see its value as 0 even before we have created any object of the class.Next we have the constructor which increments the value of our static variable b. So now when we create an object s1 of the class our static variable b whose value is 0 is incremented by one so new the value of b for each object that will be created will be 1.
    Again as we know a is an instance variable it is initialized to default values( 0 in case of int). So we can see it's value as 0 in the output. So when we create an object and print the values of our variables we get a = 0 and b = 1. TestStaticDemo is just to run the program and the code is self explanatory. Just review the way we access a static variable(and is same how we access a static function).

Note :  It is perfectly legal to access a static variable using class object but is not recommended because it destroys the very purpose of defining a variable as static. To restrict anyone from modifying our static variables we can define our variable as final  eg private final static int a. Note convention and access levels of access modifiers are still applicable.

To get the clear picture of how static keyword works refer to the following image - 


static block

  • The static block, is a block of statement inside a Java class that will be executed when a class is first loaded in to the JVM.
  • A static block helps to initialize the static data members, just like constructors help to initialize instance members.

Example for static block usage

public class Greetings
{
    static {
       //code goes here
     }
}

Sunday, 24 March 2013

FAQ #6 What is the difference between Java and Java Script?

Answer: There is none except the word "Java". Java is programming language from Oracle. JavaScript is a scripting language from Netscape, which runs in the browsers.

FAQ #5 What is the difference between Application and Applet in Java?

Answer: Java applications runs as stand-alone application whereas applet runs in web browser. Application is a Java class that has a main() method. Applet class extends java.applet.Applet class.

FAQ #4 Do I need to know C++ to learn Java?

Answer: No, you don't need to know C or C++ to learn Java. Java is much simpler that C++.

FAQ #3 Where can I download latest version of Java?

Answer: Latest version of JDK can be downloaded from Oracle web site 

FAQ #2 What platforms is the Java-technology software available on?

Answer: Oracle provides ports of the Java 2 Platform for Windows 95, Windows 98, Windows NT, Windows 2000, Solaris-SPARC, Solaris-Intel, and Linux.

FAQ #1 Why there are no global variables in Java?

Answer: Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:
  • The global variables breaks the referential transparency.
  • Global variables creates collisions in namespace.

Singleton Design pattern

Singleton Design patterns is the most simple of all the design patterns in Java. It is also the most frequently asked interview question. So lets go ahead and understand what this design pattern is all about.


Understanding Singleton Design pattern

              Singleton as the name suggests there can be only one instance of the class.There are various cases in which we strictly need only one instance of the class. Like for example we Window manager or Print spoolers or filesystems.  There are only two main points in the definition of Singleton Design pattern - 

  1. There must be only instance allowed for the class.
  2. This single instance of the class must be allowed global point of access.
For better understanding see the following class diagram -

 

Singleton instance creation

         Lets see the code first and then we will try to understand it.


package designPatterns;

public class SingletonPatternDemo {

    private static volatile SingletonPatternDemo singleInstance;

    private SingletonPatternDemo() {
    } // Constructor

    public static SingletonPatternDemo getSingleInstance() {
        if (singleInstance == null) {
            synchronized (SingletonPatternDemo.class) {
                if (singleInstance == null) {
                    singleInstance = new SingletonPatternDemo();
                }
            }

        }
        return singleInstance;
    }
}

     Lets understand the code written above. First of all we have the package and the class declaration. Carefully analyze the next line  private static SingletonPatternDemo singleInstance; we have a reference to the object of class SingletonPatternDemo. Note that it is just the reference and we have not created any associated object yet. Another view point can be that we have not yet used any space on heap for any object. This reference is defined as private and static. It is private which mean we cannot directly access it using class objects For Ex. objectName.singleInstance is not allowed. See Access modifiers for more details. Next it is also defined to be static which means the variable belongs to the class and not individual objects. We will get to static keyword in subsequent tutorials but for now you understand it this way - we can access the variable using SingletonPatternDemo.singleInstance i.e className.instanceVariableName. Next we have defined our constructor to be private which means we cannot create any objects by using the new keyword. Only way to create a object is the getSingleInstance() function which is public and static and returns an object of SingletonPatternDemo class. Again static means we can access it using the class Ex. SingletonPatternDemo.getSingleInstance().

         Inside the getSingleInstance() method we first check whether instance of the class is already created. If it is already created we return the same instance of the class(as we are allowed to have only one instance of the class) but if there is no instance of the class that is already created we create one and return it.What we have inside the getSingleInstance() method is what we call a Double locking mechanism which i will 
explain explicitly.But before that lets understand what synchronized is.

Note : 

Also note that the  singleton instance is defined to be volatile. This keyword is used for consistency of data across threads. You know that each thread has it's cache where the data reference by the thread is cached and when a thread modifies the data it is still in it's local cache and may not be visible to other threads. To avoid this problem variables can be declared volatile. By declaring a variable as volatile we essentially instruct JVM not to cache the variable in threads cache. Instead all the reads and writes must directly happen in the main memory.

Understanding synchronized keyword

          This keyword is used when we are dealing with multi-threading. Note that only member functions can be defined as  synchronized not the member variables or class itself. When we declare a function to be synchronized it means only one thread can access it at a given point of time. Other than synchronized functions we can have synchronized blocks like the one we have used in the above code. It also means the same - only one thread can access the block at a given point of time. We will cover this in depth when we go through what do we mean by a class being thread-safe and related advanced topics but till then given information should suffice.Next lets understand what is the Double locking mechanism we talked about.

Understanding Double locking mechanism

     Lets see the above code again


if (singleInstance == null) {
            synchronized (SingletonPatternDemo.class) {
                if (singleInstance == null) {
                    singleInstance = new SingletonPatternDemo();
                }
            }

This is double locking mechanism. Lets see how this works. Now our aim was to allow only single instance of the class. In multi-threading scenario lets say one thread checks  singleInstance finds it to be null and enters the synchronized block. Lets say now there is s context switch or time quantum of the process is over. Next thread takes over, checks if singleInstance is null which is true so even this thread will enter the first if block. Now if we did not have the second check in the synchronized block both thread would go ahead and create an instance of the class. Final result would be we having two instances of our class which is against our Singleton goal. Hence we do a double check once again in the synchronized block. Now since it is in synchronized block only one thread will execute it at a given time and create a instance. When second thread enters this block it will find singleInstance is not null and will not create a new instance. This method is what we call double locking mechanism.

Early and lazy instantiation in singleton pattern

       What we did in above code example is  lazy instantiation which means we create instance of the class only when it is needed. On the other hand we have Early instantiation which means we create the instance once as soon as the class is loaded and return the same when user need it. Code for  Early instantiation is as follows - 


package designPatterns;

public class SingletonPatternDemo {

    private static SingletonPatternDemo singleInstance  = new
 SingletonPatternDemo() ;

    private SingletonPatternDemo() {
    } // Constructor

    public static SingletonPatternDemo getSingleInstance() {
        return singleInstance;
    }
}

  So we create instance of the class as soon as class is loaded and just return it when getSingleInstance() is called. This demonstrates Early instantiation.




Note : 


You must have notice there is no synchronization involved in early initialization. Since Singleton instance is static variable it initialized when class is first loaded into memory so creation of instance is inherently thread-safe.


Eclipse Snapshot

 


Note : In Java you must have used Runtime class quite some time. For example to execute processes from Java - Runtime.getRuntime().exec(). This Runtime class is a Singleton class. There is only one instance of this class per JVM.



yes as you must have notice it, they have use Early initialization ( not lazy init).

Is Singleton instance garbage collected?

Simple plain answer is No!

This was an issue prior to Java 1.2 in which if singleton instance did not have a global reference it would be garbage collected. This defeated the very purpose of singleton as next reference created a new instance of it. But this was fixed in Java 1.2.

New garbage collection model forbids any of the classes that it has loaded from being garbage collected unless all the classes are unreferenced (in which case the class loaded is itself eligible for GC). So unless the class loader is garbage collected the singleton class having static reference to singleton instance is never eligible for garbage collection. So you can be sure that the singleton instance will never be GCed.


When Singleton does not remain Singleton?

There are various ways Singleton property can be violated
  1. Use reflection to create new instance
  2. Deserialize and Serialize it again
  3. Clone it if it implements Cloneable interface.
  4. Use different class loaders etc.
Prevention :
  1. Create constructor and throw exception from it
  2. Implement Serializable and return same instance in readResolve() method
  3. throw exception from clone method
But the best way to avoid these is to design singleton object using enum : The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants.

Related Links


Friday, 22 March 2013

Introduction to Design Patterns

What are design patterns?

        Programmers usually face some common problems while designing and formulating their programs. Various such problems patterns are identified and their solution is documented which we call design patterns.
So in a nutshell Design Patterns are best practices how to solve common know problems.


Understanding a bit more.

     Let us try to understand these design patterns by considering one such design problem.

     Single printer in a company

      Lets say we have a single printer in the entire company and we have an associated service class which provides printer service to every employee who wishes to print something. Now what sub goals do you have while designing such a service class. You have only one printer and hence you need only one instance of this service class. To achieve this goal you would design your class is such a way that at all time you can have only one instance of the service class. This design pattern is commonly know as Singleton Design pattern. We will look into it in more details but i guess this example will suffice in achieving our goal to understand what these design patterns are all about.

   Another example would be your logging class. You want only one instance of logger to be used. So you would prefer using Singleton Pattern.

Important principles in OO Design 

  • Code for interface not implementation.
  • Prefer composition over inheritance.
  • Interacting Objects should be loosely couple.
  • For each class design aim for low coupling and high cohesion.
  • Classes should be open for extension but closed for modification.
These are used in almost all design patterns and form like the basic guidelines. So do keep these in mind. We will use them while discussing about design patterns in detail.

 

Types of design patterns

   Design patterns are categorized into 3 types as follows - 

Places where design patterns are used in Java

Singleton pattern is used in Java.lang.Runtime , java.util.Calendar, Java.awt.Toolkit, Java.awt.Desktop classes, Factory pattern is used along with various Immutable classes likes Integer e.g. Integer.valueOf and Observer pattern which is used in Swing and many event listener frameworks.Book that I would recommend to study Design Patterns for the beginners  is -
  • "Head first Design Patterns"


Or you can refer to the book written by the Gang of Four themselves - 
  • "Design Patterns"- Elements of Reusable Object-Oriented Software


Related Posts

Sunday, 17 March 2013

Interview Question #5 What is the difference between creating string as new () and as a literal?

This is a very common and most basic interview question asked in Java and yet programmers are not able to explain it properly.

  • When we create a String using new operator it is created in heap and not added to String pool whereas String created as literals are created in String pool itself which exist in PermGen area of heap.
  • Let us take example to understand this better -

    1. Case1)   Lets create two string literals with different names.
      String firstLanguage = "Java";
      String secondLanguage = "Java";


      Now if we say

      if(firstLanguage == secondLanguage )
      {
           System.out.println("Both references point to same String \n");
      }
      else
      {
           System.out.println("Both references point to different Strings \n");
      }


      Output : Both references point to same String

      Explaination :
      When we create firstLanguage as literal it is created and stored in String pool. Now when we try to create secondLanguage JVM know that such a string already exists in the pool and hence returns reference of the same String and hence the output shown above.

      Note : '==' operator will return true only if both references or variables point to same object. In case of String if you really need to check if content of two strings are equal you must use .equals() method.
    2. Case2) Now lets create two String objects and repeat the same exercise we did above.

      String firstLanguage = new String("Java");
      String secondLanguage = new String("Java");


      Now if we say

      if(firstLanguage == secondLanguage )
      {
           System.out.println("Both references point to same String \n");
      }
      else
      {
           System.out.println("Both references point to different Strings \n");
      }



      Output :Both references point to different Strings

      Explaination :
      When we create firstLanguage as new() it is created and stored on the heap as a String object. Similarly when we create secondLanguage as new() it is again cretaed on heap as a different String object. Now since == operator returns true only when both variables point to same object which is not the case we get false.

      Note : As mentioned above if you want to check whether contents of firstLanguage object and secondLanguage object are the same that you can use .equals() method. It will return true if content of both String objects are same.

Saturday, 16 March 2013

Basic Calculator program in Java

I guess we are ready to write some good quality basic Java programs. One thing i would like to state here is that even if you are finding Java a bit new, you will eventually master it only by practice and hence it is essential to keep writing codes and not just understanding the theory.

        Let write a very basic Java program for calculator. There is no GUI involved since we have not covered Swing yet. This program will just take two numbers as input and perform the required operations like addition, subtraction etc.  Though it is basic it will cover most of the topics we have learned till now. I am writing and running Java programs on Eclipse and hence you may find it's snapshots here but you can even write codes and execute using command line or use other IDE's like Netbeans. So lets get started.

Java code for Calculator

      Lets first create a class where we implement the calculator logic.Create a new Java project in Eclipse called Calculator. Next create a package in it called basicCalculator. In this package make two new classes
class Calculation where we would implement the calculator logic and class ProgramLauncher which will have the main() function from which we will create class Calculation object and execute it.

Create class Calculation and insert the code below.

package basicCalculator;

import java.util.Scanner;

public class Calculation {

    private float firstOperannd;
    private float secondOperannd;
    private float result;
    private int operator;
    private Scanner input = new Scanner(System.in);
    private boolean exitCalculator = false;

    public void startCalculator() {
        while (!exitCalculator) {

            System.out.println("Enter 1 for addition \n"
                    + "Enter 2 for subtraction \n"
                    + "Enter 3 for multiplication \n"
                    + "Enter 4 for division \n" + "Enter 0 for Exit : ");
            operator = input.nextInt();

            switch (operator) {
            case 1:
                result = add();
                System.out.println("Result is " + result);
                break;

            case 2:
                result = subtract();
                System.out.println("Result is " + result);
                break;

            case 3:
                result = multiply();
                System.out.println("Result is " + result);
                break;

            case 4:
                result = divide();
                System.out.println("Result is " + result);
                break;

            case 0:
                exitCalculator = true;
                System.out.println("Calculator program Terminated \n");
                break;

            default:
                System.out.println("Please provide proper input \n");

            }
        }
    }

    private float add() {
        System.out.println("Enter first number : ");
        firstOperannd = input.nextInt();
        System.out.println("Enter second number : ");
        secondOperannd = input.nextInt();
        return firstOperannd + secondOperannd;
    }

    private float subtract() {
        System.out.println("Enter first number : ");
        firstOperannd = input.nextInt();
        System.out.println("Enter second number : ");
        secondOperannd = input.nextInt();
        return firstOperannd - secondOperannd;
    }

    private float multiply() {
        System.out.println("Enter first number : ");
        firstOperannd = input.nextInt();
        System.out.println("Enter second number : ");
        secondOperannd = input.nextInt();
        return firstOperannd * secondOperannd;
    }

    private float divide() {
        System.out.println("Enter first number : ");
        firstOperannd = input.nextInt();
        System.out.println("Enter second number : ");
        secondOperannd = input.nextInt();
        return firstOperannd / secondOperannd;
    }

}
  There are many point that need to be explained here so be patient. First lets get our code up and running.
So create next class class ProgramLauncher and insert the code below.


package basicCalculator;

public class ProgramLauncher {

    public static void main(String[] args) {

        Calculation calculator = new Calculation();
        calculator.startCalculator();

    }

}

    Just execute the program and try check the output for various test cases. For how to create a project, package , class, how to see standard output in eclipse please go through our post on Hello World.

When you execute this program you will see output something like below - 


 It clearly says what you need to input and what are the corresponding operations. If you press 0 program will terminate. Go ahead and try out various cases.More importantly try division by 0 or something like 0/0. I will explain these but you can go ahead and try it now.


Sample outputs


Understanding the Code

      Launcher code is very simple. All we do is create a Calculation class object and call the startCalculator() method. Just for the record we could call the method like calculator.startCalculator(); because the method is defined to be public. You can't do the same with other functions like add() as they are private. We will explain why we have taken such a decision but till then understand the program behavior.

    Lets go to our calculator logic code now.


Initializations



         We have defined two float operands firstOperannd and secondOperand.Similarly we have defined float result to store result, int operator to store values corresponding to various opearations and finally a scanner object to take use input. Again note that all these are instance variables and are private.So at any point of time you cannot access them using class Calculation object. They can only be manipulated using public functions provided. We also have exitCalculator to keep track whether to exit our program or not. Default value is set to false which means do not close the program unless user says so.

startCalculator() function

     Inside this function we have a while loop which keeps on executing unless exitCalculator is set to true.
Inside the loop we ask user to choose which operation he is interested in. He must input one of the available options i.e 0,1,2,3 or 4. We then have the switch statement which has operator as the argument. 

   Note : Switch statement supports String as argument only in JSE 7 . So i have used int to make the program run for everyone but if you are using  Java SE 7 you can go ahead and use String as input directly.

     Inside the switch statements we have cases each corresponding to different operations.We have defined separate functions for each operation i.e add(),subtract() etc and all we do in each case in switch statement is call these functions. Note the usage of break statement. We are computing the result in each case and printing the same on standard output.Each function computes the result and returns it back. Note that if user enters 0 then exitCalculator is set to true and the program terminates. For all other inputs default statement is executed which says you must provide correct input. Execution will continue unless user enter 0.

Why are functions like add() defined private?

         Before you define anything in Java or for that matter any programming language you must decide what is it going to be used for. Like in this case we know that add() function will only be used by

startCalculator() method and we don't want to allow any usage like objectName.add(). Hence functions are defined to be private. These functions can only be used in other functions of the same class.

Interesting cases

     Lets discuss some of the interesting cases that might arise in case of division.
  • 4/0 : What happens when i divide any number by 0. Technically you can't divide by 0 and you must get an error. You will get an error if you divide by zero in case on integers but in case of float you will get result as infinity. Note if you are using your firstOperand and secondOperand as int's you need to handle that divide by 0 runtime exception. Also if you use int and user types in something like 4.2 it will be truncated to 4.
  • 0/0: What happens when you divide 0 by a 0. Definitely not infinity in this case. Its a value called  NaN(not a number). Again if you use int you will get a runtime exception and program will terminate.These are some of the reasons why we have chosen float over int.


    Eclipse output snapshots



Output for 6/0 operation

Output for 0/0 operation


Do post any doubts you have in the comments sections.

Interview Question #4 What is immutable object? Can you write immutable object?

Immutable classes in java are classes whose object cannot be modified. Most instance variables and functions of immutable classes are also final in order from preventing subclasses to change the values by overriding methods which may compromise immutability. But there are other ways too, like declaring the members as private and changing it's value only in constructor.

For more details on how you can make your class immutable refer -

There can be more follow up questions like why would you make a class immutable? Well the answer is thread safety :) as immutable objects are inherently thread safe. More details in the linked answer above.

      For example in Java String is an immutable class. Once a string is created it cannot be modified.What happens when we call functions like .substring() one might ask. What it does is it simply creates and returns a new String object by taking the sub-string from the source string.

    Other example includes the wrapper classes for the primitive types: java.lang.Integer, java.lang.Byte, java.lang.Character, java.lang.Short, java.lang.Boolean, java.lang.Long, java.lang.Double, java.lang.Float etc.

Yo know why String was decided to be made immutable go through the following article -


Related Links

MCQ #10

Question) If you do not use curly braces for a while loop body , what will execute if the while condition is true?

Options)

  • Nothing
  • First statement of while
Answer) A copy of the value

Explanation)   If you do not provide braces to any loop statements then 1st statement is taken by default. Same is true even for if-else statement For more details refer the post on Loop Statements.

MCQ #9

Question) When you pass variable as an argument to a method call, what are you passing?

Options)
  • The actual value
  • A copy of the value
Answer) A copy of the value

Explanation)   Java works that way - pass by copy. For more details refer the post on Classes in Java.

MCQ #8

Question) Assume x = 0 and y = 3. What is the value of x after :  x = y++;

Options)

  • 0
  • 3
  • 4
Answer) 3

Explanation)   You must know the difference between pre-increment (++x) and post-increment(x++)  operators before you can answer this question.

Difference between ++x and x++

       Pre-increment operator(++x) will first increment the value of x and then carry out any operations that are due whereas in post-increment(x++) operator , operation is first carried out and then x in incremented.
     Sounds a bit hard to digest?
       Lets take an example to ensure we understand it completely.

int x = 0;
int y = 3;

Lets consider pre-increment operator first(++y)

x = ++y;

Result of above will be x = 4 and y = 4 because pre-increment operator first increments the value i.e value becomes 5 and then carries out the = operation.

Now lets see the post-increment operator(y++)

x = y++;

 Result of above will be x = 3 and y = 4 because post-increment operator first carries out the = operation i.e assigns value 3 to x and then increments the value of y to 4.

       Our question represents the second case(post-increment). So our answer is 3.

MCQ #7

Question) Can you compare boolean to an integer?

Options)

  • True
  • False
Answer) False

Explanation)   In Java boolean has value true or false and not 1 or 0 or anything else. So you just can't do it(Watch out C folks!).

MCQ #6

Question) x = false; y = true; What is the result of x && y

Options)
  • True
  • False
Answer) False

Explanation)  This is a straightforward question. Lets revise the entire table once -

x         y          x&&y
true    true      true
true    false     false
false   true      false
false  false      false

So basically in  expression1&&(and)expression2, entire expression is false if any one of the expressions or both are false. On the other hand this evaluates to be true only when both expressions are true.

Our question represents 3rd row of the above table.The answer is therefore False. 

Friday, 15 March 2013

Object Stream in Java

Background

Just to recall we have are going through I/O streams in Java. We have already seen byte stream, character stream and use of scanner class. Lets see the final topic on I/O streams in Java i.e Object stream.

Object streams

       Object streams are used for I/O of objects. For objects of classes to support this I/O they must implement a special interface called Serializable Interfaces are not explained yet so do not bother what that is as of now but just from the programming perspective it is as simple as saying 

class ObjectStreamDemo implements Serializable
{
      //member variables and functions 
} 

 Serializable in itself is a topic worth a post which we can cover in next tutorial but as of now i will demonstrate how can we read and write objects through object streams.

Java code 

      We will create a class, create it's object, store it in a file and retrieve it.Sounds simple enough? It actually is!

Let us create a simple class ObjectStreamDemo first.It must implement Serializable in order to use it's objects in Object stream.

package streamsDemo;
import java.io.Serializable;

public class ObjectStreamDemo implements Serializable {

private static final long serialVersionUID = 1L;    
private String greetings;

    public String getGreetings() {
        return greetings;
    }

    public void setGreetings(String greetings) {
        this.greetings = greetings;
    }

}
     So now we have a class which implements Serializable. We have an instance variable called greetings and we have defined it's getter and setter methods.Note you have to import java.io.Serializable.Wondering what serialVersionUID  is? We will come to that in some time. Now lets move on to implementation of Object streams.

package streamsDemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class ObjectStreamImplementation {

    public static void main(String args[]) {
        ObjectStreamDemo obj = new ObjectStreamDemo();
        obj.setGreetings("Hello World!");
        ObjectInputStream ois = null;
        ObjectOutput oos = null;

        try {
            try {
                oos = new ObjectOutputStream(new FileOutputStream(new File(
                        "testFile.txt")));
                ois = new ObjectInputStream(new FileInputStream(new File(
                        "testFile.txt")));
                oos.writeObject(obj);
                ObjectStreamDemo newObj = (ObjectStreamDemo) ois.readObject();
                System.out.println("greetings : " + newObj.getGreetings());
            } finally {
                if (ois != null) {
                    ois.close();
                }
                if (oos != null) {
                    oos.close();
                }

            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

}

Output

Standard Output in Eclipse


Before we move on to understanding the code just go through the try-catch block. I had explained it while explaining code in character streams. You may want to go through it once. Also note why have we initialized ois and oos to null .Answer is because they are local variables and compiler will complaint if we use local variables without initializing. Refer this post to check revise the differences between local variables and instance variables.

Understanding the code

        In the main function we create an object of ObjectStreamDemo class called obj. Then we set it's instance variable greetings to "Hello World!". Then we declare references  to objects of ObjectInputStream and ObjectOutputStream. Note these are just reference and not objects.What i mean by that is no memory is allocated on heap. These are just pointers which we know will point to objects of ObjectInputStream and ObjectOutputStream.
      Next we actually create object of ObjectInputStream and  ObjectOutputStream. Expression looks familiar. Yes! it does. ObjectInputStream and ObjectOutputStream are just wrappers around FileInputStream and FileOutputStream which are nothing but byte I/O streams for file operations.Then we write the object we created obj to the file.Finally we read the object objNew from file and print it's instance variable greetings on the standard output. Output is as expected "Hello World!"

Note : we have to type cast to ObjectStreamDemo as .readObject() will return an Object.

What is this serialVersionUID we defined in

ObjectStreamDemo class and what is it's use?

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:

ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members.

If you using an IDE like Eclipse or Netbeans you will automatically get warning to  put a  serialVersionUID. IDE can also put a default value if you instruct so.

Related Links

    

Sunday, 10 March 2013

Using Scanner for input in Java

Background

In last few posts we saw various I/O streams. We saw example code for byte stream and character stream.We saw BufferedStream and we even saw how to take input from standard input using BufferedReader.Now lets see how can we use Scanner to take input and understand When and why do we use it?

Why scanning?

       Objects of type scanner are useful for breaking down formatted input into tokens and translating individual tokens according to their data type.By default, a scanner uses white space to separate tokens. (White space characters include blanks, tabs, and line terminators.

   Lets see how Scanner works by taking an example.

Example code


public class ScannerDemonstartor{
    public static void main(String[] args) throws IOException {

        Scanner s = null;

        try {
            s = new Scanner(new BufferedReader(new FileReader("inFile.txt")));

            while (s.hasNext()) {
                System.out.println(s.next());
            }
        } finally {
            if (s != null) {
                s.close();
            }
        }
    }
}
 

Code Analysis and Explanation

        As explained earlier Scanner scan word by word, basically part of line separated by a separator(default is a white space). If you want this separator to be your separator they you do something like below - 


s = new Scanner(new BufferedReader(new FileReader("inFile.txt")),"mySeparator");
 


Remaining structure of code is very much similar to what we have explained  in last few posts.One more thing we use .hasNext() method to check if more tokens exist.

Using scanner to take input from Standard input

                Scanner sc = new Scanner(System.in);
                String readLine = sc.nextLine();
                int readInt = sc.nextInt();
                boolean readChar = sc.nextBoolean();

and so on.....
In this way you can take any data type as input.We would mostly use Scanner class to take standard inputs in all our future code so understand this completely.Do let me know if you have any questions.

Related Links 

 

Character stream in Java

 Background

As we saw in our last post byte stream classes are derived from InputStream and OutputStream classes. Similarly, for character stream all classes descend from Reader and Writer classes.

We generally use character streams for I/O so i would recommend to understand this post very thoroughly. Byte streams are used only for low level I/O operations.

Background

Similar to byte streams we will primarily focus on File I/O streams.Classes for the same are FileReader and FileWriter.We will also discuss reading from standard Input.

    In last post we wrote a code and then said that it was not the perfect way to write it.We discussed what might be a better way and why do we have to close the streams.So like the last example code we will not let our main() function throw any exception. We will catch it and then close the stream in finally block. Though we have not explained Exception Handling this would be a basic code to start with.There will be an entire post on Exception Handling. So try to understand the logic behind writing the following code than to understand Exceptions.We will write this code more systematically. 

Example code

public class CharacterStreamDemonstrator {

    public static void main(String[] args) {
        FileReader reader = null;
        FileWriter writer = null;

        try {
            try {
                reader = new FileReader("inFile.txt");
                writer = new FileWriter("outFile.txt");
                int readStatus;
                while ((readStatus = reader.read()) != -1) {
                    writer.write(readStatus);
                }
            } finally {
                if (reader != null) {
                    reader.close();
                }
                if (writer != null) {
                    writer.close();
                }
            }

        } catch (FileNotFoundException e) {
            System.out.println("File could not be found \n");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("IO Exception occured \n");
            e.printStackTrace();
        }
    }
} 
     

Code Analysis and Explanation

      I repeat do not get confused looking at the try-catch-finally statements.Though this is one of the proper way to write the code our aim in this post is to understand character streams though i will try my best to explain entire code in as generic was as possible.

Lets go line by line.First we define FileReader and FileWriter objects.

Why are FileReader and FileWriter objects initialized to null?

     These objects are local variables (not instance variables) and if you recall the post which explained difference between local and instance variables, compiler will complaint if you try to use local variables without initializing.So we have initialized it to null.


     Reading and writing logic is very much similar what we used in byte stream except that we read and write character at a time rather that a byte at a time.Now let me explain what are those try-catch-finally statements doing in the code.

Understanding try-catch-finally statements

    If you observe the code carefully we have try-finally statement inside try-catch statement.Let see what both of them actually do.

     The inner try-finally statements execute the reading.writing logic and finally close the streams.Also recall from the last post why do we check the stream for null before closing them.
     The outer try-catch statement will execute everything in it's try block which is nothing but our inner try-finally block and then catch any Exceptions that may occur in the try block. e.printStackTrace()  will print the cause of exception in an sequential manner like what caused the exception or what exception cause this exception to occur.

    So basically what your try-catch statement does is execute something in try block and catch if any exception arises in try block with catch block.

Note :  Compiler will not compile unless you either throw or catch any possible exceptions that might occur in your code (such exceptions are called checked exceptions). Java is designed that way to reduce the errors and increase security.


Understanding finally statement

      The reason i am explaining finally statement separately than try-catch-finally statement is that finally block has special importance and there are various thing you need to know about it.Note that finally block cannot exist on it's own. You must have either try-catch-finally syntax or try-finally syntax.

   finally block will execute regardless of whether Exception has occurred or not. So we use it to close our steams. So regardless of what happens our streams will be closed.Note that there is one case in which finally block will not be executed and that is if you say System.exit() but except that finally block will always be executed even if there is a return statement in try block.

However it does not make sense to read and write one character at a time. Can we read a line at a time?

      Yes! of course you can. We have BufferedReader and PrintWriter/BufferedWriter for the same purpose.Think of these as wrappers around our Reader and Writer classes. As the name suggests it buffers characters ahead of time and reads/write a line at a time.

Lets see code to do so.I will not write the entire code again because the structure remains the same.All we have to change is our reading/writing logic.


BufferedReader reader = new BufferedReader(new FileReader("inFile.txt"));  
BufferedWriter writer = new BufferedWriter(new FileWriter("outFile.txt"));
String readLine;
while ((readLine = reader.readLine()) != null) {
    writer.write(readLine);
} 

One of the difference to mention here is that as we are reading line we compare it with null to check if all the data from input stream is read.You can also use PrintWriter instead of BufferedWriter. Difference is that PrintWriter flushes the data every time we write whereas in BufferedWriter data is flushed when it encounters '\n' i.e new line or we explicitly say so. Note this concept of flushing comes into picture only when streams are buffered, not otherwise.

Reading from standard input.

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String readLine = reader.readLine();

I think the code is pretty straightforward and easy to understand. Only thing worth mentioning in this is System.in which just tell your input stream must come from standard input.

Note : character stream internally uses byte stream only.

In our next post we will see another way to read data from various streams and that is by using scanner class.This was one of the important tutorials in Java, so let me know if there is any doubt in any part explained above.


Related Links 

Saturday, 9 March 2013

Byte Streams in Java

Background

We saw in last post in Java Tutorials section what streams in Java are.Byte stream is one of the type of streams used to perform to perform input and output of 8-bit bytes.All byte stream classes are descended from InputStream and OutputStream.

     There are many byte stream classes. To demonstrate how byte streams work, we'll focus on the file I/O byte streams, FileInputStream and FileOutputStream. Other kinds of byte streams are used in much the same way; they differ mainly in the way they are constructed.

Let us examine the way bytes streams are used by looking at an example -

Example code


public class ByteStreamDemonstrator {
    
    public static void main(String args[]) throws IOException
    {
        FileInputStream in = new FileInputStream(new File("inFile.txt"));
        FileOutputStream out = new FileOutputStream(new File("outFile.txt"));
        int c;
        
        while((c = in.read())!= -1)
        {
            out.write(c);
        }
        if(in!=null){
           in.close();
          }
        if(out!=null){     
           out.close();
          }
    }
}



Lets analyze the code now.


    We have define two byte streams FileInputStream in and FileOutputStream out.
Each stream take a File object as an input which in turn takes filename as an argument.Note that you can directly give filename as an argument to FileInputStream and FileOutputStream. Also note this filename is of type String.This file must be in your source directory, if not you can always give absolute path in the place of filename.
    In above code we have inFile and outFile as two files in src directory.We read from inFile and write to outFile.Note that read() function return an integer and when all data in input stream is read it will return -1 which can be used as a condition to terminate our loop.

Always close streams

   Never forget to close the streams you have opened. In above code we close the streams using .close() function. Note that we are checking if the stream is open or not before closing it because if due to some error stream was not opened and if we try closing it, it will throw runtime Exception. 


Better approach to write above code

    Above code is not the best way to write it.Since Exceptions are not explained yet above code will suffice our requirements in understanding byte stream.But the more correct approach to do above is put out reading/writing logic in try statement, catch the exception to handle the exceptions like FileNotFound Exception in catch block and use the Finally block to close the streams.

What is this throwing Exception?


   In above code observer the line throws IOException besides the main function.What it means that if there is any Exception just throw it (don't catch). Generally when a function throws an exception Exception is thrown to the function which has called the function throwing that Exception.The calling function must then either catch it and handle it or again throw it to it's parent function.

So what happens when every function throws the Exception and no one catches it?

   If no function catches the Exception it will finally come to the main() function.If even the main() function does not handle the Exception and just throws it like what we have done in above code then JVM will just shut down, terminating the program.Lets not worry about this at this point. We will cover this in much details when we learn about Exception handling.

When not to use byte stream?

    Since inFile and outFile contains characters the best way to do it is to use character stream which will be explained in our next post. Byte streams should only be used for primitive I/O.

So why talk about byte streams?

     Because all other stream types are built on byte streams. 

Related Links 

MCQ #5

Question) In switch construct , the default statement must be placed after all the case statements.

Options)

  • True
  • False
Answer) False

Explanation) Go through the Java tutorial on switch statement to know more about switch statement and it's usage.As for our question, default statement can be put anywhere in the switch construct but it will be called only when none of the other cases match. Also since default statement is the last one to be checked we need not even write break statement in default statement.So the answer is clearly False.

MCQ #4

Question) Member (instance) variables are always assigned a default value if not explicitly initialized.

Options)

  • True
  • False
Answer) True

Explanation) Go through the Java tutorial on Objects in java to know the difference between instance variables and local variables.As for our question, yes instance variables are assigned default values if not explicitly initialized.On the other hand compiler will complaint if local variables are used without initialization.

MCQ #3

Question)Assume x = 6 and y = 7 .What is the result of (!(y == x))

Options)

  • True
  • False
Answer) True

Explanation) The answer is pretty straight forward . x=6  and y=7 so y == x is false. Negation ( ! ) of false is true and hence our final result is True. Remember brackets have higher preference than any of the operators.

MCQ #2

Question) Using a break in a for loop causes the loop to break out of the current execution and jump to next iteration.

Options)
  • True
  • False
Answer) Flase

Explanation) I would recommend go through the post on Transfer Statements in Java Tutorials section.break keyword will cause loop to break out of current execution permanently and continue with the code after the loop.Note that break statement is used only in loops and switch statement.So answer is False.

MCQ #1

Question) Methods which are marked protected can be accessed only by classes within the same package

Options)
  • True
  • False
Answer) Flase

Explanation) I would recommend go through the post on Access Modifiers in Java Tutorials section.If a member (be it a member variable or a member function) is defined to be protected then it is accessible by members in same class, in same package and also in all the sub classes of class in which the protected member is defined. So it is not just the same package.Hence answer is False.

Understanding I/O streams in Java

Background    

User input is required to make our programs more interactive and dynamic.For this it is essential to know what are Input and Output streams and how they work.

What are I/O streams in Java?

  • An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays.
  •  Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways.
  • No matter how they work internally, all streams present the same simple model to programs that use them: A stream is a sequence of data

Types of Streams in Java.

     A program uses an input stream to read data from a source, one item at a time:



A program uses an output stream to write data to a destination, one item at time:


 

   Streams can hold all sorts of data from primitive types to advanced objects.
   In next few posts we will go through various types of I/O streams like byte stream, character stream, object stream etc. Check for links in the Relates Links section at the bottom of this post.


The java.io library defines four abstract classes that are the parents of all stream classes defined within the API:
  1. InputStream, 
  2. OutputStream, 
  3. Reader, and 
  4. Writer.

Above are classified into two sets of classes - InputStream/OuputStream and Reader/Writer. Difference being -
  • The stream classes are used for inputting and outputting all types of binary or byte data.
  • The reader and writer classes are used for inputting and outputting only character and String data.
NOTE : When wrapping a stream you can mix and match only types that inherit from the same abstract parent stream.
Eg. following combinations will not work -

new BufferedInputStream(new FileReader("data.txt")); // char stream inside byte stream
new BufferedWriter(new FileOutputStream("data.txt")); // byte stream inside char stream
new ObjectInputStream(new FileOutputStream("data.txt")); // input and output streams mixed


Note : The data source and data destination pictured above can be anything that holds, generates, or consumes data. Obviously this includes disk files, but a source or destination can also be another program, a peripheral device, a file, a network socket, or an array.




Related Links 


t> UA-39527780-1 back to top