String
String
• Example:
String message = "Hello World!";
System.out.println( message );
3
Useful String methods
• Suppose we have
String message = "Hello World!";
4
Useful String methods
• Substrings:
– The substring method returns a String consisting
of the characters starting from the first position
inclusive up to but NOT including the second
position:
String str = "abcdefghijklmno";
String str2 = str.substring( 2, 5 );
– Result is "cde“
• Case changes
toLowerCase( ), toUpperCase( )
5
Comparing Strings
6
Comparing Strings
• Example 2:
String str1 = "abcde" ;
String str2 = "ab" ;
int result = str1.compareTo(str2);
7
Comparison of 2 strings:-
(BY THE HELP OF == OPERATOR)
class HelloWorld
{
public static void main(String[] args)
{
String s1="hello";
String s2="hello";
if(s1==s2)
System.out.println("both are equal");
}
}
o/p:- both are equal.
class HelloWorld
{
public static void main(String[] args)
{
String s1="hello";
String s2=new String("hello“);
if(s1==s2)
System.out.println("both are equal");
Else
System.out.println(“both are not equal”);
}
}
o/p:- both are not equal.
Comparison of 2 strings by the help
of .equls() Method
class HelloWorld
{
public static void main(String[] args)
{
String s1="hello";
String s2="hello";
if(s1.equals(s2))
System.out.println("both are equal");
else
System.out.println(“both are not equal”);
}
}
o/p:- both are equal.
10
Difference between == and equals()
while comparing strings
s1=“hello”;
Difference between the following statements
String s=“hello”;
String s=new String(“hello”);
14
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
o/p:-Sachin Tensdulkar
15
1:- Search for a given string in an array of strings.
16