String is used to hold character sequences. We do not have to use new to create a new instance of this class.

toUpperCase converts everything to uppercase.

// *** 1. Start (toUpperCase)
String s1 = "test";
String s2 = s1.toUpperCase();
System.out.println("s2 = " + s2);
// *** 1. End
toLowercase converts everything to lowercase.

// *** 2. Start (to toLowerCase)
String s3 = "TEST";
String s4 = s3.toLowerCase();
System.out.println("s4 = " + s4);
// *** 2. End
indexOf finds index of substring within a string. If the substring is not found in string, it returns -1. contains indicates if the substring is inside the string.

// *** 3. Start (index of, contains)
String s5 = "abcdefghi jklmnopq";
int locOfi = s5.indexOf('i');
System.out.println("locOfi = " + locOfi);
boolean conLetti = s5.contains("i");
System.out.println("conLetti = " + conLetti);
// *** 3. End
Two strings can be checked for equality with equals. For a equality check that ignores case, use equalsIgnoreCase.

// *** 4. Start (equals)
String s6 = "president";
String s7 = "president";
boolean b1 = s6.equals(s7);
boolean b2 = s6.equals("President");
boolean b3 = s6.equalsIgnoreCase("President");
System.out.println("b1 = " + b1 +
"\tb2 = " + b2 +
"\tb3 = " + b3);
// *** 4. End
toCharArray converts a string to character array. The method length() finds length of string, while the field length does the same for character arrays.

// *** 5. Start (String to char[], length)
String s8 = "Time";
char[] cArr = s8.toCharArray();
System.out.println(cArr);
int lenOfs8 = s8.length();
int lenOfcArr = cArr.length;
System.out.println("lenOfs8 = " + lenOfs8 +
"\tlenOfcArr = " + lenOfcArr );
// *** 5. End
package com.javaAndroid.ex5;
public class Ex5 {
public static void main(String[] args) {
// *** 1. Start (toUpperCase)
String s1 = "test";
String s2 = s1.toUpperCase();
System.out.println("s2 = " + s2);
// *** 1. End
// *** 2. Start (to toLowerCase)
String s3 = "TEST";
String s4 = s3.toLowerCase();
System.out.println("s4 = " + s4);
// *** 2. End
// *** 3. Start (index of, contains)
String s5 = "abcdefghi jklmnopq";
int locOfi = s5.indexOf('i');
System.out.println("locOfi = " + locOfi);
boolean conLetti = s5.contains("i");
System.out.println("conLetti = " + conLetti);
// *** 3. End
// *** 4. Start (equals)
String s6 = "president";
String s7 = "president";
boolean b1 = s6.equals(s7);
boolean b2 = s6.equals("President");
boolean b3 = s6.equalsIgnoreCase("President");
System.out.println("b1 = " + b1 +
"\tb2 = " + b2 +
"\tb3 = " + b3);
// *** 4. End
// *** 5. Start (String to char[], length)
String s8 = "Time";
char[] cArr = s8.toCharArray();
System.out.println(cArr);
int lenOfs8 = s8.length();
int lenOfcArr = cArr.length;
System.out.println("lenOfs8 = " + lenOfs8 +
"\tlenOfcArr = " + lenOfcArr );
// *** 5. End
}
}
No comments:
Post a Comment