Page 348 - CITS - Computer Software Application -TT
P. 348

COMPUTER SOFTWARE APPLICATION - CITS



           2  String s=new String(ch);

           Java String cla s provides a lot of methods to perform operations on strings such as compare(), concat(), equals(),
           split(), length(), replace(), compareTo(), intern(), substring() etc.
           The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
           What is String in Java?

           Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of
           characters. The java.lang.String class is used to create a string object.
           How to create a string object?

           There are two ways to create String object:
           1  By string literal
           2  By new keyword
           1  String Literal
           Java String literal is created by using double quotes.
           For example:

           1  String s=”welcome”;
           Why Java uses the concept of String literal?
           To make Java more memory efficient (because no new objects are created if it exists already in the string constant
           pool).
           2  By new keyword
              1  String s=new String(“Welcome”);//creates two objects and one reference variable
           In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal “Welcome” will
           be placed in the string constant pool. The variable s will refer to the object in a heap (non-pool).
           Java String Example
           StringExample.java
           public class StringExample{

           public static void main(String args[]){
           String s1=”java”;//creating string by Java string literal
           char ch[]={‘s’,’t’,’r’,’i’,’n’,’g’,’s’};
           String s2=new String(ch);//converting char array to string
           String s3=new String(“example”);//creating Java string by new keyword

           System.out.println(s1);
           System.out.println(s2);
           System.out.println(s3);
           }}

           Output:
           java













                                                           335
                               CITS : IT&ITES - Computer Software Application - Lesson 85 - 93
   343   344   345   346   347   348   349   350   351   352   353