Declaring/Initializing/Constructing Strings:
-
Directly Declaring/Initializing:
String realBoy; //declaration
//declaration must only happen once per 'scope' block
realBoy = "Pinocchio"; //initialization
String conscience = "Jiminy Cricket"; //declaration-initialization combo, most common construct -
Using a String 'constructor':
String elderlyCarpenter = new String("Geppetto"); -
Empty vs.
nullStringsString temp = ""; //empty: can be used as a building block
String badBoy = null; //declared but not initialized;
/*
'Holds space' but will throw a 'NULL POINTER EXCEPTION' if you try to use an instance method with it
*/ -
Using a
chararray as a parameter to an (overloaded) constructor:char bug[] = {'J', 'I', 'M', 'I', 'N', 'Y'}; //initializer list String bugStr = new String(bug); //String is NOT a char array!!! -
From a
char:char ch = 'x'; //using an easy 'hack,' almost like a 'cast' String hackedLtr = "" + ch; //using various 'Wrapper' classes String ltr = String.valueOf(ch); String duplicateLtr = Character.toString(ch);
Concatenating Strings:
-
Using the (+) operator:
String p1 = "Pinocchio"; String p2 = "Knows Strings!"; String p3 = p1 + " " + p2;
-
Using the
concatmethod:String p4 = "When you wish"; String p5 = " upon a star..."; String p6 = p4.concat(p5);
Beloved String Methods:
| Method/Concept | Example | Output | Usage/Comments |
|---|---|---|---|
|
String whale = "Monstro"; int len = whale.length(); System.out.println(whale + " has " + len + " letters"); |
'Monstro has 7 letters' |
Note that |
|
String phrase = "Pinocchio Knows Strings";
char symbol = phrase.charAt(21);
System.out.println("symbol = " + symbol);
|
'symbol = g' |
Beware of 'zero-based indexing!' The first letter in a String is at an index value of Note that a |
|
String phrase = "Pinocchio Knows Strings";
int ndx = phrase.indexOf("s");
System.out.println("first instance of 's' is at index: " + ndx);
ndx = phrase.indexOf("n", 10);
System.out.println("an instance of 'n' is at index: " + ndx);
|
'first instance of 's' is at index: 14' |
The reverse of
Another parameter signature: This allows you to begin a search starting from If a instance is not found, the method returns a -1 |
|
String phrase = "Pinocchio Knows Strings";
int ndx = phrase.lastIndexOf("o");
System.out.println("last instance of 'o' is at index: " + ndx);
|
'last instance of 'o' is at index: 12 |
Identical in nature to |
|
String phrase = " 'Spaces are evil!' "; String trimmedPhrase = phrase.trim(); System.out.println(trimmedPhrase); |
'Spaces are evil!' |
Trims away all leading and/or trailing 'whitespace' Using this method is essential when obtaining input from users! |
b: beginning ndx [b, ∞) or [b, u) |
String tenDigits = "0123456789"; String result1 = tenDigits.substring(6); System.out.println(result1); String result2 = tenDigits.substring(2, 5); System.out.println(result2); |
'6789' |
Takes a portion of a String; the difficult thing about this overloaded method is that the 2-parameter version goes up to but not including the last index mentioned. A helpful check: returned substring length: upToNdx - startNdx |
|
//Example 1:
String name1 = new String("Programiz");
String name2 = new String("Programiz");
System.out.println("Check if two strings are equal");
// check if two strings are equal
// using == operator
boolean result1 = (name1 == name2);
System.out.println("Using == operator: " + result1);
// using equals() method
boolean result2 = name1.equals(name2);
System.out.println("Using equals(): " + result2);
//Example 2:
String name1 = new String("Programiz");
String name2 = name1;
System.out.println("Check if two strings are equal");
// check if two strings are equal
// using == operator
boolean result1 = (name1 == name2);
System.out.println("Using == operator: " + result1);
// using equals() method
boolean result2 = name1.equals(name2);
System.out.println("Using equals(): " + result2);
|
Example 1:
Check if two strings are equal
Using == operator: false
Using equals(): true
Example 2:
Check if two strings are equal
Using == operator: true
Using equals(): true
|
Moral:NEVER use == to compare Strings! Example 1: Example 2: This was a nifty example from the internet! |
|
String hero1 = "Spiderman";
String hero2 = "Antman";
System.out.println(hero1.compareTo(hero2)); // Returns >0 because Spiderman comes after Antman in dictionary
String hulk1 = "hulk smash!";
String hulk2 = "HULK SMASH!";;
System.out.println(hero1.compareToIgnoreCase(hero2)); //same except for casing
|
18 (S is 18 steps from A in alphabet) 0 |
Cool for 'lexicographic' comparisons (alphabetizing) |
|
String shout = "Boo!";
shout = shout.toUpperCase();
System.out.println(shout);
String whisper = "Hush!";
whisper = whisper.toLowerCase();
System.out.println(whisper);
|
'BOO!' 'hush!' |
Java Strings are case-sensitive |
|
String someAvengersStr = "Thor|Spider-man|Hulk|Dr. Strange";
String avengers[] = someAvengersStr.split("|");
for(String a : avengers) System.out.println(a);
|
Thor |
A convenient way to create a primitive array of Strings |
The methods above work with |
String phrase = "Spaces are Evil! ";
String sanitizedPhrase = phrase.replace(" ", "-");
System.out.println(sanitizedPhrase);
|
'Spaces-are-Evil!---' |
Learn more about sanitizing phrases at our Password Peek-a-boo app! |
|
String x = "AP C Sci";
ArrayList<Boolean> casing = new ArrayList<Boolean>();
for(int ndx = 0; ndx < x.length(); ndx++){
String ltr = x.substring(ndx, ndx+1);
char ch = x.charAt(ndx);
if(Character.isUpperCase(ch)) casing.add(true);
else casing.add(false);
}//end for loop
System.out.println(x);
System.out.println(casing);
|
AP Computer Science |
Use the Character class's isUpperCase() method on a character to determine its casing status.
|
|
import java.text.DecimalFormat;
double number = 987654.321;
DecimalFormat df = new DecimalFormat("#,###.00");
String formattedNumber = df.format(number);
|
987,654.32 |
Use the DecimalFormat class to create formatted String output. |
|
String w = "manipulate";
char firstChar = w.charAt(0);
String firstLtr = "" + firstChar; //hack to get char to String
char lastChar = w.charAt(len-1);
String lastLtr = String.valueOf(lastChar); //method way to convert
//another way:
//String lastLtr = Character.toString(lastChar);
System.out.println("firstLtr, lastLtr = " + firstLtr + ", " + lastLtr);
|
firstLtr, lastLtr = m, e |
Notice there are several techniques to get the nth letter from a String. Some are 'hacky, ' others are based on class methods from either String or Character classes. |
Helpful String Manipulations:
There are additional String Manipulation Methods on our Java Utilities page as well.
| User Method Call | Code |
|---|---|
Get Last Symbol in StringString x = "Hello, World!"; String lastSymbl = lastSymbol(x); |
public static String lastSymbol(String str){
int len = str.length();
char lastChar = str.charAt(len-1);
return String.valueOf(lastChar);
}//end lastSymbol
Could easily overload this to return a last char |
