Lecture - 6
Agenda • Program to swap two integers. • Strings in Java • In-class quiz 12:15PM to 12:45PM
Strings in Java • String is a sequence of characters. • In Java, Strings belong to Java.lang.string. Because it is a common class, we need not write a corresponding import statement. • How to declare a variable as a string? Ex: String a=“Hi”;
Operations on Strings • Comparing : equals() and compareTo() • Trim • Uppercase/Lowercase: toLowercase(), toUppercase() • Substring • Replace • indexOf • Concat • length
Example Programs EQUALS: String a = "csc185"; String b = “csc185"; if(a.equals(b)) System.out.println(“Strings are equal!"); else System.out.println(“Strings not equal!");
CompareTo(): Return an integer value. Return ‘0’ if they are equal String a = "csc185"; String b = "csc185"; int result = a.compareTo(b); System.out.println("result is: "+result);
Upper case: String b = "csc185"; String upperresult = b.toUpperCase(); System.out.println(upperresult);
• Substring: 2 methods String b = "csc185"; String upperresult = b.substring(2); System.out.println(upperresult);
• Replace: String b = "csc185"; String upperresult = b.replace('c', 'p'); System.out.println(upperresult);