String Function
String Function
compareTo(str2) == 0) {
public static void main(String[] args) {
String str1 = "Learn Java"; System.out.println("str1 and str2 are
String str2 = "Learn Kolin"; equal");
int result; }
else {
// comparing str1 with str2 System.out.println("str1 and str2 are not
result = str1.compareTo(str2); equal");
}
System.out.println(result); }
} }
}
Example 3: compareTo() With Case
// Output: -1 The compareTo() method takes the letter case
(uppercase and lowercase) into consideration.
Example: Java String compareTo()
class Main { class Main {
public static void main(String[] args) { public static void main(String[] args) {
String str1 = "Learn Java"; String str1 = "Learn Java";
String str2 = "Learn Java"; String str2 = "learn Java";
String str3 = "Learn Kolin"; int result;
int result;
// comparing str1 with str2
// comparing str1 with str2 result = str1.compareTo(str2);
result = str1.compareTo(str2);
System.out.println(result); // -32
System.out.println(result); // 0 }
}
// comparing str1 with str3 Java String length()
result = str1.compareTo(str3); In this tutorial, we will learn about the Java
String length() method with the help of
System.out.println(result); // -1 examples.
// comparing str3 with str1 The length() method returns the length of the
result = str3.compareTo(str1); string.
System.out.println(result); // 1 Example
} class Main {
} public static void main(String[] args) {
class Main { String str1 = "Java is fun";
public static void main(String[] args) {
String str1 = "Learn Python"; System.out.println(str1.length());
String str2 = "Learn Java";
}
// if str1 and str2 are equal, the result is 0 }
// Output: 6
// Output: 11
Java String charAt()
Java String replace() In this tutorial, we will learn about the Java
In this tutorial, we will learn about the Java String charAt() method with the help of
String replace() method with the help of examples.
examples.
The charAt() method returns the character at
The replace() method replaces each matching the specified index.
occurrence of the old character/text in the
string with the new character/text. Example
class Main {
Example public static void main(String[] args) {
class Main { String str1 = "Java Programming";
public static void main(String[] args) {
String str1 = "bat ball"; // returns character at index 2
System.out.println(str1.charAt(2));
// replace b with c
System.out.println(str1.replace('b', 'c'));
}
} }
}
// Output: v
// Output: cat call
ava String indexOf()
In this tutorial, we will learn about the Java
String indexOf() with the help of examples.
Example
class Main {
public static void main(String[] args) {
String str1 = "Java is fun";
int result;
System.out.println(result);
}
}