Module-5 15CS561 Java
Module-5 15CS561 Java
1
Notes for Programming in Java (Open Elective - 15CS561)
MODULE 5
Syllabus:
• Enumerations
• Type Wrappers
• I/O: I/O Basics, Reading Console Input, Writing Console Output, The PrintWriter Class, Reading
and Writing Files
• Applets: Applet Fundamentals
• String Handling: The String Constructors, String Length, Special String Operations, Character
Extraction, String Comparison, Searching Strings, Modifying a String, Data Conversion Using
valueOf(), Changing the Case of Characters Within a String , Additional String Methods,
StringBuffer, StringBuilder.
• Other Topics: The transient and volatile Modifiers, Using instanceof, strictfp, Native Methods,
Using assert, Static Import, Invoking Overloaded Constructors Through this()
5.1 Enumerations
An enumeration is a list of named constants. In Java, enumerations define class types. That is, in Java,
enumerations can have constructors, methods and variables. An enumeration is created using the
keyword enum. Following is an example –
enum Person
{
Married, Unmarried, Divorced, Widowed
}
The identifiers like Married, Unmarried etc. are called as enumeration Constants. Each such constant
is implicitly considered as a public static final member of Person.
After defining enumeration, we can create a variable of that type. Though enumeration is a class type,
we need not use new keyword for variable creation, rather we can declare it just like any primitive data
type. For example,
Person p= Person.Married;
We can use == operator for comparing two enumeration variables. They can be used in switch-case
also. Printing an enumeration variable will print the constant name. That is,
System.out.println(p); // prints as Married
enum Person
{
Married, Unmarried, Divorced, Widowed
}
class EnumDemo
{
public static void main(String args[])
{
Person p1;
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 2
Notes for Programming in Java (Open Elective - 15CS561)
p1=Person.Unmarried;
System.out.println("Value of p1 :" + p1);
switch(p1)
{
case Married: System.out.println("p1 is Married");
break;
case Unmarried: System.out.println("p1 is Unmarried");
break;
case Divorced: System.out.println("p1 is Divorced");
break;
case Widowed: System.out.println("p1 is Widowed");
break;
}
}
}
The values() method returns an array of enumeration constants. The valueOf() method returns the
enumeration constant whose value corresponds to the string passed in str.
enum Person
{
Married, Unmarried, Divorced, Widowed
}
class EnumDemo
{ public static void main(String args[])
{ Person p;
for(Person p1:all)
System.out.println(p1);
p=Person.valueOf("Married");
System.out.println("p contains "+p);
}
}
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 3
Notes for Programming in Java (Open Elective - 15CS561)
Output:
Following are Person constants:
Married
Unmarried
Divorced
Widowed
p contains Married
enum Apple
{
Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8);
Apple(int p)
{
price = p;
}
int getPrice()
{
return price;
}
}
class EnumDemo
{
public static void main(String args[])
{
Apple ap;
System.out.println("Winesap costs " + Apple.Winesap.getPrice());
for(Apple a : Apple.values())
System.out.println(a + " costs " + a.getPrice() + " cents.");
}
}
Output:
Winesap costs 15
All apple prices:
Jonathan costs 10 cents.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 4
Notes for Programming in Java (Open Elective - 15CS561)
Here, we have member variable price, a constructor and a member method. When the variable ap is
declared in main( ), the constructor for Apple is called once for each constant that is specified.
Although the preceding example contains only one constructor, an enum can offer two or more
overloaded forms, just as can any other class. Two restrictions that apply to enumerations:
– an enumeration can’t inherit another class.
– an enum cannot be a superclass.
It returns the ordinal value of the invoking constant. Ordinal values begin at zero. We can compare the
ordinal value of two constants of the same enumeration by using the compareTo() method. It has this
general form:
final int compareTo(enum-type e)
Here, e1 and e2 should be the enumeration constants belonging to same enum type. If the ordinal value
of e1 is less than that of e2, then compareTo() will return a negative value. If two ordinal values are
equal, the method will return zero. Otherwise, it will return a positive number.
We can compare for equality an enumeration constant with any other object by using equals( ), which
overrides the equals( ) method defined by Object.
enum Person
{
Married, Unmarried, Divorced, Widowed
}
enum MStatus
{
Married, Divorced
}
class EnumDemo
{
public static void main(String args[])
{
Person p1, p2, p3;
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 5
Notes for Programming in Java (Open Elective - 15CS561)
MStatus m=MStatus.Married;
for(Person p:Person.values())
System.out.println(p + " has a value " + p.ordinal());
p1=Person.Married;
p2=Person.Divorced;
p3=Person.Married;
if(p1.compareTo(p2)<0)
System.out.println(p1 + " comes before "+p2);
else if(p1.compareTo(p2)==0)
System.out.println(p1 + " is same as "+p2);
else
System.out.println(p1 + " comes after "+p2);
if(p1.equals(p3))
System.out.println("p1 & p3 are same");
if(p1==p3)
System.out.println("p1 & p3 are same");
if(p1.equals(m))
System.out.println("p1 & m are same");
else
System.out.println("p1 & m are not same");
The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean. These
classes offer a wide array of methods that allow you to fully integrate the primitive types into Java’s object
hierarchy.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 6
Notes for Programming in Java (Open Elective - 15CS561)
Primitive Wrapper
boolean java.lang.Boolean
byte java.lang.Byte
char java.lang.Character
double java.lang.Double
float java.lang.Float
int java.lang.Integer
long java.lang.Long
short java.lang.Short
void java.lang.Void
Character Wrappers: Character is a wrapper around a char. The constructor for Character is
Character(char ch)
Here, ch specifies the character that will be wrapped by the Character object being created. To
obtain the char value contained in a Character object, call charValue(), shown here:
char charValue( )
Boolean Wrappers: Boolean is a wrapper around boolean values. It defines these constructors:
Boolean(boolean boolValue)
Boolean(String boolString)
In the first version, boolValue must be either true or false. In the second version, if boolString
contains the string “true” (in uppercase or lowercase), then the new Boolean object will be true.
Otherwise, it will be false. To obtain a boolean value from a Boolean object, use
boolean booleanValue( )
The Numeric Type Wrappers: The most commonly used type wrappers are those that represent
numeric values. All of the numeric type wrappers inherit the abstract class Number. Number
declares methods that return the value of an object in each of the different number formats. These
methods are shown here:
byte byteValue( )
double doubleValue( )
float floatValue( )
int intValue( )
long longValue( )
short shortValue( )
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 7
Notes for Programming in Java (Open Elective - 15CS561)
For example, doubleValue( ) returns the value of an object as a double, floatValue( ) returns the
value as a float, and so on. These methods are implemented by each of the numeric type
wrappers.
All of the numeric type wrappers define constructors that allow an object to be constructed from a
given value, or a string representation of that value. For example, here are the constructors
defined for Integer:
Integer(int num)
Integer(String str)
If str does not contain a valid numeric value, then a NumberFormatException is thrown. All of
the type wrappers override toString(). It returns the human-readable form of the value contained
within the wrapper. This allows you to output the value by passing a type wrapper object to
println(), for example, without having to convert it into its primitive type.
Ex:
class TypeWrap
{
public static void main(String args[])
{
Character ch=new Character('#');
System.out.println("Character is " + ch.charValue());
String s=Integer.toString(25);
System.out.println("s is " +s);
}
}
Output:
Character is #
Boolean is true
Boolean is false
12 is same as 12
x is 21
s is 25
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 8
Notes for Programming in Java (Open Elective - 15CS561)
Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created.
To obtain an InputStreamReader object that is linked to System.in, use the following constructor:
InputStreamReader(InputStream inputStream)
Because System.in refers to an object of type InputStream, it can be used for inputStream.
Putting it all together, the following line of code creates a BufferedReader that is connected to the
keyboard:
After this statement executes, br is a character-based stream that is linked to the console through
System.in. To read a character from a BufferedReader , we use read() method. Each time that read( )
is called, it reads a character from the input stream and returns it as an integer value. It returns –1 when
the end of the stream is encountered.
import java.io.*;
class BRRead
{
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do
{
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 9
Notes for Programming in Java (Open Elective - 15CS561)
Sample Output:
Enter characters, 'q' to quit.
abcdjqmn
a
b
c
d
j
q
The above program allows reading any number of characters and stores them in buffer. Then, all the
characters are read from the buffer till the ‘q’ is found and are displayed.
In Java, the data read from the console are treated as strings (or sequence of characters). So, if we need
to read numeric data, we need to parse the string to respective numeric type and use them later in the
program. Following is a program to read an integer value.
import java.io.*;
class BRRead
{
public static void main(String args[]) throws IOException
{
int x;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number:");
x=Integer.parseInt((br.readLine()).toString());
x=x+5;
System.out.println(x);
}
}
Ex:
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 10
Notes for Programming in Java (Open Elective - 15CS561)
import java.io.*;
public class PrintWriterDemo
{
public static void main(String args[])
{
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("This is a string");
int i = -7;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}
}
To open a file, you simply create an object of one of these classes, specifying the name of the file as an
argument to the constructor. Two constructors are of the form:
FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException
Here, fileName specifies the name of the file that you want to open. When you create an input stream, if
the file does not exist, then FileNotFoundException is thrown. For output streams, if the file cannot be
created, then FileNotFoundException is thrown. When an output file is opened, any preexisting file by
the same name is destroyed. When you are done with a file, you should close it by calling close( ). To
read from a file, you can use a version of read( ) that is defined within FileInputStream. To write data into
a file, you can use the write( ) method defined by FileOutputStream.
import java.io.*;
class ReadFile
{
public static void main(String args[]) throws IOException
{
int i;
FileInputStream f;
try
{
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 11
Notes for Programming in Java (Open Elective - 15CS561)
f = new FileInputStream("test.txt");
} catch(FileNotFoundException e)
{
System.out.println("File Not Found");
return;
}
do
{
i = f.read();
if(i != -1)
System.out.print((char) i);
} while(i != -1);
f.close();
}
}
When you run above program, contents of the “test.txt” file will be displayed. If you have not created the
test.txt file before running the program, then “File Not Found” exception will be caught.
import java.io.*;
class WriteFile
{
public static void main(String args[]) throws IOException
{
int i;
FileOutputStream fout;
char c;
try
{
fout = new FileOutputStream("test1.txt");
} catch(FileNotFoundException e)
{
System.out.println("Error Opening Output File");
return;
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 12
Notes for Programming in Java (Open Elective - 15CS561)
do
{
c = (char) br.read();
fout.write((int)c);
} while(c != 'q');
}
}
When you run above program, it will ask you to enter few characters. Give some random characters as
an input and provide ‘q’ to quit. The program will read all these characters from the buffer and write into
the file “test1.txt”. Go the folder where you have saved this program and check for a text file “test1.txt”.
Open the file manually (by double clicking on it) and see that all characters that you have entered are
stored in this file.
5.4 Applets
Using Java, we can write either Application or Applet. Applets are small applications that are accessed
on an Internet server, transported over the Internet, automatically installed, and run as part of a web
document. After an applet arrives on the client, it has limited access to resources so that it can produce a
graphical user interface and run complex computations without introducing the risk of viruses or
breaching data integrity.
To write an applet, we need to import Abstract Window Toolkit (AWT) classes. Applets interact with the
user (either directly or indirectly) through the AWT. The AWT contains support for a window-based,
graphical user interface. We also need to import applet package, which contains the class Applet. Every
applet that you create must be a subclass of Applet. Consider the below given program:
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleApplet" width=200 height=60>
</applet>
*/
The class SimpleApplet must be declared as public, because it will be accessed by code that is outside
the program. The paint() method is defined by AWT and must be overridden by the applet. paint( ) is
called each time that the applet must redisplay its output. This situation can occur for several reasons:
– the window in which the applet is running can be overwritten by another window and then
uncovered.
– the applet window can be minimized and then restored.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 13
Notes for Programming in Java (Open Elective - 15CS561)
The compilation of the applet is same as any normal Java program. But, to run the applet, we need some
HTML (HyperText Markup Language) support. <applet> tag is used for this purpose with the attributes
code which is assigned with name of the class file, and size of the applet window in terms of width and
height. The HTML script must be written as comment lines. Use the following statements:
When you run above program, you will get an applet window as shown below –
Applet Life Cycle: Applet class has five important methods, and any class extending Applet class may
override these methods. The order in which these methods are executed is known as applet life cycle
as explained below:
init(): This is the first method to be called. This is where you should initialize variables. This
method is called only once during the run time of your applet.
start( ) : It is called after init(). It is also called to restart an applet after it has been stopped. start()
is called each time an applet’s HTML document is displayed onscreen. So, if a user leaves a web
page and comes back, the applet resumes execution at start().
paint( ): This is called each time your applet’s output must be redrawn.
stop( ) : This method is called when a web browser leaves the HTML document containing the
applet—when it goes to another page, for example. When stop() is called, the applet is probably
running. You should use stop() to suspend threads that don’t need to run when the applet is not
visible. You can restart them when start() is called if the user returns to the page.
destroy( ) : This method is called when the environment determines that your applet needs to be
removed completely from memory. At this point, you should free up any resources the applet may
be using. The stop() method is always called before destroy().
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 14
Notes for Programming in Java (Open Elective - 15CS561)
In case, we need a modifiable string, we should use StringBuffer or StringBuilder classes. String,
StringBuffer and StringBuilder classes are in java.lang and are final classes. Thus, no class can
inherit these classes. All these classes implement CharSequence interface.
3. To create a string object that contains same characters as another string object:
String(String strObj);
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 15
Notes for Programming in Java (Open Elective - 15CS561)
For example,
String s= new String(“Hello”);
String s1= new String(s);
For example,
char ch[]={‘h’, ‘e’, ‘l’, ‘l’, ‘o’};
String s= new String(ch); //s contains hello
For example,
char ch[]={‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’’, ‘g’};
String s= new String(ch, 2, 3); //Now, s contains cde
• Even though Java’s char type uses 16 bits to represent the basic Unicode character set, the
typical format for strings on the Internet uses arrays of 8-bit bytes constructed from the ASCII
character set. Because 8-bit ASCII strings are common, the String class provides constructors
that initialize a string when given a byte array.
For example,
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii); // s1 contains ABCDEF
String s2 = new String(ascii, 2, 3); // s2 contains CDE
• JDK 5 and higher versions have two more constructors. The first one supports the extended
Unicode character set.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 16
Notes for Programming in Java (Open Elective - 15CS561)
• String Literals: Instead of using character arrays and new operator for creating string instance,
we can use string literal directly. For example,
char ch[]={‘H’, ‘e’, ‘l’, ‘l’, ‘o’};
String s1=new String(ch);
or
String s2= new String (“Hello”);
Can be re-written, for simplicity, as –
String s3=“Hello”; //usage of string literal
A String object will be created for every string literal and hence, we can even use,
System.out.println(“Hello”.length()); //prints 5
• String Concatenation: Java does not allow any other operator than + on strings. Concatenation
of two or more String objects can be achieved using + operator. For example,
String age = “9”;
String s = "He is " + age + " years old.";
System.out.println(s); //prints He is 9 years old.
One practical use of string concatenation is found when you are creating very long strings.
Instead of letting long strings wrap around within your source code, you can break them into
smaller pieces, using the + to concatenate them.
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: We can concatenate String with other data types.
For example,
int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s); //prints He is 9 years old.
Here, 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. But, we should be careful while mixing data types:
String s= “Four : ” + 2 + 2;
System.out.println(s); //prints Four : 22
This is because, “Four :” is concatenated with 2 first, then the resulting string is again
concatenated with 2. We can prevent this by using brackets:
String s = “Four : ” + (2+2);
System.out.println(s); //prints Four : 4
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 17
Notes for Programming in Java (Open Elective - 15CS561)
• String Conversion and toString(): Java uses valueOf( ) method for converting data into its
string representation during concatenation. valueOf( ) is a string conversion method defined by
String. valueOf( ) is overloaded for all the primitive types and for type Object. For the primitive
types, valueOf( ) returns a string that contains the human-readable equivalent of the value with
which it is called. For objects, valueOf( ) calls the toString( ) method on the object. Every class
implements toString( ) because it is defined by Object. However, the default implementation of
toString( ) is seldom sufficient. For our own classes, we may need to override toString() to give
our own string representation for user-defined class objects. The toString( ) method has this
general form:
String toString( )
To implement toString( ), simply return a String object that contains the human-readable string
that appropriately describes an object of our class.
class Box
{
double width, height, depth;
class StringDemo
{
public static void main(String args[])
{
Box b = new Box(10, 12, 14);
String s = "Box b: " + b; // concatenate Box object
System.out.println(s); // convert Box to string
System.out.println(b);
}
}
Output:
Box b: Dimensions are 10.0 by 14.0 by 12.0
Dimensions are 10.0 by 14.0 by 12.0
Note: Observe that, Box’s toString( ) method is automatically invoked when a Box object is
used in a concatenation expression or in a call to println( ).
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 18
Notes for Programming in Java (Open Elective - 15CS561)
• charAt() : This method is used to extract a single character from a String. It has this general
form:
char charAt(int where)
Here, where is the index of the character that you want to obtain. The value of where must be
nonnegative and specify a location within the string. For example,
char ch;
ch= “Hello”.charAt(1); //ch now contains e
• getChars() : If you need to extract more than one character at a time, you can use this method. It
has the following general form:
Care must be taken to assure that the target array is large enough to hold the number of
characters in the specified substring.
class StringDemo1
{
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);
}
}
Output:
demo
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.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 19
Notes for Programming in Java (Open Elective - 15CS561)
• toCharArray() : If you want to convert all the characters in a String object into a character array,
the easiest way is to call toCharArray( ). It returns an array of characters for the entire string. It
has this general form:
char[ ] toCharArray( )
This function is provided as a convenience, since it is possible to use getChars( ) to achieve the
same result.
String s1="hello";
char[] ch=s1.toCharArray();
for(int i=0;i<ch.length;i++)
System.out.print(ch[i]);
• equals() and equalsIgnoreCase(): To compare two strings for equality, we have two methods:
boolean equals(Object str)
boolean equalsIgnoreCase(String str)
Here, str is the String object being compared with the invoking String object. The first method is
case sensitive and returns true, if two strings are equal. The second method returns true if two
strings are same, whatever may be their case.
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1.equals(s2)); //true
System.out.println(s1.equals(s3)); //false
System.out.println(s1.equals(s4)); //false
System.out.println(s1.equalsIgnoreCase(s4)); //true
• regionMatches(): The regionMatches( ) method compares a specific region inside a string with
another specific region in another string. There is an overloaded form that allows you to ignore
case in such comparisons. Here are the general forms for these two methods:
startIndex specifies the index at which the region begins within the invoking String.
str2 the String being compared.
str2StartIndex The index at which the comparison will start within str2.
numChars The length of the substring being compared.
ignoreCase used in second version. If it is true, the case of the characters is ignored.
Otherwise, case is significant.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 20
Notes for Programming in Java (Open Elective - 15CS561)
System.out.println(s1.regionMatches(6,s2,0,3)); //false
System.out.println(s1.regionMatches(true,6,s2,0,3)); //true
• startsWith( ) and endsWith(): These are the specialized versions of the regionMatches()
method. The startsWith() method determines whether a given String begins with a specified
string. The endsWith() method determines whether the String in question ends with a specified
string. They have the following general forms:
boolean startsWith(String str)
boolean endsWith(String str)
Ex:
"Foobar".endsWith("bar") //true
"Foobar".startsWith("Foo") //true
Here, startIndex specifies the index into the invoking string at which point the search will begin.
"Foobar".startsWith("bar", 3) //returns true.
• equals( ) v/s == : The equals( ) method compares the characters inside a String object. The ==
operator compares two object references to see whether they refer to the same instance.
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1.equals(s2)); //true
System.out.println((s1 == s2)); //false
• compareTo(): This method is used to check whether a string is less than, greater than or equal
to the other string. The meaning of less than, greater than refers to the dictionary order (based on
Unicode). It has this general form:
int compareTo(String str)
This method will return 0, if both the strings are same. Otherwise, it will return the difference
between the ASCII values of first non-matching character. If you want to ignore case differences
when comparing two strings, use compareToIgnoreCase(), as shown here:
int compareToIgnoreCase(String str)
Ex:
String str1 = "String method tutorial";
String str2 = "compareTo method example";
String str3 = "String method tutorial";
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 21
Notes for Programming in Java (Open Elective - 15CS561)
Method Purpose
int indexOf(int ch) To search for the first occurrence of a
character
int lastIndexOf(int ch) To search for the last occurrence of a
character,
int indexOf(String str) To search for the first or last occurrence
of a substring
int lastIndexOf(String str)
int indexOf(int ch, int startIndex) Used to specify a starting point for the
search. Here, startIndex specifies the
int lastIndexOf(int ch, int startIndex) index at which point the search begins.
For indexOf() method, the search runs
int indexOf(String str, int startIndex)
from startIndex to the end of the string.
int lastIndexOf(String str, int For lastIndexOf( ) method, the search
startIndex) runs from startIndex to zero.
class Demo
{
public static void main(String args[])
{
String s = "Now is the time for all good men to come to the aid of their
country.";
System.out.println(s.indexOf('t')); //7
System.out.println(s.lastIndexOf('t')); //65
System.out.println(s.indexOf("the")); //7
System.out.println(s.lastIndexOf("the")); //55
System.out.println(s.indexOf('t', 10)); //11
System.out.println(s.lastIndexOf('t', 60)); //55
System.out.println(s.indexOf("the", 10)); //44
System.out.println(s.lastIndexOf("the", 60)); //55
}
}
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 22
Notes for Programming in Java (Open Elective - 15CS561)
substring(): Used to extract a substring from a given string. It has two formats:
o String substring(int startIndex): Here, startIndex specifies the index at which the substring
will begin. This form returns a copy of the substring that begins at startIndex and runs to
the end of the invoking string.
o String substring(int startIndex, int endIndex): Here, startIndex specifies the beginning
index, and endIndex specifies the stopping point. The string returned contains all the
characters from the beginning index, up to, but not including, the ending index.
Ex:
String org = "This is a test. This is, too.";
String result ;
result=org.substring(5);
System.out.println(result); //is a test. This is, too.
result=org.substring(5, 7);
System.out.println(result); //is
replace():The first form of this method replaces all occurrences of one character in the invoking
string with another character.
String replace(char original, char replacement)
Here, original specifies the character to be replaced by the character specified by replacement.
For example,
String s = "Hello".replace('l', 'w');
puts the string “Hewwo” into s.
The second form of replace( ) replaces one character sequence with another.
String replace(CharSequence original, CharSequence replacement)
trim():The trim( ) method returns a copy of the invoking string from which any leading and trailing
white-space has been removed. It has this general form:
String trim( )
Here is an example:
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 23
Notes for Programming in Java (Open Elective - 15CS561)
For example,
int value=30;
String s1=String.valueOf(value);
System.out.println(s1+10); //prints 3010
For example,
String str = "Welcome!";
String s1 = str.toUpperCase();
System.out.println(s1); //prints WELCOME!
String s2= str.toLowerCase();
System.out.println(s2); //prints welcome!
Method Description
int codePointAt(int i) Returns the Unicode code point at the location specified by i.
int codePointBefore(int i) Returns the Unicode code point at the location that precedes
that specified by i.
int codePointCount(int start, int end) Returns the number of code points in the portion of the
invoking String that is between start and end–1.
boolean contains(CharSequence str) Returns true if the invoking object contains the string specified
by str. Returns false, otherwise.
boolean contentEquals(CharSequence str) Returns true if the invoking string contains the same string as
str. Otherwise, returns false.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 24
Notes for Programming in Java (Open Elective - 15CS561)
boolean contentEquals(StringBuffer str) Returns true if the invoking string contains the same string as
str. Otherwise, returns false.
boolean matches(string regExp) Returns true if the invoking string matches the regular
expression passed in regExp. Otherwise, returns false.
int offsetByCodePoints(int start, int num) Returns the index with the invoking string that is num code
pointsbeyond the starting index specified by start.
String replaceFirst(String regExp, String Returns a string in which the first substring that matches the
newStr) regular expression specified by regExp is replaced by newStr.
String replaceAll(String regExp, String Returns a string in which all substrings that match the regular
newStr) expression specified by regExp are replaced by newStr.
String[ ] split(String regExp) Decomposes the invoking string into parts and returns an
array that contains the result. Each part is delimited by the
regular expression passed in regExp.
String[ ] split(String regExp, Decomposes the invoking string into parts and returns an
int max) array that contains the result. Each part is delimited by the
regular expression passed in regExp. The number of pieces is
specified by max. If max is negative, then the invoking string is
fully decomposed. Otherwise, if max contains a nonzero
value, the last entry in the returned array contains the
remainder of the invoking string. If max is zero, the invoking
string is fully decomposed.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 25
Notes for Programming in Java (Open Elective - 15CS561)
StringBuffer class provides various methods to perform certain tasks, which are mainly focused on
changing the content of the string (Remember, String class is immutable – means content of the String
class objects cannot be modified). Some of them are discussed hereunder:
length() and capacity(): These two methods can be used to find the length and total allocated
capacity of StringBuffer object. As an empty object of StringBuffer class gets 16 character space,
the capacity of the object will be sum of 16 and the length of string value allocated to that object.
Example:
ensureCapacity(): If you want to preallocate room for a certain number of characters after a
StringBuffer has been constructed, you can use this method to set the size of the buffer. This is
useful if you know in advance that you will be appending a large number of small strings to a
StringBuffer. The method ensureCapacity() has this general form:
void ensureCapacity(int capacity)
Here, capacity specifies the size of the buffer.
• charAt() and setCharAt(): The value of a single character can be obtained from a StringBuffer
via the charAt() method. You can set the value of a character within a StringBuffer using
setCharAt(). Their general forms are shown here:
char charAt(int where)
void setCharAt(int where, char ch)
For charAt(), where specifies the index of the character being obtained. For setCharAt(), where
specifies the index of the character being set, and ch specifies the new value of that character.
Example:
Output would be –
buffer before = Hello
charAt(1) before = e
buffer after = Hi
charAt(1) after = i
getChars(): To copy a substring of a StringBuffer into an array, use the getChars( ) method. It
has this general form:
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 26
Notes for Programming in Java (Open Elective - 15CS561)
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. This means that the substring contains
the characters from sourceStart through sourceEnd–1. The array that will receive the characters
is specified by target. The index within target at which the substring will be copied is passed in
targetStart. Care must be taken to assure that the target array is large enough to hold the number
of characters in the specified substring.
• append(): The append() method concatenates the string representation of any other type of data
to the end of the invoking StringBuffer object. It has several overloaded versions. Here are a few
of its forms:
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
String.valueOf() is called for each parameter to obtain its string representation. The result is
appended to the current StringBuffer object. The buffer itself is returned by each version of
append( ) to allow subsequent calls.
String s;
int a = 42;
StringBuffer sb = new StringBuffer(40);
s = sb.append("a=").append(a).append("!").toString();
System.out.println(s); //prints a=42!
• insert(): The insert() method inserts one string into another. It is overloaded to accept values of
all the simple types, plus Strings, Objects, and CharSequences. Like append(), it calls
String.valueOf( ) to obtain the string representation of the value it is called with. This string is
then inserted into the invoking StringBuffer object. Few forms are:
– StringBuffer insert(int index, String str)
– StringBuffer insert(int index, char ch)
– StringBuffer insert(int index, Object obj)
Here, index specifies the index at which point the string will be inserted into the invoking
StringBuffer object. Example:
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb); //I like Java
• delete() and deleteCharAt(): You can delete characters within a StringBuffer by using the
methods delete() and deleteCharAt(). These methods are shown here:
StringBuffer delete(int startIndex, int endIndex)
It deletes a sequence of characters from the invoking object. Here, startIndex specifies the index
of the first character to remove, and endIndex specifies an index one past the last character to
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 27
Notes for Programming in Java (Open Elective - 15CS561)
remove. Thus, the substring deleted runs from startIndex to endIndex–1.The resulting
StringBuffer object is returned.
StringBuffer deleteCharAt(int loc)
It deletes the character at the index specified by loc. It returns the resulting StringBuffer object.
Example:
• replace(): You can replace one set of characters with another set inside a StringBuffer object by
calling replace( ). Its signature is shown here:
StringBuffer replace(int startIndex, int endIndex, String str)
The substring being replaced is specified by the indexes startIndex and endIndex. Thus, the
substring at startIndex through endIndex–1 is replaced. The replacement string is passed in str.
The resulting StringBuffer object is returned.
• substring() : You can obtain a portion of a StringBuffer by calling substring(). It has the
following two forms:
String substring(int startIndex)
String substring(int startIndex, int endIndex)
The first form returns the substring that starts at startIndex and runs to the end of the invoking
StringBuffer object. The second form returns the substring that starts at startIndex and runs
through endIndex–1. These methods work just like those defined for String that were described
earlier.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 28
Notes for Programming in Java (Open Elective - 15CS561)
int indexOf(String str, int Searches the invoking StringBuffer for the first occurrence of
startIndex) str, beginning at startIndex. Returns the index of the match, or
–1 if no match is found.
int lastIndexOf(String str) Searches the invoking StringBuffer for the last occurrence of
str. Returns the index of the match, or –1 if no match is found.
int lastIndexOf(String str, int Searches the invoking StringBuffer for the last occurrence of
startIndex) str, beginning at startIndex. Returns the index of the match, or
–1 if no match is found.
int offsetByCodePoints(int start, int Returns the index with the invoking string that is num code
num) points beyond the starting index specified by start.
void trimToSize( ) Reduces the size of the character buffer for the invoking object
to exactly fit the current contents.
class A
{
int i, j;
}
class B
{
int i, j;
}
class C extends A
{
int k;
}
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 29
Notes for Programming in Java (Open Elective - 15CS561)
class InstanceOfEx
{
public static void main(String args[])
{
A a = new A();
B b = new B();
C c = new C();
A ob;
ob = c;
class Hypot
{
public static void main(String args[])
{
double side1, side2;
double hypot;
side1 = 3.0;
side2 = 4.0;
hypot = sqrt(pow(side1, 2) + pow(side2, 2));
System.out.println(" the hypotenuse is " + hypot);
}
}
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 30
Notes for Programming in Java (Open Elective - 15CS561)
this(arg-list)
When this() is executed, the overloaded constructor that matches the parameter list specified by arg-list
is executed first. Then, if there are any statements inside the original constructor, they are executed. The
call to this() must be the first statement within the constructor.
class MyClass
{
int a, b;
MyClass(int i, int j)
{
a = i;
b = j;
}
MyClass(int i)
{
this(i, i); // invokes MyClass(i, i)
}
MyClass( )
{
this(0); // invokes MyClass(0)
}
void disp()
{
System.out.println(“a=”+a + “ b=”+b);
}
}
class thisDemo
{
public static void main(String args[])
{
MyClass m1 = new MyClass();
m1.disp();
Output:
a= 0 b=0
a= 8 b=8
a= 2 b=3
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]
This document can be downloaded from www.chetanahegde.in with most recent updates. 31
Notes for Programming in Java (Open Elective - 15CS561)
Questions:
1. Define Enumerations. Give an example.
2. Discuss values() and valueOf() methods in Enumerations with suitable examples.
3. "Enumerations in Java are class types" - justify this statement with appropriate examples.
4. Write a note on ordinal() and compareTo() methods.
5. What are wrapper classes? Explain with examples.
6. Write a program to read n integers from the keyboard and find their average.
7. Write a program to read data from keyboard and to store it into a file.
8. Write a program to read data from an existing file and to display it on console.
9. Define an Applet. Write a program to demonstrate simple applet.
10. Explain life cycle of an applet.
11. List and explain any four constructors of String class with suitable examples.
12. Write a note on following String class methods:
(i) charAt()
(ii) toCharArray()
(iii) regionMatches()
(iv) startsWith() and endsWith()
(v) replace()
(vi) trim()
(vii) substring()
13. Explain various forms of indexOf() and lastIndexOf() methods with a code snippet.
14. Differentiate StringBuffer class methods length() and capacity().
15. Write a note on StringBuffer class methods:
(i) setCharAt()
(ii) append()
(iii) insert()
(iv) reverse()
(v) delete()
(vi) deleteCharAt()
16. Write a note on
(i) instanceof Operator
(ii) static import
(iii) this()
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: [email protected]