Collections: Strings

Python Java
A string is a sequence of 0 or more characters.

Strings are instances of the str class. Strings are immutable objects.

The len function returns the number of characters in a string.

The subscript operator ([]) accesses a character at a given position.

Example:

aString = “Hello world!”

print(len(aString), aString[2])

Strings can be compared using the standard comparison operators ==, <, etc.

A string is a sequence of 0 or more characters

Strings are instances of the String class. Strings are immutable objects.

The length() method returns the number of characters in a string.

The charAt method accesses a character at a given position.

Example:

String aString = “Hello world!”

System.out.println(aString.length());
System.out.println(aString.charAt(2));

The String class includes many useful methods for searching, obtaining substrings, and so forth.

Strings should be compared using the methods equals and compareTo.

© Ken Lambert. All rights reserved.