Java String Basics & Concatenation

Student Notes (Intro CS / AP CSA)

What is a String?

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");

String Concatenation

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");

Common Mistakes to Avoid

❌ Forgetting Quotes

String name = Joe;   // ERROR

✅ Correct Version

String name = "Joe";

❌ Comparing Strings with ==

✅ Use .equals() instead.

Key Takeaways

  • String is a class used to store text.
  • Strings use double quotes.
  • Use + for concatenation.
  • Java reads concatenation left to right.
  • Use .equals() to compare Strings.
```