Download String Manipulation in Java: Comprehensive Guide and more Summaries Computer science in PDF only on Docsity!
Chapter 16
String Handling
String is a predefined class of java.lang package. The object of this class stores the data values in sequence of characters. String is an immutable object which means it is constant and cannot be changed once it has been created. String is also defined as sequence of characters.
Declaring and initializing a string variable
A string variable is a named memory location that contains a string constant or string literal.
A string variable is declared using the given syntax โ
- Static declaration โ To declare a string variable statically the given syntax is used. Syntax โ <variable/object> ; Example โ String s;
2. Dynamic declaration โ To declare a string variable dynamically the
given syntax is used. Syntax โ <variable/object> = <String ()>; Example โ String s = new String();
A string variable is initialized using the given syntaxes โ
1. Direct assignment โ
Syntax 1 โ = ; Example โ String s = "Computer Application"; Syntax 2 โ = <String (String Literal)>; Example โ String s = new String("Computer Application");
2. Assignment from terminal window
- Using InputStreamReader and BufferedReader class Syntax โ = .<Reading method ()>; Example โ String s = BufferedReader object. readLine ();
- Using Scanner class Syntax โ = .<Reading method ()>; Example โ String s = Scanner object. nextLine();
Note โ By default, String data type creates a character array to store the set of characters in different cells. Thus, assigning a string means assigning a character array to a string object.
Example 1 โ String s = "Carmel@123";
It means char s [] = {'C', 'a', 'r', 'm', 'e', 'l', '@', '1', '2', '3'};
C a r m e l @ 1 2 3
[ Example 2 โ
char arr [] = {'S', 'c', 'h', 'o', 'o', 'l', '@', '9', '8', '7'};
String st = new String (arr);
Here, we are passing the array arr (character array) to a string variable (object) st. Therefore, the value of String variable st will be School@987.
Note โ The array (Character type) can only be passed to a dynamically declared String variable directly at the time of its creation by passing the array in the String constructor. Syntax โ String st = new String (array name);
Example โ char a [] = {'A', 'b', 'c' };
String st = new String (a);
Passing the character array to String variable directly using the assignment operator will generate a syntax error.
Example โ char a [] = {'A', 'b', 'c'};
String st = new String(); st = a; OR String s =a; This generates the syntax error โincompatible type s โ char[] cannot be converted to java.lang.String.
Index No.
Elements
Example โ String st = " carmel school "; String c = st. trim(); //value of c will be carmel school;
- indexOf() โ This function returns the index of a character available in the string. It returns integer (int) type value. Syntax 1 โ int variable = stringvariable.indexOf(character); Example โ String st = "carmel chamba";
int len = st. indexOf ('a'); //value of len will be 1
Syntax 2 โ int variable = stringvariable.indexOf(character, index); Example โ String st = "carmel chamba";
int len = st. indexOf ('a' , 5); //value of len will be 9
Note โ indexOf returns -1 if the entered character is not available in the string.
- lastIndexOf() โ This function returns the index of the last occurrence of a character in the string. It returns integer (int) type value. Syntax โ int variable = stringvariable.lastIndexOf(character); Example โ String st = "carmel school";
int len = st.lastIndexOf ('o'); //value of len will be 11
Note โ lastIndexOf() returns -1 if the entered character is not available in the string.
- substring() โ This function is used to extract a part of string from one index to another. It returns a string type value. Syntax 1 โ String variable = stringvariable.substring(index); Example โ String st = "carmel school"; String sub = st. substring (3); //value of sub will be mel school
Syntax 2 โ String variable = stringvariable.substring(index, index); Example โ String st = "carmel school"; String sub = st. substring (3,9); //value of sub will be mel sc
- toLowerCase() โ This function returns the letters of the string in lower case. It returns string type value. Syntax 1 โ String variable = stringvariable.toLowerCase(); Example โ String st = "CARMEL SCHOOL"; String sub = st.toLowerCase(); //value of sub will be carmel school
- toUpperCase() โ This function returns the letters of the string in upper case. It returns string type value. Syntax 1 โ String variable = stringvariable.toUpperCase(); Example โ String st = "carmel school"; String sub = st.toUpperCase(); //value of sub will be CARMEL SCHOOL
- replace() โ This function is used to replace a character by another character or to replace a string by another string at all its occurrences in the given string. It returns string type value. Syntax 1 โ String variable = stringvariable.replace (character to be replaced, character to replace with); Example โ String st = "carmel school";
String sub = st.replace ('c' , 'o');
//value of sub will be oarmel sohool
Syntax 2 โ String variable = stringvariable. replace(string to be replaced , string to replace with);
Example2 โ String st = "carmel"; String str = "carmel"; boolean c = st. equalsIgnoreCase (str); //value of c will be true;
Example3 โ String st = "carmel"; String str = "Carmel"; boolean c = st. equalsIgnoreCase (str); //value of c will be true;
Note โ equalsIgnoresCase ignores the case of the strings and then compare the strings
- compareTo() โ This function is used to compare two strings together to check whether they are identical or not. It also checks whether a string is bigger or smaller than the other string. It returns integer (int) type value. It works on the given criteria: Value returned Results or meaning variable = 0 Both the strings are same variable > 0 First string (st) is greater than string second (str) variable < 0 First string (st) is less than string second (str) Note โ It compares the ASCII codes of the characters from both the strings at same index and generates an integer value in return.
Syntax โ int variable =stringvariable1.compareTo (stringvariable2);
Example 1 โ String st = "carmel"; String str = "carmel"; int c = st. compareTo(str); //value of c will be 0 Note โ here both the string will be considered same and identical.
Example 2 โ String st = "carmel"; String str = "school"; int c = st. compareTo (str); //value of c will be -
Note โ here string second (str) will be considered as greater. Example 3 โ String st = "carmel"; String str = "Carmel"; int c = st. compareTo (str); //value of c will be 32 Note โ here first string (st) will be considered as greater.
- endswith() โ This function is used to check whether a given string has a specified suffix or not. It checks whether the entered string is available at the end of other string or not. It returns boolean type value. Syntax โ boolean variable = stringvariable.endswith(string variable);
Example 1 โ String st = "carmel school"; String str = "ool" boolean sub = st.endswith(str); //value of sub will be true
Example 2 โ String st = "carmel school"; String str = "el" boolean sub = st.endswith(str); //value of sub will be false
- startswith() โ This function is used to check whether a given string has a specified prefix or not. It check whether the entered string is available at the starting of other string. It returns boolean type value. Syntax โ boolean variable = stringvariable.startswith(string variable);
Example 1 โ String st = "carmel school"; String str = "car" boolean sub = st. startswith (str); //value of sub will be true
Example 2 โ String st = "carmel school"; String str = "cat";
String s = "123.25"; float a = Float.valueOf (s); // value of a will be 123.
Example 4 โ String to Double type data String s = "1.25564164"; double a = Double.valueOf (s); // value of a will be 1.
Example 5 โ String to Boolean type data String s = "true"; boolean a = Boolean.valueOf(s); // value of a will be true
Questions
- Predict the output of the given program snippet public static void main() { String s = "carmel"; String st = "school"; s.concat(st); System.out.println(s); }
Answer: carmel Reason: String class is immutable (unchangeable)
- Predict the output of the given program snippet public static void main() { StringBuffer s = new StringBuffer("carmel"); StringBuffer st = new StringBuffer("school"); s.append(st); System.out.println(s); }
Answer: carmelschool Reason: StringBuffer class is mutable(changeable)
- Predict the output of the given program snippet public static void main() { String s = "This is a fine day";
System.out.println(s.substring (1,8).charAt(4)) }
Answer: i
- Give an example to pass an StringBuffer objects value to a String object. Answer: public static void main() { StringBuffer s = new StringBuffer("car"); s.reverse(); String st = new String(s); System.out.println(st); } The output generated by the program given will be rac.