Loading

Quipoin Menu

Learn • Practice • Grow

data-structure-with-java / Strings in Java
tutorial

Strings in Java

Strings are sequences of characters. In Java, strings are objects of the String class. They are immutable (cannot be changed after creation). For DSA, strings appear in many problems (palindromes, anagrams, pattern matching).

Creating Strings


String s1 = "Hello"; // string literal
String s2 = new String("World"); // using constructor
String s3 = s1 + " " + s2; // concatenation

Common String Methods


String str = " Java DSA ";
int len = str.length(); // 11
String trimmed = str.trim(); // "Java DSA"
String upper = str.toUpperCase(); // " JAVA DSA "
char ch = str.charAt(2); // 'J' (after spaces)
boolean contains = str.contains("DSA"); // true
int index = str.indexOf("DSA"); // 6 (position of 'D')
String sub = str.substring(2, 9); // "Java DSA" (from 2 to 8)
boolean equals = s1.equals(s2); // compare content
boolean ignoreCase = s1.equalsIgnoreCase("hello"); // true

StringBuilder for Mutability
Since String is immutable, use StringBuilder for frequent modifications (e.g., building strings in loops).


StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("DSA");
String result = sb.toString(); // "Hello DSA"
sb.reverse(); // reverse the string
Two Minute Drill
  • Strings are immutable objects in Java.
  • Use common methods: length(), charAt(), substring(), indexOf(), etc.
  • Use equals() for content comparison, not ==.
  • For frequent modifications, use StringBuilder (mutable).
  • StringBuilder methods: append(), insert(), delete(), reverse().

Need more clarification?

Drop us an email at career@quipoinfotech.com