Java strings
A string is a grouping of text. You can store this group of a text in a variable that would then be known as a String variable. You can print strings, and you can also use various functions to perform operations on strings such as returning the string's length.
This tutorial focuses on:
- Declaring a string
- Printing a string
- Concatenation
- String functions
Declaring a string
Syntax:
String nameOfString = "stringValue";
String nameOfString = new String("stringValue");
Example:
String aString = "This is a string";
String aString = new String("This is a string");
Whether you declare a string as a variable or with the new keyword, it becomes an instance of the String class. We discuss classes in detail in the Object-oriented Java page. For now, you should just know that a class is a special type of variable.
Printing a string
Use the System.out.print or System.out.println methods to print a string.
Example:
String myString = "I like pineapple";
//print a string variable
System.out.println(myString);
//print a non-variable string
//just put some text in double quotes and it's done
System.out.println("Green is a great color");
Output:
I like pineapple
Green is a great color
Concatenation
Concatenation is the process by which two or more strings are joined together. This is achieved with the use of the + operator. You can use concatenation to join two or more strings into one or print two or more strings together.
Example:
String aString = "Here is some text. ";
String anotherString = "Here is some more text.";
//declare a third string and
//combine into it the first two strings
String combinedString = aString + anotherString;
System.out.println(combinedString);
//print two strings together
System.out.println("Notepad is a " + "simple text editor.");
Output:
Here is some text. Here is some more text.
Notepad is a simple text editor.
String functions
The String class has various functions (methods) you can use to work with text.
-
charAt(int index) - Returns a character from a string at a specified index.
-
equals() - Compares two strings and returns true if they are the same.
-
length() - Returns the length of a string.
-
toUpperCase() - Converts all letters in a string to upper case.
Example:
String aString = "Here is some text";
String anotherString = "Here is some more text";
//extract the third character
//from the aString string and print it
System.out.println(aString.charAt(2));
//compare the two strings aString and anotherString
//and specify if they are the same or not
System.out.println("The two strings match: " + aString.equals(anotherString));
//print the length of the aString string
System.out.println("The length of the aString string variable is " + aString.length());
//print the anotherString string in all uppercase letters
System.out.println(aString.toUpperCase());
Output:
r
The two strings match: false
The length of the aString string variable is 17
HERE IS SOME TEXT