You are on page 1of 24

Contents

3 Strings and Things 1


3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
3.2 String class and its constructors . . . . . . . . . . . . . . . . . . . . . . . 1
3.3 Taking Strings Apart with Substrings . . . . . . . . . . . . . . . . . . . . 6
3.4 Breaking Strings Into Words . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.5 Putting Strings Together with StringBuilder . . . . . . . . . . . . . . . . 11
3.5.1 Synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.5.2 StringBuilder Methods . . . . . . . . . . . . . . . . . . . . . . . . 11
3.6 Processing a String One Character at a Time . . . . . . . . . . . . . . . 15
3.6.1 Checksum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.7 Reversing a String by Word or by Character . . . . . . . . . . . . . . . . 16
3.8 Expanding and Compressing Tabs . . . . . . . . . . . . . . . . . . . . . . 17
3.9 Controlling Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.9.1 Difference between == and equals() method in Java . . . . . . . . 18
3.9.1.1 Difference between String Literal and New String object 19
3.10 Indenting Text Documents . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.11 Entering Nonprintable Characters . . . . . . . . . . . . . . . . . . . . . . 22
3.11.1 Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.12 Trimming Blanks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.13 Copy the content of the file linewise . . . . . . . . . . . . . . . . . . . . . 23

i
Chapter 3

Strings and Things

3.1 Introduction
• String is the array of character.

• We use them for printing messages for the user; for referring to files on disk or
other external media; and for peoples names, addresses, and affiliations.

• String is a defined type (class) in Javathat is, a string is an object and therefore
has methods. It is not an array of characters (though it contains one) and should
not be thought of as an array.

• Notice that a given String object, once constructed, is immutable.

• If you need to change characters within a String , you should instead create a
StringBuilder (possibly initialized to the starting value of the String ), manipu-
late the StringBuilder to your hearts content, and then convert that to String at
the end, using the ubiquitous toString() method.

• Java provides three classes to represent a sequence of characters: String, String-


Buffer, and StringBuilder. The String class is an immutable class whereas String-
Buffer and StringBuilder classes are mutable.

3.2 String class and its constructors


1. Program for create a immutable string object by the help of parameterized con-
structor and print it.
Solution:

String str = new String ( " XYZ ") ;

2. Program for create a empty string object.

1
Solution:

String str = new String ( "" );

3. Write program to create a two string object initialize it using any string constant
and print it.
Solution:

String str = " XYZ " ;

Table 3.1: Java String Methods

Methods Description

concat() joins the two strings together

equals() compares the value of two strings

charAt() returns the character present in the specified location

getBytes() converts the string to an array of bytes

indexOf() returns the position of the specified character in the string

length() returns the size of the specified string

replace() replaces the specified old character with the specified new
character

substring() returns the substring of the string

split() breaks the string into an array of strings

toLowerCase() converts the string to lowercase

toUpperCase() converts the string to uppercase

valueOf() returns the string representation of the specified data

2
Solution:String methods demo

String str1 = " Ravana " ;


String str2 = " Rama " ;
// Concat str1 and str2
System . out . println ( " Concat =" +( str1 . concat ( str2 ) ) ) ;
System . out . println ( " Concat =" + str1 + str2 ) ;
// find length of str1
System . out . println ( " Length of str1 =" + str1 . length () ) ;
// equals and compareto
boolean res = str1 . equals ( str2 ) ; // false
int res1 = str1 . compareTo ( str2 ) ; // 9 (v -m =9)
System . out . println ( res + " " + res1 ) ; // false 9
// substring ( beg , end )
System . out . println ( str1 . substring (2) ) ;
System . out . println ( str1 . substring (4) ) ;
// last 2 chars from string using substring
System . out . println ( str2 . substring ( str2 . length () -2) ) ;
// int indexOf ( String str , int fromIndex )
int index = str . indexOf ( "m " ,1) ;
System . out . println ( index ); // 2
Output :
Concat = RavanaRama
Concat = RavanaRama
Length of str1 =6
false 9
9
vana
na
ma
2

Solution: split() Demo

// syntax : split ( regex )


// extract words form the string
String str1 = " my name is rama ";
String [] words = str1 . split ( " ") ;
System . out . println ( words [0]) ;
// for each loop
for ( String s: words )
System . out . println (s );
Output :
my
my
name
is
rama

3
Assignment
1. Write a Java program to compare two strings lexicographically. Two strings are
lexicographically equal if they are the same length and contain the same charac-
ters in the same positions.
Solution

String s1 = " Rama " ;


String s2 = " Haris ";
if ( s1 . length () == s2 . length () )
{
int res = s1 . compareTo ( s2 ) ;
if ( res ==0)
System . out . println ( " lexicographically equal " );
else
System . out . println ( " Not equal " );
}
else
System . out . println ( " Not equal " );

2. Write a Java program to compare two strings lexicographically, ignoring case dif-
ferences.
Solution

String s1 = " Rama " ;


String s2 = " Haris ";
if ( s1 . length () == s2 . length () )
{
int res = s1 . compareToIgnoreCase ( s2 ) ;
if ( res ==0)
System . out . println ( " lexicographically equal " );
else
System . out . println ( " Not equal " );
}
else
System . out . println ( " Not equal " );

3. Write a Java program to check whether a given string ends with the contents of
another string.

4
Solution

String str1 = " Python Exercises " ;


String str2 = " Python Exercise ";
// The String to check the above two Strings to see
// if they end with this value ( se ).
String end_str = " se ";
// Extract the end of str1 and str2
String end1 = str1 . substring ( str1 . length () - end_str . length () ) ;
String end2 = str2 . substring ( str2 . length () - end_str . length () ) ;
// Check first two Strings end with end_str
boolean ends1 = end1 . equals ( end_str ) ;
boolean ends2 = end2 . equals ( end_str ) ;
// Display the results of the endsWith calls .
System . out . println ( str1 + " ends with " + end_str + "? : "
+ ends1 );
System . out . println ( str2 + " ends with " + end_str + "? : "
+ ends2 );
Output :
Python Exercises ends with se ? : false
Python Exercise ends with se ? : true

4. Write a Java program to test if a given string contains the specified sequence of
char values.
Solution

String str1 = " PHP Exercises and Python Exercises " ;


String str2 = " and ";
System . out . println ( " Original String : " + str1 ) ;
System . out . println ( " Specified sequence of char values : " +
str2 );
System . out . println ( str1 . contains ( str2 ) ) ;

5. Write a Java program to get the index of all the characters of the alphabet. "The
quick brown fox jumps over the lazy dog."; String str = "The quick brown fox
jumps over the lazy dog.";
Solution

// Get the index of all the characters of the alphabet


// starting from the beginning of the String .
int ch = ’a ’;
for ( int i =0; i < 26; i ++)
{
int index = str . indexOf ( ch ) ;
System . out . println ( " Index of " +(( char ) ch ) + " is
:" + index ) ;
ch = ch +1;
}

5
6. Write a program to enter a string and count the frequency each character present
in it.
Solution

class Main {
static void CountOccr ( String s )
{
int count []= new int [26];
// remove the spaces if any
s = s. replace ( " " , " ") ;
s =s. toLowerCase () ;
for ( int i =0; i < s . length () ; i ++)
{
char ch =s . charAt ( i ) ;
count [ch -97]++;
}
// print
for ( int i =0; i <26; i ++)
{
if ( count [ i ]!=0)
{
System . out . println ((( char ) ( i +97) ) + "
"+ count [ i ]) ;
}
}
}
public static void main ( String [] args ) {
String s= " java programs " ;
CountOccr (s) ;
}
}

3.3 Taking Strings Apart with Substrings


• You want to break a string apart into substrings by position.

• Use the String objects substring() method.

• The substring() method constructs a new String object made up of a run of


characters contained somewhere in the original string, the one whose substring()
you called.

• The substring method is overloaded:both forms require a starting index (which is


always zero-based).

• The one-argument form returns from startIndex to the end.

• The two-argument form takes an ending index

• Note that the end index is one beyond the last character! Java adopts this half
open interval (or inclusive start, exclusive end) policy fairly consistently;

6
Assignment
1. Demonstrate how to use substring() and its variation, indexOf(), lastIndexOf(),
length() .
Solution:

String str = new String ( " iter is my college " );


String sub1 = str . substring ( startIndex ) ;
String sub1 = str . substring ( startIndex , endIndex ) ;

2. Write a program to find sub string of a string from a start index.

3. Write a program to find sub string of a string from a start index to end index.

4. Write a program which read two string from user and concat the sub string from
0 to 5 index of first string with the 0 to 7 indexed of the second string and print
the resultant string.
Not: Your program must handle the any length string.

3.4 Breaking Strings Into Words


• You need to take a string apart into words or tokens.

• To accomplish this, construct a StringTokenizer present in java.util package,


around your string and call its methods hasMoreTokens() and nextToken() .

• A StringTokenizer normally breaks the String into tokens at what we would think
of as word boundaries in European languages.
Example:

StringTokenizer st = new StringTokenizer ( " Hello World of


Java ");
while ( st . hasMoreTokens ( ) )
System . out . println ( " Token : " + st . nextToken ( ) ) ;
Output :
Token : Hello
Token : World
Token : of
Token : Java

• Sometimes you want to break at some other character. No problem. When you
construct your StringTokenizer, in addition to passing in the string to be tok-
enized, pass in a second string that lists the break characters. For example:

7
Example:

StringTokenizer st = new StringTokenizer ( " Hello ,


World | of | Java " , " , | ") ;
while ( st . hasMoreElements ( ) )
System . out . println ( " Token : " + st . nextElement ( ) ) ;
Output :
Token : Hello
Token : World
Token : of
Token : Java

Assignment
1. Demonstrate the use of StringTokenizer class and its method hasMoreToken(),
nextToken()
Solution:

StringTokenizer st = new StringTokenizer ( " Hello World of


Java ");
while ( st . hasMoreTokens ( ) )
System . out . println ( " Token : " + st . nextToken ( ) ) ;

2. Write a program to read a string and tokenize the string for ’,’ or ’|’ token.

Solution:

StringTokenizer st = new StringTokenizer ( " Hello ,


World | of | Java " , " , | ") ;
while ( st . hasMoreElements ( ) )
System . out . println ( " Token : " + st . nextElement ( ) ) ;

3. Write a program to display delimiter and all tokens present in a sting.


Solution:

StringTokenizer st = new StringTokenizer ( " Hello ,


World | of | Java " , " , | " , true ) ;
while ( st . hasMoreElements ( ) )
System . out . println ( " Token : " + st . nextElement ( ) ) ;
Output :
Token : Hello
Token : ,
Token :
Token : World
Token : |
Token : of
Token : |
Token : Java

8
4. Write a program which read a string and process it, if consecutive delimiter comes
ignore it else print the token.
Solution

import java . util .*;


class Main {
public final static int MAXFIELDS = 5;
public final static String DELIM = " |" ;
public static String [] process ( String line ) {
String [] results = new String [ MAXFIELDS ];
StringTokenizer st = new StringTokenizer ( line ,
DELIM , true ) ;
int i = 0;
// stuff each token into the current slot in the array
.
while ( st . hasMoreTokens () ) {
String s = st . nextToken () ;
if ( s. equals ( DELIM ) )
{
if ( i ++ >= MAXFIELDS )
throw new IllegalArgumentException ( "
Input line " + line + " has too many
fields " ) ;
continue ;
}
results [i ] = s ;
}
return results ;
}

public static void printResults ( String input , String []


outputs ) {
System . out . println ( " Input : " + input ) ;
for ( String s : outputs )
System . out . println ( " Output " + s + " was : " + s ) ;
}

9
Solution

public static void main ( String [] args ) {


printResults ( " A| B| C| D" , process ( "A |B |C |D ") ) ;
printResults ( " A || C |D " , process ( " A || C |D ") ) ;
printResults ( " A ||| D| EF " , process ( " A ||| D| EF ") ) ;
}
}
Output :
Input : A|B|C|D
Output A was : A
Output B was : B
Output C was : C
Output D was : D
Output null was : null
Input : A || C|D
Output A was : A
Output null was : null
Output C was : C
Output D was : D
Output null was : null
Input : A ||| D| EF
Output A was : A
Output null was : null
Output null was : null
Output D was : D
Output EF was : EF

5. Write a program using java to read a string and find number of words present in
that string.

6. Write a program to read a string whose words are separated by ’,’ find the num-
ber of words and number of ’,’ present in that string.
Solution

import java . util .*;


class Main {
public static void main ( String [] args ) {
String str = " Hello , World , of , Java " ;
StringTokenizer st = new StringTokenizer ( str , " ," , true ) ;
int words =0 , delim =0;
while ( st . hasMoreTokens () )
{
String s= st . nextToken () ;
if (s. equals ( " ,") )
delim = delim +1;
else
words +=1;
}
System . out . println ( " Words = "+ words + "
Delimeters =" + delim ) ;
}
}
Output :
Words =4 Delimeters =3

10
3.5 Putting Strings Together with StringBuilder
An object of one of the StringBuilder classes basically represents a collection of charac-
ters. It is similar to a String object, but, as mentioned, Strings are immutable. String-
Builders are mutable and designed for, well, building Strings.

3.5.1 Synchronization
Only one thread at a time is allowed to run the given method (or any other synchro-
nized method in the same class) in a given object instance (for static methods, only
one thread is allowed to run the method at a time). You can synchronize methods or
smaller blocks of code.
Problem: The add() method simply uses the current number of objects as an ar-
ray index then increments it.

public void add ( Object obj ) {


data [ max ] = obj ; // 1
max = max + 1; // 2
}

1. Threads A and B both wish to call this method. Suppose that Thread A gets
interrupted after 1 but before 2, and then Thread B gets to run.

2. Thread B does , overwriting the contents of data[max] ; weve now lost all refer-
ence to the object that Thread A passed in!

3. Thread B then increments max at and returns. Later, Thread A gets to run again;
it resumes at and increments max past the last valid object. So not only have we
lost an object, but we have an uninitialized reference in the array.

A list of differences between StringBuffer and StringBuilder are given below:

No. StringBuffer StringBuilder


1) StringBuffer is synchronized i.e. StringBuilder is non-synchronized i.e.
thread safe. It means two threads not thread safe. It means two threads
can’t call the methods of StringBuffer can call the methods of StringBuilder
simultaneously. simultaneously.
2) StringBuffer is less efficient than StringBuilder is more efficient than
StringBuilder. StringBuffer.

3.5.2 StringBuilder Methods


1. append()

11
Problem: // Build a StringBuilder and append some things to it.

StringBuilder sb2 = new StringBuilder () ;


sb2 . append ( " Hello " );
sb2 . append ( ’, ’);
sb2 . append ( ’ ’);
sb2 . append ( " World " );

2. Problem: StringBuilder delete(int start, int end): This method removes the
characters in a substring of this sequence.
Solution: delete() demo

class Main {
public static void main ( String [] args )
{
StringBuilder str = new StringBuilder ( " Rama Chandra " );
System . out . println ( " Original String = " + str ) ;
// remove the substring from index 7
StringBuilder afterRemoval = str . delete (7 ,8) ;
System . out . println ( afterRemoval ) ;
// remove the substring 7 -9
System . out . println ( str . delete (7 ,10) ) ;
}
}
Output :
Original String = Rama Chandra
Rama Chndra
Rama Cha

3. StringBuilder deleteCharAt(int index): This method removes the char at the


specified position in this sequence.

Solution: deleteCharAt() demo

StringBuilder str = new StringBuilder ( " Rama Chandra " );


System . out . println ( " Original String :" + str ) ;
System . out . println ( " After Removal : "+ str . deleteCharAt (0) ) ;
Output :
Original String : Rama Chandra
After Removal : ama Chandra

4. StringBuilder insert(): This method inserts the string representation of the char
argument into this sequence.

12
Solution: insert() demo

StringBuilder str = new StringBuilder ( " Tutorial " );


System . out . println ( " string = " + str ) ;
// insert character value at offset 8
str . insert (8 , ’s ’) ;
// prints StringBuilder after insertion
System . out . print ( " After insertion = ") ;
System . out . println ( str . toString () ) ;

5. StringBuilder replace(int start, int end, String str): This method replaces
the characters in a substring of this sequence with characters in the specified
String.

Solution: // Java program to demonstrate the replace() Method.

class GFG {
public static void main ( String [] args )
{
// create a StringBuilder object
// with a String pass as parameter
StringBuilder str = new StringBuilder ( " Tony Stark
will die ");
// print string
System . out . println ( " String = " + str . toString () ) ;
// replace Character from index 15 to 16 by " not "
StringBuilder strReturn = str . replace (15 , 16 , "
not ") ;
// print string
System . out . println ( " After Replace () String = " +
strReturn . toString () ) ;
}
}

6. StringBuilder reverse(): This method causes this character sequence to be re-


placed by the reverse of the sequence.

Solution:reverse() demo

StringBuilder str = new StringBuilder ( " AAAABBBCCCC ") ;


// reverse the string
StringBuilder reverseStr = str . reverse () ;
String = AAAABBBCCCC
Reverse String = CCCCBBBAAAA

13
Solution: Performance Comparision of StringBuilder and StringBuffer

public class PerfTest {


public static void main ( String [] args ) {
// StringBuffer
long startTime = System . currentTimeMillis () ;
StringBuffer sb = new StringBuffer ( " Java ") ;
for ( int i =0; i <100000; i ++)
sb . append ( " StringBuffer " );
int TotalTime = ( int ) ( System . currentTimeMillis () -
startTime );
System . out . println ( " StringBuffer Time : "+ TotalTime + " ms ") ;
// StringBuilder
startTime = System . currentTimeMillis () ;
StringBuilder sb2 = new StringBuilder ( " Java " );
for ( int i =0; i <100000; i ++)
sb2 . append ( " StringBuilder " );
TotalTime = ( int ) ( System . currentTimeMillis () - startTime ) ;
System . out . println ( " StringBuilder Time :" + TotalTime +
" ms " );
}
}
Output :
StringBuffer Time :7 ms
StringBuilder Time :3 ms

Assignment
1. WAP to read a string from user and remove all delimeters from the string and
create an output string which consist of string without any delimeters of the in-
put string.

2. WAP to convert a list of items into a comma-separated list, while avoiding get-
ting an extra comma after the last element of the list.
Solution

public class CommaList {


public static void main ( String [] args ) {
String s= " my name is hari " ;
StringBuilder sb = new StringBuilder () ;
String words []= s . split ( " " );
int i;
for (i =0; i < words . length -1; i ++)
{
sb . append ( words [ i ]) ;
sb . append ( " , " );
}
sb . append ( words [ i ]) ;
System . out . println ( sb ) ;
}
}
Output :
my , name , is , hari

14
3.6 Processing a String One Character at a Time
Problem
You want to process the contents of a string, one character at a time.
Solution
Use a for loop and the String’s charAt() method. Or a “for each” loop and the String’s
toCharArray() method.
Solution

String a = " Java ";


for ( int i =0; i < a. length () ; i ++) // Don ’t use foreach
System . out . println ( " Char " + i + " is " + a . charAt ( i ) ) ;
String s = " Hello " ;
// for ( char ch : s) {...} Does not work , in Java 7
for ( char ch : s. toCharArray () )
System . out . println ( ch ) ;
Output :
Char 0 is J
Char 1 is a
Char 2 is v
Char 3 is a
H
e
l
l
o

3.6.1 Checksum
A “checksum” is a numeric quantity representing and confirming the contents of a file.

Assignment
1. Write a program which read a string from the user and find its checksum.

2. WAP to read a file using FileReader and BufferedReader and find the checksum.
BufferedReader
Reads text from a character-input stream, buffering characters so as to provide
for the efficient reading of characters, arrays, and lines.
Example: BufferedReader Demo

InputStreamReader r= new InputStreamReader ( System . in ) ;


BufferedReader br = new BufferedReader ( r ) ;
System . out . println ( " Enter your name " );
String name = br . readLine () ;
System . out . println ( " Welcome "+ name ) ;

15
Solution

import java . io .*;


class Main {
static int process ( BufferedReader br ) throws Exception
{
int sum =0;
String inputline ;
while (( inputline = br . readLine () ) != null )
{
for ( char ch : line . toCharArray () )
checksum += Character . getNumericValue ( ch ) ;
}
return sum ;
}
public static void main ( String [] args ) throws Exception {
FileReader fr = new FileReader ( " input . txt " );
BufferedReader br = new BufferedReader ( fr ) ;
int checksum = process ( br ) ;
System . out . println ( checksum ) ;
}
}

3.7 Reversing a String by Word or by Character


Problem
You wish to reverse a string, a character, or a word at a time.
Solution
• You can reverse a string by character easily, using a StringBuilder reverse()
method.

• One natural way is to use a StringTokenizer and a Stack. Stack is a class (de-
fined in java.util) that implements an easy-to-use last-in, first-out (LIFO) stack of
objects.

Example: Reverse a String by word and by character

StringBuilder str = new StringBuilder ( " This is a test message " ) ;


// reverse the string StringBuilder reverseStr =
str . reverse () ;
System . out . println ( reverseStr ) ;
String s= " This is a test message ";
String words []= s. split ( " " );
StringBuilder revWords = new StringBuilder () ;
for ( int i= words . length -1; i >=0; i - -)
{
revWords . append ( words [ i ]) ;
revWords . append ( " ") ;
}
System . out . println ( " Reverse String =" + revWords ) ;

16
Example: Reverse string by word using StringTokenizer and a stack

String s = " My name is rama " ;


Stack < String > MyStack = new Stack < String >() ;
StringTokenizer st = new StringTokenizer ( s ) ;
// push strings into the stack
while ( st . hasMoreTokens () )
{
MyStack . push ( st . nextToken () ) ;
}
// pop
System . out . println ( " String :" +s ) ;
StringBuilder sb = new StringBuilder () ;
while (! MyStack . empty () )
{
String ts = MyStack . pop () ;
sb . append ( ts );
sb . append ( " ");
}
System . out . print ( " Reverse : "+ sb ) ;
Output :
String : My name is rama
Reverse : rama is name My

Example: Reverse an integer array using Stack

int num []= {10 ,20 ,30 ,40 ,50};


// Put it in the stack frontwards
Stack < Integer > myStack = new Stack < >() ;
for ( int i: num )
myStack . push (i);
// Print the stack backwards
System . out . println ( " Pop the stck :" );
while (! myStack . empty () ) {
System . out . print ( myStack . pop () ) ;
System . out . print ( ’ ’);
}

3.8 Expanding and Compressing Tabs


1. WAP to replace all space in a string by tabs.

2. WAP to replace all tabs, spaces, and newline in a string by spaces.

17
Solution

public class TabsTest {


public static void main ( String [] args ) {
String originalStr = " Demo \ tText ";
System . out . println ( " Original String with tabs , spaces
and newline : \ n" + originalStr ) ;
originalStr = originalStr . replaceAll ( " [\\ n \\ t ]" , " ") ;
System . out . println ( " \ nString after removing tabs ,
spaces and new line : " + originalStr ) ;
}
}

3.9 Controlling Case


Problem
You need to convert strings to uppercase or lowercase, or to compare strings without
regard for case.
Solution

• The String class has a number of methods for dealing with documents in a partic-
ular case. toUpperCase() and toLowerCase() each return a new string that is
a copy of the current string, but converted as the name implies.

• equalsIgnoreCase() tells you if all characters are the same regardless of case.

Solution:

String name = " Java Cookbook ";


System . out . println ( " Normal :\ t" + name ) ;
System . out . println ( " Upper :\ t " + name . toUpperCase () ) ;
System . out . println ( " Lower :\ t " + name . toLowerCase () ) ;
String javaName = " java cookBook "; // If it were Java
identifiers : -)
if (! name . equals ( javaName ) )
System . err . println ( " equals () correctly reports false ") ;
else
System . err . println ( " equals () incorrectly reports true " );
if ( name . equalsIgnoreCase ( javaName ) )
System . err . println ( " equalsIgnoreCase () correctly reports
true ");
else
System . err . println ( " equalsIgnoreCase () incorrectly reports
false " );

3.9.1 Difference between == and equals() method in Java


In general both equals() and == operator in Java are used to compare objects to check
equality but here are some of the differences between the two:

18
1. Main difference between equals() method and == operator is that one is method
and other is operator.

2. We can use == operators for reference comparison (address comparison) and


equals() method for content comparison. In simple words, == checks if both
objects point to the same memory location whereas equals() evaluates to the
comparison of values in the objects.

Example: equals() and

public class Test {


public static void main ( String [] args ) {
String s1 = new String ( " HELLO " );
String s2 = new String ( " HELLO " );
System . out . println ( s1 == s2 ) ;
System . out . println ( s1 . equals ( s2 ) ) ;
}
}
Output
false
true

3.9.1.1 Difference between String Literal and New String object

String object created in following two expression :


String strObject = new String ( " Java " );
and
String strLiteral = " Java " ;

Both expression gives you String object, but there is subtle difference between them.

• When you create String object using new() operator, it always create a new ob-
ject in heap memory.

• On the other hand, if you create object using String literal syntax e.g. "Java", it
may return an existing object from String pool (a cache of String object in Perm
gen space, which is now moved to heap space in recent Java release), if it’s al-
ready exists.

• Otherwise it will create a new string object and put in string pool for future re-
use.

Example:String Literal Demo

String a = " Java ";


String b = " Java ";
System . out . println (a == b ) ; // True

19
Figure 3.1: Difference between String literal and String object

Example:String Object Demo

// Here two different objects are created and they have


different references
String c = new String ( " Java " );
String d = new String ( " Java " );
System . out . println (c == d ) ; // False

3.10 Indenting Text Documents


Problem
You need to indent (or undent or dedent) a text document.
Solution

1. To indent (add space), either generate a fixed-length string and prepend it to


each output line, or use a for loop and print the right number of spaces:

20
Solution: Indent Demo

import java . io .*;


public class IndentLine {
static int nSpaces =5;
public static void main ( String [] args ) throws Exception {
String inputLine ;
FileReader fr = new FileReader ( " input . txt " );
BufferedReader br = new BufferedReader ( fr ) ;
while (( inputLine = br . readLine () ) != null ) {
System . out . println ( inputLine ) ;
for ( int i =0; i < nSpaces ; i ++)
System . out . print ( ’ ’);
System . out . println ( inputLine ) ;
}
}
}
Output :
Test Indent
Test Indent

A more efficient approach to generating the spaces might be to construct a long


string of spaces and use substring() to get the number of spaces you need.

2. To undent (remove space), use substring to generate a string that does not
include the leading spaces. Be careful of inputs that are shorter than the amount
you are removing!
Solution: Undent Demo

import java . io .*;


public class UndentDemo {
static int nSpaces =5;
public static void main ( String [] args ) throws Exception {
FileReader fr = new FileReader ( " input1 . txt ") ;
BufferedReader br = new BufferedReader ( fr ) ;
String inputLine ;
while (( inputLine = br . readLine () ) != null ) {
System . out . println ( inputLine ) ;
int toRemove = 0;
for ( int i =0; i < nSpaces &&
Character . isWhitespace ( inputLine . charAt ( i ) ) &&
i < inputLine . length () ; i ++)
++ toRemove ;
System . out . println ( inputLine . substring ( toRemove ) ) ;
System . out . println ( " Number of Spaces
Removed : "+ toRemove ) ;
}
}
}
Output :
Test Message
Test Message
Number of Spaces Removed :5

21
3.11 Entering Nonprintable Characters
Problem
You need to put nonprintable characters into strings.
Solution
Use the backslash character and one of the Java string escapes.

3.11.1 Assignment
1. WAP to put a \t in a string.

2. WAP to put a \n in a string.

3. WAP to put a \ in a string.

Example:Nonprintable Characters Demo

System . out . println ( " An alarm entered in Octal : \007 " );


System . out . println ( " A tab key : \ t( what comes after )" );
System . out . println ( " A newline : \ n( what comes after )" );
System . out . println ( " A UniCode character : \ u02AF " );
System . out . println ( " A backslash character : \\ " );

3.12 Trimming Blanks


Problem
You need to work on a string without regard for extra leading or trailing spaces a user
may have typed.
Solution

• Use the String class trim() method.

• The java lang.string.trim() is a built-in function that eliminates leading and


trailing spaces. The Unicode value of space character is 0̆020.

• The trim() method in java checks this Unicode value before and after the string,
if it exists then removes the spaces and returns the omitted string.

• trim() returns the omitted string with no leading and trailing spaces.

22
Example:

// trims the trailing and leading spaces


String s = " Use the String class trim () method ";
System . out . println (s. trim () ) ;
// trims the leading spaces
s = " Chetna loves reading books ";
System . out . println (s. trim () ) ;
Output :
Use the String class trim () method
Chetna loves reading books

3.13 Copy the content of the file linewise


Example:

import java . io .*;


public class CopyFile {
// copy operation
static void process ( BufferedReader br , FileWriter fw ) throws
Exception
{
String line ;
while (( line = br . readLine () ) != null ) {
fw . write ( line ) ;
fw . write ( " \n ") ;
}
}
public static void main ( String [] args ) throws Exception {
/* * The file that we read and format */
FileReader fr = new FileReader ( " input . txt " );
BufferedReader br = new BufferedReader ( fr ) ;
/* * Where the output goes */
FileWriter fw = new FileWriter ( " output . txt ") ;
process (br , fw );
fw . close () ;
}
}

23

You might also like