Page 321 - CITS - Computer Software Application -TT
P. 321
COMPUTER SOFTWARE APPLICATION - CITS
String res = st1+age;
System.out.println(res);
}
}
Output
Hello500
3 String Methods
• Java provides a wide range of methods for working with strings, such as length(), charAt(), substring(),
indexOf(), toUpperCase(), toLowerCase(), and many others. These methods allow you to perform various
operations on strings.
String text = “Hello, World!”;
int length = text.length(); // 13
char firstChar = text.charAt(0); // ‘H’
String substring = text.substring(7); // “World!”
4 String Comparison
• You can compare strings in Java using the equals() method for content-based comparison and == for reference-
based comparison. It’s important to use equals() when comparing the contents of two strings because ==
checks if two string references point to the same memory location.
String str1 = “Hello”;
String str2 = “Hello”;
boolean areEqual = str1.equals(str2); // true
Example
class Test {
public static void main(String args[]){
String s1=”Rachin”;
String s2=”Rachin”;
String s3=new String(“Rachin”);
//true (because both refer to same instance)
System.out.println(s1==s2);
//false(because s3 refers to instance created in nonpool)
System.out.println(s1==s3);
}
}
Output
true
false
5 String Formatting
• Java provides the String.format() method and the printf() method for formatting strings using placeholders
and format specifiers, similar to C’s printf().
308
CITS : IT&ITES - Computer Software Application - Lesson 78 - 84