0% found this document useful (0 votes)
20 views22 pages

Session 6

This document provides an overview of the fundamentals of Java strings, including their creation, manipulation, and various methods for comparison and searching. It explains string constructors, string literals, concatenation, character extraction, and special operations like replace and trim. Additionally, it covers string comparison methods and how to handle string lengths and byte conversions.

Uploaded by

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

Session 6

This document provides an overview of the fundamentals of Java strings, including their creation, manipulation, and various methods for comparison and searching. It explains string constructors, string literals, concatenation, character extraction, and special operations like replace and trim. Additionally, it covers string comparison methods and how to handle string lengths and byte conversions.

Uploaded by

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

UNIT I: FUNDAMENTALS OF JAVA

TECHNOLOGY
AND PROGRAMMING

Strings
Strings
• Java implements strings as objects of type
String
• Java has methods to compare two strings,
search for a substring, concatenate two
strings, and change the case of letters within a
string.
The String Constructors
The String class supports several constructors. To create an
empty String, you call the default constructor. For example,
String s = new String();
will create an instance of String with no characters in it.
To create a String initialized by an array of characters, use the
constructor shown here:
String(char chars[ ])
Here is an example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string “abc”
The String Constructors
You can specify a subrange of a character array as an initializer using the
following constructor:
String(char chars[ ], int startIndex, int numChars)
Here, startIndex specifies the index at which the subrange begins, and
numChars specifiesthe number of characters to use.
Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
This initializes s with the characters cde.
You can construct a String object that contains the same character sequence
as another
String object using this constructor:
String(String strObj)
Here, strObj is a String object.
Strings

Consider this example:


// Construct one String from another.
class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
The output from this program is as follows:
Java
Java
Strings
The String class provides constructors that initialize a string when given a
byte array.
String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)
Here, asciiChars specifies the array of bytes.
constructors:
// Construct string from subset of char array.
class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}This program generates the following output:
ABCDEF
CDE
String Length

The length of a string is the number of characters that it contains. To obtain


this value, call the length( ) method
int length( )
The following fragment prints “3”, since there are three characters in the
string s:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
Special String Operations

String Literals
To create a String instance explicitly from an array of characters by using the
new operator
However, there is an easier way to do this using a string literal.
For each string literal in your program, Java automatically constructs a String
object.
Thus, you can use a string literal to initialize a String object
char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars);
String s2 = "abc"; // use string literal
Because a String object is created for every string literal, you can use a string
literal any place you can use a String object.
String Concatenation
Java does not allow operators to be applied to String objects
One exception to this rule is the + operator, which concatenates two strings,
producing a String object as the result.
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
This displays the string “He is 9 years old.”
Use concatenation to prevent long lines
class ConCat {
public static void main(String args[]) {
String longStr = "This could have been " +
"a very long line that would have " +
"wrapped around. But string concatenation " +
"prevents this.";
System.out.println(longStr);
}}
String Concatenation with Other Data Types

You can concatenate strings with other types of data. For example, consider
this slightly different version of the earlier example:
int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);
In this case, age is an int rather than another String, but the output produced
is the sameas before.
This is because the int value in age is automatically converted into its string
representation within a String object
The compiler will convert an operand to its string equivalent whenever the
other operand of the + is an instance of String
String Concatenation

Be careful when you mix other types of operations with string concatenation
expressions,
You might get surprising results. Consider the following:
String s = "four: " + 2 + 2;
System.out.println(s);
This fragment displays
four: 22
rather than the
four: 4
Operator precedence causes the concatenation of
“four” with the string equivalent of 2 to take place first.
This result is then concatenated with the string equivalent of 2 a second time.
To complete the integer addition first, you must use
parentheses, like this:
String s = "four: " + (2 + 2);
Now s contains the string “four: 4”.
Character Extraction

The String class provides a number of ways in which characters can be


extracted from a String object
CharAt():
To extract a single character from a String, you can refer directly to an
individual character
via the charAt( ) method. It has this general form:
char charAt(int where)
where is the index of the character that you want to obtain
char ch;
ch = "abc".charAt(1);
assigns the value “b” to ch
getChars( )
If you need to extract more than one character at a time, you can use the
getChars( ) method.
It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
Here, sourceStart specifies the index of the beginning of the substring, and
sourceEnd specifies an index that is one past the end of the desired
substring.
The following program demonstrates getChars( ):
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);}}
Here is the output of this program:
Demo
getBytes( )

• There is an alternative to getChars( ) that stores the characters in an array


of bytes.
• This method is called getBytes( ), and it uses the default character-to-byte
conversions provided by the
• platform. Here is its simplest form:
byte[ ] getBytes( )
• Other forms of getBytes( ) are also available. getBytes( ) is most useful
when you are exporting a String value into an environment that does not
support 16-bit Unicode characters.
• For example, most Internet protocols and text file formats use 8-bit ASCII
for all text interchange.
toCharArray( )

If you want to convert all the characters in a String object into a character
array, the easiestway is to call toCharArray( ).

It returns an array of characters for the entire string. It has this

general form:

char[ ] toCharArray( )
char[] ch=s1.toCharArray();

This function is provided as a convenience, since it is possible to use


getChars( ) to achieve the same result
String Comparison

The String class includes several methods that compare strings or substrings
within strings

equals( ) and equalsIgnoreCase( )

To compare two strings for equality, use equals( ).


general form:
boolean equals(Object str)

Here, str is the String object being compared with the invoking String object.

It returns true if the strings contain the same characters in the same order, and
false otherwise.

The comparison is case-sensitive.

To perform a comparison that ignores case differences,call equalsIgnoreCase( ).


String Comparison

boolean equalsIgnoreCase(String str)


Here, str is the String object being compared with the invoking String object.
It, too, returnstrue if the strings contain the same characters in the same
order, and false otherwise.
Here is an example that demonstrates equals( ) and equalsIgnoreCase( ):
// Demonstrate equals() and equalsIgnoreCase().
class equalsDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
String Comparison

System.out.println(s1 + " equals " + s2 + " -> " +


s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +
s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +
s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4));
}}
The output from the program is shown here:
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true
compareTo( )
For sorting applications, you need to know which is less than, equal to, or greater
than the next.
A string is less than another if it comes before the other in dictionary order.
A string is greater than another if it comes after the other in dictionary order.
The String method compareTo( ) servesthis purpose.
General form:
int compareTo(String str)
Here, str is the String being compared with the invoking String. The result of the
comparison is returned and is interpreted, as shown here:
Value Meaning
Less than zero- The invoking string is less than str.
Greater than zero The invoking string is greater than str.
Zero - The two strings are equal.

Example:
int result = str1.compareTo( str2 );
System.out.println(result);
Searching Strings
The String class provides two methods that allow you to search a string for a
specified character or substring:
• indexOf( ) Searches for the first occurrence of a character or substring.
• lastIndexOf( ) Searches for the last occurrence of a character or substring.
concat( )
You can concatenate two strings using concat( ), shown here:
String concat(String str)
This method creates a new object that contains the invoking string with the
contents of str appended to the end. concat( ) performs the same function
as +. For example,
String s1 = "one";
String s2 = s1.concat("two");
puts the string “onetwo” into s2.
It generates the same result as the following sequence:
String s1 = "one";
String s2 = s1 + "two";
replace() & trim()
replace( )
The replace( ) method has two forms. The first replaces all occurrences of one character
in the invoking string with another character.
General form:
String replace(char original, char replacement)

Here, original specifies the character to be replaced by the character specified by


replacement.
The resulting string is returned. For example,
• String s1="javatpoint is a very good website";
• String replaceString=s1.replaceAll("a","e");
• System.out.println(replaceString);

trim( )
The trim( ) method returns a copy of the invoking string from which any leading and
trailing whitespace has been removed. It has this general form:
String trim( )
trim( )
String s = " Hello World ".trim();
This puts the string “Hello World” into s.
It uses trim( ) to remove any leading or trailing whitespace that may have
inadvertently been entered by the user.

Example:
String Str = new String(" Welcome to Tutorialspoint.com ");
System.out.print("Return Value :" ); System.out.println(Str.trim() );

Output:
Return Value :Welcome to Tutorialspoint.com

You might also like