OOP Java - String and Scanner
OOP Java - String and Scanner
3
String and Scanner
• Introduction to String
• How to Create String
• String Methods
• String Literals vs String Object
• String Equality
• Mutable vs Immutable Object
• Why String is Immutable in Java
• StringBuffer & StringBuilder
• What is Scanner Class in Java
• User Input through Scanner
Introduction to String
String is probably the most used class in Java’s class library. The obvious reason for this is
that strings are a very important part of programming.
The first thing to understand about strings is that every string you create is an object of type
String. Even string constants are String objects. For example, in the statement
The second thing to understand about strings is that objects of type String are immutable.
Once a String object is created, its contents cannot be altered. It will be discussed in detail
later in the note.
Strings can be constructed in a variety of ways. The easiest is to use a statement like this:
Once you have created a String object, you can use it anywhere that a string is allowed.
For example, this statement displays myString:
System.out.println(myString);
Java defines one operator for String objects: +. It is used to concatenate two strings. For
example, this statement
In the first statement, str1 is declared as a String reference and initialized with a string
literal "Hello World". In the second statement, str2 is declared as a String reference and
initialized via the new operator and constructor to contain "Hello Java".
String literals are stored in a common pool. This facilitates sharing of storage for strings
with the same contents to conserve storage. String objects allocated via new operator are
stored in the heap, and there is no sharing of storage for the same contents.
String Methods
The commonly used method in the String class are summarized below.
String s1 = “Hello”;
String s2 = “World”;
String s3 = “Hello”;
No Method Example
1 length() - returns the number of characters in the String. s1.length(); // 5
2 charAt() - returns the character at the specified index. s2.charAt(2); // r
3 equals() - returns true if two strings have equal contents. s1.equals(s2); // false
s1.equals(s3); // true
4 compareTo() -returns 0 if equal, Less than zero – if the s1.compareTo(s2) // -15
invoking String is "less than” the other, Greater than s1.compareTo(s3) // 0
zero - if the invoking String is "greater than" the other. s2.compareTo(s3) // 15
5 indexOf() - returns the index within the string of the first s1.indexOf(‘e’) // 1
occurrence of the specified string. s1.indexOf(‘l’) // 2
6 substring() - returns a portion of the String's text. s1.substring(2) // lo
s1.substring(0, 2) // Hel
7 toUpperCase(), toLowerCase() - converts the String to s1.toUpperCase() // HELLO
upper- or lower-case characters. s1.toLowerCase() // hello
8 concat() - concatenates specified string to the end of this s1.concat(s2) // HelloWorld
string.
As mentioned, there are two ways to construct a string: implicit construction by assigning a
string literal or explicitly creating a String object via the new operator and constructor. For
example,
Java has provided a special mechanism for keeping the String literals - in a so-called string
common pool. If two string literals have the same contents, they will share the same storage
inside the common pool. This approach is adopted to conserve storage for frequently used
strings. On the other hand, String objects created via the new operator and constructor are
kept in the heap. Each String object in the heap has its own storage just like any other object.
There is no sharing of storage in heap even if two String objects have the same contents.
String Equality
You can use the method equals() of the String class to compare the contents of two Strings.
You can use the relational equality operator '==' to compare the references of two objects. Let
us examine the following codes:
Mutable Immutable
Fields can be changed after the object creation Fields cannot be changed after object creation
Generally, provides a method to modify the Does not have any method to modify the field
field value value
Has Getter and Setter methods Has only Getter method
Example: String, Boxed primitive objects like
Example: StringBuilder, java.util.Date
Integer, Long and etc
The following code will create only one string object in the heap.
JDK provides two classes to support mutable strings: StringBuffer and StringBuilder (in core
package java.lang). A StringBuffer or StringBuilder object is just like any ordinary object,
which are stored in the heap and not shared, and therefore, can be modified without causing
adverse side-effect to other objects.
StringBuilder class was introduced in JDK 5. It is the same as StringBuffer class, except that
StringBuilder is not synchronized for multi-thread operations. However, for single-thread
program, StringBuilder, without the synchronization overhead, is more efficient.
Method Description
append(String str) This method is used for adding new text at the end of an existing
append(int number) mutable string.
insert(int index, String Used for inserting text at a specified position in a given string. In the
str) given syntax index specifies the starting index of at which the string
insert(int index, char ch) will be inserted.
delete(int start, int end) Used for deleting characters from a mutable string. Start indicates the
and deleteCharAt(int starting index of the first character to be removed and the end index
index) indicates an index of one past the last character to be removed.
replace(int startindex, int Used for replacing character sequence between startindex and
endindex, String str) endindex-1 with the specified string.
JDK 1.5 introduces java.util.Scanner class, which greatly simplifies formatted text input
from input source (e.g., files, keyboard, network). Scanner, as the name implied, is a simple
text scanner which can parse the input text into primitive types and strings using regular
expressions. It first breaks the text input into tokens using a delimiter pattern, which is by
default the white spaces (blank, tab and newline). The tokens may then be converted into
primitive values of different types using the various nextXxx() methods (nextInt(),
nextByte(), nextShort(), nextLong(), nextFloat(), nextDouble(), nextBoolean(), next() for
String, and nextLine() for an input line). You can also use the hasNextXxx() methods to
check for the availability of a desired input.
To create an object of Scanner class, we usually pass the predefined object System.in, which
represents the standard input stream.
N.B: We may pass an object of class File if we want to read input from a file.
import java.util.Scanner;
Exercises
1. Write a Java program to find the length of a given string. The string is “Hello Java”.
2. Write a Java program to concatenate a given string to the end of another string. First
String is “This is a simple text”, and the second string is “concatenated string”.
3. Write a Java program to check whether two strings are equal or not.
4. Write a Java program to reverse a string. (take user input using scanner).