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
- String functions
Declaring a string
String nameOfString = "stringValue";
String nameOfString = new String("stringValue");
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.
String myString = "I like pineapple";
//print a string variable
//print a non-variable string
//just put some text in double quotes and it's done
System.out.println("Green is a great color");
I like pineapple
Green is a great color
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.
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;
//print two strings together
System.out.println("Notepad is a " + "simple text editor.");
Here is some text. Here is some more text.
Notepad is a simple text editor.
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.
String aString = "Here is some text";
String anotherString = "Here is some more text";
//extract the third character
//from the aString string and print it
//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
The two strings match: false
The length of the aString string variable is 17
HERE IS SOME TEXT