Comparing Strings
There is a difference
Comparing Primitives
• Primitives are compared with an operator:
== <
<=
>
>=
!=
//given an int called x, if( x == 100)…
//given a double called num, while(num >= 0)…
//given a boolean called done if(done == true)…
Comparing Strings
• String equality is compared with the dot-equals method: //given a String called word, if(word.equals(“Gamera01”) System.out.println(“Correct Password”); else System.out.println(“Incorrect Password”); if(! option.equals(“Y”) && !option.equals(“N”))
System.out.println(“that is not an option”);
Comparing Strings
• String order is compared with the dot-compareTo method: x.compareTo(y) returns a negative # if x < y returns a positive # if x > y returns zero if x.equals(y) if(word.compareTo(“MMM”) < 0)
System.out.println(word + “ is in the first ½ of the dictionary”); else System.out.println(word + “ is in the last ½ of the dictionary”);
• To better remember which way dot-compareTo is comparing, visualize the operator where the method call is: if(word.compareTo(“MMM”) < 0)
//if word < “MMM”
if(word.compareTo(“MMM”) > 0)
//if word > “MMM”
if(word.compareTo(“MMM”) == 0)
//if word ==“MMM”
Adding Strings together
• Concatination: add strings together using the
+ operator to return a new String.
String x = “hello”;
String y = “world domination”;
String z = x + “ “ + y.substring(0, 5);
System.out.println(z);
Adding Strings together
• Concatination: add strings together using the
+ operator to return a new String.
String x = “hello”;
String y = “world domination”;
String z = x + “ “ + y.substring(0, 5);
System.out.println(z);
//output: hello world
PigLatin Translator
• Input: a single word
• Output: the word in Piglatin.
• Rules:
– If the word starts with a vowel, add “way” to the end: toPig(“apple”) should return “appleway”
- If word starts with a consonant pair (“th”, “ch”, “st”, etc), move the pair to the end of the word and add “ay”: toPig(“shoe”) should return