Strings and Characters


A character is a single item. Any key you press on the keyboard is a character, whether visible or not. All characters are part of the set of ASCII characters.

ASCII stands for American Standard Code for Information Exchange. Every character has its own ASCII value, which is a numeric representation of the character - this is how the computer stores the character. For example, the letter 'A' is stored as the number 65. ASCII values range from 0 to 255.

A String is an array of characters. Java uses a class file to manage this array. Some of the more common things to do with Strings are:

char charAt(int index)

returns the character at the specified array location of the String 

String someString = "Hello, World!";
char cRetVal = someString.charAt(5);

boolean equals(Object anObject)

returns the truth of the equality usually used to compare two Strings

DO NOT use == to compare two Strings

String string1 = "Joe";
String string2 = "joe";
boolean isEqual = string1.equals(string2);
System.out.println("The answer is: " + isEqual);

int indexOf(String str)
int indexOf(String str, int fromIndex)

returns the array location in which the specified String starts within the larger string.

String someString = "Please, Please help me I'm falling";
int index1 = someString.indexOf("Please");
int index2 = someString.indexOf("Please", index1+1);

int length()

returns the length of the string

String someString = "Hello";
int iLen = someString.length();

NOTE:  To determine the size of an array, you use the length property - no parentheses.  To determine the size of a string, you use the length method - with parentheses.

String substring(int beginIndex)
String substring(int beginIndex, int endIndex)

returns a part of the string starting at the beginIndex position

the first version goes to the end of the string

the second goes up to, but does not include, the position at endIndex

String someString = "I Love Java!";
String sub1 = someString.substring(8); // ava!
String sub2 = someString.substring(2,5); // Lov

toUpperCase() toLowerCase()

returns the upper/lower case version of the String 

String sUpper = someString.toUpperCase();
String sLower = someString.toLowerCase();