0% found this document useful (0 votes)
106 views

String

The document discusses the String type in Java. Some key points: - A String represents a sequence of characters. It is an object of the predefined String class. - Strings can be declared and initialized using String variables and string literals. Common methods like length(), charAt(), concat(), trim() etc. allow manipulating strings. - The + operator is used to concatenate strings. Static methods are invoked on the class name while instance methods require a String object. - The document provides examples of declaring and initializing strings, accessing characters, concatenating, converting case and trimming whitespace. It also discusses reading strings from the console.

Uploaded by

Code 304
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
106 views

String

The document discusses the String type in Java. Some key points: - A String represents a sequence of characters. It is an object of the predefined String class. - Strings can be declared and initialized using String variables and string literals. Common methods like length(), charAt(), concat(), trim() etc. allow manipulating strings. - The + operator is used to concatenate strings. Static methods are invoked on the class name while instance methods require a String object. - The document provides examples of declaring and initializing strings, accessing characters, concatenating, converting case and trimming whitespace. It also discusses reading strings from the console.

Uploaded by

Code 304
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 80

The String Type

 A string is a sequence of characters.


 The char type represents only one character.
 To represent a string of characters, use the data type called String.

For example, the following code declares message to be a string with


the value "Welcome to Java".

String message = "Welcome to Java";


 String is a predefined class in the Java library, just like the classes Math and Scanner.
 The String type is not a primitive type.
 It is known as a reference type.
 Here, message is a reference variable that references a string object with contents
Welcome to Java.
 Reference data types will be discussed in detail in Objects and Classes.
 Objective
 how to declare a String variable,
 how to assign a string to the variable, and
 how to use the methods in the String class.
The following Table lists the String methods:

 For obtaining string length,


 For accessing characters in the string,
 For concatenating strings,
 For converting a string to upper or lower cases, and
 For trimming a string.
Simple Methods for String Objects

Method Description
s.length() Returns the number of characters in this string.
s.charAt(index) Returns the character at the specified index from this
string.
s.concat(s1) Returns a new string that concatenates this string with string s1.
s.toUpperCase() Returns a new string with all letters in uppercase.
s.toLowerCase() Returns a new string with all letters in lowercase
s.trim() Returns a new string with whitespace characters trimmed on both
sides.
instance method

static method

 Strings are objects in Java.


 The methods in the above Table can only be invoked from a specific string instance.
 For this reason, these methods are called instance methods.
 A noninstance method is called a static method.
 A static method can be invoked without using an object.
 All the methods defined in the Math class are static methods.
 They are not tied to a specific object instance.
 What is instance method?
 Instance method are methods which require an object of its class to be created before
it can be called.
 To invoke a instance method, we have to create an Object of the class in within which
it defined.

 What is the difference between a static method and an instance method?


 Static method means which will exist as a single copy for a class. ...
 But instance methods exist as multiple copies depending on the number of instances
created for that class
 The syntax to invoke an instance method is
referenceVariable.methodName(arguments).

 A method may have many arguments or no arguments.


For example,
the charAt(index) method has one argument,
but the length() method has no arguments.
 Recall that the syntax to invoke a static method is
ClassName.methodName(arguments).

For example,
the pow method in the Math class can be invoked using Math.pow(2, 2.5).
Getting String Length

 You can use the length() method to return the number of characters in a string.

For example,
the following code
String message = "Welcome to Java";
System.out.println("The length of " + message + " is "+ message.length());
Indices

message

message.length() is 15
public class Testing {

public static void main(String[] args) {


String message = "Welcome to Java";
System.out.println("The length of " + message + " is " + message.length());

}
}
 string literal,
 empty string

Note
 When you use a string, you often know its literal value.
 For convenience, Java allows you to use the string literal to refer directly to strings
without creating new variables.
Thus,
"Welcome to Java".length() is correct and returns 15.
 Note that ""denotes an empty string and
"".length() is 0.
public class Testing {

public static void main(String[] args) {

System.out.println("Welcome to Java".length());
System.out.println("".length());

}
Getting Characters from a String

 The s.charAt(index) method can be used to retrieve a specific character in a string s,


where the index is between 0 and s.length()–1.

 Note that the index for the first character in the string is 0.

String message="Welcome from java";


System.out.println(message.charAt(0));
System.out.println(message.charAt(14));
Indices

message

message.charAt(0) message.length() is 15 message.charAt(14)

 The characters in a String object can be accessed using its index.


For example,
message.charAt(0) returns the character W, as shown in the above Figure.
 string index range

 Caution
 Attempting to access characters in a string s out of bounds is a common programming
error.
To avoid it, make sure that you do not use an index beyond s.length() – 1.

For example,
s.charAt(s.length()) would cause a StringIndexOutOfBoundsException.
public class Testing {

public static void main(String[] args) {


String s = "Welcome to Java";
System.out.println("Length ="+s.length());
System.out.println(s.charAt(s.length()));

}
}
public class Testing {

public static void main(String[] args) {


String s = "Welcome to Java";
System.out.println("Length ="+s.length());
System.out.println(s.charAt(s.length()-1));

}
}
Concatenating Strings

 You can use the concat method to concatenate two strings.


The statement shown below,
For example,
concatenates strings s1 and s2 into s3:

String s3 = s1.concat(s2);
public class Testing {

public static void main(String[] args) {


String s1 = "Hello ";
String s2 = "Java";
String s3 = s1.concat(s2);
System.out.println(s3);

}
}
 Because string concatenation is heavily used in programming, Java provides a convenient
way to accomplish it.
 You can use the plus (+) operator to concatenate two strings, so the previous statement is
equivalent to

String s3 = s1 + s2; //String s3=s1.concat(s2);


public class Testing {

public static void main(String[] args) {


String s1 = "Hello ";
String s2 = "Java";
String s3 = s1+s2;
System.out.println(s3);

}
}
 The following code combines the strings message, " and ", and "HTML" into one
string:
String message=“Welcome from Java”;
String myString = message + " and " + "HTML";
System.out.println(myString);
public class Testing {

public static void main(String[] args) {


String message = "Welcome to Java";
String myString = message + " and " + "HTML";

System.out.println(myString);

}
}
concatenate strings and numbers

 place. Recall that the + operator can also concatenate a number with a string.
 In this case, the number is converted into a string and then concatenated.
 Note that at least one of the operands must be a string in order for concatenation to take
 If one of the operands is a nonstring (e.g., a number), the nonstring value is converted
into a string and concatenated with the other string.

Here are some examples:


// Three strings are concatenated
String message = "Welcome " + "to " + "Java";
// String Chapter is concatenated with number 2
String s = "Chapter" + 2; // s becomes Chapter2
// String Supplement is concatenated with character B
String s1 = "Supplement" + 'B'; // s1 becomes SupplementB
public class Testing {

public static void main(String[] args) {


// Three strings are concatenated
String message = "Welcome " + "to " + "Java";
// String Chapter is concatenated with number 2
String s = "Chapter" + 2; // s becomes Chapter2
// String Supplement is concatenated with character B
String s1 = "Supplement" + 'B'; // s1 becomes SupplementB
System.out.println(message);
System.out.println(s);
System.out.println(s1);

}
}
 If neither of the operands is a string, the plus sign (+) is the addition operator that adds
two numbers.
 += operator can also be used for string concatenation.

For example, the following code appends the string "and Java is fun" with the string
"Welcome to Java" in message.
String message= "Welcome to Java" ;
message += " and Java is fun";
So the new message is "Welcome to Java and Java is fun".
public class Testing {

public static void main(String[] args) {

String message = "Welcome to Java";


message += " and Java is fun";
System.out.println(message);
}
}
If i = 1 and j = 2, what is the output of the following statement?

System.out.println("i + j is " + i + j);

 The output is "i + j is 12" because "i + j is " is concatenated with the value of
i first.
 To force i + j to be executed first, enclose i + j in the parentheses, as follows:

System.out.println("i + j is " + (i + j));


Converting Strings

 toLowerCase() method returns a new string with all lowercase letters and the
 toUpperCase() method returns a new string with all uppercase letters.

For example,
"Welcome".toLowerCase() returns a new string welcome.
"Welcome".toUpperCase() returns a new string WELCOME.
public class Testing {

public static void main(String[] args) {

System.out.println("Welcome".toLowerCase());
System.out.println("Welcome".toUpperCase());
}
}
 The trim() method returns a new string by eliminating whitespace characters from both
ends of the string.
 The characters ' ', \t, \f, \r, or \n are known as whitespace characters.

For example,
"\t Good Night \n".trim() returns a new string Good Night.
public class Testing {

public static void main(String[] args) {

System.out.println("\t Good Night \n".trim() );

}
}
Reading a String from the Console
To read a string from the console, invoke the next() method on a Scanner object.
Forexample, the following code reads three strings from the keyboard:
Scanner input = new Scanner(System.in);
System.out.print("Enter three words separated by spaces: ");
String s1 = input.next();
String s2 = input.next();
String s3 = input.next();
System.out.println("s1 is " + s1);
System.out.println("s2 is " + s2);
System.out.println("s3 is " + s3);
Enter three words separated by spaces:
Welcome to Java
s1 is Welcome
s2 is to
s3 is Java
 The next() method reads a string that ends with a whitespace character.
 You can use the nextLine() method to read an entire line of text.
 The nextLine() method reads a string that ends with the Enter key pressed.

For example, the following statements read a line of text.


Scanner input = new Scanner(System.in);
System.out.println("Enter a line: ");
String s = input.nextLine();
System.out.println("The line entered is " + s);
Enter a line: Welcome to Java
The line entered is Welcome to Java
avoid input errors
Important Caution

 To avoid input errors, do not use nextLine() after nextByte(), nextShort(),


nextInt(), nextLong(), nextFloat(), nextDouble(), or next().

Reason:How does scanner work?


Reading a Character from the Console
 To read a character from the console, use the nextLine() method to read a string
and then invoke the charAt(0) method on the string to return a character.
For example, the following
//code reads a character from the keyboard:
Scanner input = new Scanner(System.in);
System.out.print("Enter a character: ");
String s = input.nextLine();
char ch = s.charAt(0);
System.out.println("The character entered is " + ch);
//code reads a character from the keyboard:
Scanner input = new Scanner(System.in);
System.out.print("Enter a character: ");
//String s = input.next();
char ch = sc.next().charAt(0);
System.out.println("The character entered is " + ch);
Comparing Strings

 The String class contains the methods as shown in following Table for comparing two
strings.
Comparison Methods for String Objects
Method Description
equals(s1) Returns true if this string is equal to string s1.
equalsIgnoreCase(s1) Returns true if this string is equal to string s1; it is case insensitive.
compareTo(s1) compareTo() method is used for comparing two strings lexicographically.
Each character of both the strings is converted into a Unicode value for
comparison.
If both the strings are equal then this method returns 0 else it returns
positive or negative value.
The result is positive if the first string is lexicographically greater than the
second string else the result would be negative.
compareToIgnoreCase(s1) Same as compareTo except that the comparison is case

insensitive.

startsWith(prefix) Returns true if this string starts with the specified prefix.

endsWith(suffix) Returns true if this string ends with the specified suffix.

contains(s1) Returns true if s1 is a substring in this string.


 How do you compare the contents of two strings?
 You might attempt to use the == operator, as follows:

String s1 = "Welcome to Java";


String s2 = "Welcome to Java";
if (string1 == string2)
System.out.println("string1 and string2 are the same object");
else
System.out.println("string1 and string2 are different objects");

 However, the == operator checks only whether string1 and string2 refer to the same
object(address); it does not tell you whether they have the same contents.
 Therefore, you cannot use the == operator to find out whether two string variables have the
same contents. Instead, you should use the equals method.
 The following code, for instance, can be used to compare two strings:
if (string1.equals(string2))
System.out.println("string1 and string2 have the same contents");
else
System.out.println("string1 and string2 are not equal");

For example, the following statements display true and then false.
String s1 = "Welcome to Java";
String s2 = "Welcome to Java";
String s3 = "Welcome to C++";
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // false
 The compareTo method can also be used to compare two strings.

For example, consider the following code:


s1.compareTo(s2)
 The method returns the value 0 if s1 is equal to s2,
 The method returns the negative value if s1 is lexicographically (i.e., in terms of Unicode
ordering) less than s2,
 The method returns the positive value if s1 is lexicographically greater than s2.
 The actual value returned from the compareTo method depends on the offset of the first
two distinct characters in s1 and s2 from left to right.
For example, suppose
s1 =“abc”;
s2 =“abg”;
s1.compareTo(s2) returns -4.
The first two characters (a vs. a) from s1 and s2 are compared. Because they are equal,
the second two characters (b vs. b) are compared.Because they are also equal,
the third two characters (c vs. g) are compared.
Since the character c is 4 less than g, the comparison returns -4.
public class compareTo {

public static void main(String[] args) {


String s1="abc";
String s2="abg";
System.out.println(s1.compareTo(s2));
}
}
Caution(သတိထားရန်)
 Syntax errors will occur if you compare strings by using relational operators >, >=, <, or
<=. Instead, you have to use s1.compareTo(s2).

Note
 The equals method returns true if two strings are equal and false if they are not.
 The compareTo method returns 0, a positive integer, or a negative integer, depending
on whether one string is equal to, greater than, or less than the other string.
 The String class also provides the equalsIgnoreCase and compareToIgnoreCase

methods for comparing strings.

 The equalsIgnoreCase and compareToIgnoreCase methods ignore the case of the letters

when comparing two strings.

 str.startsWith(prefix) to check whether string str starts with a specified prefix,

 str.endsWith(suffix) to check whether string str ends with a specified suffix, and str

 .contains(s1) to check whether string str contains string s1 .


public class equalsIgnoreCase {
public static void main(String[] args) {
String s1="welcome";
String s2="WELCOME";
System.out.println(s1.equals(s2)); //false
System.out.println(s1.equalsIgnoreCase(s2)); //true
}
}
public class compareToIgnoreCase {
public static void main(String[] args) {
String s1="a";
String s2="A";
System.out.println(s1.compareTo(s2)); //32
System.out.println(s1.compareToIgnoreCase(s2)); //0
}

}
For example,
"Welcome to Java".startsWith("We") returns true.
"Welcome to Java".startsWith("we") returns false.
"Welcome to Java".endsWith("va") returns true.
"Welcome to Java".endsWith("v") returns false.
"Welcome to Java".contains("to") returns true.
"Welcome to Java".contains("To") returns false.
 Gives a program that prompts the user to enter two cities and displays them
inalphabetical order.
 The String class contains the methods for obtaining substrings.
Method Description
substring(beginIndex) Returns this string’s substring that begins with the character at
the specified beginIndex and extends to the end of the string,
substring(beginIndex,endIndex)Returns this string’s substring that begins at the
specified beginIndex and extends to the character at index
endIndex – 1. Note that the character at endIndex is not part of the substring.
Obtaining Substrings
 You can obtain a single character from a string using the charAt method.
 You can also obtain a substring from a string using the substring method in the String
class, as shown in the following Table
For example,
String message = "Welcome to Java";
String message = message.substring(0, 11) + "HTML";
The string message now becomes Welcome to HTML.
Indices

message

message.substring(11)

message.substring(0, 11)

 The substring method obtains a substring from a string.


Note
 If beginIndex is endIndex (beginIndex <= endIndex), substring(beginIndex, endIndex)
returns an empty string with length 0.
 If beginIndex > endIndex, it would be a runtime error.
Finding a Character or a Substring in a String
The String class provides several versions of indexOf and lastIndexOf methods to find
a character or a substring in a string, as shown in the following Table
 The String class contains the methods for finding substrings.

Method Description
index(ch) Returns the index of the first occurrence of ch in the string. Returns -1 if not matched.
indexOf(ch, fromIndex) Returns the index of the first occurrence of ch after fromIndex in the string. Returns -1
if not matched.
indexOf(s) Returns the index of the first occurrence of string s in this string. Returns -1 if not
matched.
indexOf(s, fromIndex) Returns the index of the first occurrence of string s in this string after fromIndex.
Returns -1 if not matched.
lastIndexOf(ch) Returns the index of the last occurrence of ch in the string. Returns -1 if not matched.
lastIndexOf(ch, fromIndex) Returns the index of the last occurrence of ch before fromIndex in this string.
Returns -1 if not matched.
lastIndexOf(s) Returns the index of the last occurrence of string s. Returns -1 if not matched.
lastIndexOf(s, fromIndex) Returns the index of the last occurrence of string s before fromIndex. Returns -1 if not
For example,
"Welcome to Java".indexOf('W') returns 0.
"Welcome to Java".indexOf('o') returns 4.
"Welcome to Java".indexOf('o', 5) returns 9.
"Welcome to Java".indexOf("come") returns 3.
"Welcome to Java".indexOf("Java", 5) returns 11.
"Welcome to Java".indexOf("java", 5) returns -1.
For Example:

"Welcome to Java".lastIndexOf('W') returns 0.


"Welcome to Java".lastIndexOf('o') returns 9.
"Welcome to Java".lastIndexOf('o', 5) returns 4.
"Welcome to Java".lastIndexOf("come") returns 3.
"Welcome to Java".lastIndexOf("Java", 5) returns -1.
"Welcome to Java".lastIndexOf("Java") returns 11.
Suppose a string s contains the first name and last name separated by a space.
You can use the following code to extract the first name and last name from the string:

int k = s.indexOf(' ');


String firstName = s.substring(0, k);
String lastName = s.substring(k + 1);
For example, if s is Kim Jones, the following diagram illustrates how the first name and last
name are extracted.

Indicies

s.substring k is 3
(0, k) is Kim s.substring
(k + 1) is Jones
Conversion between Strings and Numbers
You can convert a numeric string into a number.

 To convert a string into an int value, use the Integer.parseInt method, as follows:

int intValue = Integer.parseInt(intString);

where intString is a numeric string such as "123".


 To convert a string into a double value, use the Double.parseDouble method, as follows:

double doubleValue = Double.parseDouble(doubleString);

where doubleString is a numeric string such as "123.45".


 If the string is not a numeric string, the conversion would cause a runtime error.
 The Integer and Double classes are both included in the java.lang package, and thus they
are automatically imported.
 You can convert a number into a string, simply use the string concatenating operator as
follows:

String s = number + "";


Q1.Suppose that s1, s2, and s3 are three strings, given as follows:
String s1 = "Welcome to Java";
String s2 = "Programming is fun";
String s3 = "Welcome to Java";
What are the results of the following expressions?
(a) s1 == s2
(b) s2 == s3
(c) s1.equals(s2)
(d) s1.equals(s3)
(e) s1.compareTo(s2)
(f) s2.compareTo(s3)
(g) s2.compareTo(s2)
(h) s1.charAt(0)
(i) s1.indexOf('j')
(j) s1.indexOf("to")
(k) s1.lastIndexOf('a')
(l) s1.lastIndexOf("o", 15)
(m) s1.length()
(n) s1.substring(5)
(o) s1.substring(5, 11)
(p) s1.startsWith("Wel")
(q) s1.endsWith("Java")
(r) s1.toLowerCase()
(s) s1.toUpperCase()
(t) s1.concat(s2)
(u) s1.contains(s2)
(v) "\t Wel \t".trim()
Q2.Show the output of the following statements (write a program to verify your results):
System.out.println("1" + 1);
System.out.println('1' + 1);
System.out.println("1" + 1 + 1);
System.out.println("1" + (1 + 1));
System.out.println('1' + 1 + 1);
Q3.Evaluate the following expressions (write a program to verify your results):
1 + "Welcome " + 1 + 1
1 + "Welcome " + (1 + 1)
1 + "Welcome " + 'a' + 1
Q4.Let s1 be " Welcome " and s2 be " welcome ". Write the code for the following
statements:
(a) Check whether s1 is equal to s2 and assign the result to a Boolean variable isEqual.
(b) Check whether s1 is equal to s2, ignoring case, and assign the result to a
Boolean variable isEqual.
(c) Compare s1 with s2 and assign the result to an int variable x.
(d) Compare s1 with s2, ignoring case, and assign the result to an int
variable x.
(e) Check whether s1 has the prefix AAA and assign the result to a Boolean
variable b.
(f) Check whether s1 has the suffix(postfix) AAA and assign the result to a Boolean
variable b.
(g) Assign the length of s1 to an int variable x.
(h) Assign the first character of s1 to a char variable x.
(i) Create a new string s3 that combines s1 with s2.
(j) Create a substring of s1 starting from index 1.
(k) Create a substring of s1 from index 1 to index 4.
(l) Create a new string s3 that converts s1 to lowercase.
(m) Create a new string s3 that converts s1 to uppercase.
(n) Create a new string s3 that trims whitespace characters on both ends of s1.
(o) Assign the index of the first occurrence of the character e in s1 to an int
variable x.
(p) Assign the index of the last occurrence of the string abc in s1 to an int
variable x.

You might also like