Datatype String

Data types specify whether the data are numbers (integer, double float), characters (char), strings (string), truth values (boolean), or other.
Strings consist of words, characters, digits, or a combination thereof, delimited from program code by double apostrophes.

The length of a String is the number of characters it consists of. The individual characters of a string of length n are numbered from 0 to n-1. As an alternative to strings, you could also work with arrays of characters.

The data type String in Java is not a simple data type like int or double or boolean. It is a class of its own. A variable of type string therefore does not contain the string itself, but it contains a reference to an object of the class string.


String string = "hello world";

// equivalent to
char data[] = { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd' };
String str = new String(data);

Java String Methods

Code Explanation

1Import the Java Scanner class used to retrieve user input
3Declares a public class called DataTypeString
4Declares a static class called main() of type void. So the method does not expect any returns. The input parameters of the main() method (string[] args) are command-line arguments
5Creates a new variable named string of datatype string with the value “hello world”
6Creates a new variable named data of datatype char of array with the value ‘h’, ‘e’, ‘l’, ‘l’, ‘o’
7Creates a new variable named str of datatype string and assign the array of chars to it
8Creates a new variable called concatenate. The value of this variable is the concatenation of the variables str and string
10 – 18All methods of the String class can be called via a String object. Different string methods are shown here
import java.util.Scanner;

public class DataTypeString {
	public static void main(String[] args) {
		String string = "hello world";
		char data[] = { 'h', 'e', 'l', 'l', 'o'};
		String str = new String(data);
		String concatenate = str + string;

		System.out.print("string.length(): " + string.length() + "\n" +
				"string.charAt(6): " + string.charAt(6) + "\n" +
				"string.trim(): " + string.indexOf('o') + "\n" +
				"string.substring(): " + string.substring(6) + "\n" +
				"string.toLowerCase(): " + string.toLowerCase() + "\n" +
				"string.toUpperCase(): " + string.toUpperCase() + "\n" +
				"str.concat(): " + str.concat(" world") + "\n" +
				"str.replace('e', 'a'): " + str.replace('e', 'a') + "\n" +
				"string + str: " + concatenate);
string.length(): 11
string.charAt(6): w
string.trim(): 4
string.substring(): world
string.toLowerCase(): hello world
string.toUpperCase(): HELLO WORLD
str.concat(): hello world
str.replace('e', 'a'): hallo
string + str: hellohello world