Unit-5 String Class in Java

Example : MakeString

import java.io.*;
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 : MakeString

String Concatenation in Java…

Example : ConCat

import java.io.*;
class ConCat
{
public static void main(String args[])
{
String longStr="This could have been"+"a very long line that would have"+"Wrapped around.But String concatenation"+"Prevents this.";
System.out.println(longStr);
}
}
Output : ConCat

String Methods in Java….

Example 1 : EqualsDemo

import java.io.*;
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 : EqualsDemo

Example 2 : IndexOfDemo

import java.io.*;
class IndexOfDemo
{
public static void main(String args[])
{
String s="Now is the time for the 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("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 : IndexOfDemo

Example 3 : ChangeCase

import java.io.*;
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 : ChangeCase

StringBuffer Methods in Java…

Example : Manipulate

import java.io.*;
class Manipulate
{
public static void main(String args[])
{
StringBuffer s1=new StringBuffer("Object Language:");
System.out.println("\nOriginalString :"+s1);
System.out.println("\nLength 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("\nModified String:"+s1);
s1.setCharAt(6,'-');
System.out.println("\nString Now:"+s1);
s1.append("improves security");
System.out.println("\nAppended String:"+s1);
}
}
Output : Manipulate