Lesson 10 +10 XP

Java Strings

A String stores text, like "Hello World". Strings are written in double quotes and are one of the most used types in Java.

Creating a string


java

### String greeting = "Hello World";

### System.out.println(greeting);

Useful string methods


java

### String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(txt.length()); // prints 26

String txt2 = "Please locate where 'locate' occurs!";
System.out.println(txt2.indexOf("locate")); // prints 7
  • length() returns the number of characters.
  • indexOf("text") returns the position of the first occurrence.

Changing case


java

### String txt = "Hello World";
System.out.println(txt.toUpperCase()); // HELLO WORLD
System.out.println(txt.toLowerCase()); // hello world

Concatenation

Join strings with +:


java

### String firstName = "John";

### String lastName = "Doe";

### System.out.println(firstName + " " + lastName);

Or use the concat() method:


java

### String x = "Hello";

### String y = "World";

### System.out.println(x.concat(y));

String positions

String positions start at 0, so in "locate" inside the example, the l is at position 7.

TL;DR

  • Strings hold text in double quotes.
  • length() counts characters.
  • + or concat() joins strings.
  • toUpperCase() and toLowerCase() change case.