loading

Strings

Java Strings

Text can be stored in strings.

A group of characters enclosed in double quotations make up a String variable:

Example

Create a variable of type String and assign it a value:

				
					String greeting = "Hello";
				
			

String Length

In Java, a string is essentially an object that has methods on it that may be used to manipulate strings. For instance, the length() method can be used to determine the length of a string:

Example

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

More String Methods

Numerous string methods exist, such as toLowerCase() and toUpperCase():

Example

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

Finding a Character in a String

The index, or location, of the first instance of a given text in a string (including whitespace) is returned by the indexOf() method:

Example

				
					String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate")); // Outputs 7
				
			

Java starts counting at zero.

In a string, 0 is the first place, 1 is the second, and 2 is the third.

Share this Doc

Strings

Or copy link

Explore Topic