NOTICE ISP is back up.. Stay tuned for class status for Thursday 2017-03-23
Free Java Tutorials >> Table of contents >> Strings And Chars

1. The char type

Initializing chars

A char stores a single character, such as 'x'. More about char will be covered when we learn about strings. The important thing to remember is that a character is stored internally as a number, and that characters can be casted to ints easily. First, let's create some chars:

public class MyProgram {
    public static void main(String[] args) {
		char var = 'a'; //the variable var stores the character 'a'
		char a   = 'x'; //the variable a stores the character 'x'
		//it is important to realize the variable name and the internal character can be different
		System.out.println(var); //prints the character a
		System.out.println(a);   //prints the character x
		System.out.println('b'); //prints b
    }
}

Casting chars to/from ints

The character 'a' is stored internally as the number 97. The character 'A' (capital A) is the number 65. We can find many of these on conversions on "ASCII Tables" and "Unicode Tabls" you can find on the internet. Indeed, these days there are many characters that computers can support besides those from English. The original 127 characters were part of the ASCII table, but many new characters such as those from Asian languages are part of the extended unicode table. Here's how to cast a character to an integer to find its numerical value:

public class MyProgram {
    public static void main(String[] args) {
		System.out.println(    (int)'a'  ); //prints 97. The spaces are here just for clarity
		char a = 'A';
		System.out.println(    (int)a    ); //prints 65
		System.out.println(   ((int)'x') ); //some people like additional parenthesis, though not required

		System.out.println( (char)97 ); //prints the character 'a' 
		System.out.println( (char)65 ); //prints the character 'A'
    }
}

Special characters and Escape characters

Keys such as enter, space, and tab are also characters (10, 32, and 9). However, you can't put every character in single quotes to signify a char. For example, although println('a') works, println(''') does not, since Java thinks the second single quote is ending the char. Thus, to print a single quote, you actually need println('\''). Typing the slash in front of the single quote is called "escaping" the character, or creating an "escape sequence". Here are some more escape sequences:

public class MyProgram {
    public static void main(String[] args) {
		System.out.println('\t'); //a tab
		System.out.println('\b'); //a backspace (deletes the previous character printed!)
		System.out.println('\n'); //a new line character, used as a new line for Linux, MacOSX
		System.out.println('\r'); //a "carriage return". Windows uses a \r\n for new lines
		System.out.println('\''); //single quote
		System.out.println('\"'); //double quote
		System.out.println('\\'); //a backslash
		System.out.println("She said she \"literally\" ate my cat");
		//Previous line prints: She said she "literally" at my cat
    }
}


			
Run

2. String concatenation, length, charAt

String expressions and variables, concatenation

We already have seen strings before with println("Hello World");. While characters are a single character enclosed in single quotes, Strings expressions are multiple characters enclosed in double quotes. We can also store them in the variable type String. Unlike all the previous variable types we have learned, the String variable type is capitalized. There is an important reason for this that we will learn later on (Strings are classes), however for now you can treat them like the other variable types:

public class MyProgram {
    public static void main(String[] args) {
		System.out.println("The babel fish likes causing wars");
		String s = "Leek dance";
		System.out.println(s); //prints leek dance
    }
}

We can concatenate, or connect, Strings together using the plus operator. The word concatenate seems fancy, but it's actually quite simple: "hello" + "cat" is "hellocat". If you want spaces in Strings, you must explicitely include them: "hello "+"world" is "hello world". We can also use variables:

public class MyProgram {
    public static void main(String[] args) {
		String a = "nyan";
		String b = "cat";
		System.out.println(a+" "+b);  //prints nyan cat
		System.out.println(a+" "+12); //Java will automatically convert 12 into the String "12", making this "nyan 12"
		System.out.println(""+5+5);   //This is an important example that prints "55"
						              //""+5 is run first, giving the String "5", then "5"+"5" is "55"
    }
}

Previously, we created variables like sum to add up a bunch of numbers into sum. We can also create a String and make it longer and longer by adding characters into it. For example:

public class MyProgram {
    public static void main(String[] args) {
		String v = "this ";
		v = v + "is ";  //now v is "this is "
		v += "a ";      //same as v = v + "a", now v is "this is a ";
		v = v + 4 + 2;  //does v + 4 to yield "this is a 4", then adds 2 as a string for "this is a 42"
		v += ' ';       //we can concatenate characters too
		v += "foot long flying squirrel";
		System.out.println(v);
    }
}

The length() function

"Hello".length() is the int 5, since there are five characters in "Hello". Spaces, tabs, and other escape characters also count. Thus, "cat mat".length() is 7, not 6. Because new line characters are "\r\n" in windows, sometimes a new line can take up two characters in length. However, most modern text editors use "\n" as a new line.

public class MyProgram {
    public static void main(String[] args) {
		System.out.println("hello".length() * 2); //10
		String drink = "tea";
		System.out.println(tea.length() > 2);     //true
    }
}

The charAt(int i) function

Internally, Strings are actually arrays of characaters. However, in Java, we cannot use square brackets to get a single character out of a String. Instead, if we wanted the first character in "Hello" (the 'H'), we would use the expression "Hello".charAt(0). The second character would be "Hello".charAt(1), and the last character would be "Hello".charAt(hello.length()-1). The minus one is needed since we count starting from 0. Here are some more examples:

public class MyProgram {
    public static void main(String[] args) {
		char c = "Hello".charAt(0); 
		System.out.println(c); //prints 'H'
		String test = "iluvatar";
		System.out.println(test.charAt(2));      //prints 'u'
		System.out.println(test.charAt(2)=='u'); //prints the boolean true
		System.out.println(test.charAt(2)>'Z');  //prints true, since 'u' is after capital 'Z' in unicode
    }
}


			
Run

3. String equals, compareTo, reversal

The equals(String o) function

String and other capitalized types are called object types or class types. This is in contrast to boolean, byte, short, int, long, float, double, char which are primitive types

You often cannot or should not use boolean < > >= <= == != operators with object types. Instead you must use equals() and compareTo(). We will show the use of equals here first:

public class MyProgram {
    public static void main(String[] args) {
		String a = "dessert";
		String b = "disaster";
		String c = "dessertdisaster";
		System.out.println( (a+b).equals(c) ); //true cause "dessert"+"disaster" equals "dessertdisaster"
		System.out.println(     a.equals(a) ); //true
		System.out.println(!(a+b).equals(c) ); //! reverses the boolean, making this false
		System.out.println(  a+b == c       ); //this prints false. do not use == to compare!!
		System.out.println( a.equals(b)     ); //false as expected since "dessert" is not "disaster"
		System.out.println(("big"+"toe").equals("bigtoe")); //this works too!
    }
}

Notice that you need to take a String or String expression, add a dot to the end, then equals, then a set of parenthesis with another String or String expression in it. The whole expression then evalutes to a boolean.

The compareTo(String o) function

Comparing the order of Strings is done with the compareTo function, which is case sensitive. To compare two strings, we do this:

public class MyProgram {
    public static void main(String[] args) {
		System.out.println("aa".compareTo("bb"));  //-1, negative since aa is before bb alphabetically
		System.out.println("bb".compareTo("aa"));  //1, positive since bb is after aa
		System.out.println("aa".compareTo("aa"));  //zero since they are equal. For String this is same as .equals()
		System.out.println("aa".compareTo("BB"));  //31, positive since a is AFTER capital "B" in the ASCII table
		System.out.println("AA".compareTo("bb"));  //-33, the number is not as important as the sign (positive/neg)
		System.out.println("bb".compareTo("bc"));  //-1, it checks the second character if the first matches
		System.out.println("bb".compareTo("ba"));  //1
		System.out.println("bb".compareTo("bbb")); //-1, since the second is the same just longer
		System.out.println("bbb".compareTo("bb")); //1
    }
}

As you can see compareTo evaluates to a number, and you can use whether it is smaller than zero, greater than zero, or equal to zero to know the order. Like equals(), we can use variables rather than just expressions.

Check if a string is a palindrome

First we will reverse a string:

public class MyProgram {
    public static void main(String[] args) {
		String x = "racecar";
		
		String reverse = "";
		for(int i = x.length() - 1; i >= 0; i--) reverse += x.charAt(i);
		
		if(x.equals(reverse)) {
			System.out.println(x+" is a palindrome");
		}else {
			System.out.println(x+" is not palindrome");
		}
    }
}


			
Run

4. StringBuilder

StringBuilder

String concatenation is an O(n) operation. That means if you are concatenating in a loop, the algorithm is often O(n^2). However, a class called StringBuilder exists to make concatenation ("append") operations faster:

public class MyProgram { public static void main(String[] args) { StringBuilder x = new StringBuilder(); //we will learn what the new Means later //now we have a StringBuilder called x for(int i = 0; i < 10000; i++) { x.append(i+" "); } System.out.println(x.toString()); //the StringBuilder.toString outputs a string } }


			
Run

Previous: Common Functions

Next: String Functions