Java Strings

Strings are used to store text.

A String variable is a series of characters enclosed in double quotes:

Example

Create a String variable and assign it a value:

String carBrand = "Toyota";




String Length

In Java, a String is actually an object that comes with methods to perform various operations. For instance, you can find out the length of a string using the length() method:

Example

String carModels = "CamryCorollaRAV4Highlander";
System.out.println("The length of the carModels string is: " + carModels.length());




More String Methods

Java provides many methods for strings, such as toUpperCase() and toLowerCase():

Example

String carName = "Toyota Supra";
System.out.println(carName.toUpperCase());   // Outputs "TOYOTA SUPRA"
System.out.println(carName.toLowerCase());   // Outputs "toyota supra"




Finding a Character in a String

The indexOf() method returns the position of the first occurrence of a specified text within a string (including spaces):

Example

String advertisement = "Please find where 'find' appears in this car ad!";
System.out.println(advertisement.indexOf("find")); // Outputs 7
Scroll to Top