0% found this document useful (0 votes)
25 views20 pages

نسخة من Lab01

This document provides an overview of the String class in Java, including how to create Strings and some common String methods. It lists 11 String constructors and details 5 String methods: length(), compareTo(), compareToIgnoreCase(), indexOf(), and lastIndexOf().

Uploaded by

termedelox1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views20 pages

نسخة من Lab01

This document provides an overview of the String class in Java, including how to create Strings and some common String methods. It lists 11 String constructors and details 5 String methods: length(), compareTo(), compareToIgnoreCase(), indexOf(), and lastIndexOf().

Uploaded by

termedelox1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

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);
System.out.println( helloString );
}
}

Strings Methods List :

Sr.No. 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 = str1.length();
System.out.println( "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 .

string1.concat(string2);
public class StringDemo {

public static void main(String args[]) {


String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
System.out.println(string1.concat("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 = s.charAt(8);
System.out.println(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 = str1.compareTo( str2 );


System.out.println(result);

result = str2.compareTo( str3 );


System.out.println(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 = str1.compareToIgnoreCase( str2 );


System.out.println(result);

result = str2.compareToIgnoreCase( str3 );


System.out.println(result);

result = str3.compareToIgnoreCase( str1 );


System.out.println(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 = Str.endsWith( "immutable!!" );


System.out.println("Returned Value = " + retVal );

retVal = Str.endsWith( "immu" );


System.out.println("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 = Str1.equals( Str2 );


System.out.println("Returned Value = " + retVal );

retVal = Str1.equals( Str3 );


System.out.println("Returned Value = " + retVal );

retVal = Str1.equalsIgnoreCase( Str4 );


System.out.println("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 Tutorialspoint.com");
System.out.print("Found Index :" );
System.out.println(Str.indexOf( '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 Tutorialspoint.com");
System.out.print("Found Index :" );
System.out.println(Str.indexOf( '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 Tutorialspoint.com");
System.out.print("Found Last Index :" );
System.out.println(Str.lastIndexOf( '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 Tutorialspoint.com");

System.out.print("Return Value :" );


System.out.println(Str.replace('o', 'T'));

System.out.print("Return Value :" );


System.out.println(Str.replace('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 Tutorialspoint.com");

System.out.print("Return Value :" );


System.out.println(Str.startsWith("Welcome") );

System.out.print("Return Value :" );


System.out.println(Str.startsWith("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 Tutorialspoint.com");

System.out.print("Return Value :" );


System.out.println(Str.substring(10) );
System.out.println(Str.substring(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 Tutorialspoint.com");

System.out.print("Return Value :");


System.out.println(Str.toLowerCase());
}
}

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 Tutorialspoint.com");

System.out.print("Return Value :" );


System.out.println(Str.toUpperCase() );
}
}

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
Tutorialspoint.com");
char[] Str2 = new char[7];

Str1.getChars(2, 5, Str2, 2);


for ( char c: Str2 )
System.out.print( c );
System.out.println();

}
} \\ 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 Tutorialspoint.com ");

System.out.print("Return Value :" );


System.out.println(Str.trim() );
}}

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 Tutorialspoint.com");

System.out.print("Return Value :" );


System.out.println(Str.toCharArray());
}
}

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("Welcome-to-Tutorialspoint.com");
System.out.println("Return Value :" );
String[] str2 = Str.split("-");
for (int i=0 ;i<Str.length() ;i++) {
System.out.println(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";
System.out.println();
System.out.println("Original String: " + str1);
System.out.println("Specified sequence of char values: " + str2);
System.out.println(str1.contains(str2));
System.out.println();
}
}

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 java.io.*;
public class Test {

public static void main(String args[]) {


String Str1 = new String("Welcome to
Tutorialspoint.com");
String Str2 = new String("Tutorials");
String Str3 = new String("TUTORIALS");

System.out.print("Return Value :" );


System.out.println(Str1.regionMatches(11, Str2, 0, 9));

System.out.print("Return Value :" );


System.out.println(Str1.regionMatches(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. sb.append("Java");//now original string is changed
5. System.out.println(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. sb.insert(1,"Java");//now original string is changed
5. System.out.println(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. sb.replace(1,10,"Java");
5. System.out.println(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. sb.delete(1,8);
5. System.out.println(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. sb.reverse();
5. System.out.println(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 example.com and example.com: 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

You might also like