What is a String?
- A String is an object in Java that stores text.
- Strings are made up of characters (letters, numbers, symbols).
- In Java,
Stringstarts with a capital S because it is a class.
Creating a String
String name = "Joe";
String school = "Klein Collins";
Remember: Text must be inside double quotes
" ".
Printing Strings
System.out.println(name);
System.out.println("Hello world");
printlnprints and moves to a new line.printprints without moving to a new line.
String Concatenation
- Concatenation means joining Strings together.
- Java uses the
+operator to concatenate Strings.
Basic Example
String firstName = "Joe";
String lastName = "Cusack";
String fullName = firstName + " " + lastName;
System.out.println(fullName);
Output
Joe Cusack
Concatenating Strings and Numbers
String + String
String greeting = "Hello " + "World";
Hello World
String + Number
int age = 16;
System.out.println("Age: " + age);
Age: 16
Important: When a String is involved, Java converts numbers into text automatically.
Order Matters (Left to Right)
System.out.println(10 + 5 + " apples");
System.out.println("Apples: " + 10 + 5);
Output
15 apples
Apples: 105
Why? Java evaluates left to right. Once it sees a String, everything after becomes a String.
Common String Methods
.length()
Returns the number of characters in a String.
String word = "Java";
System.out.println(word.length());
4
.equals()
Used to compare String values.
String a = "hello";
String b = "hello";
System.out.println(a.equals(b));
true
Do NOT use
== to compare Strings. Use .equals().
Escape Characters
Escape characters let you place special characters inside Strings.
System.out.println("He said \"Hello\"");
System.out.println("Line1\nLine2");
\"→ quotation mark\n→ new line
Common Mistakes to Avoid
❌ Forgetting Quotes
String name = Joe; // ERROR
✅ Correct Version
String name = "Joe";
❌ Comparing Strings with ==
✅ Use .equals() instead.
Key Takeaways
Stringis a class used to store text.- Strings use double quotes.
- Use
+for concatenation. - Java reads concatenation left to right.
- Use
.equals()to compare Strings.