← Back to Core Java Course | Chapter 6: Strings | Lesson 1 of 5

Java String Introduction

Creating Strings

A String in Java is an object representing an immutable sequence of characters, and you can create one either with a literal ("hello") or explicitly with new String("hello"), though the literal form is almost always preferred. Both approaches produce a fully usable String object with the same methods available.

Example: Creating Strings

java
public class Main {
	public static void main(String[] args) {
		String a = "hello";
		String b = new String("hello");
		System.out.println(a);
		System.out.println(b);
	}
}

Understanding the String Pool

To save memory, Java stores string literals in a special region called the string pool, so two literals with identical text actually point to the exact same object in memory rather than two separate copies. You can see this with == comparing true for two identical literals, which is precisely why == is the wrong tool for comparing string content.

Example: Understanding the String Pool

java
public class Main {
	public static void main(String[] args) {
		String a = "hello";
		String b = "hello";
		System.out.println(a == b); // true: same pooled object
	}
}

String Immutability

Strings are immutable: once created, a String object's characters can never be changed in place. Every method that appears to "modify" a string — toUpperCase(), concat(), replace() — actually returns a brand-new String object, leaving the original untouched.

Example: String Immutability

java
public class Main {
	public static void main(String[] args) {
		String original = "hello";
		String upper = original.toUpperCase();
		System.out.println(original); // unchanged
		System.out.println(upper); // new string
	}
}

Checking String Length

The length() method returns the total character count of a String, including spaces, punctuation, and digits, not just letters. Since it's a method (not a field like an array's length), remember the parentheses: str.length().

Example: Checking String Length

java
public class Main {
	public static void main(String[] args) {
		String text = "Hello World";
		System.out.println(text.length());
	}
}

Accessing Single Characters

charAt(index) retrieves a single character at a given zero-based position, so charAt(0) gets the first character. Calling it with an index equal to or beyond the string's length throws a StringIndexOutOfBoundsException.

Example: Accessing Single Characters

java
public class Main {
	public static void main(String[] args) {
		String text = "Hello";
		System.out.println(text.charAt(0));
	}
}
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.