MediumStrings Fundamentals. This guide covers the fundamental… | by Saumya14 | Medium
Sitemap

Strings Fundamentals

4 min readAug 3, 2025

--

Press enter or click to view image in full size
Photo by Sincerely Media on Unsplash

This guide covers the fundamental concepts of working with strings in Java.

Key Concepts

1. String Creation

  • String literals: String str = "Hello World";
  • Constructor: String str = new String("Hello World");
  • Conversion: String str = String.valueOf(123);

2. String Immutability

Strings in Java are immutable, meaning once created, they cannot be changed. Methods like toUpperCase(), toLowerCase(), trim() return new String objects rather than modifying the original.

3. String Concatenation

  • + operator: String result = str1 + " " + str2;
  • concat() method: String result = str1.concat(str2);

4. String Length

Use the length() method to get the number of characters in a string.

5. Character Access

Use charAt(index) to access individual characters. Indexing starts at 0.

6. String Comparison

  • == operator: Compares references (not recommended for content comparison)
  • equals() method: Compares content
  • equalsIgnoreCase(): Compares content ignoring case

7. Common String Methods

  • trim(): Removes leading and trailing whitespace
  • toUpperCase() / toLowerCase(): Changes case
  • substring(start, end): Extracts a portion
  • replace(old, new): Replaces characters/strings
  • contains(str): Checks if string contains substring
  • startsWith(str) / endsWith(str): Checks prefix/suffix

Get Saumya14’s stories in your inbox

Join Medium for free to get updates from this writer.

8. String Formatting

  • String.format(): Creates formatted strings
  • printf(): Prints formatted output
  • Format specifiers: %s (string), %d (integer), %f (float), %.2f (float with 2 decimal places)

9. String Building

Use StringBuilder for efficient string concatenation in loops:

StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" World");
String result = sb.toString();

10. String Splitting

Use split(regex) to break a string into an array:

String[] parts = "apple,banana,orange".split(",");

11. String Joining (Java 8+)

Use String.join(delimiter, elements) to combine strings:

String result = String.join(" - ", "Java", "is", "awesome");

12. Empty and Null Checks

  • isEmpty(): Checks if string is empty (length == 0)
  • length() == 0: Alternative way to check emptiness
  • Always check for null before calling methods to avoid NullPointerException

Important Notes

  1. String Pool: String literals are stored in a string pool for memory efficiency
  2. Immutability: Strings cannot be modified after creation
  3. Performance: Use StringBuilder for multiple concatenations
  4. Comparison: Always use equals() for content comparison, not ==
  5. Null Safety: Always check for null before calling string methods

Running the Example

To compile and run the example:

javac StringBasics.java
java StringBasics
public class StringBasics {
public static void main(String[] args) {
System.out.println("=== Java String Basics ===\n");

// 1. Creating Strings
System.out.println("1. Creating Strings:");
String str1 = "Hello World"; // String literal
String str2 = new String("Hello World"); // Using constructor
String str3 = String.valueOf(123); // Converting from other types
System.out.println("str1: " + str1);
System.out.println("str2: " + str2);
System.out.println("str3: " + str3);
System.out.println();

// 2. String Immutability
System.out.println("2. String Immutability:");
String original = "Java";
String modified = original.toUpperCase();
System.out.println("Original: " + original);
System.out.println("Modified: " + modified);
System.out.println("Original unchanged: " + original);
System.out.println();

// 3. String Concatenation
System.out.println("3. String Concatenation:");
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName; // Using + operator
String greeting = "Hello, ".concat(fullName); // Using concat() method
System.out.println("Full name: " + fullName);
System.out.println("Greeting: " + greeting);
System.out.println();

// 4. String Length
System.out.println("4. String Length:");
String text = "Programming";
System.out.println("Text: " + text);
System.out.println("Length: " + text.length());
System.out.println();

// 5. Accessing Characters
System.out.println("5. Accessing Characters:");
String word = "Java";
System.out.println("Word: " + word);
System.out.println("First character: " + word.charAt(0));
System.out.println("Last character: " + word.charAt(word.length() - 1));
System.out.println();

// 6. String Comparison
System.out.println("6. String Comparison:");
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");
String s4 = "Hello";

System.out.println("s1 == s2: " + (s1 == s2)); // true (same reference)
System.out.println("s1 == s3: " + (s1 == s3)); // false (different objects)
System.out.println("s1.equals(s3): " + s1.equals(s3)); // true (same content)
System.out.println("s1.equals(s4): " + s1.equals(s4)); // false (different case)
System.out.println("s1.equalsIgnoreCase(s4): " + s1.equalsIgnoreCase(s4)); // true
System.out.println();

// 7. Common String Methods
System.out.println("7. Common String Methods:");
String sample = " Hello World ";
System.out.println("Original: '" + sample + "'");
System.out.println("trim(): '" + sample.trim() + "'");
System.out.println("toUpperCase(): '" + sample.toUpperCase() + "'");
System.out.println("toLowerCase(): '" + sample.toLowerCase() + "'");
System.out.println("substring(2, 7): '" + sample.substring(2, 7) + "'");
System.out.println("replace('o', '0'): '" + sample.replace('o', '0') + "'");
System.out.println("contains('World'): " + sample.contains("World"));
System.out.println("startsWith(' Hello'): " + sample.startsWith(" Hello"));
System.out.println("endsWith('World '): " + sample.endsWith("World "));
System.out.println();

// 8. String Formatting
System.out.println("8. String Formatting:");
String name = "Alice";
int age = 25;
double height = 1.75;

String formatted = String.format("Name: %s, Age: %d, Height: %.2f", name, age, height);
System.out.println(formatted);

// Using printf (same as format)
System.out.printf("Name: %s, Age: %d, Height: %.2f%n", name, age, height);
System.out.println();

// 9. String Building
System.out.println("9. String Building:");
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
sb.append("!");
String result = sb.toString();
System.out.println("Built string: " + result);
System.out.println();

// 10. String Splitting
System.out.println("10. String Splitting:");
String csv = "apple,banana,orange,grape";
String[] fruits = csv.split(",");
System.out.println("CSV string: " + csv);
System.out.println("Split fruits:");
for (int i = 0; i < fruits.length; i++) {
System.out.println(" " + (i + 1) + ". " + fruits[i]);
}
System.out.println();

// 11. String Joining (Java 8+)
System.out.println("11. String Joining:");
String joined = String.join(" - ", "Java", "is", "awesome");
System.out.println("Joined: " + joined);
System.out.println();

// 12. Empty and Null Checks
System.out.println("12. Empty and Null Checks:");
String empty = "";
String nullString = null;
String normal = "text";

System.out.println("empty.isEmpty(): " + empty.isEmpty());
System.out.println("normal.isEmpty(): " + normal.isEmpty());
System.out.println("empty.length() == 0: " + (empty.length() == 0));
System.out.println("normal.length() == 0: " + (normal.length() == 0));

// Safe null check
System.out.println("nullString == null: " + (nullString == null));
// System.out.println("nullString.isEmpty(): " + nullString.isEmpty()); // This would throw NullPointerException
System.out.println();

System.out.println("=== End of String Basics ===");
}
}

--

--