Day11: Using "String" Class

 Using String Class

In java "String" is used one of the most commonly used class and it provides a bunch of useful method for performing various operation. But most of the string class method are non-static by nature so to call these method create class of the object.

class Student
{
     int roll;
     char grade;
     float percentage;
    public static void main(String [] args)
    {
        Student S = new Student();
     }   
   // OR
    //Student S;    //Object Reference
    //S = new Student();
}

    
Output: When we Run the above program :



class Test
{
    public static void main(String[] args)
    {
        String S1;
        S1 = new String("Bhopal");
        String S2;
        S2 = new String("Bhopal");
        System.out.println(S1);
        System.out.println(S2);
        System.out.println(S1==S2); //false because it's adresses are not equal
    }
}


Output : 



String Method : 

#Useful String Method
    (1) int length() :
  •  It is an predefined instance method(non - static) of string class.
  • It takes no argument and return the length of the string.
  • Since it is an instance method we have to call it using object reference of the string class.
class Test
{
    public static void main(String[] args)
      {
        String S1;
        S1 = new String("Bhopal");
        String S2;
        S2 = new String("Goa");
        int x,y;
        x = S1.length();
        System.out.println("S1 is "+S1);
        System.out.println("It's length is "+x);
        y = S2.length();
        System.out.println("S2 is "+S2);
        System.out.println("It's length is "+y);
        }
}

OUTPUT : 
        S1 is Bhopal
        It's length is 6
        S2 is Goa
        Its length is 3



Comments

Popular posts from this blog

What does System.out.printf( "%-15s%03d\n", s1, x) do?

Day22 : Object Initialization

Day 20 : Double Dimensional Array