World's most popular travel blog for travel bloggers.
Showing posts with label java programming. Show all posts
Showing posts with label java programming. Show all posts

String Handling

String is probably the most commonly used class in java library. String class is encapsulated under java.lang package. In java, every string that you create is actually an object of type String. One important thing to notice about string object is that string objects are immutable that means once a string object is created it cannot be altered.

What is an Immutable object?

An object whose state cannot be changed after it is created is known as an Immutable object. String, Integer, Byte, Short, Float, Double and all other wrapper classes objects are immutable.

Creating an Immutable class

public final class MyString
{
 final String str;
 MyString(String s)
 {
  this.str = s;
 }
 public String get()
 {
  return str;
 }
}
In this example MyString is an immutable class. MyString's state cannot be changed once it is created.

Creating a String object

String can be created in number of ways, here are a few ways of creating string object.

1) Using a String literal

String literal is a simple string enclosed in double quotes " ". A string literal is treated as a String object.
String str1 = "Hello";

2) Using another String object

String str2 = new String(str1);

3) Using new Keyword

String str3 = new String("Java");

4) Using + operator (Concatenation)

String str4 = str1 + str2;
or,
String str5 = "hello"+"Java";

Each time you create a String literal, the JVM checks the string pool first. If the string literal already exists in the pool, a reference to the pool instance is returned. If string does not exist in the pool, a new string object is created, and is placed in the pool. String objects are stored in a special memory area known as string constant pool inside the heap memory.

String object and How they are stored

When we create a new string object using string literal, that string literal is added to the string pool, if it is not present there already.
String str= "Hello";

And, when we create another object with same string, then a reference of the string literal already present in string pool is returned.
String str2=str;

But if we change the new string, its reference gets modified.
str2=str2.concat("world");


Concatenating String

There are 2 methods to concatenate two or more string.
  1. Using concat() method
  2. Using + operator

1) Using concat() method

string s = "Hello";
string str = "Java";
string str2 = s.concat(str);
String str1 = "Hello".concat("Java");    //works with string literals too.

2) Using + operator

string str = "Rahul";
string str1 = "Dravid";
string str2 = str + str1;
string st = "Rahul"+"Dravid";

String Comparison

String comparison can be done in 3 ways.
  1. Using equals() method
  2. Using == operator
  3. By CompareTo() method

Using equals() method

equals() method compares two strings for equality. Its general syntax is,
boolean equals (Object str)
It compares the content of the strings. It will return true if string matches, else returns false.
String s = "Hell";
String s1 = "Hello";
String s2 = "Hello";
s1.equals(s2);    //true
s.equals(s1) ;   //false

Using == operator

== operator compares two object references to check whether they refer to same instance. This also, will return true on successful match.
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(s1 == s2)     //true
test(s1 == s3)      //false
Reason:
Its because we are creating a new object using new operator, and thus it gets created in a non-pool memory area of the heap. s1 is pointing to the String in string pool while s3 is pointing to the String in heap and hence, when we compare s1 and s3, the answer is false.

By compareTo() method

compareTo() method compares values and returns an int which tells if the string compared is less than, equal to or greater than the other string. It compares the String based on natural ordering i.e alphabetically. Its general syntax is,
int compareTo(String str)
String s1 = "Abhi";
String s2 = "Viraaj";
String s3 = "Abhi";
s1.compareTo(S2);     //return -1 because s1 < s2 
s1.compareTo(S3);     //return 0 because s1 == s3 
s2.compareTo(s1);     //return 1 because s2 > s1
In the previous chapter of inheritance we have learnt about the different rules of method overriding, In this chapter we will be learning about the super keyword –

3 ways of Using Super Keyword :

Super is used to refer the immediate parent of the class. Whenever we create an object of the child class then the reference to the parent class will be created automatically.
We can user super keyword by using three ways –
  • Accessing Instance Variable of Parent Class
  • Accessing Parent Class Method
  • Accessing Parent Class Class Constructor

Way 1 : Accessing Instance Variable of Parent Class using Super

package com.c4learn.inheritance;

public class ParentClass {
    int ageClass = 100;
 
    public static void main(String[] args) {
        ChildClass c1 = new  ChildClass();
        c1.display();
        
    }
}

class ChildClass extends ParentClass{
    int ageClass = 200;

    public void display() {
 System.out.println("ageClass : " + ageClass); 
    }
}
Output of the Program
ageClass : 200
Consider the above example –
  1. We have same variable declared inside the parent class as well as in child class.
  2. Whenever we try to access the variable using the object of child class, always instance variable of child will be returned.
Suppose we want to access the the same variable from the parent class then we can modify the display() method as below –
public void display() {
     System.out.println("ageClass : " + super.ageClass);
}

Way 2 : Accessing Parent Class Method using Super

package com.c4learn.inheritance;

public class ParentClass {
    int ageClass = 100;
 
    public int getValue() {
     return 20;
    }
    
    public static void main(String[] args) {
        ChildClass c1 = new  ChildClass();
        c1.display();        
    }
}

class ChildClass extends ParentClass{
    int ageClass = 200;

    public int getValue() {
     return 50;
    }
    
    public void display() {
      System.out.println("result : " + super.getValue());
    }
}

Output :

result : 20
In this example we have same method declared inside parent and child class.
public void display() {
     System.out.println("result : " + super.getValue());
}
In order to execute the parent method from the child class we need to use super keyword.

Way 3 : Accessing Parent Class Constructor using Super

We will be learning super keyword and constructor in more details in the next chapter.

Method Overriding

Declaring a method in sub class which is already present in parent class is known as method overriding. Overriding is done so that a child class can give its own implementation to a method which is already provided by the parent class. In this case the method in parent class is called overridden method and the method in child class is called overriding method. In this guide, we will see what is method overriding in Java and why we use it.

Method Overriding Example

Lets take a simple example to understand this. We have two classes: A child class Boy and a parent class Human. The Boy class extends Human class. Both the classes have a common method void eat(). Boy class is giving its own implementation to the eat() method or in other words it is overriding the eat() method.
The purpose of Method Overriding is clear here. Child class wants to give its own implementation so that when it calls this method, it prints Boy is eating instead of Human is eating.
class Human{
   //Overridden method
   public void eat()
   {
      System.out.println("Human is eating");
   }
}
class Boy extends Human{
   //Overriding method
   public void eat(){
      System.out.println("Boy is eating");
   }
   public static void main( String args[]) {
      Boy obj = new Boy();
      //This will call the child class version of eat()
      obj.eat();
   }
}
Output:
Boy is eating

Advantage of method overriding

The main advantage of method overriding is that the class can give its own specific implementation to a inherited method without even modifying the parent class code.
This is helpful when a class has several child classes, so if a child class needs to use the parent class method, it can use it and the other classes that want to have different implementation can use overriding feature to make changes without touching the parent class code.

Method Overriding and Dynamic Method Dispatch

Method Overriding is an example of runtime polymorphism. When a parent class reference points to the child class object then the call to the overridden method is determined at runtime, because during method call which method(parent class or child class) is to be executed is determined by the type of object. This process in which call to the overridden method is resolved at runtime is known as dynamic method dispatch. Lets see an example to understand this:
class ABC{
   //Overridden method
   public void disp()
   {
 System.out.println("disp() method of parent class");
   }    
}
class Demo extends ABC{
   //Overriding method
   public void disp(){
 System.out.println("disp() method of Child class");
   }
   public void newMethod(){
 System.out.println("new method of child class");
   }
   public static void main( String args[]) {
 /* When Parent class reference refers to the parent class object
  * then in this case overridden method (the method of parent class)
  *  is called.
  */
 ABC obj = new ABC();
 obj.disp();

 /* When parent class reference refers to the child class object
  * then the overriding method (method of child class) is called.
  * This is called dynamic method dispatch and runtime polymorphism
  */
 ABC obj2 = new Demo();
 obj2.disp();
   }
}
Output:
disp() method of parent class
disp() method of Child class
In the above example the call to the disp() method using second object (obj2) is runtime polymorphism (or dynamic method dispatch).
Note: In dynamic method dispatch the object can call the overriding methods of child class and all the non-overridden methods of base class but it cannot call the methods which are newly declared in the child class. In the above example the object obj2 is calling the disp(). However if you try to call the newMethod() method (which has been newly declared in Demo class) using obj2 then you would give compilation error with the following message:
Exception in thread "main" java.lang.Error: Unresolved compilation 
problem: The method xyz() is undefined for the type ABC

Rules of method overriding in Java

  1. Argument list: The argument list of overriding method (method of child class) must match the Overridden method(the method of parent class). The data types of the arguments and their sequence should exactly match.
  2. Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the overridden method of parent class. For e.g. if the Access Modifier of parent class method is public then the overriding method (child class method ) cannot have private, protected and default Access modifier,because all of these three access modifiers are more restrictive than public.
    For e.g. This is not allowed as child class disp method is more restrictive(protected) than base class(public)
    class MyBaseClass{
       public void disp()
       {
           System.out.println("Parent class method");
       }
    }
    class MyChildClass extends MyBaseClass{
       protected void disp(){
          System.out.println("Child class method");
       }
       public static void main( String args[]) {
          MyChildClass obj = new MyChildClass();
          obj.disp();
       }
    }
    Output:
    Exception in thread "main" java.lang.Error: Unresolved compilation 
    problem: Cannot reduce the visibility of the inherited method from MyBaseClass
    However this is perfectly valid scenario as public is less restrictive than protected. Same access modifier is also a valid one.
    class MyBaseClass{
       protected void disp()
       {
           System.out.println("Parent class method");
       }
    }
    class MyChildClass extends MyBaseClass{
       public void disp(){
          System.out.println("Child class method");
       }
       public static void main( String args[]) {
          MyChildClass obj = new MyChildClass();
          obj.disp();
       }
    }
    Output:
    Child class method
  3. private, static and final methods cannot be overridden as they are local to the class. However static methods can be re-declared in the sub class, in this case the sub-class method would act differently and will have nothing to do with the same static method of parent class.
  4. Overriding method (method of child class) can throw unchecked exceptions, regardless of whether the overridden method(method of parent class) throws any exception or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. We will discuss this in detail with example in the upcoming tutorial.
  5. Binding of overridden methods happen at runtime which is known as dynamic binding.
  6. If a class is extending an abstract class or implementing an interface then it has to override all the abstract methods unless the class itself is a abstract class.

Super keyword in Method Overriding

The super keyword is used for calling the parent class method/constructor. super.myMethod() calls the myMethod() method of base class while super() calls the constructor of base class. Let’s see the use of super in method Overriding.
As we know that we we override a method in child class, then call to the method using child class object calls the overridden method. By using super we can call the overridden method as shown in the example below:
class ABC{
   public void myMethod()
   {
 System.out.println("Overridden method");
   }    
}
class Demo extends ABC{
   public void myMethod(){
 //This will call the myMethod() of parent class
 super.myMethod();
 System.out.println("Overriding method");
   }
   public static void main( String args[]) {
 Demo obj = new Demo();
 obj.myMethod();
   }
}
Output:
Class ABC: mymethod()
Class Test: mymethod()