Chap 2 Pt. 2 String Class
Chap 2 Pt. 2 String Class
Chap 2 Pt. 2 String Class
&
String Class
Scanner Object
Building interactive Java programs, that reads user input from the
console.
System’s Static Fields
• System.in is an InputStream which is typically connected
to keyboard input of console programs.
• System.out is a PrintStream which normally outputs the
data you write to it to the console.
• System.err is a PrintStream. It works like System.out
except it is normally only used to output error texts.
Remember: You have been using System.out since your first “Hello
World” program, now we see System.in is an InputStream.
Input and System.in
• interactive program: Reads input from the console.
• While the program runs, it asks the user to type input.
• The input typed by the user is stored in variables in the code.
• Can be tricky; users are unpredictable and misbehave.
• But interactive programs have more interesting behavior
• Example:
Scanner console = new Scanner(System.in);
Scanner next Methods
Method Description
nextInt() reads an int from user
nextDouble() reads a double from the user
next() reads a one-word String from the user
nextLine() reads a one-line String from the user
Returns:
”Problem".length(); 7
”Window".charAt(2); ’n'
Methods — substring()
• Returns a new String by copying characters from an existing String.
String subs = word.substring (i, k); television
• returns the substring of chars in positions from
i k
i to k-1
String subs = word.substring (i); television
• returns the substring from the i-th char to the
end i
Returns:
"television".substring (2,5); “lev"
"immutable".substring (2); “mutable"
"bob".substring (9); "" (empty string)
Methods — Concatenation
String word1 = “re”, word2 = “think”; word3 = “ing”;
int num = 2;
• String result = word1 + word2;
//concatenates word1 and word2 “rethink“
• String result = word1.concat (word2);
//the same as word1 + word2 “rethink“
• result += word3;
//concatenates word3 to result “rethinking”
• result += num; //converts num to String
//and concatenates it to result “rethinking2”
Methods Find —indexOf()
0 2 89 16
b = “Java”.equals(“Java”);//true
b = “Java”.equals(“Jawa”);//false
b = “Java”.equalsIgnoreCase(“java”);//true
Testing Strings for Equality
• Important note: The == operator cannot be used to test
String objects for equality.
• Variables of type String are references to objects (ie. memory
addresses)
• Comparing two String objects using == actually compares their
memory addresses. Two separate String objects may contain the
equivalent text, but reside at different memory locations.
Output:
false
true
Comparing Strings: “==“ vs. equals()
• Relational operators such as < and == fail on objects.
Scanner console = new Scanner(System.in);
System.out.print("What is your favorite subject? ");
String name = console.next();
if (name == “Java") {
System.out.println(“Java love you, you love Java,");
• This code will compile, but it will not print the output.