Saturday, December 21, 2013

Wrapper classes



We have discussed few classes in previous posts. Lets get in to this topic. You know that Java is object oriented language. So Java see everything as an objects. In Scanner class we got user input as objects. Like this Java see all the things as objects. Wrapper classes are used to convert simple data types (byte,short,int,long,float,double char,boolean) into objects. 

Why we need to convert data types to objects ?

  • You need to convert primitives to objects, if you want to use data structures in Java. They only allows objects.
  • If you want to use collections, you have to use objects not primitives.
  • Other thing is, objects can be assigned to null and it can be send null parameters to methods or constructors. To do this thing you have to use objects. It cannot be done with primitives.


    What are the wrapper classes ?

    Wrapper classes can wrap primitives to objects and also remove the wrap from objects. Think about a gift. 

    The gifts are wrapped. But you have to unwrap it to see what inside.
    Wrapper classes are like them. It provides methods to wrap and unwrap them. 

    Why we need to use wrapper classes ?

    In Java, wrapper classes produces two things.

    • Provide the procedure to wrap primitive data types to objects.
    • Provide an assortment of utility functions to primitives. 
    When you are using collections like List, Set, Map...etc they allows objects as their elements.


    Wrapper classes for primitive values




    You can see wrapper classes are belongs to java.lang package. So you need not to import it. Simply wrapper class name is same as primitive name except char. But primitives begin with lower case. 


    How to create wrapper objects ?

    There are three approaches to create wrapper objects in Java.

    1. Using wrapper constructors
    2. Using valueOf() methods
    3. Using wrapper conversion utilities.


    1.Creating wrapper objects using wrapper constructors.

    As to above graph you can see, each wrapper classes provide two constructors except Character type. One for its primitive type and other one for its String representation.



    public class WrapperClassTest {
            public static void main(String args[]){
      
                   int x=10;
      
                   Integer x1 = new Integer(10);
                   Integer x2 = new Integer("100");
      
                   System.out.println(x1);
                   System.out.println(x2); 
            }
    }
    
    
    


    2.Creating wrapper objects using valueOf() methods.

    This is the second method to create wrapper classes. 

    • This is a static method. So it can be invoked directly on the class. 
    • In this method there are two forms. 

    Form 1

    • In this method it takes the value of specify primitive (int, float, double...etc) and assign it to its wrapper object type. 
    • In following example you can see that I assign value 10 to integer type object x.


    public class WrapperClassTest {
           public static void main(String args[]){
      
                  Integer x = Integer.valueOf(10);
        
                  System.out.println(x);
           }
    }
    
    
    

    Form 2


    • In this method, there are two parameters(value and radix).
    • This radix indicates in what base the first argument is represented. 
    • In following example I converted "10110" to three integer objects.


    public class WrapperClassTest {
           public static void main(String args[]){
      
                   Integer x1 = Integer.valueOf("10110", 2);
                   Integer x2 = Integer.valueOf("10110", 8);
                   Integer x3 = Integer.valueOf("10110", 16);
        
                   System.out.println("Decimal value of 10110    : " + x1);
                   System.out.println("Octal value of 10110      : " + x2);
                   System.out.println("Hexadecimal value of 10110: " + x3);
           }
    }
    
    
    


    3. Creating wrapper objects using wrapper conversion utilities.


    In Java we use some methods to do this task.

    • xxxValue()
    • parseXxx() 
    • toString()
    • toXxxString()


    xxxValue() method


    This method is used to convert wrapped numeric value into another primitive type. So there are six no arg methods. Try following example to understand about this method.



    public class WrapperClassTest {
           public static void main(String args[]){
      
                    Integer x = new Integer(10);
      
                    byte b = x.byteValue();
                    short s = x.shortValue();
                    long l = x.longValue();
                    float f = x.floatValue();
                    double d = x.doubleValue();
      
                    System.out.println(b);
                    System.out.println(s);
                    System.out.println(l);
                    System.out.println(f);
                    System.out.println(d);
      
           }
    }
    
    
    

    parseXxx() method

    This method is used to represent the primitive data type of a String. Either you can one argument or two arguments like following example.


    public class WrapperClassTest {
            public static void main(String args[]){
    
                   int i1 = Integer.parseInt("100");
                   int i2 = Integer.parseInt("10110", 2);
      
                   System.out.println(i1);
                   System.out.println(i2);
      
            }
    }
    
    
    

    You may get confuse about the different between this method ( parseXxx() ) and valueOf() methods.


    • valueOf() - This method returns a newly created wrapper object.
    • parseXxx() - This returns the primitive value of given value.

    toString() method

    This method is used to get the String representation of a numerical object. Try these simple programs to understand about this method.

    public class WrapperClassTest {
            public static void main(String args[]){
      
                    Integer x = 100;
                    String s = x.toString();
      
                    System.out.println(x.toString());
                    System.out.println(s);
                    System.out.println(Integer.toString(1000));
            }
    }
    
    
    

    toXxxString() method
     
    This method is used to convert base 10 numbers of Integer and Long to base 2, 8 or 16. t can be used as follows.


    public class WrapperClassTest {
            public static void main(String args[]){
      
                     System.out.println(Integer.toBinaryString(10));
                     System.out.println(Integer.toOctalString(10));
                     System.out.println(Integer.toHexString(10));
      
                     System.out.println(Long.toBinaryString(100));
                     System.out.println(Long.toOctalString(100));
                     System.out.println(Long.toHexString(100));
      
            }
    }
    
    

    Do you know, Wrapper objects are Immutable

    Wrapper classes are immutable classes, it means the value of wrapper object cannot be changed once you initialized it. This is like String immutability. Try this program.

    public class WrapperClassTest {
           public static void main(String args[]){
      
                   Integer x = 100;
                   Integer y = x++;
      
                   if(x==y){
                          System.out.println("x = y"); 
                   }
                   else{
                          System.out.println("x != y");
                   }
           }
    }
    
    
    


    Special note about Wrapper classes



    I move on Boxing, Un-boxing,  Auto boxing and Auto Un-boxing in next post.

    Monday, November 25, 2013

    Scanner class



    What is Scanner class ?

    • This is a one of methods that can be used to get user inputs in a program.
    • There are various types of user inputs. They may be int, double, float, char, String...etc.
    • So this is very important thing in Java programming.
    • Scanner is not safe for multithreaded use without external synchronization. 

    How to use Scanner class ?

    • Scanner class belongs to java.util.Scanner class.
    • You have to import it. (Not like String class)
                   import.java.util.Scanner;

    • Above statement import the Scanner class or you can import whole util package like below.(' * ' symbol define whole)
                   import.java.util.*;

    • After you import it, user can input inputs either using keyboard or using file. 
    • But you have to create Scanner object.

      Creating Scanner objects

      • Instead of creating int, char or other types, we are creating scanner type objects.
      • You have a great knowledge about, how to create objects and constructors.
      • It is mostly like creating other objects(String, StringBuffer, StringBuilder). But there is something different. 
                           Scanner scn = new Scanner(System.in);

      • This is the Scanner constructor that provide inputs of specified input stream(That is why we used System.in).
      • scn is a Scanner type reference variable.
      • In above statement there is something called System.in, This is used to specify that will be a system input.
      • There can be other types also. I mention few of them.
                       Scanner(file resource) - Scan values from specified file
                       Scanner(readable resource) - Scan values from specified source
                       Scanner(string resource) - Scan values from specified string

      How do Scanner work ?

      • Now you have created Scanner types variable(scn).
      • This variable can hold the value that you have input using Scanner.
      • Then we have to place that value in memory(heap).
      • To do that, we have to define a reference variable to refer the value  entered above by user.
      • It means, if you want to handle String type of data(name,city), you have to define String variable. If you want to handle int type data(id,age), you have to define int type variable.

      scn just hold the value of user input

      scn.next() is put in the heap by s

      • It can be done as follows. 

      import java.util.Scanner;
      public class ScannerTest {
              public static void main(String args[]){
        
                      Scanner scn = new Scanner(System.in);
                      System.out.print("Please enter your name: ");
        
                      String s  = scn.next();
        
                      System.out.println("Your name is " + s);
              }
      
      }
      
      
      
      In this program I want to get the user name. It is a String type one. So I define a String type variable called 's'. Then I assign scn.next() to the variable s. WHAT IS THIS NEXT() ?


      Scanner class methods

      Like other classes Scanner class also have set of methods(More than 50). You need to understand few of them if you wand to ready to OCPJP 6 1Z0-851 examination. Without these methods we cannot assign a memory space using reference variable. In above example I have used next() method. Below I mention few special methods in Scanner class.

      next()
      This method finds and return the next complete token from Scanner. Receives the next token from scanner object as a String. 

      int nextInt()
      This method finds and returns the next token from Scanner as an int.

      float nextFloat()
      This method finds and returns the next token from Scanner as an float.

      long nextLong()
      This method finds and returns the next token from Scanner as an long.

      double nextDouble()
      This method finds and returns the next token from Scanner as an double.

      String nextLine()
      This method receives the next line of the String.

      Scanner reset()
      This method resets the Scanner.

      void close()
      This method close the Scanner.

      Boolean hasNextInt()
      Returns true if the next token in the Scanner object can be interpreted as an int value.

      Boolean hasNextDouble()
      Returns true if the next token in the Scanner object can be interpreted as an double value.

      Boolean hasNextFloat()
      Returns true if the next token in the Scanner object can be interpreted as an float value.

      Boolean hasNextLong()
      Returns true if the next token in the Scanner object can be interpreted as an long value.

      Boolean hasNext()
      Returns true if the next token in the Scanner has another token in its input.

      Boolean hasNextLine()
      Returns true if there is another line in the input of this Scanner.

      Now you can practice these methods. Look at the following example.

      import java.util.Scanner;
      public class ScannerTest {
             public static void main(String args[]){
        
                    Scanner scn = new Scanner(System.in);
        
                    System.out.print("Please enter your name: ");
                    String name  = scn.next();
        
                    System.out.print("Please enter your id: ");
                    int id = scn.nextInt();
        
                    System.out.println("Your name is " + name);
                    System.out.println("Your id is " + id);
            }
      }
      
      

      This is a simple program that asking you to input your name and id. I have used String name for name and int id for id. When you run the program It asks to enter your name and then id. You can see that I used nextInt() method for it. It means you have to provide int type id. What will happen if you enter String type? It will return an exception when you enter it. We talk more about exceptions in later posts. The exception is InputMismatchException. It means the data type you entered is incorrect as to the program.

      This is a simple calculator program. But I didn't handle the exceptions here. You will be learn it later.


      import java.util.Scanner;
      public class ScannerTest {
             public static void main(String args[]){
                    Scanner scn = new Scanner(System.in);
        
                    System.out.print("Please enter number one: ");
                    float num1  = scn.nextFloat();
                    System.out.print("Please enter number two: ");
                    float num2 = scn.nextFloat();
                    System.out.print("Please enter the operator: ");
                    String op = scn.next();
        
                    switch(op){
                      case "+":
                         System.out.println("Result: " + (num1+num2));
                         break;
                      case "-":
                         System.out.println("Result: " + (num1-num2));
                         break;
                      case "*":
                         System.out.println("Result: " + (num1*num2));
                         break;
                      case "/":
                         System.out.println("Result: " + (num1/num2));
                         break;
                      default:
                         System.out.println("Please enter valid numbers.");
                    }
             }
      }
      
      
      

      Try this program to get idea about Boolean methods.


      import java.util.Scanner;
      public class ScannerTest {
              public static void main(String args[]){
        
                    Scanner scn = new Scanner(System.in);
        
                    System.out.print("Please enter number one: ");
                    boolean num  = scn.hasNextInt();
        
                    if(num==true){
                          System.out.println("You have entered an int");
                    }
                    else
                          System.out.println("You entered value is not an int");
                    }
      }
      
      
      

      hasNextInt() method will return true or false. If true it will print something in this program, else print another thing. You can use this to avoid popup exceptions in simple calculator program.







      Wednesday, November 20, 2013

      String buffer & String builder classes


      What are they ?

      The java.lang.StringBuilder and java.lang.StringBuffer classes are final classes which are used to make a lot of modifications to Strings of characters. They are not immutable classes like String class, you can modify again and again without leaving behind a lot of new unused objects. Both of methods are doing same job but there are few differences between them. 

      Differences between StringBuilder and StringBuffer 



      When to use String, StringBuilder and StringBuffer ?

      Think about String class(Go to String class & String Immutability post). I have said that Strings are immutable. So there is a disadvantage. It creates a heavy garbage. Because it uses more memory. But StringBuilder & StringBuffer classes are not immutable. It use a memory in efficient way. Try this program(In this program I have used append() method. You will learn later on this post. Just think it is like concat() method),

      public class StringTest {
              public static void main(String args[]){
        
                      String s1 = "Nokia";
                      s1.concat(" lumia");
                      System.out.println(s1);
        
                      s1= s1.concat("Lumia");
                      System.out.println(s1);
        
                      StringBuffer s2 = new StringBuffer("Nokia");
                      s2.append("Lumia");
                      System.out.println(s2);
              }
      }
      
      

      Now you can see outputs. Look at the following pictures here. First three pictures for String object creation in String class. In this way it creates two String objects. At last one object is useless without reference and it wastes memory.  






      Following pictures are for object creation in StringBuffer class. In this way, it creates one object and then it is updated. No memory wasting is here.





      Important methods in StringBuffer class

      append()

      This method is used to update the value of a object that invoked the method. You saw it on above post also. This is doing same job that concat() method does. This method can be used not only Strings but also int, char, long, float...etc. 


      public class StringTest {
              public static void main(String args[]){
        
                      StringBuffer s1 = new StringBuffer("java");
                      System.out.println(s1.append("blog"));
       
                      StringBuffer s2 = new StringBuffer("My age: ");
                      System.out.println(s2.append(23));
      
              }
      }
      
      


      reverse()

      This method is used to reverse a String. try this example and see how it works.

      public class StringTest {
              public static void main(String args[]){
        
                     StringBuffer s1 = new StringBuffer("This is an apple");
                     System.out.println(s1.reverse());
              }
      }
      
      


      toString()

      This method is used to return a value of a StringBuffer object that invoked the method call as a String.

      public class StringTest {
             public static void main(String args[]){
        
                    StringBuffer s1 = new StringBuffer("This is an apple");
                    System.out.println(s1.toString());
             }
      }
      
      

      Important methods in StringBuilder class


      delete()

      This method is consist of two parameters(begin and end). It is used to  remove any characters from original method as to the index you provide.

      public class StringTest {
              public static void main(String args[]){
        
                     StringBuilder s1 = new StringBuilder("ABCDEF");
                     System.out.println(s1.delete(2,4));
              }
      }
      
      

      insert()

      This method is used to insert a String into the provided StringBuilder object. There are also two parameters, first one for index(int type) and second one(String type) for characters you want to insert.


      public class StringTest {
              public static void main(String args[]){
        
                      StringBuilder s1 = new StringBuilder("ABCDEF");
                      System.out.println(s1.insert(3," XXX "));
              }
      }
      
      





      Tuesday, November 19, 2013

      String class 02 - Special methods of String class



      In String class there are set of methods. But we are talking about few special methods of String class.

      length()

      In this method you can find the number of characters in your String. It returns the number of characters in a String. 

      public class MethodTest {
            public static void main(String[] args) {
      
                String s1 = "chevrolet";
                String s2 = "CHEVrolet_1234#$&--";
        
                System.out.println(s1.length());
                System.out.println(s2.length());
            }
      }
      
      

      charAt()

      This method is used to find the char at position you want. In this method, you have to provide the index as parameter. Then it will return the character as to the mentioned index.

      public class MethodTest {
            public static void main(String[] args) {
                String s1 = "chevrolet";
                String s2 = "CHEVrolet_1234#$&--";
        
                System.out.println(s1.charAt(5));
                System.out.println(s2.charAt(85));
            }
      }
      

      When you compile this program it will return a character and then a exception(java.lang.StringIndexOutOfBoundsException). We talk about exceptions in later posts. It is very easy to understand this exception, String index out of bounds. You can understand about this only thinking about the meaning of this. There are only 23 characters in String s2. So charAt() method is asking for a index out of bounds.


      substring()

      This method is used to return a part of a String . In this method you can pass only beginning index  or both beginning and ending indexes. Try following example and carefully look about the outputs(Think about ending index and output).

      public class MethodTest {
            public static void main(String[] args) {
      
                String s1 = "0123456789";
        
                System.out.println(s1.substring(2));
                System.out.println(s1.substring(2,5));
            }
      }
      
      

      concat()

      This method is used to join Strings.

      public class MethodTest {
            public static void main(String[] args) {
      
                String s1 = "easy";
                String s2 = "java";
        
                System.out.println(s1.concat(s2));
                System.out.println(s2.concat("se"));
                System.out.println(s1.concat(s2).concat("se"));
            }
      }
      
      

      replace()

      This method is used to replace any character in a String. In this method you have to use old character as first parameter and new character as second parameter.

      public class MethodTest {
            public static void main(String[] args) {
      
                String s1 = "block";
        
                System.out.println(s1);
                System.out.println(s1.replace('b','c'));
                System.out.println(s1);
            }
      }
      
      


      trim()

      This method is used to remove white spaces at both ends in a String. But if there are white spaces in middle, it does not affect.

      public class MethodTest {
            public static void main(String[] args) {
      
                String s1 = "      This is ";
                String s2 = "Nokia Lumia      ";
                String s3 = "1020";
        
                System.out.println(s1 + s2 + s3);
                System.out.println(s1.trim() + s2.trim() + s3.trim() );   
            }
      }
      
      

      indexOf()


      This method is used to return the index of provided character of a String. You can find the indexes of character or word. If there are no choice it will return -1.

      public class MethodTest {
            public static void main(String[] args) {
      
                String s1 = "Chevrolet Tahoe is amazing";
      
                System.out.println(s1.indexOf("v")); //there is one 'v' in s1
                System.out.println(s1.indexOf("e")); //there are 3 'e's in s1
                System.out.println(s1.indexOf('e',3));//start position is 3
                System.out.println(s1.indexOf("x")); //x is not in s1
                System.out.println(s1.indexOf(' ')); //find the index of a space  
                System.out.println(s1.indexOf("is"));//search the index of a word
                System.out.println(s1.lastIndexOf('e'));//fine the last index
            }    
      }
      
      
      equals()

      In this method it will return a Boolean output(true or false). This method is used to check equality of  Strings. In this method there is a special method called equalsIgnoreCase(). This can be used if you want to skip case sensitive. 

      public class MethodTest {
            public static void main(String[] args) {
      
                String s1 = "Nokia";
                String s2 = "Nokia";
                String s3 = "nokia";
                String s4 = "Lumia";
      
                System.out.println(s1.equals(s2));
                System.out.println(s1.equals(s3));
                System.out.println(s1.equals(s4));
                System.out.println(s1.equalsIgnoreCase(s2));
            }
      }
      
      

      toUpperCase() / toLowerCase()

      This is very simple to understand. It changes the characters lower to upper or upper to lower.

      public class MethodTest {
            public static void main(String[] args) {
      
                String s1 = "NOKIA";
                String s2 = "Nokia";
      
                System.out.println(s1.toLowerCase());
                System.out.println(s2.toUpperCase());
           }
      }
      
      

      compareTo()  

      This method is complicated. You have to refer the example to understand this thing more clearly.In this method you have to think about first letter, number of characters, if first letter is same you have to think about second letter so on.


      public class MethodTest {
            public static void main(String[] args) {
      
                String s1 = "apple";
                String s2 = "Apple";
                String s3 = "grape";
                String s4 = "apples";
                String s5 = "axxxx";
      
                System.out.println(s1.compareTo(s1)); //apple=apple
                System.out.println(s1.compareToIgnoreCase(s2)); 
       
                System.out.println(s1.compareTo(s3)); 
                System.out.println(s1.compareTo(s4)); 
                System.out.println(s1.compareTo(s5));
                
                System.out.println(s3.compareTo(s1));
                System.out.println(s3.compareTo(s2));
                System.out.println(s3.compareTo(s4));
                
      
            }
      }
      
      

      toString()

      This method is used to covert number to String. There are 3 types to convert a number to a String. This method is used as one type of them.

      public class MethodTest {
            public static void main(String[] args) {
                Integer x = 100; //Integer is a wrapper class
                String s = x.toString();
        
                System.out.println(s);
                System.out.println(x + 200);
                System.out.println(s + 200);
             }
      }
      
      
      Chained methods


      This is a statement with chain of a method(collection of methods). Try following example to understand about it. Any time left method  is invoked the second method.


      public class MethodTest {
            public static void main(String[] args) {
      
                 String s = "Apples are red";
                 String p = s.toLowerCase().concat(" and green");
        
                 System.out.println("Original String: " + s);
                 System.out.println("Edited String: " + p);
           }
      }
      
      




      Saturday, November 16, 2013

      String class 01 - Strings and String immutability



      What is the String class ?


      You may heard about packages in Java like java.util , java.lang and so on. String class is belongs to java.lang package. You need not to import this package to your program, it is imported by default by the compiler. But if you are not familiar with importing packages it will be a mess for you. Look at the following example to see how to import a package. In this program I have imported java.util.Scanner package. This is used to get a user input to a program(This things will be discussed later).

      import java.util.Scanner;
      
      public class Apple{
       public static void main(String args[]){
        Scanner scn = new Scanner(System.in);
        
        System.out.print("Please enter your name: ");
        String name = scn.nextLine();
        System.out.println("Your name is: " + name);
        
       }
       
      }
      

      I think now it is cleared. Only you need to understand that String class doesn't require any import statements. I will drop down the things in String class as follows.

      • Strings are objects like other objects.
      • They can create instances and they can have constructors and methods.
      • String is final class, so they can't be extended and overridden. 
      • Strings are immutable objects(We talk about this thing later in this post).
      • They can be assigned to String variables.
      • They can be used as parameters in methods and constructors.

      How to create String objects ?

      Really there are two ways to create String objects. 

      First way:         String s = "apple";

      • In this situation String object is 'apple'. 's' is the reference variable to refer 'apple'.
      • It means in this way it is created one object and one reference variable.
      • "apple" will be placed at the heap area(pool) and "s" refers it.
      Second way:     String s = new String ("apple");

      • In this way it creates two objects. Because we have used new keyword.
      • But both are not placed at the pool. "apple" object will be placed at the pool while another object(new String) stay in the normal memory. 

      String immutability

      • Immutability means cannot  be changed. It means once you create a String, its value cannot  be changed again and it cannot be alternated.
      • That is called "String immutability". 
      • But you need to understand that, its reference variable is not immutable. It can be changed(Example program 01).
      This is very important. Look at these examples. I think it is better, try these programs in your machine and compile and run to see the outputs. Then only you can understand, what I'm talking about.

      Example program 01

      public class StringTest1 {
       public static void main(String args[]){
        
        String x = "Nokia";
        x="Lumia";
        
        System.out.println(x);
       }
      }
      

      When you try this you can see the output is "Lumia". So now you may think what happen to "Nokia" String. I can express this program as follow graphical representation.




      1. First I have create a String object "Nokia", its reference variable is x.
      2. Then I created another String object "Lumia" with same reference variable(x).
      3. When you run the program, you can see the output as "Lumia".
      4. You may think what happen to Nokia object.
      5. It is still there in String pool(In the heap) without reference. Because now x is connected with "Lumia" object.

      Example program 02

      public class StringTest2 {
       public static void main(String args[]){
        
        String x = "Nokia";
        String y = x;
        
        y = "Lumia";
        
        System.out.println(x);
        System.out.println(y);
       }
      }
      
      





      1. In this situating first I created String object "Nokia". Its reference variable is "x".
      2. Then I assign "x" variable to another variable called "y".
      3. Now you can see both of variables point to "Nokia" object.
      4. In next line I created another String object "Lumia" which is referenced by "y".
      5. "y" was pointed to "Nokia", but now that connection is over and "y" now points to "Lumia" object.
      6. In this program x will print Nokia and y will print Lumia.

      Example program 03

      public class StringTest3 {
       public static void main(String args[]){
        
        String x = "Nokia";
        x.concat(" Lumia");
      
        String y = x.concat(" Lumia");
        
        System.out.println(x);
        System.out.println(y);
       }
      }
      
      




      1. In this program I have used java concat() method. This method belongs to java.lang.String package. What this method does is, concatenate String to the end of the another defined String.
      2. According to the second picture I have created x.concat("Lumia") String object.
      3. But I did not define a reference variable. Also in this case it is allocated memory in the pool for x.concat("Lumia") object.
      4. Then I assigned a new reference variable called "y" to x.concat("Lumia") object.

      What is String Literal Pool ? 


      String literal pool is a section of heap in the memory. This is pool of Strings which is maintained by JVM(Java Virtual Machine) to store Strings. Once you create a String, JVM checks it already exists in the pool. If it exist, a reference to the instance in the pool returns. If it not exists a new String object will be created. 

      Why Strings are immutable ?

      I said before, Strings are immutable. It is very valuable factor when you think about above situation with String literal pool. That optimization can only be done with String's immutability. If there is no immutability, we cannot talk about String literal pool which helps to reduce memory allocation in the memory and to reduce depending time. 

      Try following program to understand,

      public class StringTest2 {
       public static void main(String args[]){
        
        String s1 = "aaa";
        String s2 = "aaa";
        
        String s3 = new String("bbb");
        String s4 = new String("bbb");
        
        System.out.println(s1==s2);
        System.out.println(s3==s4);  
       }
      }
      
      

      Advantages of immutability 


      • It helps to reduce memory usage(Allowing identical values to be combined together and referenced from various locations in your codes)
      • It simplifies multi-threaded programming(Once you initialized, the value cannot be changed)
      • Safe to work(There is no problem with alternatives)  
      • It simplifies the design and implementation(Re-usability of a String )


      Disadvantages of immutability


      • Less efficient(It creates a heavy garbage collection)


      In this program(example 01), you can see it has a reference variable for Nokia object at first time. But then reference variable changed to Lumia. Then there is a object without reference(Nokia).




        Thursday, November 14, 2013

        Enums





        What is Enum ?

        This is not only an hereditary thing for Java. Most of the languages(C, C#, C++, Ada, Pascal...) use "enums".

        • This is a special data type which is called enum type not a int, long String or other type.
        • The things in the enumerated list are called enums.
        • This was introduced to Java in Java 5.0
        • Enum is related to java.lang.Enum and it is an abstract class.
        • Enums are comparable and serializable.
        What the hell of using this enum ?

        • Very simply we can say, enum is used to represent fixed number of well known values.
        How to declare enums ?

        • Enum declaration is like class declaration. Look at that,
                      enum Fruits { Apple, Mango, Pineapple, Cherry };

        • Enums can be declared as their own class inside another class or outside another class. But when it is outside the class, it cannot be used static, final, abstract,protected or private keywords.
        • Enums can not be declared within a method.
        • In the example I have used semi colon at the end. But it is optional thing, If you want you can use otherwise you can leave it without semi colon.

        Rules for enums

        • Enum types cannot be extended. They are final types(Final subclass of java.lang.Enum).
        • Enum can contain constructors, methods, variables and constant class bodies.
        • Enum constructors can have arguments and they can be overloaded.
        • Enum constants are implicitly public static and final, cannot be changed once created.

        Enum outside  the class






        Enum inside the class






        Enum with constructors

                             enum Apple { RED ("eat"), GREEN ("cook") }

        • Think about above declaration of enum.
        • Enums can have constructors to pass data while creating enum constants.
                             Ex: RED is associated with 'eat'

        • It cannot be invoked an enum constructor directly. It is invoked automatically with the arguments you define after the constant value.
                              Ex: GREEN ("cook")

        • Enum constructors can be overloaded.
        • There can be more than one arguments.
        • Constructors for enum type should be declared as private. 
        Following code is an example for enums with constructors.


        enum Apple {
           RED("drink"), GREEN("cook");  
           
           private final String color;      
           
           Apple(String color) {     
              this.color = color;
           }
           
           String getColor() {      
              return color;
           }
        }
         
        public class EnumTest3 {
         
           public static void main(String[] args) {
            
              for (Apple a : Apple.values()) {
                 System.out.println(a +" Apples are used to "+ a.getColor());
              }
           }
        }
        
        



        Tuesday, November 12, 2013

        Constructors


        This is the 17th post on my blog. This post had to be posted before. But I tried much to finish it quickly as I can. Enjoy with constructors. 


        What is the constructor?

        This is another valuable thing in programming. You may heard about constructor companies. What they are doing is constructing somethings means building, roads or whatever. Likewise in programming there are also constructors. But they don't creating that buildings or roads. When you creating objects, constructors are always invoked. If you use 'new' keyword, constructors are running. 

        Rules of constructor

        • Every class even abstract classes must have a constructor. There can be one or more.
        • Interfaces don't have constructors.
        • Constructor name should be exactly same as the class name.
        • Constructor does not have a return type.
        • Constructors can use any access modifiers (private, protected,default or public).

        Default constructor

        • 'The default constructor' is created by default by the compiler if you don't create any constructors in your class, but if the programmer wants to create a constructor, he can type it as,  
                           Class ConstructorTest{
                                   ConstructorTest() {  }
                           }

        • The default constructor is always no-args constructor. But no-arg constructor is not necessarily the default.
        • Every constructor has, as its first statement either this() or super()
                           this()   -   overloaded constructor
                           super()   -   superclass constructor  

        • Default constructor provide no-arg call to super(). It means if you don't type any constructor, it will be generated a default constructor and it create no-arg call to super().
        • Default constructor is provide the default values for objects. They may be 0 or null or etc.


        public class DefaultCon {
             int id;
             float avg;
             double d;
             String name;
                   
             void test(){
                  System.out.println(id + " | " + name + " | " + avg + " | " + d);
             }
                     
             public static void main(String args[]){
                  DefaultCon obj1 = new DefaultCon();
                  obj1.test();
             }
        } 
        

        In the above section we have talked about default constructor, super() and such like these things. Following shows the auto generated code for what you typed code.




        Other constructors with parameters


        public class OtherCon {
             int id;
             String name;
          
             OtherCon(int id, String name){
                  this.id=id;
        
                  this.name=name;
             }
         
             void display(){
                  System.out.println(id + "   " + name);
             }
         
             public static void main(String args[]){
                  OtherCon obj1 = new OtherCon(1,"John");
                  OtherCon obj2 = new OtherCon(2,"Adam");
          
                  System.out.println("ID  Name");
                  obj1.display();
                  obj2.display();
             }
        }
        


        Constructor Overloading


        public class OverloadingCon {
             String name;
             int marks;
         
             OverloadingCon(String name, int marks){
                  this.marks=marks;
                  this.name=name;
             }
         
             OverloadingCon(String name){
                  this.name=name;
             }
         
             void display(){
                  System.out.println(name+ "  " + marks);
             }
         
             public static void main(String args[]){
                  OverloadingCon obj1 = new OverloadingCon("Adam",80);
                  OverloadingCon obj2 = new OverloadingCon("John");
          
                  obj1.display();
                  obj2.display();
             }
         }
        
        


        Constructor chaining

        • This occurred when a class inherits another class.
        • You know that subclass inherits the things in superclass. 
        • When you create an object from subclass, its constructor is invoked.
        • But thing is, the super class constructor needs to be invoked because of inheritance.
        • It is done by super() keyword and it can be done as follows.


        class Fruit{
             String type; 
                   
             Fruit(String type){
                 this.type=type;
             }
        }    
        
        
        class Apple extends Fruit{
        
             String color;
             Apple(String type, String color){
                  super(type); 
                  this.color=color;
             }
         
             void display(){
                  System.out.println("Fruit type is: " + type);
                  System.out.println("Fruit color is: " + color);
             }
        }   
        public class ConstructorChain {
        
             public static void main(String args[]){
                   Apple obj = new Apple("Sweet", "Red");
                   obj.display();
             }
        }
        
        
        

        Click here to download above codes




        Wednesday, November 6, 2013

        Var-args (Variable arguments)



        Before you learn about Var-args it is better to understand the different about parameters and arguments. Following example demonstrate a use of these things. 




        Now you can see, what the arguments are and what the parameters are.
        • Arguments are the things you specify between the parentheses you are invoking a method.
        • Parameters are the things the method's signature that in indicate what the method must receive when it's invoked.
        Var-args standards for Variable Arguments. It means in this section we are going to talk about special arguments called variable arguments (Var-args).This is introduced in Java version 5.0.This concept allows you to create methods that can take a variable number of arguments.




        Rules for var-args


        • You must mention the type of the argument of the var-args parameter that your method can receive.
        • You must type the var-arg method as I mentioned above (var-args parameter…name of the array). 
          • Void getName ( int… x );
          • Void doThing ( Vehicle… vhl );
        • There can be other parameters also uses a var-args.
        • The var-args must be the last parameter in the method’s signature.
        • You can have only one var-args in a method. 
        There are examples for legal and illegal declarations.



        Legal 



            void getName(int… x);

          void getName(float f,int… x);

          void getName(char c,double d,int.. x);
          void getName(Vehicle… vhl);



        Illegal



           void getName(int x…); //syntax error

          void getName(int… x,float f); //var-args must be placed in last

          void getName(int… x,char… c); //only one var-arg is allowed



        Try following example to understand about var-args.





        Click here to download this java file

        In this program I have used Enhanced for loop. For more go to "Loops in Java with examples" post.