SlideShare a Scribd company logo
1 of 42
Download to read offline
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 1
DEPARTMENT OF INFORMATION TECHNOLOGY
R2017 - SEMESTER III
CS3391 – OBJECT ORIENTED PROGRAMMING
UNIT IV - UNIT IV I/O, GENERICS,
STRING HANDLING
CLASS NOTES
Complimented with
PERSONALIZED LEARNING MATERIAL (PLM)
With
PERSONALIZED ASSESSMENT TESTS (PATs)
PERSONALIZED LEARNING MATERIAL (PLM)
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 2
An Introduction to PLM
The PERSONALIZED LEARNING MATERIAL (PLM) is special Type of Learning Material
designed and developed by Er. K.Khaja Mohideen , Assistant Professor , Aalim Muhammed
Salegh College of Engineering, Avadi-IAF, Chennai – 600 055, India.
This material called PLM is an innovative Learning Type based Artificial Intelligence
based Suggestive learning Strategy (SLS) that recommends the selective Topics to Learners
of different Learning mind sets groups.
We identified three major such Learner Groups from Subject Learning Student
Communities and are as follows:
1) Smart Learning Groups
2) Effective Learning Groups
3) Slow Learning Groups
The three Coloring depicts the following levels of Experiencing Learners groups:
1) Smart Learning Groups – Greenish Shadow
2) Effective Learning Groups – Orange Shadow
3) Slow Learning Groups – Red Shadow
The following picture illustrates the same:
Note: The decision on PLM Topic grouping type is based on the Designer’s Academic
Experience and his Academic Excellence on the selective Course Domain.
MOST IMPORTANT IMPORTANT NOT IMPORTANT
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 3
PERSONALIZED ASSESSMENT TESTS (PATs)
An Introduction to PAT
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 4
INDEX
UNIT IV I/O, GENERICS, STRING HANDLING
SL NO TOPIC
UNIT – IV : Syllabus with PL
1 I/O BASICS
2 READING AND WRITING FILES
3 CONSOLE I/O PROGRAMMING
4 GENERICS: GENERIC PROGRAMMING
5 GENERIC CLASSES
6 GENERIC METHODS
7 BOUNDED TYPES
8 RESTRICTIONS AND LIMITATIONS
9 STRINGS: BASIC STRING CLASS
10 METHODS
11 STRING BUFFER CLASS
.–––.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 5
UNIT – IV: Syllabus with PL
SYLLABUS:
UNIT IV I/O, GENERICS, STRING HANDLING 9
I/O Basics – Reading and Writing Console I/O – Reading and Writing Files.
Generics: Generic Programming – Generic classes – Generic Methods – Bounded Types
– Restrictions and Limitations.
Strings: Basic String class, methods and String Buffer Class.
TOTAL TOPICS: 11
NOTE:
 Important Topic
 Less Important
  Not Important
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 6
BASICS OF I/O
// Java program to demonstrate
// ArithmeticException
class ArithmeticException_Demo {
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
System.out.println("Result = " + c);
}
catch (ArithmeticException e) {
System.out.println("Can't divide a number by 0");
}
}
}
Output:
Can't divide a number by 0
2. ArrayIndexOutOfBounds Exception : It is thrown to indicate that an array has been accessed with an illegal
index. The index is either negative or greater than or equal to the size of the array.
// Java program to demonstrate
// ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of Bounds");
}
}
}
Output:
Array Index is Out Of Bounds
ClassNotFoundException : This Exception is raised when we try to access a class whose definition is NOT
FOUND
1. FileNotFoundException : This Exception is raised when a file is not accessible or does not open.
// Java program to demonstrate
// FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
public static void main(String args[])
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 7
{
try {
// Following file does not exist
File file = new File("E:// file.txt");
FileReader fr = new FileReader(file);
}
catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}
Output:
File does not exist
IOException : It is thrown when an input-output operation failed or interrupted
// Java program to illustrate IOException
import java.io.*;
class Geeks {
public static void main(String args[])
{
FileInputStream f = null;
f = new FileInputStream("abc.txt");
int i;
while ((i = f.read()) != -1) {
System.out.print((char)i);
}
f.close();
}
}
Output:
error: unreported exception IOException; must be caught or declared to be thrown
2. InterruptedException : It is thrown when a thread is waiting, sleeping, or doing some processing, and it is
interrupted.
// Java Program to illustrate
// InterruptedException
class Geeks {
public static void main(String args[])
{
Thread t = new Thread();
t.sleep(10000);
}
}
Output:
error: unreported exception InterruptedException; must be caught or declared to be thrown
NoSuchMethodException : t is thrown when accessing a method which is not found.
// Java Program to illustrate
// NoSuchMethodException
class Geeks {
public Geeks()
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 8
{
Class i;
try {
i = Class.forName("java.lang.String");
try {
Class[] p = new Class[5];
}
catch (SecurityException e) {
e.printStackTrace();
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
new Geeks();
}
}
Output:
error: exception NoSuchMethodException is never thrown
in body of corresponding try statement
3. NullPointerException : This exception is raised when referring to the members of a null object. Null
represents nothing
// Java program to demonstrate NullPointerException
class NullPointer_Demo {
public static void main(String args[])
{
try {
String a = null; // null value
System.out.println(a.charAt(0));
}
catch (NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
Output:
NullPointerException..
4. NumberFormatException : This exception is raised when a method could not convert a string into a numeric
format.
// Java program to demonstrate
// NumberFormatException
class NumberFormat_Demo {
public static void main(String args[])
{
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 9
try {
// "akki" is not a number
int num = Integer.parseInt("akki");
System.out.println(num);
}
catch (NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
Output:
Number format exception
5. StringIndexOutOfBoundsException : It is thrown by String class methods to indicate that an index is either
negative than the size of the string.
// Java program to demonstrate
// StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch (StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}
Output:
StringIndexOutOfBoundsException
Java.lang.StackTraceElement class in Java
An element in a stack trace, as returned by Throwable.getStackTrace(). Each element represents a single stack frame.
All stack frames except for the one at the top of the stack represent a method invocation. The frame at the top of the
stack represents the execution point at which the stack trace was generated.
This class describes single stack frame, which is an individual element of a stack trace when an exception occur.
 All stack frames except for the one at the top of the stack represent a method invocation.
 The frame at the top of the stack represent the execution point of which the stack trace was generated.
 Each stack frame represents an execution point, which includes such things as the name of the method, the
name of file and the source code line number.
 An array of StackTraceElement is returned by getStackTrace()
method of the Throwable class.
Constructor: Creates a stack trace element representing the specified execution point.
StackTraceElement(String declaringClass,
String methodName, String fileName, int lineNumber)
Parameters:
 declaringClass – the fully qualified name of the class containing the execution point represented by the stack
trace element.
 methodName – the name of the method containing the execution point represented by the stack trace element.
 fileName – the name of the file containing the execution point represented by the stack trace element, or null if
this information is unavailable
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 10
 lineNumber – the line number of the source line containing the execution point represented by this stack trace
element, or a negative number if this information is unavailable. A value of -2 indicates that the method
containing the execution point is a native method.
Throws: NullPointerException – if declaringClass or methodName is null.
Methods:
boolean equals(ob): Returns try if the invoking StackTraceElementis as the one passed in ob. Otherwise it returns
false.
1. Syntax: public boolean equals(ob)
2. Returns: true if the specified object is
3. another StackTraceElement instance representing the same execution
4. point as this instance.
5. Exception: NA
// Java code illustrating equals() method
import java.lang.*;
import java.io.*;
import java.util.*;
public class StackTraceElementDemo
{
public static void main(String[] arg)
{
StackTraceElement st1 = new StackTraceElement("foo", "fuction1",
"StackTrace.java", 1);
StackTraceElement st2 = new StackTraceElement("bar", "function2",
"StackTrace.java", 1);
Object ob = st1.getFileName();
// checking whether file names are same or not
System.out.println(st2.getFileName().equals(ob));
}
}
Output:
true
String getClassName(): Returns the class name of the execution point described by the
invoking StackTraceElement.
Syntax: public String getClassName().
Returns: the fully qualified name of the Class
containing the execution point represented by this stack trace element.
Exception: NA.
// Java code illustrating getClassName() method.
import java.lang.*;
import java.io.*;
import java.util.*;
public class StackTraceElementDemo
{
public static void main(String[] arg)
{
System.out.println("Class name of each thread involved:");
for(int i = 0; i<2; i++)
{
System.out.println(Thread.currentThread().getStackTrace()[I].
getClassName());
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 11
}
}
}
Output:
Class name of each thread involved:
java.lang.Thread
StackTraceElementDemo
String getFileName(): Returns the file name of the execution point described by the
invoking StackTraceElement.
Syntax: public String getFileName().
Returns: the name of the file containing
the execution point represented by this stack trace element,
or null if this information is unavailable.
Exception: NA.
// Java code illustrating getFileName() method.
import java.lang.*;
import java.io.*;
import java.util.*;
public class StackTraceElementDemo
{
public static void main(String[] arg)
{
System.out.println("file name: ");
for(int i = 0; i<2; i++)
System.out.println(Thread.currentThread().getStackTrace()[i].
getFileName());
}
}
Output:
file name:
Thread.java
StackTraceElementDemo.java
int getLineNumber(): Returns the source-code line number of the execution point described by the
invoking StackTraceElement. In some situation the line number will not be available, in which case a negative value
is returned.
Syntax: public int getLineNumber().
Returns: the line number of the source line
containing the execution point represented by this stack
trace element, or a negative number if this information is
unavailable.
Exception: NA.
// Java code illustrating getLineNumber() method.
import java.lang.*;
import java.io.*;
import java.util.*;
public class StackTraceElementDemo
{
public static void main(String[] arg)
{
System.out.println("line number: ");
for(int i = 0; i<2; i++)
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 12
System.out.println(Thread.currentThread().getStackTrace()[i].
getLineNumber());
}
}
Output:
line number:
1556
10
String getMethodName(): Returns the method name of the execution point described by the
invoking StackTraceElement.
Syntax: public String getMethodName().
Returns: the name of the method containing the
execution point represented by this stack trace element.
Exception: NA.
Output:
method name:
getStackTrace
main
IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to make input and output
operation in java. In general, a stream means continuous flow of data. Streams are clean way to deal with input/output
without having every part of your code understand the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams. They are,
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of characters. Character
stream uses Unicode and therefore can be internationalized.
Byte Stream Classes
Byte stream is defined by using two abstract class at the top of hierarchy, they are InputStream and OutputStream.
These two abstract classes have several concrete classes that handle various devices such as disk files, network
connection etc.
Some important Byte stream classes.
Stream class Description
BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStream Used for Buffered Output Stream.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 13
DataInputStream Contains method for reading java standard datatype
DataOutputStream An output stream that contain method for writing java standard data type
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that contain print() and println() method
These classes define several key methods. Two most important are
1. read() : reads byte of data.
2. write() : Writes byte of data.
Character Stream Classes
Character stream is also defined by using two abstract class at the top of hierarchy, they are Reader and Writer.
These two abstract classes have several concrete classes that handle unicode character.
Some important Charcter stream classes.
Stream class Description
BufferedReader Handles buffered input stream.
BufferedWriter Handles buffered output stream.
FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
OutputStreamReader Output stream that translate character to byte.
PrintWriter Output Stream that contain print() and println() method.
Reader Abstract class that define character stream input
Writer Abstract class that define character stream output
Reading Console Input
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 14
We use the object of BufferedReader class to take inputs from the keyboard.
Reading Characters
read() method is used with BufferedReader object to read characters. As this function returns integer type value has we
need to use typecasting to convert it into char type.
int read() throws IOException
Below is a simple example explaining character input.
class CharRead
{
public static void main( String args[])
{
BufferedReader br = new Bufferedreader(new InputstreamReader(System.in));
char c = (char)br.read(); //Reading character
}
}
Reading Strings
To read string we have to use readLine() function with BufferedReader class's object.
String readLine() throws IOException
Program to take String input from Keyboard in Java
import java.io.*;
class MyInput
{
public static void main(String[] args)
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
text = br.readLine(); //Reading String
System.out.println(text);
}
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 15
Program to read from a file using BufferedReader class
import java. Io *;
class ReadTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}
Program to write to a File using FileWriter class
import java. Io *;
class WriteTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
String str="Write this string to my file";
FileWriter fw = new FileWriter(fl) ;
fw.write(str);
fw.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 16
GENERIC PROGRAMMING
Introduction to Generic Programming
 Generics mean parameterized types.
 The idea is to allow type (Integer, String, … etc., and user-defined types)
to be a parameter to methods, classes, and interfaces.
 Using Generics, it is possible to create classes that work with different
data types.
 A generic type is a generic class or interface that is parameterized over
types.
Generics in Java
 The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.
 It makes the code stable by detecting the bugs at compile time.
 Before generics, we can store any type of objects in the collection, i.e., non-generic.
 Now generics force the java programmer to store a specific type of objects.
What is Generic Programming?
 Generic programming enables the programmer to create classes, interfaces and
methods that automatically works with all types of data(Integer, String, Float etc).
 It has expanded the ability to reuse the code safely and easily.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 17
Syntax to use generic collection
Class Or Interface<Type>
Example to use Generics in java
ArrayList<String>
A Generic Class
A generic class is defined with the following format:
class name<T1, T2, ..., Tn> { /* ... */ }
 The type parameter section, delimited by angle brackets (<>), follows the class name.
It specifies the type parameters (also called type variables) T1, T2, ..., and Tn.
public class Box<T> {
// T stands for "Type"
private T t;
public void set(T t)
{
this.t = t;
}
public T get()
{ return t; }
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 18
Invoking and Instantiating a Generic Type
 To reference the generic Box class from within your code, you must perform a
generic type invocation, which replaces T with some concrete value, such as
Integer:
Box<Integer> integerBox;
 You can think of a generic type invocation as being similar to an ordinary method
invocation,
 but instead of passing an argument to a method, you are passing a type argument
— Integer in this case — to the Box class itself.
Parameterized type
An invocation of a generic type is generally known as a parameterized type.
 To instantiate this class, use the new keyword, as usual, but
place <Integer> between the class name and the parenthesis:
Box<Integer> integerBox = new Box<Integer>();
Why Use Generics?
 In a nutshell, generics enable types (classes and interfaces) to be parameters when
defining classes, interfaces and methods.
 Much like the more familiar formal parameters used in method declarations, type
parameters provide a way for you to re-use the same code with different inputs.
 The difference is that the inputs to formal parameters are values, while the inputs to
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 19
type parameters are types.
Code that uses generics has many benefits over non-generic code:
 Stronger type checks at compile time.
A Java compiler applies strong type checking to generic code and issues errors if the code
violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which
can be difficult to find.
 Elimination of casts.
The following code snippet without generics requires casting:
 List list = new ArrayList();
 list.add("hello");
 String s = (String) list.get(0);
 When re-written to use generics, the code does not require casting:
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0); // no cast
 Enabling programmers to implement generic algorithms.
By using generics, programmers can implement generic algorithms that work on
collections of different types, can be customized, and are type safe and easier to read
Advantage of Java Generics
 There are mainly 3 advantages of generics.
 They are as follows:
i) Type-safety :
 We can hold only a single type of objects in generics.
 It doesn’t allow storing other objects.
 Without Generics, we can store any type of objects.
Example:
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 20
List list = new ArrayList();
list.add(10);
list.add("10");
With Generics, it is required to specify the type of object we need to store.
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add("10");// compile-time error
ii) Type casting is not required:
 There is no need to typecast the object.
 Before Generics, we need to type cast.
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);//typecasting
After Generics, we don't need to typecast the object.
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);
iii)Compile-Time Checking:
 It is checked at compile time so problem will not occur at runtime.
 The good programming strategy says it is far better to handle the problem at compile
time than runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32);//Compile Time Error
Generic class
 A class that can refer to any type is known as generic class.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 21
 Generic class declaration defines set of parameterized type one for each possible
invocation of the type parameters.
 Here, we are using the T type parameter to create the generic class of specific type.
Different types of generics in Java
The most commonly used type parameter names are:
i) E - Element (used extensively by the Java Collections Framework)
ii) K - Key.
iii)N - Number.
iv)T - Type.
v) V - Value.
vi)S,U,V etc. - 2nd, 3rd, 4th types.
Example:
class TwoGen<T, V>
{
T ob1;
V ob2;
TwoGen(T o1, V o2)
{
ob1 = o1; ob2 = o2;
}
void showTypes() {
System.out.println("Type of T is " + ob1.getClass().getName());
System
.out.println("Type of V is " + ob2.getClass().getName());
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 22
T getob1()
{
return ob1;
}
V getob2()
{
return ob2;
}
}
public class MainClass
{
public static void main(String args[])
{
TwoGen<Integer, String> tgObj = new TwoGen<Integer, String>(88,"Generics");
tgObj.showTypes();
int v = tgObj.getob1(); System.out.println("value: " + v);
String str = tgObj.getob2(); System.out.println("value: " + str);
}
}
Generic Method
Like generic class, we can create generic method that can accept any type of argument.
public class TestGenerics4{
public static < E > void printArray(E[] elements) { for ( E element : elements){
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 23
System.out.println(element );
}
System.out.println();
}
public static void main( String args[] )
{
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A'};
System.out.println( "Printing Integer Array" );
printArray( intArray );
System.out.println( "Printing Character Array" );
printArray( charArray );
}
}
Bounded type
 The type parameters could be replaced by any class type.
 This is fine for many purposes, but sometimes it is useful to limit the types that can be
passed to a type parameter
Syntax :
<T extends superclass>
Example
class Stats<T extends Number> {
T[] nums;
Stats(T[] o) { nums = o;
}
double average() {
double sum = 0.0;
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 24
for(int i=0; i < nums.length; i++)
sum += nums[i].doubleValue(); return sum / nums.length;
}
}
public class MainClass {
public static void main(String args[]) {
Integer inums[] = { 1, 2, 3, 4, 5 };
Stats<Integer> iob = new Stats<Integer>(inums); double v = iob.average();
System.out.println("iob average is " + v);
Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
Stats<Double> dob = new Stats<Double>(dnums);
double w = dob.average();
System.out.println("dob average is " + w);
}
}
Restrictions on Generics
To use Java generics effectively, you must consider the following restrictions:
i) Cannot Instantiate Generic Types with Primitive Types
ii) Cannot Create Instances of Type Parameters
iii) Cannot Declare Static Fields Whose Types are Type Parameters
iv) Cannot Use Casts or instanceof With Parameterized Types
v) Cannot Create Arrays of Parameterized Types
vi) Cannot Create, Catch, or Throw Objects of Parameterized Types
vii) Cannot Overload a Method Where the Formal Parameter Types of Each
viii) Overload Erase to the Same Raw Type
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 25
STRINGS IN JAVA
A string is a sequence of characters. Java implements strings as objects of type String. String objects can be
constructed a number of ways, making it easy to obtain a string when needed. When you create a String object, you are
creating a string that cannot be changed.
That is, once a String object has been created, you cannot change the characters that comprise that string. Each
time you need an altered version of an existing string, a new String object is created that contains the modifications.
The original string is left unchanged.
Java provides two options: StringBuffer and StringBuilder. Both hold strings that can be modified after they
are created.
The String, StringBuffer, and StringBuilder classes are defined in java.lang. Thus, they are available to all
programs automatically. All are declared final, which means that none of these classes may be subclassed. All three
implement the CharSequence interface. a variable declared as a String reference can be changed to point at some other
String object at any time.
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”.
String Length
The length of a string is the number of characters that it contains. To obtain this value, call the length( )
method, shown here:
int length( )
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
Output:
3
String Literals
 The earlier examples showed how to explicitly create a String instance 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.
For example, the following code fragment creates two equivalent strings:
char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars);
String s2 = "abc"; // use string literal
System.out.println("abc".length());
It calls the length( ) method on the string “abc”. As expected, it prints “3”.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 26
String Class
 String is not a primitive data type in java. It is a class that can store sequence of characters.
 String class have a number of methods to operate on string.
 String class object can be created using 'new' keyword or values can be assigned directly to
string variable.
 In java all strings are stored in constant pool, that is managed by JVM.
Syntax :
String obj = new String("hello");
obj is a reference variable, which is pointing string "hello".
For every string variable one object of String class will be created.
java ease creation of string object by allowing following declaration.
Syntax :
String obj = "hello";
 New object is created, String hello will be stored in object and that object is referred by obj
reference variable.
 There is a difference in these two ways of creating string object.
Program :
class str
{
public static void main(String arg[]))
{
String obj1=new String("hello");
String obj2=new String("hello");
if(obj1==obj2) // "==" operator checks that both reference variables are pointing to same object or
not.
System.out.println("same object");
else
System.out.println("Different object");
}
}
//output:Different object
This scenario can be explained better with help of diagram
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 27
 'new' keyword always create new object, since both object having same values but still both
object allocated in separate memory.
 "==" operator don't check that both object having same value of not, it checks whether both
object having reference of same object or not.
Now if we will see direct string object creation without using 'new' keyword.
 It will first check is there any existing string object if it is, then instead of creating new string
object.
 It simply assign that object reference to new reference variable.
Program :
class str
{
public static void main(String arg[]))
{
String obj1="hello";
String obj2="hello";
if(obj1==obj2) // "==" operator checks that both reference variables are pointing to same object or
not.
System.out.println("same object");
else
System.out.println("Different object");
}
}
//output:same object
When obj2 is created, in memory already one object with same value was there. java simply assigned
that object reference to obj2.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 28
both reference variable are pointing to same object, that's why output of program is same object.
Immutability
 In java String objects are immutable.
 The meaning of immutable is that changes in string object are not possible in java or we can
say all strings are constant.
But in program given below we are denying this fact that we can't change a string.
Example :
class str
{
public static void main(String arg[]))
{
String obj1=new String("hello");
obj1= obj1+" world";
System.out.println(obj1);
}
}
//output:hello world
How it is possible if can't change string, then why above program is working properly.
Reason is when we try to concatenate "world" with obj1 string.
Java created new string with "hello world", but original string is not changed.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 29
After changing new string is created and for old string now there is no reference variable. So this
object is cleaned by garbage collector.
Example :
class str
{
public static void main(String arg[]))
{
String obj1="hello";
String obj2="hello";
if(obj1==obj2) // "==" operator checks that both reference variables are pointing to same object or
not.
System.out.println("same object");
else
System.out.println("Different object");
}
}
//output:same object
When obj2 is created, in memory already one object with same value was there. java simply assigned
that object reference to obj2.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 30
both reference variable are pointing to same object, that's why output of program is same object.
String Comparison
 Two string can be compared using equals() method.
 Equality operator can't be used for comparing string.
 Equality operator only compare reference variable, whether both reference variable pointing
to same object or not.
Example
class str
{
public static void main(String arg[])
{
String a=new String("hello");
String b=new String("hello");
if(a==b)
System.out.println("Same object");
else
System.out.println("Different Object");
}
}
/*Ouput:
Different Object
*/
 In above program two objects are created. Both having same value, But both objects are
different that's why "a==b" condition will return false.
 Equality operator return true only in case when both reference variable point to same object.
 In order to check content of string object equals() method is used. "equals()" method return
true if both object have same content.
Example
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 31
class str
{
public static void main(String arg[])
{
String a=new String("hello");
String b=new String("hello");
if(a.equals(b))
System.out.println("Same object");
else
System.out.println("Different Object");
}
}
/*Ouput:
Same Object
*/
equals() method is case sensitive, means "hello" and "Hello" string are different.
There is one more method equalsIgnoreCase() method which will ignore case and compare string.
Example
class str
{
public static void main(String arg[])
{
String a=new String("hello");
String b=new String("Hello");
if(a.equalsIgnoreCase(b))
System.out.println("Same object");
else
System.out.println("Different Object");
}
}
/*Ouput:
Same Object
*/
Length of String
 length() method is used to find out length of string.
 String class has one method length() called on string object.
Method Signature:
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 32
public int lenth()
Example
class len
{
public static void main(String arg[])
{
String s=new String("hello world");
String b="this is demo";
System.out.println("Length of s:"+s.length());
System.out.println("Length of b:"+b.length());
}
}
/* Output:
Length of s:11
Length of b:12
*/
Extraction of Characters
String class has mutiple ways through which characters can be extracted.
Below are explained all the method to extract character.
1. charAt() method
 charAt() method extract a single character on given index.
 Index is specified in charAt() method. if index is specified out of range or negative
then StringIndexOutOfBoundsException will be thrown.
 This exception is unchecked.
Method Signature
public char charAt(int index)
index specify the character's position which is need to be extracted.
Program :
class chex
{
public static void main(String arg[])
{
String h="hello world";
System.out.println("char at 0 index:"+h.charAt(0));
System.out.println("char at -1 index:"+h.charAt(-1));
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 33
}
}
/*Output:
char at 0 index:h
char at 4 index:o
*/
2. getChars() method
To extract multiple characters getChars() method is used.
Method Signature :
void getChars(int start, int end, char[] target, int targetstart)
 First argument in getChars() method start specify starting index in string and end specify
ending index.
 Characters from start index to end index are extracted and stored in target array. targetstart
specify from where to start saving extracted characters in target array.
Example :
class chex
{
public static void main(String arg[])
{
char [] buf=new char[5];
String h="hello world";
h.getChars(0,5,buf,0);
System.out.println("buffer array:"+buf);
}
}
/*Output:
buffer array:hello
*/
3. toCharArray() method
String class has a method toCharArray() to convert into character array.
Method Signature :
char[] toCharArray()
Example :
class chex
{
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 34
public static void main(String arg[])
{
String h="hello world";
char buf[]=h.toCharArray();
System.out.println("buffer array:"+buf);
}
}
/*Output:
buffer array:hello world
*/
4. getBytes()
 getBytes convert string into byte array.
 This approach is used in environment where 16-bit unicode characters are not supported.
Method Signature :
byte[] getBytes()
String Concatenation
The one exception to this rule is the + operator, which concatenates two strings, producing a String object as
the result. This allows you to chain together a series of + operations.
For example, the following fragment concatenates three strings:
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
This displays the string “He is 9 years old.”
String Conversion and toString( )
This method returns itself a string.
Syntax
Here is the syntax of this method −
public String toString()
Return Value
 This method returns the string itself.
 import java.io.*;
 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.toString());
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 35
 }
 }
 This will produce the following result −
 Output
 Return Value :Welcome to Tutorialspoint.com

 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)
or
public char charAt(int index)
char ch;
ch = "abc".charAt(1);
o/p:
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)
toCharArray( )
It returns an array of characters for the entire string. It has this
general form:
char[ ] toCharArray( )
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( ). It has this 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( ). When
it compares two strings, it considers A-Z to be the same as a-z. It has this general form:
boolean equalsIgnoreCase(String str)
// 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";
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +
s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 36
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
startsWith( ) and endsWith( )
String defines two routines that are, more or less, specialized forms of regionMatches( ).
The startsWith( ) method determines whether a given String begins with a specified string.
Conversely, endsWith( ) 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)
Here, str is the String being tested. If the string matches, true is returned. Otherwise, false
is returned. For example,
"Foobar".endsWith("bar")
and
"Foobar".startsWith("Foo")
are both true.
equals( ) Versus ==
It is important to understand that the equals( ) method and the == operator perform two
different operations. 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.
// equals() vs ==
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
o/p:
Hello equals Hello -> true
Hello == Hello -> false
compareTo( )
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( ) serves
this purpose. It has this general form:
int compareTo(String str)
Here, str is the String being compared with the invoking String
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 37
The program uses compareTo( )
to determine sort ordering for a bubble sort:
// A bubble sort for Strings.
class SortString {
static String arr[] = {
"Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country"
};
public static void main(String args[]) {
for(int j = 0; j < arr.length; j++) {
for(int i = j + 1; i < arr.length; i++) {
if(arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
The output of this program is the list of words:
Now
aid
all
come
country
for
good
is
men
of
the
the
their
time
to
to
Modifying a String
This method has two variants and returns a new string that is a substring of this string. The substring begins with the
character at the specified index and extends to the end of this string or up to endIndex – 1, if the second argument is
given.
Syntax
Here is the syntax of this method −
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 38
public String substring(int beginIndex)
Parameters
Here is the detail of parameters −
 beginIndex − the begin index, inclusive.
Return Value
 The specified substring.
Example
import java.io.*;
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) );
}
}
This will produce the following result −
Output
Return Value : Tutorialspoint.com
replace( )
The replace( ) method has two forms. The first replaces all occurrences of one character in
the invoking string with another character. It has the following 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 s = "Hello".replace('l', 'w');
puts the string “Hewwo” into s
This method returns a copy of the string, with leading and trailing whitespace omitted.
Syntax
Here is the syntax of this method −
public String trim()
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.
Example
Live Demo
import java.io.*;
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 39
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() );
}
}
This will produce the following result −
Output
Return Value :Welcome to Tutorialspoint.com
The method toLowerCase( ) converts all the characters in a string from uppercase to
lowercase. The toUpperCase( ) method converts all the characters in a string from lowercase
to uppercase. Nonalphabetical characters, such as digits, are unaffected. Here are the general
forms of these methods:
String toLowerCase( )
String toUpperCase( )
// Demonstrate toUpperCase() and toLowerCase().
class ChangeCase {
public static void main(String args[])
{
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}
The output produced by the program is shown here:
Original: This is a test.
Uppercase: THIS IS A TEST.
Lowercase: this is a test.
STRING BUFFER CLASS
StringBuffer class
 StringBuffer class used to make string object which are mutable.
 It means string stored in stringbuffer variable can be changed.
 String class don't allow changes in string.
 String class is immutable means it can't be changed, all can be done is creation of new object
with changed data.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 40
StringBuffer is a peer class of String that provides much of the functionality of strings.
String represents fixed-length, immutable character sequences. In contrast,
StringBuffer represents growable and writeable character sequences.
ava 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.
Constructor Description
StringBuffer() creates an empty string buffer with the initial capacity of 16.
StringBuffer(String str) creates a string buffer with the specified string.
StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length.
A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used
for creating mutable string.
Example :
class sb
{
static void main(String arg[])
{
StringBuffer st=new StringBuffer("hello");
System.out.println("st:"+st);
//after changing string
st.append(" java");
}
}
Example :
class sb
{
static void main(String arg[])
{
StringBuffer st=new StringBuffer("hello");
System.out.println("st:"+st);
//after changing string
StringBuilder st1=st.append("java");
if(st1==st)
System.out.println("same object");
else
System.out.println("different objects");
}
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 41
/* Output:
same object
*/
NOTE:
a) StringBuffer is mutable, means it can be changed.
b) StringBuffer takes memory from heap.
c) StringBuffer is thread safe, which means at a time only one method can call method of
StringBuffer class.
d) All methods are synchronized.
Because of thread safe property StringBuffer execute slower that StringBuilder.
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
6. }
7. }
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. }
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");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 42
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");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }
5) StringBuffer reverse() method
The reverse() method of StringBuilder class reverses the current string.
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
**************************

More Related Content

What's hot

Polymorphism in java, method overloading and method overriding
Polymorphism in java,  method overloading and method overridingPolymorphism in java,  method overloading and method overriding
Polymorphism in java, method overloading and method overridingJavaTportal
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python TutorialSimplilearn
 
Java Data Types
Java Data TypesJava Data Types
Java Data TypesSpotle.ai
 
Abstraction java
Abstraction javaAbstraction java
Abstraction javaMahinImran
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaMadishetty Prathibha
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionPritom Chaki
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methodsShubham Dwivedi
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Michelle Anne Meralpis
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In JavaSpotle.ai
 

What's hot (20)

Polymorphism in java, method overloading and method overriding
Polymorphism in java,  method overloading and method overridingPolymorphism in java,  method overloading and method overriding
Polymorphism in java, method overloading and method overriding
 
OOP java
OOP javaOOP java
OOP java
 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Abstraction java
Abstraction javaAbstraction java
Abstraction java
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaion
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
Python-DataAbstarction.pptx
Python-DataAbstarction.pptxPython-DataAbstarction.pptx
Python-DataAbstarction.pptx
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
c++ lab manual
c++ lab manualc++ lab manual
c++ lab manual
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
 

Similar to CS3391 -OOP -UNIT – IV NOTES FINAL.pdf

C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...yazad dumasia
 
core java material.pdf
core java material.pdfcore java material.pdf
core java material.pdfRasa72
 
asdabuydvduyawdyuadauysdasuydyudayudayudaw
asdabuydvduyawdyuadauysdasuydyudayudayudawasdabuydvduyawdyuadauysdasuydyudayudayudaw
asdabuydvduyawdyuadauysdasuydyudayudayudawWrushabhShirsat3
 
csharp_dotnet_adnanreza.pptx
csharp_dotnet_adnanreza.pptxcsharp_dotnet_adnanreza.pptx
csharp_dotnet_adnanreza.pptxPoornima E.G.
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdfamitbhachne
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz SAurabh PRajapati
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using ReflectionGanesh Samarthyam
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfacesKalai Selvi
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfacesDevaKumari Vijay
 
OOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfOOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfArthyR3
 
Java quick reference
Java quick referenceJava quick reference
Java quick referenceArthyR3
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)ssuser7f90ae
 
Input output files in java
Input output files in javaInput output files in java
Input output files in javaKavitha713564
 
iOS development introduction
iOS development introduction iOS development introduction
iOS development introduction paramisoft
 

Similar to CS3391 -OOP -UNIT – IV NOTES FINAL.pdf (20)

CS3391 -OOP -UNIT – II NOTES FINAL.pdf
CS3391 -OOP -UNIT – II  NOTES FINAL.pdfCS3391 -OOP -UNIT – II  NOTES FINAL.pdf
CS3391 -OOP -UNIT – II NOTES FINAL.pdf
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
 
core java material.pdf
core java material.pdfcore java material.pdf
core java material.pdf
 
asdabuydvduyawdyuadauysdasuydyudayudayudaw
asdabuydvduyawdyuadauysdasuydyudayudayudawasdabuydvduyawdyuadauysdasuydyudayudayudaw
asdabuydvduyawdyuadauysdasuydyudayudayudaw
 
csharp_dotnet_adnanreza.pptx
csharp_dotnet_adnanreza.pptxcsharp_dotnet_adnanreza.pptx
csharp_dotnet_adnanreza.pptx
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf
 
The smartpath information systems c plus plus
The smartpath information systems  c plus plusThe smartpath information systems  c plus plus
The smartpath information systems c plus plus
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfaces
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
 
OOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfOOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdf
 
Java quick reference
Java quick referenceJava quick reference
Java quick reference
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
CHAPTER 3 part1.pdf
CHAPTER 3 part1.pdfCHAPTER 3 part1.pdf
CHAPTER 3 part1.pdf
 
iOS development introduction
iOS development introduction iOS development introduction
iOS development introduction
 

More from AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING

More from AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING (20)

JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptxJAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
 
INTRO TO PROGRAMMING.ppt
INTRO TO PROGRAMMING.pptINTRO TO PROGRAMMING.ppt
INTRO TO PROGRAMMING.ppt
 
CS3391 OOP UT-I T4 JAVA BUZZWORDS.pptx
CS3391 OOP UT-I T4 JAVA BUZZWORDS.pptxCS3391 OOP UT-I T4 JAVA BUZZWORDS.pptx
CS3391 OOP UT-I T4 JAVA BUZZWORDS.pptx
 
CS3391 OOP UT-I T1 OVERVIEW OF OOP
CS3391 OOP UT-I T1 OVERVIEW OF OOPCS3391 OOP UT-I T1 OVERVIEW OF OOP
CS3391 OOP UT-I T1 OVERVIEW OF OOP
 
CS3391 OOP UT-I T3 FEATURES OF OBJECT ORIENTED PROGRAMMING
CS3391 OOP UT-I T3 FEATURES OF OBJECT ORIENTED PROGRAMMINGCS3391 OOP UT-I T3 FEATURES OF OBJECT ORIENTED PROGRAMMING
CS3391 OOP UT-I T3 FEATURES OF OBJECT ORIENTED PROGRAMMING
 
CS3391 OOP UT-I T2 OBJECT ORIENTED PROGRAMMING PARADIGM.pptx
CS3391 OOP UT-I T2 OBJECT ORIENTED PROGRAMMING PARADIGM.pptxCS3391 OOP UT-I T2 OBJECT ORIENTED PROGRAMMING PARADIGM.pptx
CS3391 OOP UT-I T2 OBJECT ORIENTED PROGRAMMING PARADIGM.pptx
 
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdfCS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
 
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
CS3391 -OOP -UNIT – III  NOTES FINAL.pdfCS3391 -OOP -UNIT – III  NOTES FINAL.pdf
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
 
CS3391 -OOP -UNIT – I NOTES FINAL.pdf
CS3391 -OOP -UNIT – I  NOTES FINAL.pdfCS3391 -OOP -UNIT – I  NOTES FINAL.pdf
CS3391 -OOP -UNIT – I NOTES FINAL.pdf
 
CS3251-_PIC
CS3251-_PICCS3251-_PIC
CS3251-_PIC
 
CS8080 information retrieval techniques unit iii ppt in pdf
CS8080 information retrieval techniques unit iii ppt in pdfCS8080 information retrieval techniques unit iii ppt in pdf
CS8080 information retrieval techniques unit iii ppt in pdf
 
CS8080 IRT UNIT I NOTES.pdf
CS8080 IRT UNIT I  NOTES.pdfCS8080 IRT UNIT I  NOTES.pdf
CS8080 IRT UNIT I NOTES.pdf
 
CS8080_IRT_UNIT - III T14 SEQUENTIAL SEARCHING.pdf
CS8080_IRT_UNIT - III T14 SEQUENTIAL SEARCHING.pdfCS8080_IRT_UNIT - III T14 SEQUENTIAL SEARCHING.pdf
CS8080_IRT_UNIT - III T14 SEQUENTIAL SEARCHING.pdf
 
CS8080_IRT_UNIT - III T15 MULTI-DIMENSIONAL INDEXING.pdf
CS8080_IRT_UNIT - III T15 MULTI-DIMENSIONAL INDEXING.pdfCS8080_IRT_UNIT - III T15 MULTI-DIMENSIONAL INDEXING.pdf
CS8080_IRT_UNIT - III T15 MULTI-DIMENSIONAL INDEXING.pdf
 
CS8080_IRT_UNIT - III T13 INVERTED INDEXES.pdf
CS8080_IRT_UNIT - III T13 INVERTED  INDEXES.pdfCS8080_IRT_UNIT - III T13 INVERTED  INDEXES.pdf
CS8080_IRT_UNIT - III T13 INVERTED INDEXES.pdf
 
CS8080 IRT UNIT - III SLIDES IN PDF.pdf
CS8080  IRT UNIT - III  SLIDES IN PDF.pdfCS8080  IRT UNIT - III  SLIDES IN PDF.pdf
CS8080 IRT UNIT - III SLIDES IN PDF.pdf
 
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdfCS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
 
CS8080_IRT_UNIT - III T12 INDEXING AND SEARCHING.pdf
CS8080_IRT_UNIT - III T12 INDEXING AND SEARCHING.pdfCS8080_IRT_UNIT - III T12 INDEXING AND SEARCHING.pdf
CS8080_IRT_UNIT - III T12 INDEXING AND SEARCHING.pdf
 
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdfCS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
 
CS8080_IRT_UNIT - III T10 ACCURACY AND ERROR.pdf
CS8080_IRT_UNIT - III T10  ACCURACY AND ERROR.pdfCS8080_IRT_UNIT - III T10  ACCURACY AND ERROR.pdf
CS8080_IRT_UNIT - III T10 ACCURACY AND ERROR.pdf
 

Recently uploaded

Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 

Recently uploaded (20)

Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 

CS3391 -OOP -UNIT – IV NOTES FINAL.pdf

  • 1. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 1 DEPARTMENT OF INFORMATION TECHNOLOGY R2017 - SEMESTER III CS3391 – OBJECT ORIENTED PROGRAMMING UNIT IV - UNIT IV I/O, GENERICS, STRING HANDLING CLASS NOTES Complimented with PERSONALIZED LEARNING MATERIAL (PLM) With PERSONALIZED ASSESSMENT TESTS (PATs) PERSONALIZED LEARNING MATERIAL (PLM)
  • 2. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 2 An Introduction to PLM The PERSONALIZED LEARNING MATERIAL (PLM) is special Type of Learning Material designed and developed by Er. K.Khaja Mohideen , Assistant Professor , Aalim Muhammed Salegh College of Engineering, Avadi-IAF, Chennai – 600 055, India. This material called PLM is an innovative Learning Type based Artificial Intelligence based Suggestive learning Strategy (SLS) that recommends the selective Topics to Learners of different Learning mind sets groups. We identified three major such Learner Groups from Subject Learning Student Communities and are as follows: 1) Smart Learning Groups 2) Effective Learning Groups 3) Slow Learning Groups The three Coloring depicts the following levels of Experiencing Learners groups: 1) Smart Learning Groups – Greenish Shadow 2) Effective Learning Groups – Orange Shadow 3) Slow Learning Groups – Red Shadow The following picture illustrates the same: Note: The decision on PLM Topic grouping type is based on the Designer’s Academic Experience and his Academic Excellence on the selective Course Domain. MOST IMPORTANT IMPORTANT NOT IMPORTANT
  • 3. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 3 PERSONALIZED ASSESSMENT TESTS (PATs) An Introduction to PAT
  • 4. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 4 INDEX UNIT IV I/O, GENERICS, STRING HANDLING SL NO TOPIC UNIT – IV : Syllabus with PL 1 I/O BASICS 2 READING AND WRITING FILES 3 CONSOLE I/O PROGRAMMING 4 GENERICS: GENERIC PROGRAMMING 5 GENERIC CLASSES 6 GENERIC METHODS 7 BOUNDED TYPES 8 RESTRICTIONS AND LIMITATIONS 9 STRINGS: BASIC STRING CLASS 10 METHODS 11 STRING BUFFER CLASS .–––.
  • 5. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 5 UNIT – IV: Syllabus with PL SYLLABUS: UNIT IV I/O, GENERICS, STRING HANDLING 9 I/O Basics – Reading and Writing Console I/O – Reading and Writing Files. Generics: Generic Programming – Generic classes – Generic Methods – Bounded Types – Restrictions and Limitations. Strings: Basic String class, methods and String Buffer Class. TOTAL TOPICS: 11 NOTE:  Important Topic  Less Important   Not Important
  • 6. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 6 BASICS OF I/O // Java program to demonstrate // ArithmeticException class ArithmeticException_Demo { public static void main(String args[]) { try { int a = 30, b = 0; int c = a / b; // cannot divide by zero System.out.println("Result = " + c); } catch (ArithmeticException e) { System.out.println("Can't divide a number by 0"); } } } Output: Can't divide a number by 0 2. ArrayIndexOutOfBounds Exception : It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array. // Java program to demonstrate // ArrayIndexOutOfBoundException class ArrayIndexOutOfBound_Demo { public static void main(String args[]) { try { int a[] = new int[5]; a[6] = 9; // accessing 7th element in an array of // size 5 } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array Index is Out Of Bounds"); } } } Output: Array Index is Out Of Bounds ClassNotFoundException : This Exception is raised when we try to access a class whose definition is NOT FOUND 1. FileNotFoundException : This Exception is raised when a file is not accessible or does not open. // Java program to demonstrate // FileNotFoundException import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; class File_notFound_Demo { public static void main(String args[])
  • 7. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 7 { try { // Following file does not exist File file = new File("E:// file.txt"); FileReader fr = new FileReader(file); } catch (FileNotFoundException e) { System.out.println("File does not exist"); } } } Output: File does not exist IOException : It is thrown when an input-output operation failed or interrupted // Java program to illustrate IOException import java.io.*; class Geeks { public static void main(String args[]) { FileInputStream f = null; f = new FileInputStream("abc.txt"); int i; while ((i = f.read()) != -1) { System.out.print((char)i); } f.close(); } } Output: error: unreported exception IOException; must be caught or declared to be thrown 2. InterruptedException : It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted. // Java Program to illustrate // InterruptedException class Geeks { public static void main(String args[]) { Thread t = new Thread(); t.sleep(10000); } } Output: error: unreported exception InterruptedException; must be caught or declared to be thrown NoSuchMethodException : t is thrown when accessing a method which is not found. // Java Program to illustrate // NoSuchMethodException class Geeks { public Geeks()
  • 8. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 8 { Class i; try { i = Class.forName("java.lang.String"); try { Class[] p = new Class[5]; } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static void main(String[] args) { new Geeks(); } } Output: error: exception NoSuchMethodException is never thrown in body of corresponding try statement 3. NullPointerException : This exception is raised when referring to the members of a null object. Null represents nothing // Java program to demonstrate NullPointerException class NullPointer_Demo { public static void main(String args[]) { try { String a = null; // null value System.out.println(a.charAt(0)); } catch (NullPointerException e) { System.out.println("NullPointerException.."); } } } Output: NullPointerException.. 4. NumberFormatException : This exception is raised when a method could not convert a string into a numeric format. // Java program to demonstrate // NumberFormatException class NumberFormat_Demo { public static void main(String args[]) {
  • 9. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 9 try { // "akki" is not a number int num = Integer.parseInt("akki"); System.out.println(num); } catch (NumberFormatException e) { System.out.println("Number format exception"); } } } Output: Number format exception 5. StringIndexOutOfBoundsException : It is thrown by String class methods to indicate that an index is either negative than the size of the string. // Java program to demonstrate // StringIndexOutOfBoundsException class StringIndexOutOfBound_Demo { public static void main(String args[]) { try { String a = "This is like chipping "; // length is 22 char c = a.charAt(24); // accessing 25th element System.out.println(c); } catch (StringIndexOutOfBoundsException e) { System.out.println("StringIndexOutOfBoundsException"); } } } Output: StringIndexOutOfBoundsException Java.lang.StackTraceElement class in Java An element in a stack trace, as returned by Throwable.getStackTrace(). Each element represents a single stack frame. All stack frames except for the one at the top of the stack represent a method invocation. The frame at the top of the stack represents the execution point at which the stack trace was generated. This class describes single stack frame, which is an individual element of a stack trace when an exception occur.  All stack frames except for the one at the top of the stack represent a method invocation.  The frame at the top of the stack represent the execution point of which the stack trace was generated.  Each stack frame represents an execution point, which includes such things as the name of the method, the name of file and the source code line number.  An array of StackTraceElement is returned by getStackTrace() method of the Throwable class. Constructor: Creates a stack trace element representing the specified execution point. StackTraceElement(String declaringClass, String methodName, String fileName, int lineNumber) Parameters:  declaringClass – the fully qualified name of the class containing the execution point represented by the stack trace element.  methodName – the name of the method containing the execution point represented by the stack trace element.  fileName – the name of the file containing the execution point represented by the stack trace element, or null if this information is unavailable
  • 10. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 10  lineNumber – the line number of the source line containing the execution point represented by this stack trace element, or a negative number if this information is unavailable. A value of -2 indicates that the method containing the execution point is a native method. Throws: NullPointerException – if declaringClass or methodName is null. Methods: boolean equals(ob): Returns try if the invoking StackTraceElementis as the one passed in ob. Otherwise it returns false. 1. Syntax: public boolean equals(ob) 2. Returns: true if the specified object is 3. another StackTraceElement instance representing the same execution 4. point as this instance. 5. Exception: NA // Java code illustrating equals() method import java.lang.*; import java.io.*; import java.util.*; public class StackTraceElementDemo { public static void main(String[] arg) { StackTraceElement st1 = new StackTraceElement("foo", "fuction1", "StackTrace.java", 1); StackTraceElement st2 = new StackTraceElement("bar", "function2", "StackTrace.java", 1); Object ob = st1.getFileName(); // checking whether file names are same or not System.out.println(st2.getFileName().equals(ob)); } } Output: true String getClassName(): Returns the class name of the execution point described by the invoking StackTraceElement. Syntax: public String getClassName(). Returns: the fully qualified name of the Class containing the execution point represented by this stack trace element. Exception: NA. // Java code illustrating getClassName() method. import java.lang.*; import java.io.*; import java.util.*; public class StackTraceElementDemo { public static void main(String[] arg) { System.out.println("Class name of each thread involved:"); for(int i = 0; i<2; i++) { System.out.println(Thread.currentThread().getStackTrace()[I]. getClassName());
  • 11. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 11 } } } Output: Class name of each thread involved: java.lang.Thread StackTraceElementDemo String getFileName(): Returns the file name of the execution point described by the invoking StackTraceElement. Syntax: public String getFileName(). Returns: the name of the file containing the execution point represented by this stack trace element, or null if this information is unavailable. Exception: NA. // Java code illustrating getFileName() method. import java.lang.*; import java.io.*; import java.util.*; public class StackTraceElementDemo { public static void main(String[] arg) { System.out.println("file name: "); for(int i = 0; i<2; i++) System.out.println(Thread.currentThread().getStackTrace()[i]. getFileName()); } } Output: file name: Thread.java StackTraceElementDemo.java int getLineNumber(): Returns the source-code line number of the execution point described by the invoking StackTraceElement. In some situation the line number will not be available, in which case a negative value is returned. Syntax: public int getLineNumber(). Returns: the line number of the source line containing the execution point represented by this stack trace element, or a negative number if this information is unavailable. Exception: NA. // Java code illustrating getLineNumber() method. import java.lang.*; import java.io.*; import java.util.*; public class StackTraceElementDemo { public static void main(String[] arg) { System.out.println("line number: "); for(int i = 0; i<2; i++)
  • 12. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 12 System.out.println(Thread.currentThread().getStackTrace()[i]. getLineNumber()); } } Output: line number: 1556 10 String getMethodName(): Returns the method name of the execution point described by the invoking StackTraceElement. Syntax: public String getMethodName(). Returns: the name of the method containing the execution point represented by this stack trace element. Exception: NA. Output: method name: getStackTrace main IO Stream Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to make input and output operation in java. In general, a stream means continuous flow of data. Streams are clean way to deal with input/output without having every part of your code understand the physical. Java encapsulates Stream under java.io package. Java defines two types of streams. They are, 1. Byte Stream : It provides a convenient means for handling input and output of byte. 2. Character Stream : It provides a convenient means for handling input and output of characters. Character stream uses Unicode and therefore can be internationalized. Byte Stream Classes Byte stream is defined by using two abstract class at the top of hierarchy, they are InputStream and OutputStream. These two abstract classes have several concrete classes that handle various devices such as disk files, network connection etc. Some important Byte stream classes. Stream class Description BufferedInputStream Used for Buffered Input Stream. BufferedOutputStream Used for Buffered Output Stream.
  • 13. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 13 DataInputStream Contains method for reading java standard datatype DataOutputStream An output stream that contain method for writing java standard data type FileInputStream Input stream that reads from a file FileOutputStream Output stream that write to a file. InputStream Abstract class that describe stream input. OutputStream Abstract class that describe stream output. PrintStream Output Stream that contain print() and println() method These classes define several key methods. Two most important are 1. read() : reads byte of data. 2. write() : Writes byte of data. Character Stream Classes Character stream is also defined by using two abstract class at the top of hierarchy, they are Reader and Writer. These two abstract classes have several concrete classes that handle unicode character. Some important Charcter stream classes. Stream class Description BufferedReader Handles buffered input stream. BufferedWriter Handles buffered output stream. FileReader Input stream that reads from file. FileWriter Output stream that writes to file. InputStreamReader Input stream that translate byte to character OutputStreamReader Output stream that translate character to byte. PrintWriter Output Stream that contain print() and println() method. Reader Abstract class that define character stream input Writer Abstract class that define character stream output Reading Console Input
  • 14. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 14 We use the object of BufferedReader class to take inputs from the keyboard. Reading Characters read() method is used with BufferedReader object to read characters. As this function returns integer type value has we need to use typecasting to convert it into char type. int read() throws IOException Below is a simple example explaining character input. class CharRead { public static void main( String args[]) { BufferedReader br = new Bufferedreader(new InputstreamReader(System.in)); char c = (char)br.read(); //Reading character } } Reading Strings To read string we have to use readLine() function with BufferedReader class's object. String readLine() throws IOException Program to take String input from Keyboard in Java import java.io.*; class MyInput { public static void main(String[] args) { String text; InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); text = br.readLine(); //Reading String System.out.println(text); } }
  • 15. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 15 Program to read from a file using BufferedReader class import java. Io *; class ReadTest { public static void main(String[] args) { try { File fl = new File("d:/myfile.txt"); BufferedReader br = new BufferedReader(new FileReader(fl)) ; String str; while ((str=br.readLine())!=null) { System.out.println(str); } br.close(); fl.close(); } catch (IOException e) { e.printStackTrace(); } } } Program to write to a File using FileWriter class import java. Io *; class WriteTest { public static void main(String[] args) { try { File fl = new File("d:/myfile.txt"); String str="Write this string to my file"; FileWriter fw = new FileWriter(fl) ; fw.write(str); fw.close(); fl.close(); } catch (IOException e) { e.printStackTrace(); } } }
  • 16. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 16 GENERIC PROGRAMMING Introduction to Generic Programming  Generics mean parameterized types.  The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces.  Using Generics, it is possible to create classes that work with different data types.  A generic type is a generic class or interface that is parameterized over types. Generics in Java  The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.  It makes the code stable by detecting the bugs at compile time.  Before generics, we can store any type of objects in the collection, i.e., non-generic.  Now generics force the java programmer to store a specific type of objects. What is Generic Programming?  Generic programming enables the programmer to create classes, interfaces and methods that automatically works with all types of data(Integer, String, Float etc).  It has expanded the ability to reuse the code safely and easily.
  • 17. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 17 Syntax to use generic collection Class Or Interface<Type> Example to use Generics in java ArrayList<String> A Generic Class A generic class is defined with the following format: class name<T1, T2, ..., Tn> { /* ... */ }  The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the type parameters (also called type variables) T1, T2, ..., and Tn. public class Box<T> { // T stands for "Type" private T t; public void set(T t) { this.t = t; } public T get() { return t; } }
  • 18. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 18 Invoking and Instantiating a Generic Type  To reference the generic Box class from within your code, you must perform a generic type invocation, which replaces T with some concrete value, such as Integer: Box<Integer> integerBox;  You can think of a generic type invocation as being similar to an ordinary method invocation,  but instead of passing an argument to a method, you are passing a type argument — Integer in this case — to the Box class itself. Parameterized type An invocation of a generic type is generally known as a parameterized type.  To instantiate this class, use the new keyword, as usual, but place <Integer> between the class name and the parenthesis: Box<Integer> integerBox = new Box<Integer>(); Why Use Generics?  In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods.  Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.  The difference is that the inputs to formal parameters are values, while the inputs to
  • 19. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 19 type parameters are types. Code that uses generics has many benefits over non-generic code:  Stronger type checks at compile time. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.  Elimination of casts. The following code snippet without generics requires casting:  List list = new ArrayList();  list.add("hello");  String s = (String) list.get(0);  When re-written to use generics, the code does not require casting: List<String> list = new ArrayList<String>(); list.add("hello"); String s = list.get(0); // no cast  Enabling programmers to implement generic algorithms. By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read Advantage of Java Generics  There are mainly 3 advantages of generics.  They are as follows: i) Type-safety :  We can hold only a single type of objects in generics.  It doesn’t allow storing other objects.  Without Generics, we can store any type of objects. Example:
  • 20. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 20 List list = new ArrayList(); list.add(10); list.add("10"); With Generics, it is required to specify the type of object we need to store. List<Integer> list = new ArrayList<Integer>(); list.add(10); list.add("10");// compile-time error ii) Type casting is not required:  There is no need to typecast the object.  Before Generics, we need to type cast. List list = new ArrayList(); list.add("hello"); String s = (String) list.get(0);//typecasting After Generics, we don't need to typecast the object. List<String> list = new ArrayList<String>(); list.add("hello"); String s = list.get(0); iii)Compile-Time Checking:  It is checked at compile time so problem will not occur at runtime.  The good programming strategy says it is far better to handle the problem at compile time than runtime. List<String> list = new ArrayList<String>(); list.add("hello"); list.add(32);//Compile Time Error Generic class  A class that can refer to any type is known as generic class.
  • 21. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 21  Generic class declaration defines set of parameterized type one for each possible invocation of the type parameters.  Here, we are using the T type parameter to create the generic class of specific type. Different types of generics in Java The most commonly used type parameter names are: i) E - Element (used extensively by the Java Collections Framework) ii) K - Key. iii)N - Number. iv)T - Type. v) V - Value. vi)S,U,V etc. - 2nd, 3rd, 4th types. Example: class TwoGen<T, V> { T ob1; V ob2; TwoGen(T o1, V o2) { ob1 = o1; ob2 = o2; } void showTypes() { System.out.println("Type of T is " + ob1.getClass().getName()); System .out.println("Type of V is " + ob2.getClass().getName()); }
  • 22. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 22 T getob1() { return ob1; } V getob2() { return ob2; } } public class MainClass { public static void main(String args[]) { TwoGen<Integer, String> tgObj = new TwoGen<Integer, String>(88,"Generics"); tgObj.showTypes(); int v = tgObj.getob1(); System.out.println("value: " + v); String str = tgObj.getob2(); System.out.println("value: " + str); } } Generic Method Like generic class, we can create generic method that can accept any type of argument. public class TestGenerics4{ public static < E > void printArray(E[] elements) { for ( E element : elements){
  • 23. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 23 System.out.println(element ); } System.out.println(); } public static void main( String args[] ) { Integer[] intArray = { 10, 20, 30, 40, 50 }; Character[] charArray = { 'J', 'A', 'V', 'A'}; System.out.println( "Printing Integer Array" ); printArray( intArray ); System.out.println( "Printing Character Array" ); printArray( charArray ); } } Bounded type  The type parameters could be replaced by any class type.  This is fine for many purposes, but sometimes it is useful to limit the types that can be passed to a type parameter Syntax : <T extends superclass> Example class Stats<T extends Number> { T[] nums; Stats(T[] o) { nums = o; } double average() { double sum = 0.0;
  • 24. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 24 for(int i=0; i < nums.length; i++) sum += nums[i].doubleValue(); return sum / nums.length; } } public class MainClass { public static void main(String args[]) { Integer inums[] = { 1, 2, 3, 4, 5 }; Stats<Integer> iob = new Stats<Integer>(inums); double v = iob.average(); System.out.println("iob average is " + v); Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 }; Stats<Double> dob = new Stats<Double>(dnums); double w = dob.average(); System.out.println("dob average is " + w); } } Restrictions on Generics To use Java generics effectively, you must consider the following restrictions: i) Cannot Instantiate Generic Types with Primitive Types ii) Cannot Create Instances of Type Parameters iii) Cannot Declare Static Fields Whose Types are Type Parameters iv) Cannot Use Casts or instanceof With Parameterized Types v) Cannot Create Arrays of Parameterized Types vi) Cannot Create, Catch, or Throw Objects of Parameterized Types vii) Cannot Overload a Method Where the Formal Parameter Types of Each viii) Overload Erase to the Same Raw Type
  • 25. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 25 STRINGS IN JAVA A string is a sequence of characters. Java implements strings as objects of type String. String objects can be constructed a number of ways, making it easy to obtain a string when needed. When you create a String object, you are creating a string that cannot be changed. That is, once a String object has been created, you cannot change the characters that comprise that string. Each time you need an altered version of an existing string, a new String object is created that contains the modifications. The original string is left unchanged. Java provides two options: StringBuffer and StringBuilder. Both hold strings that can be modified after they are created. The String, StringBuffer, and StringBuilder classes are defined in java.lang. Thus, they are available to all programs automatically. All are declared final, which means that none of these classes may be subclassed. All three implement the CharSequence interface. a variable declared as a String reference can be changed to point at some other String object at any time. 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”. String Length The length of a string is the number of characters that it contains. To obtain this value, call the length( ) method, shown here: int length( ) char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); System.out.println(s.length()); Output: 3 String Literals  The earlier examples showed how to explicitly create a String instance 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. For example, the following code fragment creates two equivalent strings: char chars[] = { 'a', 'b', 'c' }; String s1 = new String(chars); String s2 = "abc"; // use string literal System.out.println("abc".length()); It calls the length( ) method on the string “abc”. As expected, it prints “3”.
  • 26. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 26 String Class  String is not a primitive data type in java. It is a class that can store sequence of characters.  String class have a number of methods to operate on string.  String class object can be created using 'new' keyword or values can be assigned directly to string variable.  In java all strings are stored in constant pool, that is managed by JVM. Syntax : String obj = new String("hello"); obj is a reference variable, which is pointing string "hello". For every string variable one object of String class will be created. java ease creation of string object by allowing following declaration. Syntax : String obj = "hello";  New object is created, String hello will be stored in object and that object is referred by obj reference variable.  There is a difference in these two ways of creating string object. Program : class str { public static void main(String arg[])) { String obj1=new String("hello"); String obj2=new String("hello"); if(obj1==obj2) // "==" operator checks that both reference variables are pointing to same object or not. System.out.println("same object"); else System.out.println("Different object"); } } //output:Different object This scenario can be explained better with help of diagram
  • 27. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 27  'new' keyword always create new object, since both object having same values but still both object allocated in separate memory.  "==" operator don't check that both object having same value of not, it checks whether both object having reference of same object or not. Now if we will see direct string object creation without using 'new' keyword.  It will first check is there any existing string object if it is, then instead of creating new string object.  It simply assign that object reference to new reference variable. Program : class str { public static void main(String arg[])) { String obj1="hello"; String obj2="hello"; if(obj1==obj2) // "==" operator checks that both reference variables are pointing to same object or not. System.out.println("same object"); else System.out.println("Different object"); } } //output:same object When obj2 is created, in memory already one object with same value was there. java simply assigned that object reference to obj2.
  • 28. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 28 both reference variable are pointing to same object, that's why output of program is same object. Immutability  In java String objects are immutable.  The meaning of immutable is that changes in string object are not possible in java or we can say all strings are constant. But in program given below we are denying this fact that we can't change a string. Example : class str { public static void main(String arg[])) { String obj1=new String("hello"); obj1= obj1+" world"; System.out.println(obj1); } } //output:hello world How it is possible if can't change string, then why above program is working properly. Reason is when we try to concatenate "world" with obj1 string. Java created new string with "hello world", but original string is not changed.
  • 29. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 29 After changing new string is created and for old string now there is no reference variable. So this object is cleaned by garbage collector. Example : class str { public static void main(String arg[])) { String obj1="hello"; String obj2="hello"; if(obj1==obj2) // "==" operator checks that both reference variables are pointing to same object or not. System.out.println("same object"); else System.out.println("Different object"); } } //output:same object When obj2 is created, in memory already one object with same value was there. java simply assigned that object reference to obj2.
  • 30. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 30 both reference variable are pointing to same object, that's why output of program is same object. String Comparison  Two string can be compared using equals() method.  Equality operator can't be used for comparing string.  Equality operator only compare reference variable, whether both reference variable pointing to same object or not. Example class str { public static void main(String arg[]) { String a=new String("hello"); String b=new String("hello"); if(a==b) System.out.println("Same object"); else System.out.println("Different Object"); } } /*Ouput: Different Object */  In above program two objects are created. Both having same value, But both objects are different that's why "a==b" condition will return false.  Equality operator return true only in case when both reference variable point to same object.  In order to check content of string object equals() method is used. "equals()" method return true if both object have same content. Example
  • 31. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 31 class str { public static void main(String arg[]) { String a=new String("hello"); String b=new String("hello"); if(a.equals(b)) System.out.println("Same object"); else System.out.println("Different Object"); } } /*Ouput: Same Object */ equals() method is case sensitive, means "hello" and "Hello" string are different. There is one more method equalsIgnoreCase() method which will ignore case and compare string. Example class str { public static void main(String arg[]) { String a=new String("hello"); String b=new String("Hello"); if(a.equalsIgnoreCase(b)) System.out.println("Same object"); else System.out.println("Different Object"); } } /*Ouput: Same Object */ Length of String  length() method is used to find out length of string.  String class has one method length() called on string object. Method Signature:
  • 32. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 32 public int lenth() Example class len { public static void main(String arg[]) { String s=new String("hello world"); String b="this is demo"; System.out.println("Length of s:"+s.length()); System.out.println("Length of b:"+b.length()); } } /* Output: Length of s:11 Length of b:12 */ Extraction of Characters String class has mutiple ways through which characters can be extracted. Below are explained all the method to extract character. 1. charAt() method  charAt() method extract a single character on given index.  Index is specified in charAt() method. if index is specified out of range or negative then StringIndexOutOfBoundsException will be thrown.  This exception is unchecked. Method Signature public char charAt(int index) index specify the character's position which is need to be extracted. Program : class chex { public static void main(String arg[]) { String h="hello world"; System.out.println("char at 0 index:"+h.charAt(0)); System.out.println("char at -1 index:"+h.charAt(-1));
  • 33. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 33 } } /*Output: char at 0 index:h char at 4 index:o */ 2. getChars() method To extract multiple characters getChars() method is used. Method Signature : void getChars(int start, int end, char[] target, int targetstart)  First argument in getChars() method start specify starting index in string and end specify ending index.  Characters from start index to end index are extracted and stored in target array. targetstart specify from where to start saving extracted characters in target array. Example : class chex { public static void main(String arg[]) { char [] buf=new char[5]; String h="hello world"; h.getChars(0,5,buf,0); System.out.println("buffer array:"+buf); } } /*Output: buffer array:hello */ 3. toCharArray() method String class has a method toCharArray() to convert into character array. Method Signature : char[] toCharArray() Example : class chex {
  • 34. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 34 public static void main(String arg[]) { String h="hello world"; char buf[]=h.toCharArray(); System.out.println("buffer array:"+buf); } } /*Output: buffer array:hello world */ 4. getBytes()  getBytes convert string into byte array.  This approach is used in environment where 16-bit unicode characters are not supported. Method Signature : byte[] getBytes() String Concatenation The one exception to this rule is the + operator, which concatenates two strings, producing a String object as the result. This allows you to chain together a series of + operations. For example, the following fragment concatenates three strings: String age = "9"; String s = "He is " + age + " years old."; System.out.println(s); This displays the string “He is 9 years old.” String Conversion and toString( ) This method returns itself a string. Syntax Here is the syntax of this method − public String toString() Return Value  This method returns the string itself.  import java.io.*;  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.toString());
  • 35. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 35  }  }  This will produce the following result −  Output  Return Value :Welcome to Tutorialspoint.com   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) or public char charAt(int index) char ch; ch = "abc".charAt(1); o/p: 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) toCharArray( ) It returns an array of characters for the entire string. It has this general form: char[ ] toCharArray( ) 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( ). It has this 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( ). When it compares two strings, it considers A-Z to be the same as a-z. It has this general form: boolean equalsIgnoreCase(String str) // 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"; System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2)); System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3)); System.out.println(s1 + " equals " + s4 + " -> " +
  • 36. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 36 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 startsWith( ) and endsWith( ) String defines two routines that are, more or less, specialized forms of regionMatches( ). The startsWith( ) method determines whether a given String begins with a specified string. Conversely, endsWith( ) 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) Here, str is the String being tested. If the string matches, true is returned. Otherwise, false is returned. For example, "Foobar".endsWith("bar") and "Foobar".startsWith("Foo") are both true. equals( ) Versus == It is important to understand that the equals( ) method and the == operator perform two different operations. 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. // equals() vs == class EqualsNotEqualTo { public static void main(String args[]) { String s1 = "Hello"; String s2 = new String(s1); System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2)); System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2)); } } o/p: Hello equals Hello -> true Hello == Hello -> false compareTo( ) 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( ) serves this purpose. It has this general form: int compareTo(String str) Here, str is the String being compared with the invoking String
  • 37. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 37 The program uses compareTo( ) to determine sort ordering for a bubble sort: // A bubble sort for Strings. class SortString { static String arr[] = { "Now", "is", "the", "time", "for", "all", "good", "men", "to", "come", "to", "the", "aid", "of", "their", "country" }; public static void main(String args[]) { for(int j = 0; j < arr.length; j++) { for(int i = j + 1; i < arr.length; i++) { if(arr[i].compareTo(arr[j]) < 0) { String t = arr[j]; arr[j] = arr[i]; arr[i] = t; } } System.out.println(arr[j]); } } } The output of this program is the list of words: Now aid all come country for good is men of the the their time to to Modifying a String This method has two variants and returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string or up to endIndex – 1, if the second argument is given. Syntax Here is the syntax of this method −
  • 38. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 38 public String substring(int beginIndex) Parameters Here is the detail of parameters −  beginIndex − the begin index, inclusive. Return Value  The specified substring. Example import java.io.*; 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) ); } } This will produce the following result − Output Return Value : Tutorialspoint.com replace( ) The replace( ) method has two forms. The first replaces all occurrences of one character in the invoking string with another character. It has the following 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 s = "Hello".replace('l', 'w'); puts the string “Hewwo” into s This method returns a copy of the string, with leading and trailing whitespace omitted. Syntax Here is the syntax of this method − public String trim() 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. Example Live Demo import java.io.*;
  • 39. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 39 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() ); } } This will produce the following result − Output Return Value :Welcome to Tutorialspoint.com The method toLowerCase( ) converts all the characters in a string from uppercase to lowercase. The toUpperCase( ) method converts all the characters in a string from lowercase to uppercase. Nonalphabetical characters, such as digits, are unaffected. Here are the general forms of these methods: String toLowerCase( ) String toUpperCase( ) // Demonstrate toUpperCase() and toLowerCase(). class ChangeCase { public static void main(String args[]) { String s = "This is a test."; System.out.println("Original: " + s); String upper = s.toUpperCase(); String lower = s.toLowerCase(); System.out.println("Uppercase: " + upper); System.out.println("Lowercase: " + lower); } } The output produced by the program is shown here: Original: This is a test. Uppercase: THIS IS A TEST. Lowercase: this is a test. STRING BUFFER CLASS StringBuffer class  StringBuffer class used to make string object which are mutable.  It means string stored in stringbuffer variable can be changed.  String class don't allow changes in string.  String class is immutable means it can't be changed, all can be done is creation of new object with changed data.
  • 40. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 40 StringBuffer is a peer class of String that provides much of the functionality of strings. String represents fixed-length, immutable character sequences. In contrast, StringBuffer represents growable and writeable character sequences. ava 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. Constructor Description StringBuffer() creates an empty string buffer with the initial capacity of 16. StringBuffer(String str) creates a string buffer with the specified string. StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length. A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for creating mutable string. Example : class sb { static void main(String arg[]) { StringBuffer st=new StringBuffer("hello"); System.out.println("st:"+st); //after changing string st.append(" java"); } } Example : class sb { static void main(String arg[]) { StringBuffer st=new StringBuffer("hello"); System.out.println("st:"+st); //after changing string StringBuilder st1=st.append("java"); if(st1==st) System.out.println("same object"); else System.out.println("different objects"); } }
  • 41. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 41 /* Output: same object */ NOTE: a) StringBuffer is mutable, means it can be changed. b) StringBuffer takes memory from heap. c) StringBuffer is thread safe, which means at a time only one method can call method of StringBuffer class. d) All methods are synchronized. Because of thread safe property StringBuffer execute slower that StringBuilder. 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 6. } 7. } 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. } 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"); 4. sb.replace(1,3,"Java"); 5. System.out.println(sb);//prints HJavalo 6. } 7. }
  • 42. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 42 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"); 4. sb.delete(1,3); 5. System.out.println(sb);//prints Hlo 6. } 7. } 5) StringBuffer reverse() method The reverse() method of StringBuilder class reverses the current string. class StringBufferExample5{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello"); sb.reverse(); System.out.println(sb);//prints olleH } } **************************