Java for Beginners · Module 5: Data and Methods
🎯 Text in Java
Names, messages, passwords, addresses: most real data is text. Java stores text in the String class. A String is not a primitive type (Lesson 8). It is an object, and that brings useful methods and a few surprises that this lesson explains.
1️⃣ Creating and Using Strings
String greeting = "Hello, Java!";0e
1l
2l
3o
4,
5␣
6J
7a
8v
9a
10!
11
length() = 12, charAt(1) = e.Figure 1: A String is a row of characters with indexes.
Program 1: String basics
public class StringBasics {
public static void main(String[] args) {
String name = "Java";
String greeting = "Hello, " + name + "!";
System.out.println(greeting);
System.out.println("length = " + greeting.length());
System.out.println("charAt(1) = " + greeting.charAt(1));
char[] letters = {'J', 'a', 'v', 'a'};
String fromChars = new String(letters);
System.out.println(fromChars);
String empty = "";
String nothing = null;
System.out.println("empty length = " + empty.length());
System.out.println("nothing = " + nothing);
}
}
Hello, Java!
length = 12
charAt(1) = e
Java
empty length = 0
nothing = null
- Strings are written in double quotes. (A single character uses single quotes:
'A'.) +joins Strings. This is called concatenation.length()has brackets for a String, butlengthhas none for an array (Lesson 21).charAt(i)gives the character at index i, counting from 0.- An empty String
""has length 0. AnullString means “no String object at all”. They are different.
2️⃣ The String Pool
“java”
a ➜ pool “java” b ➜ pool “java” (same object)c = new String("java") ➜ separate “java” object on the heapFigure 2: Literals share one pooled object. new String(...) makes another.
Java saves memory by keeping one copy of each literal. When you write "java" twice, both variables point to the same pooled object. new String("java") forces a new, separate object.
public class PoolDemo {
public static void main(String[] args) {
String a = "java";
String b = "java";
String c = new String("java");
String d = new String("java").intern();
System.out.println("a == b : " + (a == b));
System.out.println("a == c : " + (a == c));
System.out.println("a.equals(c) : " + a.equals(c));
System.out.println("a == c.intern() : " + (a == c.intern()));
System.out.println("a == d : " + (a == d));
}
}
a == b : true
a == c : false
a.equals(c) : true
a == c.intern() : true
a == d : true
a == bis true: both literals refer to the same pooled object.a == cis false:cis a different object, even though its text is the same.a.equals(c)is true becauseequalscompares the characters.intern()returns the pooled copy, soc.intern()is the same object asa.- Rule: compare Strings with equals(), never with ==.
3️⃣ Comparing Strings
| Check | Code | Meaning | Result for “java” vs new String(“java”) |
| Same object? | a == c | compares references | false |
| Same text? | a.equals(c) | compares characters | true |
| Same text, ignore case? | a.equalsIgnoreCase(c) | ignores capitals | true |
| Dictionary order | a.compareTo(c) | negative, 0 or positive | 0 |
Figure 3: Comparing Strings: == versus equals.
public class Compare {
public static void main(String[] args) {
String x = "apple";
String y = "Apple";
System.out.println("equals : " + x.equals(y));
System.out.println("equalsIgnoreCase : " + x.equalsIgnoreCase(y));
System.out.println("compareTo : " + x.compareTo(y));
System.out.println("apple vs banana : " + "apple".compareTo("banana"));
System.out.println("banana vs apple : " + "banana".compareTo("apple"));
System.out.println("same text : " + "java".compareTo("java"));
String input = null;
System.out.println("safe check : " + "java".equals(input));
}
}
equals : false
equalsIgnoreCase : true
compareTo : 32
apple vs banana : -1
banana vs apple : 1
same text : 0
safe check : false
equalsis case-sensitive. UseequalsIgnoreCaseto ignore capitals.compareTogives 0 for equal text, a negative number if the first comes earlier in dictionary order, and a positive number if later. Here “apple” and “Apple” differ by 32, the gap between the codes of ‘a’ (97) and ‘A’ (65).- Put the known String first, as in
"java".equals(input). Ifinputis null, this simply returns false instead of crashing.
4️⃣ Strings Are Immutable
s = "Hello"object A: “Hello”
“Hello World”
s = s.concat(...), the new object B is thrown away. This is immutability.Figure 4: Strings are immutable: operations create new Strings.
public class Immutable {
public static void main(String[] args) {
String s = "Hello";
s.concat(" World");
System.out.println("after concat (ignored): " + s);
s = s.concat(" World");
System.out.println("after assigning : " + s);
String t = "java";
String u = t.toUpperCase();
System.out.println(t + " -> " + u);
String original = "abc";
String alias = original;
original = original + "d";
System.out.println("original = " + original + ", alias = " + alias);
}
}
after concat (ignored): Hello
after assigning : Hello World
java -> JAVA
original = abcd, alias = abc
- Every method that “changes” a String really returns a new String. The original stays as it was.
- If you ignore the result, nothing happens. Always store it:
s = s.concat(...). - Because Strings never change, it is safe to share them, which is why the pool is possible. The
aliasstill holds “abc” afteroriginalis changed. - Joining many Strings inside a long loop creates many temporary objects. For that job use
StringBuilder(Lesson 24).
5️⃣ Concatenation and Text Blocks
public class Concat {
public static void main(String[] args) {
int a = 3, b = 4;
System.out.println("Sum: " + a + b);
System.out.println("Sum: " + (a + b));
System.out.println(a + b + " is the sum");
String s = "Roll" + " " + 21045;
System.out.println(s);
String multi = """
Dear student,
Welcome to Java.
""";
System.out.print(multi);
}
}
Sum: 34
Sum: 7
7 is the sum
Roll 21045
Dear student,
Welcome to Java.
+works left to right (Lesson 15). In"Sum: " + a + b, the text comes first, so 3 and 4 are joined as text and give “34”. Brackets fix it:"Sum: " + (a + b).- In
a + b + " is the sum"the numbers are added first because no String has appeared yet. - A text block (
"""…""", Java 15 and later) lets you write several lines without\n. Java removes the common indentation.
6️⃣ Errors Beginners Meet
NullPointerException: calling a method on null
public class Npe {
public static void main(String[] args) {
String s = null;
System.out.println(s.length());
}
}
Exception in thread “main” java.lang.NullPointerException: Cannot invoke “String.length()” because “<local1>” is null
at Npe.main(Npe.java:4)
spoints to nothing, sos.length()has no object to work on. Checkif (s != null)first. (The message shows<local1>because the program was compiled without debug names; an IDE showss.)
Index beyond the String
public class Sioobe {
public static void main(String[] args) {
String t = "Java";
System.out.println(t.charAt(10));
}
}
Exception in thread “main” java.lang.StringIndexOutOfBoundsException: Index 10 out of bounds for length 4
at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:55)
… (several internal lines)
at java.base/java.lang.String.charAt(String.java:1544)
at Sioobe.main(Sioobe.java:4)
- “Java” has indexes 0 to 3. Read the first line for the cause, and the last line starting with your own class name for where it happened.
Mixing up quotes and types
public class Bad4 {
public static void main(String[] args) {
char c = "A";
int n = "5";
String s = 5;
}
}
Bad4.java:3: error: incompatible types: String cannot be converted to char
char c = “A”;
^
Bad4.java:4: error: incompatible types: String cannot be converted to int
int n = “5”;
^
Bad4.java:5: error: incompatible types: int cannot be converted to String
String s = 5;
^
3 errors
- Double quotes make a String, and single quotes make a char. Use
Integer.parseInt("5")andString.valueOf(5)to convert (Lesson 9).
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
s1 == s2 to compare text | Compares references | s1.equals(s2) |
s.toUpperCase(); without storing | Strings are immutable | s = s.toUpperCase(); |
input.equals("yes") when input may be null | NullPointerException | "yes".equals(input) |
| Single quotes for a String | Compile error | Use double quotes |
s.length (no brackets) | length() is a method for Strings | s.length() |
| Joining text and numbers in the wrong order | “Sum: 34” instead of 7 | Brackets around the arithmetic |
❓ Frequently Asked Questions
Q1. Why is String immutable?
It makes Strings safe to share (the pool), safe as keys in collections, and safe in multi-threaded programs.
Q2. What is the difference between “” and null?"" is a real String with no characters. null means there is no String at all.
Q3. How many objects does new String(“java”) create?
One on the heap, plus the pooled literal "java" if it was not already there.
Q4. Is String a keyword?
No. It is a class in java.lang, which Java imports automatically.
✅ Key Takeaways
- A String is an object holding text, written in double quotes, indexed from 0.
- String literals are shared through the string pool.
new String(...)makes a separate object. - Compare text with
equals()(orequalsIgnoreCase).==compares references. - Strings are immutable: methods return new Strings, so store the result.
"text".equals(x)is safe against null.
🎓 Practice questions: (1) Explain why"java" == "java"is true butnew String("java") == "java"is false. (2) Write a program that checks whether a String is a palindrome. (3) What does"Hi" + 1 + 2print, and1 + 2 + "Hi"? (4) Why doess.toUpperCase();alone do nothing? (5) How would you safely compare a user’s input with “exit” when the input might be null?
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java