You are on page 1of 2

Strings: A crash course

The String class represents character strings. All string literals in Java, such as "abc", are implemented as
instances of this class.

It is important to know that the first character of a String is at position zero.
Useful Methods

These are not all the methods of the string class, and there are a lot more useful things that strings can do.
If you want to see some other things, than look on the Javadoc for Strings.
public int .length()

This method returns the number of characters in the string.
Example:
Code Output
System.out.println(KLAB.length() ) 4

public charAt(int index)

This method returns the char value at the specified index.
Example:
Code Return
KLAB.charAt(2) A

public String substring(int beginIndex, endIndex)

Returns a new string that is a substring of this string. The substring begins with the character at
the beginIndex and extends to the endIndex -1 (it doesnt include the character at endIndex).
Code Return
KLAB.substring(1,3) LA


public String substring(int beginIndex)

Returns a new string that is a substring of this string. The substring begins with the character at
the specified index and extends to the end of this string.
This is functionally equivalent to substring(beginIndex, length())
Example:
Code Return
KLAB.substring(2) AB

public String replace(String old, String new)

Returns a string with all occurrences of old replaced with new from left to right.
Example:
Code Return
omomomom.replace(mom, key) okeyokey

String literals

String literals are instances of string objects. Only one string object is created for every distinct String
literal,.
String s = Tango;
String o = Tango;
(o == s) will evaluate to true
String s = new String("Tango");
String y = new String("Tango");
(s == y) will evaluate to false

Practice:

1. Do several problems in the Strings section of coding bat.

You might also like