String Class

Package: java.lang

In Java, strings are reference types based on the String class, not value types like int or boolean. As a result, a string variable holds a reference to an object created from the String class, not the value of the string itself.

Java lets you create strings as if they were primitive types, by assigning a string literal to a String variable, like this:

String greeting = “Hello, World!”;

Note that in Java, a String object is immutable, which means that it can’t be changed. Thus, none of the methods of the String class actually changes the value of a String object. Instead, they manipulate the value of the String object and return a new String object that is a variation of the original string.

Constructors

Method

Description

String()

Creates a new empty string.

String(String original)

Creates a new String object whose value is identical to original.

String(StringBuilder builder)

Creates a new String object whose value is identical to builder.

Methods

Method

Description

char charAt(int index)

Returns the character at the specified position in the string.

int compareTo(String anotherString)

Compares this string with another string, using alphabetical order. Returns –1 if this string comes before the other string, 0 if the strings are the same, and 1 if this string comes after the other string.

int compareToIgnore Case(String anotherString)

Similar to compareTo but ignores case.

boolean ...

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.