class strings
{
void str()
{
String name1="Aman";
String name2="Tania";
String name3="Aman";
String name4="aman";
System.out.println("length of "+ name1 + " is = " + name1.length());
System.out.println("length of "+ name2 + " is = " + name2.length());
System.out.println("character at 3 in "+ name1 + " is = " + name1.charAt(3));
System.out.println("character at 4 in "+ name2 + " is = " + name2.charAt(4));
System.out.println("comparison of the 2 names is " + name1.compareTo(name2));
System.out.println("comparison of the 2 names is " + name2.compareTo(name1));
System.out.println("comparison of the 2 names is " + name3.compareTo(name1));
System.out.println("comparison of the 2 names is " + name4.compareTo(name1));
System.out.println("equality comparison of the 2 names is " + name2.equals(name1));
System.out.println("equality comparison of the 2 names is " + name3.equals(name1));
System.out.println("concatenation of the 2 names is " + name1.concat(name2));
System.out.println("concatenation of the 2 names is " + name1+name2);
System.out.println("First occurence of 'a' in " + name2 + "is at index " + name2.indexOf('a'));
System.out.println("Last occurence of 'a' in " + name2 + " is at index " + name2.lastIndexOf('a'));
System.out.println("First occurence of 'x' in " + name2 + " is at index " + name2.indexOf('x'));
System.out.println("Substring 1 onwards in " + name2 + " is = " + name2.substring(1));
}
}
Output:
length of Aman is = 4
length of Tania is = 5
character at 3 in Aman is = n
character at 4 in Tania is = a
comparison of the 2 names is -19
comparison of the 2 names is 19
comparison of the 2 names is 0
comparison of the 2 names is 32
equality comparison of the 2 names is false
equality comparison of the 2 names is true
concatenation of the 2 names is AmanTania
concatenation of the 2 names is AmanTania
First occurence of 'a' in Taniais at index 1
Last occurence of 'a' in Tania is at index 4
First occurence of 'x' in Tania is at index -1
Substring 1 onwards in Tania is = ania
Note:
if
System.out.println("character at 5 in "+ name1 + " is = " + name1.charAt(5));
is also added to the above program, it ll throw an error:
java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java:686)
at strings.str(strings.java:16)
This is so because charAt(5) points to 5th character which is beyond the length of the string = 4
No comments:
Post a Comment