Tuesday, August 1, 2023

Java String

 

Java String

String is Collection of Character.

The String class supports several constructors. To create an empty String, you call the default constructor.

·       Example:

String s= new String();

·       Example

char chars[ ] = {'a','b','c'};

String  a = new String(chars);

·       Example

char chars[ ] = {'a','b','c','d','e','f'};

String s=new String(chars,2,3);


Example 1:

//Converting character to string

class MakeString{

      public static void main(String args[ ]){

             char c[]={'j','a','v','a'};

             String s1 = new String(c);

            String s2 = new String(s1);

           System.out.println(s1);

     System.out.println(s2);

      }

}

Output

 


String Concatenation

Java does not allow operators to be applied to String object. The one exception to this rule is the + operator, which concatenates two strings, producing a Strings object as the result. This allows you to chain together a series of + operations.

v Example

String age = "9";

String s="He is"+age+"years old.";

System.out.println(s);

 

] The output appears as given below:

"He is 9 years old".

 

       One practical use of string concatenation is found when you are creating very long strings.Instead of letting long string wrap around within your source code, you can break them into smaller pieces, using the + to concatenate them.

 

String s = "four:"+2+2;

System.out.println(s);

This fragment displays

Four:22

rather than the

four:4

Because operator precedence causes the concatenation of "four" with the string equivalent of 2 to take place first. This result in then concatenated with the string equivalent of 2 a second time. To complete the integer addition first, four must use parentheses, like this:

String s = "four:" +(2+2)

Now s contains the string "four:4".

class ConCat{

public static void main(String args[]){

String longStr="This could have been"+"a very long line that would have"+"Wrapped arround.";

int age=9;

String s="He is"+age+"years old.";

String a="four:"+2+2;

String b="four:"+(2+2);

System.out.println(longStr);

System.out.println(s);

System.out.println(a);

System.out.println(b);

}

}

Output

 


String Methods

The String class provides a number of methods to compare and search strings. Some important methods in this class are are listed in the table given below:

Method

Use

length()

Number of characters in String.

charAt()

The char at a location in the String

getChars(),getBytes()

Copy chars or bytes into an external array.

toCharSArray()

produces a char[]containing the characters in the strings.

equals(), equalsIgnoreCase()

An equality check on the contents of the two strings.

compareTo()

Result is negative,zero or positive depending on the lexicographical ordering of the String and the argument. Uppercase and Lowercase are not equal.

regionMatches()

Boolean result indicates whether the region matches.

startsWith()

Boolean result indicates  if theString starts with the argument..

endsWith()

Boolean result indicates if the argument is a suffix.

indexOf(),lastIndexOf()

Returns -1 if the argument is not found within this String,otherwise returns the index where the argumentstarts. last IndexOf() searches backwards from end.

substring()

Returns a new String object containing the specified character set.

 

 

Method

Use

Concat()

Returns a new String object containing the original String's characters followed by the characters in the argument.

Replace()

Returns a new String object with the replacements made. Uses the old String if no match is found.

To LowerCase(),to UpperCase()

Returns a new String object with the white space removed from each end.Uses the old String if no changes need to be made.

valueOf()

Returns a String containing a character representation of the argument.

Intern()

Produces one and only one String handle for each unique character sequence.

 Example 2:

//String Equals() Method

class EqualsDemo{

public static void main(String args[]){

String s1="Hello";

String s2="Hello";

String s3="Good bye";

String s4="HELLO";

System.out.println(s1+" equals "+s2+" is "+s1.equals(s2));

System.out.println(s1+" equals "+s3+" is "+s1.equals(s3));

System.out.println(s1+" equals "+s4+" is "+s1.equals(s4));

}

}

Output

 


Example 3:

//Demonstrate indexof() and lastIndexof()

class IndexOfDemo {

    public static void main(String[] args) {

        String s="Now is the time for all good men "+"to come to the aid of their country.";

        System.out.println(s);

        System.out.println("indexOf(t)="+s.indexOf('t'));

        System.out.println("lastIndexOf(t)="+s.lastIndexOf('t'));

        System.out.println("indexOf(the)="+s.indexOf("the"));       System.out.println("lastIndexOf(the)"+s.lastIndexOf("the"));

        System.out.println("indexOf(t,10)="+s.indexOf('t',10));

        System.out.println("lastIndexOf(t,60)="+s.lastIndexOf('t',60));

       System.out.println("indexOf(the,10)="+s.indexOf("the",10)) ;

       System.out.println("lastIndexOf(the,60)="+s.lastIndexOf("the",60));

    }

}

Output

 


Example 4:

//Demonstrate toUpperCase() and toLowerCase()

class ChangeCase{

public static void main(String args[])

{

String s="This is a test.";

System.out.println("Original:"+s);

String upper=s.toUpperCase();

String lower=s.toLowerCase();

System.out.println("Uppercase:"+upper);

System.out.println("Lowercase:"+lower);

}

}

Output

 


String Buffer:

String Buffer is a peer class of String that provides much of the functionality of strings.

As you know, String represents fixed-length, immutable character sequences. In contrast,

String Buffer represents grow able and write able and write able character sequence. String buffer may have characters and subs strings  inserted in the middle or appended to the end.

String buffer Constructors

         String Buffer defines these three constructors:

o  String Buffer()

o  String Buffer(int size)

o  String Buffer(String str)

String Buffer Methods:

Method

Use

toString()

Creates a String from this String Buffer.

length()

Returns the number of characters in the String Buffer.

capacity()

Returns current number of spaces allocated

ensureCapacity()

makes the String Buffer hold at least the desired number of spaces.

setLength()

Truncates or expands the previous character string. If expanding, pads with nulls.

charAt()

Returns the char at that location in the buffer.

setCharAt()

Modifies the value at that location.

getChars()

Copy chars into an external array. There is no get Bytes()as in String.

append()

The argument is converted to a string and appended to the end of the current buffer, increasing the buffer if necessary.

insert()

The second argument is converted to a string and inserted into the current buffer beginning at the offset. The size of the buffer is increased, if necessary.

reverse()

The order of the characters in the buffer is reversed.


StringBuffer

Example 1:

Program to illustrate StringBuffer class by Manipulating the String

import java.lang.*;

class Manipulate

{

public static void main(String args[])

{

StringBuffer s1=new StringBuffer("Object Language");

System.out.println("\n Original String :"+s1);

System.out.println("\n Length of the String:"+s1.length());

for(int i=0;i<s1.length();i++)

{

int p=i+1;

System.out.println("Character at Position "+p+"is:"+s1.charAt(i));

}

String s2=new String(s1.toString());

int pos=s2.indexOf(" Language");

System.out.println("Position of Language:"+pos);

s1.insert(pos," Oriented");

System.out.println("\n Modified String:"+s1);

s1.setCharAt(6,'-');

System.out.println("\nString Now:"+s1);

s1.append("improves security");

System.out.println("\nAppended String:"+s1);

}

}

Output

 


0 comments:

Post a Comment