Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
String Class
Strings, which are widely used in Java programming, are a sequence of characters. In Java programming
language, strings are treated as objects.
Creating Strings
The most direct way to create a string is to write :
String str = "Hello world!";
As with any other object, you can create String objects by using the new keyword and a constructor. The
String class has 11 constructors that allow you to provide the initial value of the string using different
sources, such as an array of characters.
public class StringDemo {
public static void main(String args[]) {
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
[Link]( helloString );
}
}
Strings Methods List :
[Link]. Method & Description
1 String Length:
returns the number of characters contained in the string object.
public class StringDemo {
public static void main(String args[]) {
String str1 = "Dot saw I was Tod";
int len = [Link]();
[Link]( "String Length is : " + len );
}}
Rasha Moh'd Altarawneh Page 1 of 20
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
2 Concatenating Strings:
The String class includes a method for concatenating two strings .
[Link](string2);
public class StringDemo {
public static void main(String args[]) {
String string1 = "saw I was ";
[Link]("Dot " + string1 + "Tod");
[Link]([Link]("Tod"));
}
}
3 char charAt(int index)
Returns the character at the specified index.
public class Test {
public static void main(String args[]) {
String s = "Strings are immutable";
char result = [Link](8);
[Link](result);
}
}
Rasha Moh'd Altarawneh Page 2 of 20
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
4 int compareTo(Object o)
Compares this String to another Object.
Return Value
The value 0 if the argument is a string lexicographically equal to this string;
a value less than 0 if the argument is a string lexicographically greater
than this string; and a value greater than 0 if the argument is a string
lexicographically less than this string.
public class Test {
public static void main(String args[]) {
String str1 = "Strings are immutable";
String str2 = new String("Strings are immutable");
String str3 = new String("Integers are not immutable");
int result = [Link]( str2 );
[Link](result);
result = [Link]( str3 );
[Link](result);
}
}
5- int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
Rasha Moh'd Altarawneh Page 3 of 20
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
Return Value
This method returns a negative integer, zero, or a positive integer as the
specified String is greater than, equal to, or less than this String, ignoring
case considerations.
public class Test {
public static void main(String args[]) {
String str1 = "Strings are immutable";
String str2 = "strings are immutable";
String str3 = "Integers are not immutable";
int result = [Link]( str2 );
[Link](result);
result = [Link]( str3 );
[Link](result);
result = [Link]( str1 );
[Link](result);
}
}
6- boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
Return Value
This method returns true if the character sequence represented by the
argument is a suffix of the character sequence represented by this object;
false otherwise. Note that the result will be true if the argument is the
empty string or is equal to this String object as determined by the
equals(Object) method.
Rasha Moh'd Altarawneh Page 4 of 20
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
public class Test {
public static void main(String args[]) {
String Str = new String("This is really not
immutable!!");
boolean retVal;
retVal = [Link]( "immutable!!" );
[Link]("Returned Value = " + retVal );
retVal = [Link]( "immu" );
[Link]("Returned Value = " + retVal );
}
}
7- boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
Return Value
This method returns true if the argument is not null and the Strings are
equal, ignoring case; false otherwise.
public class Test {
public static void main(String args[]) {
String Str1 = new String("This is really not
immutable!!");
String Str2 = Str1;
String Str3 = new String("This is really not
immutable!!");
String Str4 = new String("This IS REALLY NOT
IMMUTABLE!!");
Rasha Moh'd Altarawneh Page 5 of 20
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
boolean retVal;
retVal = [Link]( Str2 );
[Link]("Returned Value = " + retVal );
retVal = [Link]( Str3 );
[Link]("Returned Value = " + retVal );
retVal = [Link]( Str4 );
[Link]("Returned Value = " + retVal );
}
}
8- int indexOf(char ch)
This method returns the index within this string of the first occurrence of the
specified character or -1, if the character does not occur.
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to [Link]");
[Link]("Found Index :" );
[Link]([Link]( 'o' ));
}
}
9- int indexOf(char ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified
character, starting the search at the specified index.
Rasha Moh'd Altarawneh Page 6 of 20
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to [Link]");
[Link]("Found Index :" );
[Link]([Link]( 'o', 5 ));
}
}
10- int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified
character
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to [Link]");
[Link]("Found Last Index :" );
[Link]([Link]( 'o' ));
}
}
11- String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this
string with newChar.
Rasha Moh'd Altarawneh Page 7 of 20
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to [Link]");
[Link]("Return Value :" );
[Link]([Link]('o', 'T'));
[Link]("Return Value :" );
[Link]([Link]('l', 'D'));
}
}
12- boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to [Link]");
[Link]("Return Value :" );
[Link]([Link]("Welcome") );
[Link]("Return Value :" );
[Link]([Link]("Tutorials") );
}
}
Rasha Moh'd Altarawneh Page 8 of 20
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
13- String substring(int beginIndex , int end Index)
Returns a new string that is a substring of this string.
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to [Link]");
[Link]("Return Value :" );
[Link]([Link](10) );
[Link]([Link](3,6) ); \\com
}
}
14- String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the
default locale.
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to [Link]");
[Link]("Return Value :");
[Link]([Link]());
}
}
Rasha Moh'd Altarawneh Page 9 of 20
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
15-
String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the
default locale.
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to [Link]");
[Link]("Return Value :" );
[Link]([Link]() );
}
}
16- void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
public void getChars(int srcBegin, int srcEnd, char[] dst, int
dstBegin)
Parameters
Here is the detail of parameters −
srcBegin − index of the first character in the string to copy.
srcEnd − index after the last character in the string to copy.
dst − the destination array.
dstBegin − the start offset in the destination array.
Rasha Moh'd Altarawneh Page 10 of 20
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
public class Test {
public static void main(String args[]) {
String Str1 = new String("Welcome to
[Link]");
char[] Str2 = new char[7];
[Link](2, 5, Str2, 2);
for ( char c: Str2 )
[Link]( c );
[Link]();
}
} \\ lco
17- String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
Return Value
It returns a copy of this string with leading and trailing white space
removed, or this string if it has no leading or trailing white space.
public class Test {
public static void main(String args[]) {
String Str = new String(" Welcome to [Link] ");
[Link]("Return Value :" );
[Link]([Link]() );
}}
Rasha Moh'd Altarawneh Page 11 of 20
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
18- char[] toCharArray()
Converts this string to a new character array.
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to [Link]");
[Link]("Return Value :" );
[Link]([Link]());
}
}
19- String[] split(String regex)
Splits this string around matches of the given regular expression
public class Token {
public static void main(String args[]) {
String Str = new String("[Link]");
[Link]("Return Value :" );
String[] str2 = [Link]("-");
for (int i=0 ;i<[Link]() ;i++) {
[Link](str2[i]);
}
}
}
20- contains(CharSequence s)
Return Value: true if this string contains the specified sequence of char
values, false otherwise.
Rasha Moh'd Altarawneh Page 12 of 20
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
public class Example {
public static void main(String[] args)
{
String str1 = "We are good students";
String str2 = "are";
[Link]();
[Link]("Original String: " + str1);
[Link]("Specified sequence of char values: " + str2);
[Link]([Link](str2));
[Link]();
}
}
21- boolean regionMatches(int toffset,String s2,int ooffset, int
len)
Parameters
Here is the detail of parameters −
toffset − the starting offset of the subregion in this string.
other − the string argument.
ooffset − the starting offset of the subregion in the string argument.
len − the number of characters to compare.
Return Value
It returns true if the specified subregion of this string matches the specified
subregion of the string argument; false otherwise. Whether the matching is
exact or case insensitive depends on the ignoreCase argument.
Rasha Moh'd Altarawneh Page 13 of 20
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
Example
import [Link].*;
public class Test {
public static void main(String args[]) {
String Str1 = new String("Welcome to
[Link]");
String Str2 = new String("Tutorials");
String Str3 = new String("TUTORIALS");
[Link]("Return Value :" );
[Link]([Link](11, Str2, 0, 9));
[Link]("Return Value :" );
[Link]([Link](11, Str3, 0, 9));
}
}
This will produce the following result −
Output
Return Value :true
Return Value :false
Rasha Moh'd Altarawneh Page 14 of 20
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
StringBuffer Class
Class
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class
in java is same as String class except it is mutable i.e. it can be changed.
Important methods of StringBuffer class
1) StringBuffer append() method
The append() method concatenates the given argument with this string
1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. [Link]("Java");//now original string is changed
5. [Link](sb);//prints Hello Java } }
2) StringBuffer insert() method
The insert() method inserts the given string with this string at the given position.
1. class StringBufferExample2{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. [Link](1,"Java");//now original string is changed
5. [Link](sb);//prints HJavaello
6. }
7. }
Rasha Moh'd Altarawneh Page 15 of 20
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
3) StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex.
1. class StringBufferExample3{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello studants");
4. [Link](1,10,"Java");
5. [Link](sb);//prints HJavaents
6. }
7. }
4) StringBuffer delete() method
The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.
1. class StringBufferExample4{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello students");
4. [Link](1,8);
5. [Link](sb);//prints Hudents
6. }
7. }
5) StringBuffer reverse() method
The reverse() method of StringBuilder class reverses the current string.
1. class StringBufferExample5{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. [Link]();
5. [Link](sb);//prints olleH }}
Rasha Moh'd Altarawneh Page 16 of 20
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
exercises
1- Write a Java program to get the character at the given index within the
String.
Sample Output:
Original String = Java Exercises!
The character at position 0 is J
The character at position 10 is i
2- Write a Java program to compare two strings lexicographically. Two strings
are lexicographically equal if they are the same length and contain the
same characters in the same positions.
Sample Output:
String 1: This is Exercise 1
String 2: This is Exercise 2
"This is Exercise 1" is less than "This is Exercise 2"
3- Write a Java program to concatenate a given string to the end of another
string
Sample Output:
String 1: PHP Exercises and
String 2: Python Exercises
The concatenated string: PHP Exercises and Python Exercises
Rasha Moh'd Altarawneh Page 17 of 20
4- Write a Java program to test if a given string contains the specified
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
4- Write a Java program to test if a given string contains the specified
sequence of char values.
Sample Output:
Original String: PHP Exercises and Python Exercises
Specified sequence of char values: and
true
5- Write a Java program to compare a given string to the specified string
.Sample Output:
Comparing [Link] and [Link]: true
6- Write a Java program to check whether a String objects end
With specified string
Sample Output:
"Welcome to java" end with "java" ? true
"Good bye OOP " end with "java"? false
Rasha Moh'd Altarawneh Page 18 of 20
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
7- Write a Java program to get the index of all the characters of the alphabet
in any input string
Sample Output:
by name of allah
a b c d e f g h i j
=========================
4 0 -1 -1 6 9 -1 15 -1 -1
k l m n o p q r s t
===========================
-1 12 5 3 8 -1 -1 -1 -1 -1
u v w x y z
================
-1 -1 -1 -1 1 -1
8- Write a Java program to get a substring of a given string between two
specified positions.
Sample Output:
old = The quick brown fox jumps over the lazy dog.
new = brown fox jumps
9- Write a Java program to convert all the characters in a string to lowercase.
Sample Output:
Original String: The Quick BroWn FoX!
String in lowercase: the quick brown fox!
10- Write a Java program to determine if the input phone number is belonged to
zain, umnia or orange network.
Rasha Moh'd Altarawneh Page 19 of 20
Lab #01
Al_Balqa’ Applied University
IT Collage
Java Programming Lab
Instructor: Rasha Moh'd Altarawneh
How to find length of a
string using String
compareTo() method ?
Rasha Moh'd Altarawneh Page 20 of 20