You will work with Strings in Java frequently! Here is a quick overview of some of the helpful methods you can use on String objects. There are many more and you can read about them in the docs for the String class. The docs may seem intimidating, but you have learned enough to understand and take advantage of them!
To check if two Strings are equal in Java, you should use the .equals()
method. To learn why comparing Strings with ==
is perilous, check out this phenomenal StackOverflow post.
String[] innerPlanets = {"Mercury", "Venus", "Earth", "Mars"};
boolean isVenus1 = innerPlanets[1].equals("Venus");
boolean isVenus2 = innerPlanets[1].equals("venus");
System.out.println(isVenus1); // true
System.out.println(isVenus2); // false
Not only can you check if two Strings have the same contents, but you can check if a String contains another "substring."
String comment1 = "I'm not really into pancakes.";
String comment2 = "I LOVE PANCAKES.";;
boolean hasPancakes1 = comment1.contains("pancakes");
boolean hasPancakes2 = comment2.contains("pancakes");
System.out.println(hasPancakes1); // true
System.out.println(hasPancakes2); // false
The two examples above illustrate how equals()
and contains()
are case-sensitive. It's easy to change the case of Strings in Java.
String spongeBobCase = "hElLo WoRlD";
String lower = spongeBobCase.toLowerCase();
System.out.println(lower); // hello world
String upper = spongeBobCase.toUpperCase();
System.out.println(upper); // HELLO WORLD
Maybe someone will invent a function to convert text to Sponge Bob case...
The methods demonstrated below do not belong to the String class, but they are used to convert Strings to other data types.
String number = "36";
int count = Integer.parseInt(number);
System.out.println(count); // 36
String cost = "12.54";
double dollarsAndCents = Double.parseDouble(cost);
System.out.println(dollarsAndCents); // 12.54