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.






      Monday, November 4, 2013

      OOP concepts




      Before talking about some lessons ( Var-Agrs, Enums...etc ), I think it is better to talk about Object Oriented Programming ( OOP )  in Java. This part is the core of Java or any other object oriented programming language. In this section we talk about three things.
      1. Encapsulation
      2. Inheritance
      3. Polymorphism

      Encapsulation



      Encapsulation is like this. Protected data can be seen using this concept.
      Encapsulation is the technique of binding data and its corresponding methods into a single unit. This is the combination of data hiding and abstraction. 

      • This can be seen as protecting data in programming.
      • When you declared a field with private access, it can't be accessed anyone from outside of the class. Encapsulation provide a access to these private fields via public methods.
      • This can be declared as a protective gate.
      • get and set methods are used to access the protected fields. 

      Following example will describe about encapsulation.

      public class Student {
       
         private int id;
         private String name;
       
         public String getName() {
            return name;
         }
         public void setName(String name) {
            this.name = name;
         }
         public int getId() {
            return id;
         }
         public void setId(int id) {
            this.id = id;
         }
      }
      
      public class Test{
       
         public static void main(String args[]){
        
            Student obj = new Student();
            obj.setId(1);
            obj.setName("John");
        
            System.out.println("ID : " + obj.getId());
            System.out.println("Name : " + obj.getName());
         }
      }
      
      

      • In this example you can see there are two classes called Student and Test.
      • You can see two variables called name and id with private access modifier. It means these variables are visible only with in the class.
      • But in this program we have used them in another class called Test  and we have accessed it.
      • It is done by get( ) and set( ) methods. set method is used to set the value and get method is used to call the value.
      • In set method it is used a keyword called 'this'. It is used to say "private String name" is equal to "public void setname (String name)".

      Advantages of Encapsulation.

      • Encapsulated code is more flexible, maintainable and extensible.
      • The field of a class can be made read only or write only.
      • Allows admin to control who can access what.
      • It allows to change one part of the code without having any effects to the other parts. 
      CLICK HERE to download a program with encapsulation and user inputs.



      Inheritance 




      Try it yourself. If you can also your father can do it definitely. 
      • This concept can be seen in real world. It is like the relationship between parents and children. 
      • Inheritance allows us to create the bond between super classes (parents) and subclasses (children).
      • We can inherit from class of interface. If inherit from class, we use extends keyword and if it is a interface, we use implements keyword.

      Inheritance in classes

      • This can be understood using following example. 
      • There are four cars in  below picture. 
      • These are types of cars.
      • You can create a super class called "Car" and then you can create other sub-classes "Micro_car", "Hatchback" and "Sedan".
      • These sub classes are inherited by Car class.

      class Car{  }
      
      class Micro_car extends Car { }
      class Hatchback extends Car { }
      class Sedan extends Car { }
      
      


      Inheritance in interfaces

      • We talk more about this thing in later posts. But now I will give simple example to understand about inheritance in interfaces.
      • We use implements keyword to do this.

      public interface DriveCar{
         void accelerate( );
         void stop( );
      }
      
      public class Car implements DriveCar{
         void accelerate( ) { /*implementations*/ }
         oid stop( ) { /*implementations*/ }
      }
      
      

      IS-A relationship

      • IS-A refers inheritance or implementation.
      • Lets get a real life example.


      • Mitsubishi Pajero 2014 is a latest SUV product of Mitsubishi motors.
      • It is SUV range vehicle. 
      • There are 4 types in 2014 model.
        1. GLX
        2. GLX-R
        3. VRX
        4. EXCEED

      • Now you can say GLX is a type of Mitsubishi Pajero.
      • Now you can say GLX-R is a type of Mitsubishi Pajero.
      • Now you can say VRX is a type of Mitsubishi Pajero.
      • Now you can say EXCEED is a type of Mitsubishi Pajero.
       Then again you can say,
      • Mitsubishi Pajero is a SUV.
      It means SUV is a super parent then Pajero is a parent when other four types are children.



      If you want to create a classes for this example, it can be done like this.

      public class Suv {  }
      public class Mitsubishi_Pajero extends Suv {  }
      public class Glx extends Mitsubishi_Pajero {  } 
      public class Glx_R extends Mitsubishi_Pajero {  }
      public class Vrx extends Mitsubishi_Pajero {  }
      public class Exceed extends Mitsubishi_Pajero {  }
      
      

      Generalization


      Generalization is the process of casting sub classes into super classes. Think about above example.




      Specialization


      This is the up side down process of generalization. Look at this figure. 




      Has-A Relationship 

      • Has-A relationship can be understood as a type of inheritance and this is also known as Composition and Aggregation.
      • it means an instance of one class has a reference to another instance of another class or same class.
      • Lets get a real life example.
      Car IS-A vehicle and it HAS-A Engine.

      class Vehicle {  }
         class Car{
             Engine obj = new Engine(); 
         }
         class Engine {  }
      
      

      Aggregation

      • This means a directional association between objects.
      • When an object has another object, we can define a direction between then to specify which object contains another object.
      • This method is useful for code re-usability. 
      Ex: Car has Air bags.
            But a car can exist without airbags.


      Composition

      • A restricted aggregation is called composition.
      • It means objects are associated strongly.
      • There is a composition when an object( first object ) contains another object and that contained object can't exist without first object.
      EX: Class contain students.
            A student cannot exist without a class.

      Why use Inheritance ?

      • Promote code reuse
      • To use with Polymorphism 


      Polymorphism






      Now you may think what is he gonna do now with these type of pictures. You know that this is Vanessa Hudgens dressed with different costumes. She looks different with different  costumes. It means same person with different kits.

      • Polymorphism also means many forms of a one object.
      • When programming you may have to use same method in several times in different classes with different parameters. 
      • But you can think it cannot be done, because we have used that method at a one time.
      • But it is not real with OOP, Java allows you to create same method in several times in different classes with different parameters. 
      • Method name is like Vanessa Hudgens. But her costumes can be changed. ( inner and outer).
      • I have mentioned that polymorphism is a theory  that is giving you to use same methods again and again.
      • This can be done in two ways.
        1. Method overriding
        2. Method overloading

        Reference variables

        Before talking about these two things, it is necessary to talk about Reference variable. You need to understand this theory before talking about overloading or overriding. A variable that refers the class name is known as reference variable. Reference variable is the only way to access objects.You may remember how to create an objects.
                      
                          Apple obj = new Apple( );

        You can divide that statement into two steps.

                                            Apple obj;
                          obj = new Apple( );

        The first line shows you how to create Apple type reference variable. Then the reference variable is converted into an object. 


        Apple( ) is a constructor(You will be learnt about constructors later). Generally it does not return anything. But you can see we don't use void keyword. Thing is this, really a constructor return something called "class object" (object of the class). It has not a name. So it is called "Anonymous object". Then this anonymous object is assigned to reference variable(obj). 





        There are some rules to define reference variables.
        • A reference variable can be only one type and it can be declared once. That type never changed.
        • A reference variable can refer to a sub-type object same type or a super type of the object.
        • A reference variable type determine which methods can be called.

        • You can see, when creating objects left side define as a reference type (class type/super type) and right side define as a object type.
        • When method calling it should be considered about object type.
        • When instance variable access then consider about reference type.
        • Object type determines which overridden method is used at run-time.
        • Reference type determine which overloaded method will be used at compile time.

        Reference variable casting

        There are two types of casting.
        1. Upward casting
        2. Downward casting

        Upward casting (Automatic type conversions)

        Following example demonstrate how to do upward casting in Java.


        class Fruit { }
        
        class Mango extends Fruit { }
        
        public class Apple {
           public static void main(String args[]) {
              Mango mango = new Mango();
              Fruit fruit = mango; // upcast with no explicit cast
              Fruit fruit2 = (Fruit) mango; // upcast with explicit cast
           }
        }
        
        


        This conversion can be done only if the following conditions are true.
        • Two types should be compatible (int/float, int/long).
        • Destination type should be larger than the source type.

        Downward casting (Explicit type conversions)


          


        This type of conversions is useful if you want to create conversion between incompatible types. What is to be done if you want to convert long value to byte value ? We have talked about data type casting in Data types in Java post. In this section we are gonna talk about object casting. This is not like upward casting. You should specify the target type.

        In above example you will be able to see a ClassCastException exception when you run the program.

        Method overriding

        • In this type you can redefine method with limited scope.
        • It means when you override a method, method name, arguments and return type should be same as overridden method.  
        • final, static and private methods cannot be overridden.
        • Only inherited method may be overridden.
        • Overriding method cannot be less public than overridden method.
        You can try this example to understand about method overriding.


        class Apple {
           void eat() {
              System.out.println("Apple");
           }
        }
        
        class RedApple extends Apple {
           void eat() {
              System.out.println("Red Apple");
           }
        }
        
        public class Fruits {
           public static void main(String args[]) {
        
              Apple apple = new Apple();
              Apple apple2 = new RedApple();
        
              apple.eat();
              apple2.eat();
           }
        }
        

        Method overloading 

        • This is little bit different with overriding. 
        • Overloaded methods have the same name and must have different argument list. Argument may differ in data type or number or both.
        • The return type of the overloaded methods can be different or same. If argument list is different, return types are also different. 
        • They may have different access modifiers.
        • May throw different exceptions( Later on we talk about Exceptions ).

        class Processor{
           void showType(){
                System.out.println("Intel and AMD are the popular.");
           }
        }
        
        class Intel extends Processor{
           void showType(){
                System.out.println("Intel is leading vendor.");
           }
           void showType(String gen){
                System.out.println("Intel has " + gen + " generations.");
           }
        }
        
        public class MotherBoard{
           public static void main(String args[]){
              Processor obj1 = new Processor();
              Processor obj2 = new Intel();
              Intel obj3 = new Intel();
        
              obj1.showType();
              obj2.showType();
              obj3.showType("four");
           }
        }