String Basics and Operations

Back

Loading concept...

🧵 Working with Strings in Java

Your Words Are Like Magic Beads on a Necklace


The Big Picture

Imagine you have a beautiful necklace made of colorful beads. Each bead is a letter. When you string them together, you get a word or sentence. In Java, we call this collection of letters a String.

But here’s the magical part: once you make this necklace, you can never change its beads. You can only make a brand new necklace if you want different beads!


🎯 String Class Fundamentals

What is a String?

A String is like a row of letter-beads strung together. It’s one of the most important things in Java because we use words everywhere!

String greeting = "Hello";
String name = "Alex";

Think of it this way:

  • "Hello" → A necklace with 5 beads: H-e-l-l-o
  • Each bead sits at a numbered spot (starting from 0!)
Position:  0   1   2   3   4
Letter:    H   e   l   l   o

The String Class Lives in Java

Every String you create is actually a special object from Java’s String class. This class comes with superpowers (methods) to help you work with text!


🔒 String Immutability

The “No Erasing” Rule

Here’s the most important secret about Strings:

Once a String is created, it can NEVER be changed.

This is called immutability (say: im-mew-tuh-BIL-ih-tee).

The Necklace Analogy

Imagine your necklace beads are glued permanently. If you want to change one letter, you must:

  1. Create a whole new necklace
  2. The old one still exists somewhere!
String word = "cat";
word = "bat";  // Creates NEW String!
// The old "cat" is still floating around

Why This Matters

String name = "Sam";
name.toUpperCase();    // Returns "SAM"
System.out.println(name);  // Still "Sam"!

// To keep the change:
name = name.toUpperCase();
System.out.println(name);  // Now "SAM"

Key Insight: Methods don’t change the original String. They give you a brand new one!


🏊 String Pool and Interning

The Magic Swimming Pool of Words

Java has a special place in memory called the String Pool. Think of it as a swimming pool where all unique Strings hang out.

How It Works

graph TD A["You write: String a = 'hello'"] --> B{Is 'hello' in the pool?} B -->|No| C["Add 'hello' to pool"] B -->|Yes| D["Point to existing 'hello'"] C --> E["a points to pool"] D --> E

The Savings Trick

String word1 = "hello";
String word2 = "hello";
// Both point to SAME "hello" in pool!
// Java saves memory!

It’s like having one toy that two kids share, instead of buying two identical toys!

Interning: Joining the Pool

When you use new String(), the String doesn’t automatically join the pool. You can force it with .intern():

String a = new String("hi");
String b = "hi";
String c = a.intern();  // Now in pool

System.out.println(b == c);  // true!

🏗️ String Creation Methods

Four Ways to Make a Necklace

Method 1: Direct Assignment (Most Common)

String name = "Emma";
// Goes to String Pool automatically

Method 2: Using new Keyword

String name = new String("Emma");
// Creates new object in heap memory
// NOT in String Pool initially

Method 3: From Character Array

char[] letters = {'J', 'a', 'v', 'a'};
String word = new String(letters);
// Result: "Java"

Method 4: Using StringBuilder

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

Quick Comparison

Method Goes to Pool? When to Use
"text" Yes Most of the time
new String() No Rarely needed
char[] → String No Converting arrays
StringBuilder No Building long text

🔍 String Access Methods

Peeking at Your Beads

Now that you have your necklace, how do you look at specific beads?

charAt() - Get One Letter

String word = "Rainbow";
char first = word.charAt(0);  // 'R'
char third = word.charAt(2);  // 'i'

Remember: counting starts at 0, not 1!

length() - Count the Beads

String word = "Hello";
int size = word.length();  // 5

substring() - Cut a Piece

String word = "Butterfly";
String part = word.substring(0, 6);
// Result: "Butter"
// From position 0 up to (but not including) 6

toCharArray() - Separate All Beads

String word = "Cat";
char[] letters = word.toCharArray();
// letters = ['C', 'a', 't']

Visual Guide

String word = "RAINBOW";

Position:  0   1   2   3   4   5   6
Letter:    R   A   I   N   B   O   W
           ↑               ↑
     charAt(0)='R'   charAt(4)='B'

substring(0,4) = "RAIN"
substring(4,7) = "BOW"
length() = 7

🔎 String Searching Methods

Finding Treasure in Your Necklace

Sometimes you need to find where a specific bead (or pattern) is hiding.

indexOf() - Where Is It?

String sentence = "I love cats";
int pos = sentence.indexOf("love");
// pos = 2 (starts at position 2)

int catPos = sentence.indexOf("cats");
// catPos = 7

int dogPos = sentence.indexOf("dogs");
// dogPos = -1 (not found!)

lastIndexOf() - Find from the End

String text = "banana";
int first = text.indexOf("a");      // 1
int last = text.lastIndexOf("a");   // 5

contains() - Is It There?

String story = "The quick brown fox";
boolean hasQuick = story.contains("quick");
// true

boolean hasSlow = story.contains("slow");
// false

startsWith() and endsWith()

String file = "photo.jpg";
boolean isImage = file.endsWith(".jpg");
// true

String url = "https://google.com";
boolean isSecure = url.startsWith("https");
// true

Search Methods Summary

Method Returns Use For
indexOf() position or -1 Finding first match
lastIndexOf() position or -1 Finding last match
contains() true/false Checking existence
startsWith() true/false Checking beginning
endsWith() true/false Checking ending

⚖️ String Comparison Methods

Are These Necklaces the Same?

Comparing Strings is tricky! There are TWO ways to ask “are these equal?”

equals() - Same Content?

String a = "hello";
String b = "hello";
String c = "Hello";

a.equals(b);  // true - same letters
a.equals(c);  // false - capital H is different!

equalsIgnoreCase() - Ignore Big/Small Letters

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

a.equalsIgnoreCase(b);  // true!
// Ignores uppercase/lowercase

== vs equals() - The Big Trap!

String a = "hello";
String b = "hello";
String c = new String("hello");

a == b;       // true (same pool object)
a == c;       // FALSE! Different objects!
a.equals(c);  // true (same content)

Golden Rule: Always use .equals() to compare String content!

compareTo() - Which Comes First?

String a = "apple";
String b = "banana";

a.compareTo(b);  // negative (a comes before b)
b.compareTo(a);  // positive (b comes after a)
a.compareTo("apple");  // 0 (same!)

Think of it like alphabetical order:

  • Negative = first word comes before
  • Positive = first word comes after
  • Zero = they’re the same

compareToIgnoreCase()

String a = "Apple";
String b = "apple";

a.compareTo(b);            // negative (A < a)
a.compareToIgnoreCase(b);  // 0 (equal!)

🎯 Quick Reference Table

Task Method Example
Get length length() "Hi".length() → 2
Get character charAt(i) "Hi".charAt(0) → ‘H’
Find substring indexOf() "Hello".indexOf("l") → 2
Check content equals() "a".equals("a") → true
Compare order compareTo() "a".compareTo("b") → -1
Check start startsWith() "Hi".startsWith("H") → true
Check end endsWith() "Hi.txt".endsWith(".txt") → true
Contains? contains() "Hello".contains("ell") → true
Extract part substring() "Hello".substring(0,2) → “He”

🌟 Remember These Key Points

  1. Strings are immutable - Once created, never changed
  2. String Pool saves memory - Identical literals share space
  3. Use equals() not == - For comparing content
  4. Indexing starts at 0 - First character is position 0
  5. indexOf() returns -1 - When text isn’t found
  6. Methods return new Strings - They don’t modify originals

🎉 You Did It!

You now understand how Java handles text! Strings might seem simple, but they’re everywhere in programming. Every message you see, every name you type, every file you read - they all use Strings!

Keep practicing, and soon working with Strings will feel as natural as stringing beads on a necklace! 🧵✨

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.