Java Strings

Working with text data in Java programming

📝 What are Java Strings?

Java Strings are objects that represent sequences of characters. They store text data like names, messages, or any textual information and provide many useful methods for text manipulation.


// Creating strings
String greeting = "Hello World!";
String name = "Alice";
String message = "Welcome to Java programming";

System.out.println(greeting);
System.out.println("Length: " + greeting.length());
                                    

Output:

Hello World!

Length: 12

String Features

📏

Length & Access

Get string length and characters

String text = "Java";
int len = text.length();      // 4
char first = text.charAt(0);  // 'J'
🔍

Search & Find

Find text within strings

String text = "Hello World";
boolean has = text.contains("World"); // true
int pos = text.indexOf("o");          // 4
✂️

Modify & Extract

Change and extract parts of strings

String text = "Hello World";
String upper = text.toUpperCase();    // "HELLO WORLD"
String part = text.substring(0, 5);   // "Hello"
🔗

Compare & Join

Compare and combine strings

String a = "Hello", b = "World";
boolean same = a.equals(b);     // false
String joined = a + " " + b;    // "Hello World"

🔹 Creating Strings

Different ways to create strings in Java:

// String literals (most common)
String name = "John Doe";
String city = "New York";

// Using String constructor
String message = new String("Hello");

// Empty strings
String empty1 = "";
String empty2 = new String();

// Multi-line strings (Java 15+)
String poem = """
    Roses are red,
    Violets are blue,
    Java is awesome,
    And so are you!
    """;

System.out.println("Name: " + name);
System.out.println("City: " + city);
System.out.println(poem);

Output:

Name: John Doe

City: New York

Roses are red,
Violets are blue,
Java is awesome,
And so are you!

🔹 String Methods

Useful methods for working with strings:

String text = "  Hello Java World  ";

// Length and character access
System.out.println("Length: " + text.length());           // 19
System.out.println("First char: " + text.charAt(2));      // 'H'

// Case conversion
System.out.println("Uppercase: " + text.toUpperCase());   // "  HELLO JAVA WORLD  "
System.out.println("Lowercase: " + text.toLowerCase());   // "  hello java world  "

// Trimming whitespace
System.out.println("Trimmed: '" + text.trim() + "'");     // "Hello Java World"

// Searching
System.out.println("Contains 'Java': " + text.contains("Java"));     // true
System.out.println("Starts with '  H': " + text.startsWith("  H"));  // true
System.out.println("Index of 'Java': " + text.indexOf("Java"));      // 8

Output:

Length: 19

First char: H

Uppercase: HELLO JAVA WORLD

Lowercase: hello java world

Trimmed: 'Hello Java World'

Contains 'Java': true

Starts with ' H': true

Index of 'Java': 8

🔹 String Comparison

Comparing strings correctly in Java:

String name1 = "Alice";
String name2 = "alice";
String name3 = "Alice";

// Correct way to compare strings
boolean exact = name1.equals(name3);           // true
boolean different = name1.equals(name2);       // false
boolean ignoreCase = name1.equalsIgnoreCase(name2); // true

// Comparing with null safety
String nullString = null;
boolean safe = "Alice".equals(nullString);     // false (safe)

// Lexicographic comparison
int comparison = name1.compareTo(name2);       // negative (A < a in ASCII)

System.out.println("Exact match: " + exact);
System.out.println("Different case: " + different);
System.out.println("Ignore case: " + ignoreCase);
System.out.println("Comparison result: " + comparison);

Output:

Exact match: true

Different case: false

Ignore case: true

Comparison result: -32

🔹 String Extraction

Extract parts of strings using substring methods:

String fullName = "John Michael Smith";

// Extract parts using substring
String firstName = fullName.substring(0, 4);        // "John"
String lastName = fullName.substring(13);           // "Smith"
String middleName = fullName.substring(5, 12);      // "Michael"

// Split string into array
String[] nameParts = fullName.split(" ");
System.out.println("First: " + nameParts[0]);       // "John"
System.out.println("Middle: " + nameParts[1]);      // "Michael"
System.out.println("Last: " + nameParts[2]);        // "Smith"

// Replace parts of string
String replaced = fullName.replace("John", "Jane");
String removedSpaces = fullName.replace(" ", "");

System.out.println("Original: " + fullName);
System.out.println("First name: " + firstName);
System.out.println("Replaced: " + replaced);
System.out.println("No spaces: " + removedSpaces);

Output:

First: John

Middle: Michael

Last: Smith

Original: John Michael Smith

First name: John

Replaced: Jane Michael Smith

No spaces: JohnMichaelSmith

Important String Facts:

  • Strings are immutable - they cannot be changed
  • String methods return new strings , don't modify original
  • Always use .equals() to compare strings, not ==
  • String indices start at 0

🧠 Test Your Knowledge

What is the correct way to compare two strings in Java?