Jul 11, 2024
String
type.
String name = "Tony";
String fullName = "Tony Stark";
String sentence = "My name is Tony Stark.";
String phrase = "Hello, World!";
Scanner
class to get user input.
Scanner scanner = new Scanner(System.in);
String userName = scanner.nextLine();
System.out.println("Your name is " + userName);
nextLine()
for full sentence input.
scanner.nextLine() -> for full sentences
scanner.next() -> for single words
+
operator.
String firstName = "Tony";
String lastName = "Stark";
String fullName = firstName + " " + lastName;
System.out.println(fullName);
int length = fullName.length();
System.out.println("Length: " + length);
charAt
method to access specific characters in a string.
for (int i = 0; i < fullName.length(); i++) {
System.out.print(fullName.charAt(i));
}
compareTo
method.
int comparison = name1.compareTo(name2);
name1
> name2
name1
== name2
name1
< name2
if (comparison == 0) {
System.out.println("Strings are equal");
} else {
System.out.println("Strings are not equal");
}
equals
for String ComparisoncompareTo
and equals
if (string1.equals(string2)) {
System.out.println("Strings are equal");
}
substring
method.
String part = sentence.substring(11, 15); // Extracts "Tony"
String toEnd = sentence.substring(11); // Extracts "Tony Stark."