Java TOPIC 49 – BASICS OF STRINGS LESSON NOTE STRINGS ARE NOT
VARIABLES
CREATING A STRING OBJECT
We can create
a String by doing the following: String s = "hello"; `While the
above is really a short form it is the most commonly used. A more
complete way of creating a String would be: String s = new String("hello"); While Strings
are objects, we often incorrectly use the word variable to refer to them. It is often
useful to have a String that contains no characters. This is called an empty
String and is simply expressed as two double quotes "". Example String
str = ""; //Creating an empty String.
String
concatenation is the action of “sticking” two Strings together. In Java, we
use the + symbol to do this.
Example 1 – Store two different words in two
different names and then combine them using the + symbol. Place a space
between the two words. String first = "Patrick"; String last = "Campeau"; String full = first + " " + last;
System.out.println("Enter your name"); String name = DummiesIO.getString(); System.out.println("Hello " + name); INDEX OF EACH CHARACTER Each
character in a String has an index. The first character has index 0, the
second has index 1, and so on…
INSTANCE METHODS (OF STRING CLASS) There
are many built-in methods that are available to us for manipulating Strings.
You can see a full listing in the API Specification on the Java website. 1 – LENGTH
int length()
String s = "abc"; int length = s.length(); The length variable gets the value
3.
2 - SUBSTRING
String substring(int
startAt, int endBefore)
String s1 = "abcdefghijklmnopqrstuvxyz"; String s2 = s1.substring(0,4);
String name = "Patrick"; String initial = name.substring(0,1);
3 – CHANGING THE CASE
String s1 = "Hello"; String s2 = s1.toLowerCase();
//s1 will get "hello" 4 – COMPARING TWO STRINGS
boolean equals(String s)
System.out.println(“Enter a word”); String s1 = DummiesIO.getString(); System.out.println(“Enter another word”); String
s2 = DummiesIO.getString(); if
(s1.equals(s2)) { System.out.println(“Same”); } else { System.out.println(“Different”); } MULTIPLE METHOD CALLS USING “.”
String name = "patrick"; String initial = name.substring(0,1).toUpperCase(); In the above code, the substring
method is called. It returns a new String with a value of “p”. Then, the toUpperCase method is called on that new String returning
“P”. The above code is equivalent to the following: String name = "patrick"; String first = name.substring(0,1); String initial = first.toUpperCase();
if (s1.substring(0,1).equals(s2.substring(0,1))) {
System.out.println("Start with same"); }
if (s1.substring(0,1).toUpperCase().equals(s2.substring(0,1).toUpperCase())) {
System.out.println("Start with same character"); } |
|