You are on page 1of 24

Interactive Program

&
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

• Scanner: An object that can read input from many sources.


• Communicates with System.in (the opposite of System.out)
Scanner Syntax
• The Scanner class is found in the java.util package.
import java.util.Scanner;

• Constructing a Scanner object to read console input:


Scanner <Object Name> = new Scanner(System.in);

• 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

• Each method waits until the user presses Enter.


• The value typed by the user is returned.
• Reference:-
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Scanner Example
import java.util.Scanner;

public class TestInput {

public static void main(String[] args) {


Scanner objScan = new Scanner(System.in);//Scanner object

System.out.println("Input Number >> ");//Promp user input


int num = objScan.nextInt();// num is taken value form user input
System.out.println("Your input is " + num); //Show in console
}
}
String Class
String manipulation
Java – String Class
• Strings, which are widely used in Java programming, are a
sequence of characters.
• In Java, strings are treated as objects – Java platform provides
the String class to create and manipulate strings.
• The String class belongs to the java.lang package, which does not
require an import statement.
• Like other classes, String has constructors and methods.
Immutability
• Once created, a string cannot be changed: none of its
methods changes the string.
• Such objects are called immutable.
• Immutable objects are convenient because several
references can point to the same object safely: there is no
danger of changing an object through one reference without
the others being aware of the change.
Advantages Of Immutability
• Uses less memory.
String word1 = "Java"; String word1 = “Java";
String word2 = word1; String word2 = new String(word1);

word1 word1 “Java"

“Java" word2 “Java"


word2
Less efficient:
OK wastes memory
No Argument Constructors
• No-argument constructor creates an empty String. Rarely
used.
String empty = new String();

• A more common approach is to reassign the variable to an


empty literal String. (Often done to reinitialize a variable used to store
input.)

String empty = “”; //nothing between quotes


Methods — length() & charAt()
int length();  Returns the number of characters in the string

char charAt(i);  Returns the char at position i.

Character positions in strings


are numbered starting from 0
– just like arrays.

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

String str =“BCS2143 OOP - JAVA";


Returns:
str.indexOf ('B'); 0
str.indexOf (‘S'); 2
str.indexOf (“OOP"); 8
(starts searching at
str.indexOf (‘A', 16); 17
position 16)

str.indexOf (“object"); -1 (not found)


str.lastIndexOf (‘0'); 9
Methods — Equality
boolean b = word1.equals(word2);
returns true if the string word1 is equal to word2
boolean b = word1.equalsIgnoreCase(word2);
returns true if the string word1 matches word2, case-blind

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.

• Use the equals() method to test for equality.


.equals() Method vs. == Operator
String str1 = “BCS2143“;
String str2 = “BCS2143“;
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));

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.

• == compares objects by references, so it often gives false even when two


Strings have the same letters.
Comparing Strings: “==“ vs. equals()
• Objects are compared using a method named equals().
Scanner console = new Scanner(System.in);
System.out.print("What is your favorite subject? ");
String name = console.next();
if (name.equals(“Java“)) {
System.out.println(“Java love you, you love Java,");

• This code will print the output.


Methods — replace()
String word2 = word1.replace(oldCh, newCh);
returns a new string formed from word1 by replacing all occurrences
of oldCh with newCh

String word1 = “java“;


String word2 = “java“.replace(‘v’, ‘w’);
//word2 is “jawa”, but word1 is still “java“
Methods — Changing Case
String word2 = word1.toUpperCase();
String word3 = word1.toLowerCase();
returns a new string formed from word1 by converting its characters
to upper (lower) case

String word1 = “HeLLo“;


String word2 = word1.toUpperCase();//”HELLO”
String word3 = word1.toLowerCase();//”hello”
//word1 is still “HeLLo“
Numbers to Strings
Three ways to convert a number into a string:
1. String s = "" + num;
s = “” + 123;//”123”
Integer and Double are
2. String s = Integer.toString (i); “wrapper” classes from
java.lang that represent
String s = Double.toString (d); numbers as objects.
s = Integer.toString(123);//”123” They also provide useful
static methods.
s = Double.toString(3.14); //”3.14”

3. String s = String.valueOf (num);


s = String.valueOf(123);//”123”

You might also like