Fun With Strings Example Code

of 02

Java Code:

Woman using laptop in cafe
Atsushi Yamada/Photodisc/Getty Images

This program provides some example Java code of how to work with the String class. It shows the use of String Literals, manipulation of

, as well as converting them to numbers and back again.

public class FunWithStrings {

public static void main(String[] args) {

//Use a string literal to assign a value to the String
String address = "I live at 22b Baker Street!";

//The same string but using Unicode values
String unicodeAddress = "\u0049\u0020\u006C\u0069\u0076\u0065"
+ "\u0020\u0061\u0074\u0020\u0032\u0032\u0042\u0020"
+ "\u0042\u0061\u006B\u0065\u0072\u0020\u0053\u0074"
+ "\u0072\u0065\u0065\u0074\u0021";

System.out.println("Here is Sherlock's address: " + address);
System.out.println("It even works using Unicode characters: " + unicodeAddress);

//A char array can be used to make a String
char characterArray[] = {'C', 'h', 'a','r','a','c','t','e','r','s'};
String characterString = new String(characterArray);

//or even a byte arrray
byte byteArray[] = {67,104,97,114,97,99,116,101,114,115};
String byteString = new String(byteArray);

System.out.println("Char Array: " + characterString);
System.out.println("Byte Array: " + byteString);

//Dealing with unusual characters by using the Unicode value
String footballPlayer = "Thomas M\u00FCller plays for Germany.";

//Escape sequences for characters
String speech = "\"I say old chap\", he said to me";
String backSlashNewLine = "The cat was \\grining\\ from ear to ear. Or"
+ " here to\n\n\n here.";

//Looking for Who in The Who
String bandName = "The Who";
int index = bandName.indexOf("Who");

System.out.println("I found Who at position " + index);

String newBandName = bandName.substring(0,index);

//The Who is now The Clash
newBandName = newBandName + "Clash";
System.out.println("Let's change the band name to " + newBandName);

//Convert a string number to an actual number
String number = "10";
int convertedNumber = Integer.valueOf(number).intValue();
System.out.println("The number " + convertedNumber);

//Converting to a differnt number type.
int numberTwenty = 20;
String converted = Double.toString(numberTwenty);

//Time to trim some spaces
String tooManySpaces = " Neil Armstrong.. ";
tooManySpaces = tooManySpaces.trim();

//lexicographically Apple precedes Pear!
String firstString = "Apple";
String secondString = "Pear";

if (firstString.compareTo(secondString)
of 02

More Reading

The articles that go with this program code are: The String ClassThe String Literal, Comparing Strings and Manipulating Strings