DEV Community

Manikanta Yarramsetti
Manikanta Yarramsetti

Posted on

Java String Methods You'll Actually Use Every Day

I remember when I first started learning Java, strings felt weirdly complicated. Like, why so many methods? Which ones do I even need?

Turns out, you only need a handful 90% of the time. Here they are.


The Ones That Matter

length() — gives you the number of characters.

String name = "Ravi";
System.out.println(name.length()); // 4
Enter fullscreen mode Exit fullscreen mode

toUpperCase() / toLowerCase() — case conversion, simple as that.

String city = "chennai";
System.out.println(city.toUpperCase()); // CHENNAI
Enter fullscreen mode Exit fullscreen mode

trim() — removes extra spaces from both ends. Super useful when handling user input.

String input = "  hello  ";
System.out.println(input.trim()); // "hello"
Enter fullscreen mode Exit fullscreen mode

contains() — checks if a string has a certain word or character inside it.

String msg = "Java is fun";
System.out.println(msg.contains("fun")); // true
Enter fullscreen mode Exit fullscreen mode

replace() — swap out characters or words.

String s = "I like cats";
System.out.println(s.replace("cats", "dogs")); // I like dogs
Enter fullscreen mode Exit fullscreen mode

substring() — grab a piece of the string by index.

String word = "Developer";
System.out.println(word.substring(0, 3)); // Dev
Enter fullscreen mode Exit fullscreen mode

equals() vs == — this one trips up beginners a lot.

String a = "hello";
String b = "hello";

System.out.println(a == b);        // might be true (but don't rely on it)
System.out.println(a.equals(b));   // always true ✅
Enter fullscreen mode Exit fullscreen mode

Always use .equals() when comparing strings. == compares references, not content.


split() — break a string into an array based on a separator.

String fruits = "apple,mango,banana";
String[] list = fruits.split(",");
// list[0] = "apple", list[1] = "mango", list[2] = "banana"
Enter fullscreen mode Exit fullscreen mode

Quick Recap

Method What it does
length() Count characters
toUpperCase() All caps
trim() Remove edge spaces
contains() Check if something's inside
replace() Swap text
substring() Slice it
equals() Safe string comparison
split() Break into array

That's it. Learn these 8 and you're good for most beginner-to-intermediate Java work.

Strings in Java are immutable by the way — every method returns a new string, it doesn't change the original. Worth keeping that in mind.

Drop a comment if you want me to cover StringBuilder next — it's great when you're doing a lot of string manipulation in loops.

Happy coding 🙌

Top comments (0)