SlideShare a Scribd company logo
1 of 184
Lecture By,
Prabu.U
Assistant Professor,
Department of Computer Science and Engineering.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING,
V R Siddhartha Engineering College.
20ES3102 – JAVA PROGRAMMING
UNIT 2
UNIT II:
String Handling: The String Constructors, String Buffer Class, String
Tokenizer class.
Inheritance: Inheritance basics, using super, multilevel hierarchy,
method overriding, dynamic method dispatch, using abstract classes,
final with inheritance.
Packages & Interfaces: Defining a package, finding package and
CLASSPATH. Access protection, importing packages, defining an
interface, implementing interfaces, nested interfaces, applying interfaces,
variables in interfaces.
20ES3102 – JAVA PROGRAMMING
1. The String Constructors
2. String Buffer Class
3. String Tokenizer class
STRING HANDLING
1. Inheritance Basics
2. Using super
3. Creating a Multilevel Hierarchy
4. Method Overriding
5. Dynamic Method Dispatch
6. Using Abstract Classes
7. Using final with Inheritance
INHERITANCE
PACKAGES:
1. Packages
2. Access Protection
3. Importing Packages
PACKAGES AND INTERFACES
INTERFACES:
4. Defining an Interface
5. Implementing Interfaces
6. Nested Interfaces
7. Applying Interfaces
8. Variables in Interfaces
PACKAGES AND INTERFACES
1. The String Constructors
2. String Buffer Class
3. String Tokenizer class
STRING HANDLING
String Handling
 In Java a string is a sequence of characters. But, unlike some other
languages that implement strings as character arrays, Java
implements strings as objects of type String.
 Implementing strings as built-in objects allows Java to provide a
full complement of features that make string handling convenient.
 For example, Java has methods to compare two strings, search for a
substring, concatenate two strings, and change the case of letters
within a string.
 Also, String objects can be constructed a number of ways, making it
easy to obtain a string when needed.
 Somewhat unexpectedly, 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. At first, this may seem to be a
serious restriction.
 However, such is not the case. You can still perform all types of
string operations.
 The difference is that 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. This approach is used because
fixed, immutable strings can be implemented more efficiently than
changeable ones.
 For those cases in which a modifiable string is desired, 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.
 This allows certain optimizations that increase performance to take
place on common string operations. All three implement the
CharSequence interface.
 One last point: To say that the strings within objects of type String
are unchangeable means that the contents of the String instance
cannot be changed after it has been created.
 However, a variable declared as a String reference can be changed to
point at some other String object at any time.
1. The String Constructors
 The String class supports several constructors. To create an empty
String, call the default constructor. For example,
String s = new String();
will create an instance of String with no characters in it.
 Frequently, you will want to create strings that have initial values.
 The String class provides a variety of constructors to handle this. 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".
 You can specify a subrange of a character array as an initializer
using the following constructor:
String(char chars[ ], int startIndex, int numChars)
 Here, startIndex specifies the index at which the subrange begins,
and numChars specifies the number of characters to use.
 Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
 This initializes s with the characters “cde”.
 You can construct a String object that contains the same character
sequence as another String object using this constructor:
String(String strObj)
 Here, strObj is a String object
class MakeString
{
public static void main(String args[])
{
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
Java
Java
 Even though Java’s char type uses 16 bits to represent the basic Unicode
character set, the typical format for strings on the Internet uses arrays of
8-bit bytes constructed from the ASCII character set.
 Because 8-bit ASCII strings are common, the String class provides
constructors that initialize a string when given a byte array.
 Two forms are shown here:
String(byte chrs[ ])
String(byte chrs[ ], int startIndex, int numChars)
 Here, chrs specifies the array of bytes. The second form allows you to
specify a subrange.
 In each of these constructors, the byte-to-character conversion is done by
using the default character encoding of the platform.
class SubStringCons
{
public static void main(String args[])
{
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
ABCDEF
CDE
 Extended versions of the byte-to-string constructors are also defined
in which you can specify the character encoding that determines
how bytes are converted to characters.
 However, you will often want to use the default encoding provided
by the platform.
 The contents of the array are copied whenever you create a String
object from an array.
 If you modify the contents of the array after you have created the
string, the String will be unchanged.
 You can construct a String from a StringBuffer by using the
constructor shown here:
String(StringBuffer strBufObj)
 You can construct a String from a StringBuilder by using this
constructor:
String(StringBuilder strBuildObj)
 The following constructor supports the extended Unicode character
set:
String(int codePoints[ ], int startIndex, int numChars)
 Here, codePoints is an array that contains Unicode code points. The
resulting string is constructed from the range that begins at
startIndex and runs for numChars.
2. String Buffer Class
 StringBuffer supports a modifiable string. As you know, String
represents fixed-length, immutable character sequences.
 In contrast, StringBuffer represents growable and writable
character sequences. StringBuffer may have characters and
substrings inserted in the middle or appended to the end.
 StringBuffer will automatically grow to make room for such
additions and often has more characters pre-allocated than are
actually needed, to allow room for growth.
StringBuffer Constructors
 StringBuffer defines these four constructors:
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
StringBuffer(CharSequence chars)
 The default constructor (the one with no parameters) reserves room for
16 characters without reallocation.
 The second version accepts an integer argument that explicitly sets the
size of the buffer.
 The third version accepts a String argument that sets the initial contents
of the StringBuffer object and reserves room for 16 more characters
without reallocation.
 StringBuffer allocates room for 16 additional characters when no
specific buffer length is requested, because reallocation is a costly
process in terms of time.
 Also, frequent reallocations can fragment memory. By allocating
room for a few extra characters, StringBuffer reduces the number of
reallocations that take place.
 The fourth constructor creates an object that contains the character
sequence contained in chars and reserves room for 16 more
characters.
length( ) and capacity( )
 The current length of a StringBuffer can be found via the length( )
method, while the total allocated capacity can be found through
the capacity( ) method.
 They have the following general forms:
int length( )
int capacity( )
class StringBufferDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
}
}
buffer = Hello
length = 5
capacity = 21
 The output of this program shows how StringBuffer reserves extra
space for additional manipulations.
 Since sb is initialized with the string "Hello" when it is created, its
length is 5.
 Its capacity is 21 because room for 16 additional characters is
automatically added.
ensureCapacity( )
 If you want to preallocate room for a certain number of characters
after a StringBuffer has been constructed, you can use
ensureCapacity( ) to set the size of the buffer.
 This is useful if you know in advance that you will be appending a
large number of small strings to a StringBuffer. ensureCapacity( )
has this general form:
void ensureCapacity(int minCapacity)
 Here, minCapacity specifies the minimum size of the buffer. (A buffer
larger than minCapacity may be allocated for reasons of efficiency.)
setLength( )
 To set the length of the string within a StringBuffer object, use
setLength( ). Its general form is shown here:
void setLength(int len)
Here, len specifies the length of the string. This value must be
nonnegative.
 When you increase the size of the string, null characters are
added to the end.
 If you call setLength( ) with a value less than the current value
returned by length( ), then the characters stored beyond the
new length will be lost.
charAt( ) and setCharAt( )
 The value of a single character can be obtained from a StringBuffer
via the charAt( ) method.
 You can set the value of a character within a StringBuffer using
setCharAt( ). Their general forms are shown here:
char charAt(int where)
void setCharAt(int where, char ch)
 For charAt( ), where specifies the index of the character being
obtained. For setCharAt( ), where specifies the index of the character
being set, and ch specifies the new value of that character.
 For both methods, where must be nonnegative and must not specify
a location beyond the end of the string.
class setCharAtDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " + sb.charAt(1));
sb.setCharAt(1, 'i');
sb.setLength(2);
System.out.println("buffer after = " + sb);
System.out.println("charAt(1) after = " + sb.charAt(1));
}
}
buffer before = Hello
charAt(1) before = e
buffer after = Hi
charAt(1) after = i
getChars( )
 To copy a substring of a StringBuffer into an array, use the
getChars( ) method. It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
 Here, sourceStart specifies the index of the beginning of the
substring, and sourceEnd specifies an index that is one past the end
of the desired substring.
 This means that the substring contains the characters from
sourceStart through sourceEnd–1.
 The array that will receive the characters is specified by target.
 The index within target at which the substring will be copied is
passed in targetStart.
 Care must be taken to assure that the target array is large enough to
hold the number of characters in the specified substring.
insert( )
 The insert( ) method inserts one string into another. It is overloaded
to accept values of all the primitive types, plus Strings, Objects, and
CharSequences.
 Like append( ), it obtains the string representation of the value it is
called with.
 This string is then inserted into the invoking StringBuffer object.
These are a few of its forms:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
Here, index specifies the index at which point the string will be
inserted into the invoking StringBuffer object.
class InsertDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
}
I like Java!
reverse( )
 You can reverse the characters within a StringBuffer object
using reverse( ), shown here:
StringBuffer reverse( )
 This method returns the reverse of the object on which it was
called.
class ReverseDemo
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
abcdef
fedcba
replace( )
 You can replace one set of characters with another set inside a
StringBuffer object by calling replace( ). Its signature is shown
here:
StringBuffer replace(int startIndex, int endIndex, String str)
 The substring being replaced is specified by the indexes
startIndex and endIndex.
 Thus, the substring at startIndex through endIndex–1 is
replaced.
 The replacement string is passed in str. The resulting
StringBuffer object is returned.
class ReplaceDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
}
}
After replace: This was a test.
3. String Tokenizer class
 The processing of text often consists of parsing a formatted input
string.
 Parsing is the division of text into a set of discrete parts, or tokens,
which in a certain sequence can convey a semantic meaning.
 The StringTokenizer class provides the first step in this parsing
process, often called the lexer (lexical analyzer) or scanner.
 StringTokenizer implements the Enumeration interface. Therefore,
given an input string, you can enumerate the individual tokens
contained in it using StringTokenizer.
 To use StringTokenizer, you specify an input string and a string
that contains delimiters.
 Delimiters are characters that separate tokens. Each character
in the delimiters string is considered a valid delimiter—for
example, ",;:" sets the delimiters to a comma, semicolon, and
colon.
 The default set of delimiters consists of the whitespace
characters: space, tab, form feed, newline, and carriage return.
 The StringTokenizer constructors are shown here:
StringTokenizer(String str)
StringTokenizer(String str, String delimiters)
StringTokenizer(String str, String delimiters, boolean delimAsToken)
 In all versions, str is the string that will be tokenized. In the first version,
the default delimiters are used.
 In the second and third versions, delimiters is a string that specifies the
delimiters.
 In the third version, if delimAsToken is true, then the delimiters are also
returned as tokens when the string is parsed. Otherwise, the delimiters
are not returned. Delimiters are not returned as tokens by the first two
forms.
 Once you have created a StringTokenizer object, the nextToken( )
method is used to extract consecutive tokens.
 The hasMoreTokens( ) method returns true while there are more
tokens to be extracted.
 Since StringTokenizer implements Enumeration, the
hasMoreElements( ) and nextElement( ) methods are also
implemented, and they act the same as hasMoreTokens( ) and
nextToken( ), respectively.
 Here is an example that creates a StringTokenizer to parse
"key=value" pairs. Consecutive sets of "key=value" pairs are
separated by a semicolon.
import java.util.StringTokenizer;
class STDemo
{
static String in = "title=Java: The Complete Reference;" +
"author=Schildt;" +
"publisher=McGraw-Hill;" +
"copyright=2014";
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer(in, "=;");
while(st.hasMoreTokens())
{
String key = st.nextToken();
String val = st.nextToken();
System.out.println(key + "t" + val);
}
}
}
import java.util.StringTokenizer;
class STDemo
{
static String in = "title=Java: The Complete Reference;" +
"author=Schildt;" +
"publisher=McGraw-Hill;" +
"copyright=2014";
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer(in, "=;");
while(st.hasMoreTokens())
{
String key = st.nextToken();
String val = st.nextToken();
System.out.println(key + "t" + val);
}
}
}
1. Inheritance Basics
2. Using super
3. Creating a Multilevel Hierarchy
4. Method Overriding
5. Dynamic Method Dispatch
6. Using Abstract Classes
7. Using final with Inheritance
INHERITANCE
Inheritance
 In the terminology of Java, a class that is inherited is called a
superclass.
 The class that does the inheriting is called a subclass.
 Therefore, a subclass is a specialized version of a superclass.
 It inherits all of the members defined by the superclass and adds its
own, unique elements..
1. Inheritance Basics
 To inherit a class, you simply incorporate the definition of one class
into another by using the extends keyword.
 To see how, let’s begin with a short example.
 The following program creates a superclass called A and a subclass
called B.
 Notice how the keyword extends is used to create a subclass of A.
// Create a superclass
class A
{
int i, j;
void showij()
{
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A
class B extends A
{
int k;
void showk()
{
System.out.println("k: " + k);
}
void sum()
{
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance
{
public static void main(String args [])
{
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
// The subclass has access to all public members of its superclass
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
 As you can see, the subclass B includes all of the members of its
superclass, A.
 This is why subOb can access i and j and call showij( ). Also, inside
sum( ), i and j can be referred to directly, as if they were part of B.
Member Access and Inheritance
 Although a subclass includes all of the members of its superclass, it
cannot access those members of the superclass that have been
declared as private.
 For example, consider the following simple class hierarchy:
// In a class hierarchy, private members remain private to their class
// This program contains an error and will not compile
// Create a superclass
class A
{
int i; // public by default
private int j; // private to A
void setij(int x, int y)
{
i = x;
j = y;
}
}
// A's j is not accessible here
class B extends A
{
int total;
void sum()
{
total = i + j; // ERROR, j is not accessible here
}
}
class Access
{
public static void main(String args[])
{
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}
Access.java:22: error: j has private access in A
total = i + j; // ERROR, j is not accessible here
^
1 error
 This program will not compile because the use of j inside the sum( )
method of B causes an access violation.
 Since j is declared as private, it is only accessible by other members
of its own class.
 Subclasses have no access to it.
A More Practical Example
 Box class developed is extended to include a fourth component
called weight.
 Thus, the new class will contain a box’s width, height, depth, and
weight.
class Box
{
double width;
double height;
double depth;
// construct clone of an object
Box(Box ob)
{
// pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box()
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
// Here, Box is extended to include weight
class BoxWeight extends Box
{
double weight; // weight of box
// constructor for BoxWeight
BoxWeight(double w, double h, double d, double m)
{
width = w;
height = h;
depth = d;
weight = m;
}
}
class DemoBoxWeight
{
public static void main(String args[])
{
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
}
}
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
Volume of mybox2 is 24.0
Weight of mybox2 is 0.076
2. Using Super
 Whenever a subclass needs to refer to its immediate superclass, it
can do so by use of the keyword super.
 super has two general forms.
 The first calls the superclass’ constructor.
 The second is used to access a member of the superclass that has
been hidden by a member of a subclass.
Using super to Call Superclass Constructors
 A subclass can call a constructor defined by its superclass by use of
the following form of super:
super(arg-list);
 Here, arg-list specifies any arguments needed by the constructor in
the superclass.
 super( ) must always be the first statement executed inside a
subclass’ constructor.
// BoxWeight now uses super to initialize its Box attributes
class BoxWeight extends Box
{
double weight; // weight of box
// initialize width, height, and depth using super()
BoxWeight(double w, double h, double d, double m)
{
super(w, h, d); // call superclass constructor
weight = m;
}
}
 In the preceding example, super( ) was called with three arguments.
Since constructors can be overloaded, super( ) can be called using
any form defined by the superclass.
 The constructor executed will be the one that matches the
arguments.
 For example, here is a complete implementation of BoxWeight that
provides constructors for the various ways that a box can be
constructed.
 In each case, super( ) is called using the appropriate arguments.
 Notice that width, height, and depth have been made private within
Box.
class Box
{
private double width;
private double height;
private double depth;
// construct clone of an object
Box(Box ob)
{
// pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box()
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
// BoxWeight now fully implements all constructors
class BoxWeight extends Box
{
double weight; // weight of box
// construct clone of an object
BoxWeight(BoxWeight ob)
{
// pass object to constructor
super(ob);
weight = ob.weight;
}
// constructor when all parameters are specified
BoxWeight(double w, double h, double d, double m)
{
super(w, h, d); // call superclass constructor
weight = m;
}
// default constructor
BoxWeight()
{
super();
weight = -1;
}
// constructor used when cube is created
BoxWeight(double len, double m)
{
super(len);
weight = m;
}
}
class DemoSuper
{
public static void main(String args[])
{
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
BoxWeight mybox3 = new BoxWeight(); // default
BoxWeight mycube = new BoxWeight(3, 2);
BoxWeight myclone = new BoxWeight(mybox1);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
System.out.println();
vol = mybox3.volume();
System.out.println("Volume of mybox3 is " + vol);
System.out.println("Weight of mybox3 is " + mybox3.weight);
System.out.println();
vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);
System.out.println("Weight of myclone is " + myclone.weight);
System.out.println();
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
System.out.println("Weight of mycube is " + mycube.weight);
System.out.println();
}
}
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
Volume of mybox2 is 24.0
Weight of mybox2 is 0.076
Volume of mybox3 is -1.0
Weight of mybox3 is -1.0
Volume of myclone is 3000.0
Weight of myclone is 34.3
Volume of mycube is 27.0
Weight of mycube is 2.0
 Notice that super( ) is passed an object of type BoxWeight—not of type Box.
This still invokes the constructor Box(Box ob).
 As mentioned earlier, a superclass variable can be used to reference any
object derived from that class. Thus, we are able to pass a BoxWeight object
to the Box constructor. Of course, Box only has knowledge of its own
members.
 Let’s review the key concepts behind super( ). When a subclass calls super( ),
it is calling the constructor of its immediate superclass.
 Thus, super( ) always refers to the superclass immediately above the calling
class. This is true even in a multileveled hierarchy.
 Also, super( ) must always be the first statement executed inside a subclass
constructor.
A Second Use for super
 The second form of super acts somewhat like this, except that it
always refers to the superclass of the subclass in which it is used.
 This usage has the following general form:
super.member
 Here, member can be either a method or an instance variable.
 This second form of super is most applicable to situations in which
member names of a subclass hide members by the same name in the
superclass.
 Consider this simple class hierarchy:
// Using super to overcome name hiding
class A
{
int i;
}
// Create a subclass by extending class A
class B extends A
{
int i; // this i hides the i in A
B(int a, int b)
{
super.i = a; // i in A
i = b; // i in B
}
void show()
{
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper
{
public static void main(String args[])
{
B subOb = new B(1, 2);
subOb.show();
}
}
i in superclass: 1
i in subclass: 2
 Although the instance variable i in B hides the i in A, super allows
access to the i defined in the superclass.
 As you will see, super can also be used to call methods that are
hidden by a subclass.
Types of Inheritance
Single Inheritance
class A
{
public void methodA()
{
System.out.println("Base or Parent class method");
}
}
class B extends A
{
public void methodB()
{
System.out.println("Derived or Child class method");
}
}
class SingleIn
{
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling sub class method
}
}
Base or Parent class method
Derived or Child class method
Multilevel Inheritance
class A
{
public void methodA()
{
System.out.println("class A method");
}
}
class B extends A
{
public void methodB()
{
System.out.println("class B method");
}
}
class C extends B
{
public void methodC()
{
System.out.println("class C method");
}
}
class MultilevelIn
{
public static void main(String args[])
{
C obj = new C();
obj.methodA(); //calling grand parent class method
obj.methodB(); //calling parent class method
obj.methodC(); //calling child method
}
}
class A method
class B method
class C method
Hierarchical Inheritance
class A
{
void DisplayA()
{
System.out.println("This is a content of parent class");
}
}
class B extends A
{
void DisplayB()
{
System.out.println("This is a content of child class 1");
}
}
class C extends A
{
void DisplayC()
{
System.out.println("This is a content of child class 2");
}
}
class HierarchicalIn
{
public static void main(String args[])
{
System.out.println("Calling for child class B");
B b = new B();
b.DisplayA();
b.DisplayB();
System.out.println();
System.out.println("Calling for child class C");
C c = new C();
c.DisplayA();
c.DisplayC();
}
}
Calling for child class B
This is a content of parent class
This is a content of child class 1
Calling for child class C
This is a content of parent class
This is a content of child class 2
Multiple Inheritance
interface A
{
void displayA();
}
interface B
{
void displayB();
}
class C implements A,B
{
public void displayA()
{
System.out.println("Interface A : Parent 1");
}
public void displayB()
{
System.out.println("Interface B : Parent 2");
}
void displayC()
{
System.out.println("Class C : Child of Parent1 and Parent 2");
}
}
class MultipleIn
{
public static void main(String args[])
{
C obj = new C();
obj.displayA();
obj.displayB();
obj.displayC();
}
}
Interface A : Parent 1
Interface B : Parent 2
Class C : Child of Parent1 and Parent 2
3. Creating Multilevel Hierarchy
 It is perfectly acceptable to use a subclass as a superclass of another. For
example, given three classes called A, B, and C, C can be a subclass of B,
which is a subclass of A.
 When this type of situation occurs, each subclass inherits all of the traits
found in all of its superclasses. In this case, C inherits all aspects of B and
A.
 To see how a multilevel hierarchy can be useful, consider the following
program. In it, the subclass BoxWeight is used as a superclass to create
the subclass called Shipment.
 Shipment inherits all of the traits of BoxWeight and Box, and adds a field
called cost, which holds the cost of shipping such a parcel.
When Constructors Are Executed
 When a class hierarchy is created, in what order are the constructors
for the classes that make up the hierarchy executed?
 For example, given a subclass called B and a superclass called A, is
A’s constructor executed before B’s, or vice versa?
 The answer is that in a class hierarchy, constructors complete their
execution in order of derivation, from superclass to subclass.
 Further, since super( ) must be the first statement executed in a
subclass constructor, this order is the same whether or not super( ) is
used.
 If super( ) is not used, then the default or parameterless constructor
of each superclass will be executed.
4. Method Overriding
 In a class hierarchy, when a method in a subclass has the same
name and type signature as a method in its superclass, then the
method in the subclass is said to override the method in the
superclass.
 When an overridden method is called from within its subclass, it
will always refer to the version of that method defined by the
subclass.
 The version of the method defined by the superclass will be
hidden.
No. Method Overloading Method Overriding
1 Method overloading is used to increase
the readability of the program.
Method overriding is used to provide the
specific implementation of the method that
is already provided by its super class.
2 Method overloading is performed
within class.
Method overriding occurs in two classes
that have IS-A (inheritance) relationship.
3 In case of method overloading,
parameter must be different.
In case of method overriding, parameter
must be same.
4 Method overloading is the example of
compile time polymorphism.
Method overriding is the example of run
time polymorphism.
5 In java, method overloading can't be
performed by changing return type of
the method only. Return type can be same
or different in method overloading. But
you must have to change the parameter.
Return type must be same or covariant in
method overriding.
Java Method Overloading
class OverloadingExample
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
Java Method Overriding
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
}
Real example of Java Method Overriding
class Bank
{
int getRateOfInterest()
{
return 0;
}
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 8;
}
}
class ICICI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class AXIS extends Bank
{
int getRateOfInterest()
{
return 9;
}
}
class Test2
{
public static void main(String args[])
{
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
5. Dynamic Method Dispatch
 Method overriding forms the basis for one of Java’s most
powerful concepts: dynamic method dispatch.
 Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile
time.
 Dynamic method dispatch is important because this is how Java
implements run-time polymorphism.
 A superclass reference variable can refer to a subclass object. Java
uses this fact to resolve calls to overridden methods at run time.
 When an overridden method is called through a superclass
reference, Java determines which version of that method to execute
based upon the type of the object being referred to at the time the
call occurs. Thus, this determination is made at run time.
 When different types of objects are referred to, different versions of
an overridden method will be called.
 In other words, it is the type of the object being referred to (not the
type of the reference variable) that determines which version of an
overridden method will be executed.
 Therefore, if a superclass contains a method that is overridden by a
subclass, then when different types of objects are referred to
through a superclass reference variable, different versions of the
method are executed
class A
{
void callme()
{
System.out.println("Inside A's callme method");
}
}
class B extends A
{
// override callme()
void callme()
{
System.out.println("Inside B's callme method");
}
}
class C extends A
{
// override callme()
void callme()
{
System.out.println("Inside C's callme method");
}
}
class Dispatch
{
public static void main(String args[])
{
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
Inside A's callme method
Inside B's callme method
Inside C's callme method
 This program creates one superclass called A and two subclasses of it,
called B and C.
 Subclasses B and C override callme( ) declared in A. Inside the main( )
method, objects of type A, B, and C are declared. Also, a reference of type
A, called r, is declared.
 The program then in turn assigns a reference to each type of object to r
and uses that reference to invoke callme( ).
 As the output shows, the version of callme( ) executed is determined by
the type of object being referred to at the time of the call.
 Had it been determined by the type of the reference variable, r, you
would see three calls to A’s callme( ) method.
class A
{
void display()
{
System.out.println("Displaying from class A");
}
}
class B extends A
{
public void display()
{
System.out.println("Displaying from class B");
}
}
class Dispatch1
{
public static void main(String args[])
{
A a = new A(); // A reference and object
A b = new B(); // A reference but B object
a.display(); // runs the method in A class
b.display(); // runs the method in B class
}
}
Displaying from class A
Displaying from class B
class Rectangle
{
int l=8,b=4;
int area;
void area()
{
area=l*b;
System.out.println("Area of rectangle: "+area);
}
}
class Square extends Rectangle
{
void area() //overridden method
{
area=l*l;
System.out.println("Area of square: "+area);
}
}
class Triangle extends Rectangle
{
void area() //overridden method
{
area=(b*l)/2;
System.out.println("Area of triangle: "+area);
}
}
public class Dispatch2
{
public static void main(String args[])
{
Rectangle r=new Rectangle();
r.area();
r=new Square(); //Rectange reference but Square object
r.area();
r=new Triangle(); //Rectange reference but Triangle object
r.area();
}
}
Area of rectangle: 32
Area of square: 64
Area of triangle: 16
6. Using Abstract Classes
 To declare an abstract method, use this general form:
abstract type name(parameter-list);
 As you can see, no method body is present.
 Any class that contains one or more abstract methods must also
be declared abstract.
 To declare a class abstract, you simply use the abstract keyword
in front of the class keyword at the beginning of the class
declaration.
 There can be no objects of an abstract class.
 That is, an abstract class cannot be directly instantiated with the
new operator.
 Such objects would be useless, because an abstract class is not fully
defined.
 Also, you cannot declare abstract constructors, or abstract static
methods.
 Any subclass of an abstract class must either implement all of the
abstract methods in the superclass, or be declared abstract itself.
abstract class Figure
{
double dim1;
double dim2;
Figure(double a, double b)
{
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
class Rectangle extends Figure
{
Rectangle(double a, double b)
{
super(a, b);
}
// override area for rectangle
double area()
{
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure
{
Triangle(double a, double b)
{
super(a, b);
}
// override area for right triangle
double area()
{
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas
{
public static void main(String args[])
{
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
class AbstractAreas
{
public static void main(String args[])
{
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
Inside Area for Rectangle.
Area is 45.0
Inside Area for Triangle.
Area is 40.0
7. Using final with Inheritance
 The keyword final has three uses.
 First, it can be used to create the equivalent of a named constant.
 The other two uses of final apply to inheritance.
 Using final to Prevent Overriding
 Using final to Prevent Inheritance
Using final to Prevent Overriding
 While method overriding is one of Java’s most powerful features,
there will be times when you will want to prevent it from occurring.
 To disallow a method from being overridden, specify final as a
modifier at the start of its declaration.
 Methods declared as final cannot be overridden.
class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth()
{
// ERROR! Can't override.
System.out.println("Illegal!");
}
}
Using final to Prevent Inheritance
 Sometimes you will want to prevent a class from being inherited.
 To do this, precede the class declaration with final.
 Declaring a class as final implicitly declares all of its methods as
final, too.
 As you might expect, it is illegal to declare a class as both abstract
and final since an abstract class is incomplete by itself and relies
upon its subclasses to provide complete implementations.
final class A
{
//...
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
//...
}
 As the comments imply, it is illegal for B to inherit A since A is
declared as final.
PACKAGES:
1. Packages
2. Access Protection
3. Importing Packages
PACKAGES AND INTERFACES
INTERFACES:
4. Defining an Interface
5. Implementing Interfaces
6. Nested Interfaces
7. Applying Interfaces
8. Variables in Interfaces
PACKAGES AND INTERFACES
1. Packages
 The name of each example class was taken from the same name
space. This means that a unique name had to be used for each class
to avoid name collisions.
 After a while, without some way to manage the name space, you
could run out of convenient, descriptive names for individual
classes.
 You also need some way to be assured that the name you choose
for a class will be reasonably unique and not collide with class
names chosen by other programmers.
Defining a Package
 To create a package is quite easy: simply include a package
command as the first statement in a Java source file.
 Any classes declared within that file will belong to the specified
package.
 The package statement defines a name space in which classes are
stored.
 If you omit the package statement, the class names are put into the
default package, which has no name.
 This is the general form of the package statement:
package pkg;
 Here, pkg is the name of the package. For example, the following
statement creates a package called mypack:
package mypack;
 Java uses file system directories to store packages. For example, the
.class files for any classes you declare to be part of mypack must be
stored in a directory called mypack.
 Remember that case is significant, and the directory name must
match the package name exactly.
 You can create a hierarchy of packages. To do so, simply separate
each package name from the one above it by use of a period.
 The general form of a multileveled package statement is shown
here:
package pkg1[.pkg2[.pkg3]];
 A package hierarchy must be reflected in the file system of your
Java development system. For example, a package declared as
package java.awt.image;
needs to be stored in javaawtimage in a Windows environment.
 Be sure to choose your package names carefully. You cannot
rename a package without renaming the directory in which the
classes are stored.
Finding Packages and CLASSPATH
 As just explained, packages are mirrored by directories. This raises
an important question: How does the Java run-time system know
where to look for packages that you create?
 The answer has three parts.
 First, by default, the Java run-time system uses the current working
directory as its starting point.
 Thus, if your package is in a subdirectory of the current directory, it
will be found.
 Second, you can specify a directory path or paths by setting the
CLASSPATH environmental variable.
 Third, you can use the -classpath option with java and javac to specify
the path to your classes.
 For example, consider the following package specification:
package mypack
 In order for a program to find MyPack, one of three things must be true.
 Either the program can be executed from a directory immediately above
myPack, or the CLASSPATH must be set to include the path to mypack,
or the -classpath option must specify the path to mypack when the
program is run via java.
 When the second two options are used, the class path must not
include mypack, itself.
 It must simply specify the path to mypack. For example, in a
Windows environment, if the path to mypack is
C:MyProgramsJavamypack
then the class path to mypack is
C:MyProgramsJava
 The easiest way is to simply create the package directories below
your current development directory, put the .class files into the
appropriate directories, and then execute the programs from the
development directory.
package mypack;
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name = n;
bal = b;
}
void show()
{
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance
{
public static void main(String args[])
{
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++)
current[i].show();
}
}
K. J. Fielding: $123.23
Will Tell: $157.02
--> Tom Jackson: $-12.33
 Compile the file. Make sure that the resulting .class file is also in the
mypack directory.
 Then, try executing the AccountBalance class, using the following
command line:
java mypack.AccountBalance
 Remember, you will need to be in the directory above mypack when you
execute this command.
 AccountBalance is now part of the package mypack. This means that it
cannot be executed by itself.
 That is, you cannot use this command line:
java AccountBalance
 AccountBalance must be qualified with its package name.
Benefits of Packages
 In Java, by the use of packages, you can group a number of related
classes and/or interfaces together into a single unit.
 Prevents name-space collision
 Provides greater control over source code
 Makes it easy to find a class
 These are the benefits of organising classes into packages
 It prevents name-space collision
 It indicates that the classes and interfaces in the package are
related
 You know where to find the classes you want if they are in a
specific package
 It is convenient for organising your work and separating your
work from libraries provided by others
Using Packages
 Use fully qualified name
java.util.Date=new java.util.Date();
 You can use import to instruct Java where to look for things
defined outside your program
import java.util.Scanner;
Scanner sc=new Scanner(System.in);
 You can use * to import all classes in package
import java.util.*;
Scanner sc=new Scanner(System.in);
Types of Packages
Predefined Packages
 Built-in Packages
 They are already defined packages.
 Standard packages which come as a part of JRE
User defined Packages
 Programmer defined packages
 Programmer defined packages to bundle group of related classes
Foundation Java Packages
Package Name Description
java.lang Classes that apply to the language itself, which includes the Object
class, the String class, the system class and also contains classes for
primitive types, strings, math functions, threads, and exception.
Classes belonging to java.lang package need not be explicitly imported
java.util Utility classes such as Date, as well as collection classes such as Vector
and Hashtable
java.io Input and output classes for writing to and reading from streams
(such as standard input and output) and for handling files
java.net Classes for networking support, including Socket and URL (a class to
represent references to documents on the www)
java.awt Classes for implementing GUI – windows, buttons, menus etc.
Java.applet Classes to implement Java applets, including the Applet class itself, as
well as the AudioClip interface
Static Import
 Static import enables programmers to import static members
 Class name and a dot(.) are not required to use an imported static
member.
 Example: we always use sqrt() method of Math class by using Math
class i.e. Math.sqrt(), but by using static import we can access sqrt()
method directly.
//Static Import Example
import static java.lang.Math.*;
import static java.lang.System.*;
class StaticImportTest
{
public static void main(String[] args)
{
out.println(sqrt(4));
out.println(pow(2, 2));
out.println(abs(6.3));
}
}
2.0
4.0
6.3
Packages and Name Space Collision
 Namespace collision can be avoided by accessing classes with the
same name in multiple packages by their fully qualified name.
import pack1.*;
import pack2.*
pack1.Student stud1;
pack2.Student stud2;
Teacher teacher1;
Courses course1;
2. Access Protection
 Classes and packages are both means of encapsulating and
containing the name space and scope of variables and methods.
 Packages act as containers for classes and other subordinate
packages.
 Classes act as containers for data and code.
 The class is Java’s smallest unit of abstraction.
 Because of the interplay between classes and packages, Java
addresses four categories of visibility for class members:
 Subclasses in the same package
 Non-subclasses in the same package
 Subclasses in different packages
 Classes that are neither in the same package nor subclasses
 The three access modifiers, private, public, and protected, provide a
variety of ways to produce the many levels of access required by
these categories.
 While Java’s access control mechanism may seem complicated, we
can simplify it as follows.
 Anything declared public can be accessed from anywhere.
 Anything declared private cannot be seen outside of its class.
 When a member does not have an explicit access specification, it is
visible to subclasses as well as to other classes in the same package.
This is the default access.
 If you want to allow an element to be seen outside your current
package, but only to classes that subclass your class directly, then
declare that element protected.
Table: Class Member Access
 A non-nested class has only two possible access levels: default and
public.
 When a class is declared as public, it is accessible by any other
code.
 If a class has default access, then it can only be accessed by other
code within its same package.
 When a class is public, it must be the only public class declared in
the file, and the file must have the same name as the class.
 Refer Programs of packages p1 and p2
Compiling and Running the files in p1 package
C:UsersPrabuDesktop>javac ./p1/Demo.java
C:UsersPrabuDesktop>java p1.Demo
Compiling and Running the files in p2 package
C:UsersPrabuDesktop>javac ./p2/Demo.java
C:UsersPrabuDesktop>java p2.Demo
3. Importing Packages
 Java includes the import statement to bring certain classes, or entire
packages, into visibility. Once imported, a class can be referred to
directly, using only its name.
 In a Java source file, import statements occur immediately
following the package statement (if it exists) and before any class
definitions.
 This is the general form of the import statement:
import pkg1 [.pkg2].(classname | *);
 Here, pkg1 is the name of a top-level package, and pkg2 is the
name of a subordinate package inside the outer package separated
by a dot (.).
 There is no practical limit on the depth of a package hierarchy,
except that imposed by the file system.
 Finally, you specify either an explicit classname or a star (*), which
indicates that the Java compiler should import the entire package.
 This code fragment shows both forms in use:
import java.util.Date;
import java.io.*;
 All of the standard Java classes included with Java are stored in a
package called java.
 The basic language functions are stored in a package inside of the
java package called java.lang.
 Normally, you have to import every package or class that you want
to use, but since Java is useless without much of the functionality in
java.lang, it is implicitly imported by the compiler for all programs.
 It must be emphasized that the import statement is optional. Any
place you use a class name, you can use its fully qualified name,
which includes its full package hierarchy. For example, this
fragment uses an import statement:
import java.util.*;
class MyDate extends Date
{
}
 The same example without the import statement looks like this:
class MyDate extends java.util.Date
{
}
 In this version, Date is fully-qualified.
 Example: Refer the programs
package: mypack
class: Balance
directory: Desktop
class: TestBalance
Compiling the files in mypack package
C:UsersPrabuDesktop>javac ./mypack/Balance.java
Compiling and running the files in desktop
C:UsersPrabuDesktop>javac TestBalance.java
C:UsersPrabuDesktop>java TestBalance
INTERFACES:
4. Defining an Interface
5. Implementing Interfaces
6. Nested Interfaces
7. Applying Interfaces
8. Variables in Interfaces
PACKAGES AND INTERFACES
4. Defining an Interface
 Using the keyword interface, you can fully abstract a class’ interface
from its implementation.
 That is, using interface, you can specify what a class must do, but not
how it does it.
 Interfaces are syntactically similar to classes, but they lack instance
variables, and, as a general rule, their methods are declared without any
body.
 In practice, this means that you can define interfaces that don’t make
assumptions about how they are implemented.
 Once it is defined, any number of classes can implement an interface.
Also, one class can implement any number of interfaces
Defining an Interface
An interface is defined much like a class. This is a simplified general
form of an interface:
access interface name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
//...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Here is an example of an interface definition. It declares a simple
interface that contains one method called callback( ) that takes a single
integer parameter.
interface Callback
{
void callback(int param);
}
5. Implementing Interfaces
 Once an interface has been defined, one or more classes can implement
that interface.
 To implement an interface, include the implements clause in a class
definition, and then create the methods required by the interface.
 The general form of a class that includes the implements clause looks
like this:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
 If a class implements more than one interface, the interfaces are
separated with a comma.
 If a class implements two interfaces that declare the same method,
then the same method will be used by clients of either interface.
 The methods that implement an interface must be declared public.
 Also, the type signature of the implementing method must match
exactly the type signature specified in the interface definition.
 Here is a small example class that implements the Callback interface
shown earlier:
class Client implements Callback
{
// Implement Callback's interface
public void callback(int p)
{
System.out.println("callback called with " + p);
}
}
 Notice that callback( ) is declared using the public access modifier
 It is both permissible and common for classes that implement interfaces to define
additional members of their own.
 For example, the following version of Client implements callback( ) and adds the
method nonIfaceMeth( ):
class Client implements Callback
{
// Implement Callback's interface
public void callback(int p)
{
System.out.println("callback called with " + p);
}
void nonIfaceMeth()
{
System.out.println("Classes that implement interfaces " +
"may also define other members, too.");
}
}
Accessing Implementations Through Interface References
 You can declare variables as object references that use an interface rather
than a class type.
 Any instance of any class that implements the declared interface can be
referred to by such a variable.
 When you call a method through one of these references, the correct
version will be called based on the actual instance of the interface being
referred to.
 This is one of the key features of interfaces. The method to be executed is
looked up dynamically at run time, allowing classes to be created later
than the code which calls methods on them.
 The calling code can dispatch through an interface without having to
know anything about the “callee.”
 The following example calls the callback( ) method via an interface
reference variable:
class TestIface
{
public static void main(String args[])
{
Callback c = new Client();
c.callback(42);
}
}
 Notice that variable c is declared to be of the interface type Callback,
yet it was assigned an instance of Client.
 Although c can be used to access the callback( ) method, it cannot
access any other members of the Client class.
 An interface reference variable has knowledge only of the methods
declared by its interface declaration.
 Thus, c could not be used to access nonIfaceMeth( ) since it is defined
by Client but not Callback.
6. Nested Interfaces
 An interface can be declared a member of a class or another interface.
Such an interface is called a member interface or a nested interface.
 A nested interface can be declared as public, private, or protected. This
differs from a top-level interface, which must either be declared as
public or use the default access level, as previously described.
 When a nested interface is used outside of its enclosing scope, it must be
qualified by the name of the class or interface of which it is a member.
 Thus, outside of the class or interface in which a nested interface is
declared, its name must be fully qualified.
// This class contains a member interface
class A
{
// this is a nested interface
public interface NestedIF
{
boolean isNotNegative(int x);
}
}
// B implements the nested interface
class B implements A.NestedIF
{
public boolean isNotNegative(int x)
{
return x < 0 ? false: true;
}
}
class NestedIFDemo
{
public static void main(String args[])
{
// use a nested interface reference
A.NestedIF nif = new B();
if(nif.isNotNegative(10))
System.out.println("10 is not negative");
if(nif.isNotNegative(-12))
System.out.println("this won't be displayed");
}
}
10 is not negative
7. Applying Interfaces
 In Java 9 version, a new feature is added that allows us to declare
private methods inside the interface.
 The purpose of private method is just to share some task between
the non-abstract methods of the interface.
 An interface IDemo is created that has a default method and a
private method as well. Since private methods are not accessible
outside to interface. So, it is called from the default method.
interface IDemo
{
// Default method
default void msg()
{
greet();
}
// Private method
private void greet()
{
System.out.println("This is private method");
}
}
public class Demo implements IDemo
{
public static void main(String[] args)
{
Demo d = new Demo();
// calling default method
d.msg();
}
}
This is private method
8. Variables in Interfaces
 Interfaces can be used to import shared constants into multiple
classes by simply declaring an interface that contains variables that
are initialized to the desired values.
 When that interface is included in a class (that is, when you
“implement” the interface), all of those variable names will be in
scope as constants.
 If an interface contains no methods, then any class that includes
such an interface doesn’t actually implement anything.
 It is as if that class were importing the constant fields into the class
name space as final variables.
import java.util.Random;
interface SharedConstants
{
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int SOON = 4;
int NEVER = 5;
}
class Question implements SharedConstants
{
Random rand = new Random();
int ask()
{
int prob = (int) (100 * rand.nextDouble());
if (prob < 30)
return NO;
else if (prob < 60)
return YES;
else if (prob < 75)
return LATER;
else if (prob < 98)
return SOON;
else
return NEVER;
}
}
class AskMe implements SharedConstants
{
static void answer(int result)
{
switch(result)
{
case NO:
System.out.println("No");
break;
case YES:
System.out.println("Yes");
break;
case MAYBE:
System.out.println("Maybe");
break;
case LATER:
System.out.println("Later");
break;
case SOON:
System.out.println("Soon");
break;
case NEVER:
System.out.println("Never");
break;
}
}
public static void main(String args[])
{
Question q = new Question();
answer(q.ask());
answer(q.ask());
answer(q.ask());
answer(q.ask());
}
}
Later
Soon
No
Yes
References
1. Herbert Schildt, “Java The Complete Reference”, 9th Edition,
McGraw-Hill Education, New Delhi, 2017.
Thank You

More Related Content

What's hot

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
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection frameworkankitgarg_er
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and ObjectsPrabu U
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming languageMd.Al-imran Roton
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Java - Packages Concepts
Java - Packages ConceptsJava - Packages Concepts
Java - Packages ConceptsVicter Paul
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaRahulAnanda1
 
Chapter 13 - Recursion
Chapter 13 - RecursionChapter 13 - Recursion
Chapter 13 - RecursionAdan Hubahib
 
Constructor in java
Constructor in javaConstructor in java
Constructor in javaHitesh Kumar
 

What's hot (20)

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)
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objects
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Java constructors
Java constructorsJava constructors
Java constructors
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Basic concept of OOP's
Basic concept of OOP'sBasic concept of OOP's
Basic concept of OOP's
 
Java - Packages Concepts
Java - Packages ConceptsJava - Packages Concepts
Java - Packages Concepts
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Chapter 13 - Recursion
Chapter 13 - RecursionChapter 13 - Recursion
Chapter 13 - Recursion
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
JAVA APPLET BASICS
JAVA APPLET BASICSJAVA APPLET BASICS
JAVA APPLET BASICS
 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 

Similar to JAVA STRING HANDLING

L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)teach4uin
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string classfedcoordinator
 
3.7_StringBuilder.pdf
3.7_StringBuilder.pdf3.7_StringBuilder.pdf
3.7_StringBuilder.pdfAnanthi68
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20myrajendra
 
Java string handling
Java string handlingJava string handling
Java string handlingSalman Khan
 
Java R20 - UNIT-5.docx
Java R20 - UNIT-5.docxJava R20 - UNIT-5.docx
Java R20 - UNIT-5.docxPamarthi Kumar
 
Strings-Computer programming
Strings-Computer programmingStrings-Computer programming
Strings-Computer programmingnmahi96
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotesSowri Rajan
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)Ravi_Kant_Sahu
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)Ravi Kant Sahu
 

Similar to JAVA STRING HANDLING (20)

StringBuffer.pptx
StringBuffer.pptxStringBuffer.pptx
StringBuffer.pptx
 
package
packagepackage
package
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)
 
String handling
String handlingString handling
String handling
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string class
 
3.7_StringBuilder.pdf
3.7_StringBuilder.pdf3.7_StringBuilder.pdf
3.7_StringBuilder.pdf
 
M C6java7
M C6java7M C6java7
M C6java7
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
 
Java String
Java String Java String
Java String
 
Java string handling
Java string handlingJava string handling
Java string handling
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
07slide
07slide07slide
07slide
 
Java R20 - UNIT-5.docx
Java R20 - UNIT-5.docxJava R20 - UNIT-5.docx
Java R20 - UNIT-5.docx
 
Java R20 - UNIT-5.pdf
Java R20 - UNIT-5.pdfJava R20 - UNIT-5.pdf
Java R20 - UNIT-5.pdf
 
String.ppt
String.pptString.ppt
String.ppt
 
Strings-Computer programming
Strings-Computer programmingStrings-Computer programming
Strings-Computer programming
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 

More from Prabu U

Computation Using Scipy, Scikit Image, Scikit Learn
Computation Using Scipy, Scikit Image, Scikit LearnComputation Using Scipy, Scikit Image, Scikit Learn
Computation Using Scipy, Scikit Image, Scikit LearnPrabu U
 
Concurrency and Parallelism, Asynchronous Programming, Network Programming
Concurrency and Parallelism, Asynchronous Programming, Network ProgrammingConcurrency and Parallelism, Asynchronous Programming, Network Programming
Concurrency and Parallelism, Asynchronous Programming, Network ProgrammingPrabu U
 
File Input/output, Database Access, Data Analysis with Pandas
File Input/output, Database Access, Data Analysis with PandasFile Input/output, Database Access, Data Analysis with Pandas
File Input/output, Database Access, Data Analysis with PandasPrabu U
 
Arrays with Numpy, Computer Graphics
Arrays with Numpy, Computer GraphicsArrays with Numpy, Computer Graphics
Arrays with Numpy, Computer GraphicsPrabu U
 
Lambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream APILambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream APIPrabu U
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingPrabu U
 
Building XML Based Applications
Building XML Based ApplicationsBuilding XML Based Applications
Building XML Based ApplicationsPrabu U
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XMLPrabu U
 
WEB SERVICES
WEB SERVICESWEB SERVICES
WEB SERVICESPrabu U
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGPrabu U
 
Internet Principles and Components, Client-Side Programming
Internet Principles and Components, Client-Side ProgrammingInternet Principles and Components, Client-Side Programming
Internet Principles and Components, Client-Side ProgrammingPrabu U
 
Operation Management
Operation ManagementOperation Management
Operation ManagementPrabu U
 
Nature and Importance of Management
Nature and Importance of ManagementNature and Importance of Management
Nature and Importance of ManagementPrabu U
 
Replacement and Maintenance Analysis
Replacement and Maintenance AnalysisReplacement and Maintenance Analysis
Replacement and Maintenance AnalysisPrabu U
 
Elementary Economic Analysis
Elementary Economic AnalysisElementary Economic Analysis
Elementary Economic AnalysisPrabu U
 
Introduction to Engineering Economics
Introduction to Engineering EconomicsIntroduction to Engineering Economics
Introduction to Engineering EconomicsPrabu U
 
Files in C
Files in CFiles in C
Files in CPrabu U
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and PointersPrabu U
 
Decision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, StringsDecision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, StringsPrabu U
 

More from Prabu U (20)

Computation Using Scipy, Scikit Image, Scikit Learn
Computation Using Scipy, Scikit Image, Scikit LearnComputation Using Scipy, Scikit Image, Scikit Learn
Computation Using Scipy, Scikit Image, Scikit Learn
 
Concurrency and Parallelism, Asynchronous Programming, Network Programming
Concurrency and Parallelism, Asynchronous Programming, Network ProgrammingConcurrency and Parallelism, Asynchronous Programming, Network Programming
Concurrency and Parallelism, Asynchronous Programming, Network Programming
 
File Input/output, Database Access, Data Analysis with Pandas
File Input/output, Database Access, Data Analysis with PandasFile Input/output, Database Access, Data Analysis with Pandas
File Input/output, Database Access, Data Analysis with Pandas
 
Arrays with Numpy, Computer Graphics
Arrays with Numpy, Computer GraphicsArrays with Numpy, Computer Graphics
Arrays with Numpy, Computer Graphics
 
Lambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream APILambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream API
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
 
Building XML Based Applications
Building XML Based ApplicationsBuilding XML Based Applications
Building XML Based Applications
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
WEB SERVICES
WEB SERVICESWEB SERVICES
WEB SERVICES
 
XML
XMLXML
XML
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMING
 
Internet Principles and Components, Client-Side Programming
Internet Principles and Components, Client-Side ProgrammingInternet Principles and Components, Client-Side Programming
Internet Principles and Components, Client-Side Programming
 
Operation Management
Operation ManagementOperation Management
Operation Management
 
Nature and Importance of Management
Nature and Importance of ManagementNature and Importance of Management
Nature and Importance of Management
 
Replacement and Maintenance Analysis
Replacement and Maintenance AnalysisReplacement and Maintenance Analysis
Replacement and Maintenance Analysis
 
Elementary Economic Analysis
Elementary Economic AnalysisElementary Economic Analysis
Elementary Economic Analysis
 
Introduction to Engineering Economics
Introduction to Engineering EconomicsIntroduction to Engineering Economics
Introduction to Engineering Economics
 
Files in C
Files in CFiles in C
Files in C
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and Pointers
 
Decision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, StringsDecision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, Strings
 

Recently uploaded

Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
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
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
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
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
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
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 

Recently uploaded (20)

Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
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
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
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...
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
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
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
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
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
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
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 

JAVA STRING HANDLING

  • 1. Lecture By, Prabu.U Assistant Professor, Department of Computer Science and Engineering. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, V R Siddhartha Engineering College. 20ES3102 – JAVA PROGRAMMING UNIT 2
  • 2. UNIT II: String Handling: The String Constructors, String Buffer Class, String Tokenizer class. Inheritance: Inheritance basics, using super, multilevel hierarchy, method overriding, dynamic method dispatch, using abstract classes, final with inheritance. Packages & Interfaces: Defining a package, finding package and CLASSPATH. Access protection, importing packages, defining an interface, implementing interfaces, nested interfaces, applying interfaces, variables in interfaces. 20ES3102 – JAVA PROGRAMMING
  • 3. 1. The String Constructors 2. String Buffer Class 3. String Tokenizer class STRING HANDLING
  • 4. 1. Inheritance Basics 2. Using super 3. Creating a Multilevel Hierarchy 4. Method Overriding 5. Dynamic Method Dispatch 6. Using Abstract Classes 7. Using final with Inheritance INHERITANCE
  • 5. PACKAGES: 1. Packages 2. Access Protection 3. Importing Packages PACKAGES AND INTERFACES
  • 6. INTERFACES: 4. Defining an Interface 5. Implementing Interfaces 6. Nested Interfaces 7. Applying Interfaces 8. Variables in Interfaces PACKAGES AND INTERFACES
  • 7.
  • 8. 1. The String Constructors 2. String Buffer Class 3. String Tokenizer class STRING HANDLING
  • 9. String Handling  In Java a string is a sequence of characters. But, unlike some other languages that implement strings as character arrays, Java implements strings as objects of type String.  Implementing strings as built-in objects allows Java to provide a full complement of features that make string handling convenient.  For example, Java has methods to compare two strings, search for a substring, concatenate two strings, and change the case of letters within a string.  Also, String objects can be constructed a number of ways, making it easy to obtain a string when needed.
  • 10.  Somewhat unexpectedly, 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. At first, this may seem to be a serious restriction.  However, such is not the case. You can still perform all types of string operations.  The difference is that each time you need an altered version of an existing string, a new String object is created that contains the modifications.
  • 11.  The original string is left unchanged. This approach is used because fixed, immutable strings can be implemented more efficiently than changeable ones.  For those cases in which a modifiable string is desired, 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.
  • 12.  This allows certain optimizations that increase performance to take place on common string operations. All three implement the CharSequence interface.  One last point: To say that the strings within objects of type String are unchangeable means that the contents of the String instance cannot be changed after it has been created.  However, a variable declared as a String reference can be changed to point at some other String object at any time.
  • 13. 1. The String Constructors  The String class supports several constructors. To create an empty String, call the default constructor. For example, String s = new String(); will create an instance of String with no characters in it.  Frequently, you will want to create strings that have initial values.  The String class provides a variety of constructors to handle this. To create a String initialized by an array of characters, use the constructor shown here: String(char chars[ ])
  • 14.  Here is an example: char chars[] = { 'a', 'b', 'c' }; String s = new String(chars);  This constructor initializes s with the string "abc".  You can specify a subrange of a character array as an initializer using the following constructor: String(char chars[ ], int startIndex, int numChars)  Here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of characters to use.
  • 15.  Here is an example: char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; String s = new String(chars, 2, 3);  This initializes s with the characters “cde”.  You can construct a String object that contains the same character sequence as another String object using this constructor: String(String strObj)  Here, strObj is a String object
  • 16. class MakeString { public static void main(String args[]) { char c[] = {'J', 'a', 'v', 'a'}; String s1 = new String(c); String s2 = new String(s1); System.out.println(s1); System.out.println(s2); } } Java Java
  • 17.  Even though Java’s char type uses 16 bits to represent the basic Unicode character set, the typical format for strings on the Internet uses arrays of 8-bit bytes constructed from the ASCII character set.  Because 8-bit ASCII strings are common, the String class provides constructors that initialize a string when given a byte array.  Two forms are shown here: String(byte chrs[ ]) String(byte chrs[ ], int startIndex, int numChars)  Here, chrs specifies the array of bytes. The second form allows you to specify a subrange.  In each of these constructors, the byte-to-character conversion is done by using the default character encoding of the platform.
  • 18. class SubStringCons { public static void main(String args[]) { byte ascii[] = {65, 66, 67, 68, 69, 70 }; String s1 = new String(ascii); System.out.println(s1); String s2 = new String(ascii, 2, 3); System.out.println(s2); } } ABCDEF CDE
  • 19.  Extended versions of the byte-to-string constructors are also defined in which you can specify the character encoding that determines how bytes are converted to characters.  However, you will often want to use the default encoding provided by the platform.  The contents of the array are copied whenever you create a String object from an array.  If you modify the contents of the array after you have created the string, the String will be unchanged.
  • 20.  You can construct a String from a StringBuffer by using the constructor shown here: String(StringBuffer strBufObj)  You can construct a String from a StringBuilder by using this constructor: String(StringBuilder strBuildObj)  The following constructor supports the extended Unicode character set: String(int codePoints[ ], int startIndex, int numChars)  Here, codePoints is an array that contains Unicode code points. The resulting string is constructed from the range that begins at startIndex and runs for numChars.
  • 21. 2. String Buffer Class  StringBuffer supports a modifiable string. As you know, String represents fixed-length, immutable character sequences.  In contrast, StringBuffer represents growable and writable character sequences. StringBuffer may have characters and substrings inserted in the middle or appended to the end.  StringBuffer will automatically grow to make room for such additions and often has more characters pre-allocated than are actually needed, to allow room for growth.
  • 22. StringBuffer Constructors  StringBuffer defines these four constructors: StringBuffer( ) StringBuffer(int size) StringBuffer(String str) StringBuffer(CharSequence chars)  The default constructor (the one with no parameters) reserves room for 16 characters without reallocation.  The second version accepts an integer argument that explicitly sets the size of the buffer.  The third version accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation.
  • 23.  StringBuffer allocates room for 16 additional characters when no specific buffer length is requested, because reallocation is a costly process in terms of time.  Also, frequent reallocations can fragment memory. By allocating room for a few extra characters, StringBuffer reduces the number of reallocations that take place.  The fourth constructor creates an object that contains the character sequence contained in chars and reserves room for 16 more characters.
  • 24. length( ) and capacity( )  The current length of a StringBuffer can be found via the length( ) method, while the total allocated capacity can be found through the capacity( ) method.  They have the following general forms: int length( ) int capacity( )
  • 25. class StringBufferDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("Hello"); System.out.println("buffer = " + sb); System.out.println("length = " + sb.length()); System.out.println("capacity = " + sb.capacity()); } } buffer = Hello length = 5 capacity = 21
  • 26.  The output of this program shows how StringBuffer reserves extra space for additional manipulations.  Since sb is initialized with the string "Hello" when it is created, its length is 5.  Its capacity is 21 because room for 16 additional characters is automatically added.
  • 27. ensureCapacity( )  If you want to preallocate room for a certain number of characters after a StringBuffer has been constructed, you can use ensureCapacity( ) to set the size of the buffer.  This is useful if you know in advance that you will be appending a large number of small strings to a StringBuffer. ensureCapacity( ) has this general form: void ensureCapacity(int minCapacity)  Here, minCapacity specifies the minimum size of the buffer. (A buffer larger than minCapacity may be allocated for reasons of efficiency.)
  • 28. setLength( )  To set the length of the string within a StringBuffer object, use setLength( ). Its general form is shown here: void setLength(int len) Here, len specifies the length of the string. This value must be nonnegative.  When you increase the size of the string, null characters are added to the end.  If you call setLength( ) with a value less than the current value returned by length( ), then the characters stored beyond the new length will be lost.
  • 29. charAt( ) and setCharAt( )  The value of a single character can be obtained from a StringBuffer via the charAt( ) method.  You can set the value of a character within a StringBuffer using setCharAt( ). Their general forms are shown here: char charAt(int where) void setCharAt(int where, char ch)  For charAt( ), where specifies the index of the character being obtained. For setCharAt( ), where specifies the index of the character being set, and ch specifies the new value of that character.  For both methods, where must be nonnegative and must not specify a location beyond the end of the string.
  • 30. class setCharAtDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("Hello"); System.out.println("buffer before = " + sb); System.out.println("charAt(1) before = " + sb.charAt(1)); sb.setCharAt(1, 'i'); sb.setLength(2); System.out.println("buffer after = " + sb); System.out.println("charAt(1) after = " + sb.charAt(1)); } }
  • 31. buffer before = Hello charAt(1) before = e buffer after = Hi charAt(1) after = i
  • 32. getChars( )  To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has this general form: void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)  Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one past the end of the desired substring.  This means that the substring contains the characters from sourceStart through sourceEnd–1.
  • 33.  The array that will receive the characters is specified by target.  The index within target at which the substring will be copied is passed in targetStart.  Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring.
  • 34. insert( )  The insert( ) method inserts one string into another. It is overloaded to accept values of all the primitive types, plus Strings, Objects, and CharSequences.  Like append( ), it obtains the string representation of the value it is called with.  This string is then inserted into the invoking StringBuffer object. These are a few of its forms: StringBuffer insert(int index, String str) StringBuffer insert(int index, char ch) StringBuffer insert(int index, Object obj)
  • 35. Here, index specifies the index at which point the string will be inserted into the invoking StringBuffer object. class InsertDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("I Java!"); sb.insert(2, "like "); System.out.println(sb); } } I like Java!
  • 36. reverse( )  You can reverse the characters within a StringBuffer object using reverse( ), shown here: StringBuffer reverse( )  This method returns the reverse of the object on which it was called.
  • 37. class ReverseDemo { public static void main(String args[]) { StringBuffer s = new StringBuffer("abcdef"); System.out.println(s); s.reverse(); System.out.println(s); } } abcdef fedcba
  • 38. replace( )  You can replace one set of characters with another set inside a StringBuffer object by calling replace( ). Its signature is shown here: StringBuffer replace(int startIndex, int endIndex, String str)  The substring being replaced is specified by the indexes startIndex and endIndex.  Thus, the substring at startIndex through endIndex–1 is replaced.  The replacement string is passed in str. The resulting StringBuffer object is returned.
  • 39. class ReplaceDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("This is a test."); sb.replace(5, 7, "was"); System.out.println("After replace: " + sb); } } After replace: This was a test.
  • 40. 3. String Tokenizer class  The processing of text often consists of parsing a formatted input string.  Parsing is the division of text into a set of discrete parts, or tokens, which in a certain sequence can convey a semantic meaning.  The StringTokenizer class provides the first step in this parsing process, often called the lexer (lexical analyzer) or scanner.  StringTokenizer implements the Enumeration interface. Therefore, given an input string, you can enumerate the individual tokens contained in it using StringTokenizer.
  • 41.  To use StringTokenizer, you specify an input string and a string that contains delimiters.  Delimiters are characters that separate tokens. Each character in the delimiters string is considered a valid delimiter—for example, ",;:" sets the delimiters to a comma, semicolon, and colon.  The default set of delimiters consists of the whitespace characters: space, tab, form feed, newline, and carriage return.
  • 42.  The StringTokenizer constructors are shown here: StringTokenizer(String str) StringTokenizer(String str, String delimiters) StringTokenizer(String str, String delimiters, boolean delimAsToken)  In all versions, str is the string that will be tokenized. In the first version, the default delimiters are used.  In the second and third versions, delimiters is a string that specifies the delimiters.  In the third version, if delimAsToken is true, then the delimiters are also returned as tokens when the string is parsed. Otherwise, the delimiters are not returned. Delimiters are not returned as tokens by the first two forms.
  • 43.  Once you have created a StringTokenizer object, the nextToken( ) method is used to extract consecutive tokens.  The hasMoreTokens( ) method returns true while there are more tokens to be extracted.  Since StringTokenizer implements Enumeration, the hasMoreElements( ) and nextElement( ) methods are also implemented, and they act the same as hasMoreTokens( ) and nextToken( ), respectively.  Here is an example that creates a StringTokenizer to parse "key=value" pairs. Consecutive sets of "key=value" pairs are separated by a semicolon.
  • 44. import java.util.StringTokenizer; class STDemo { static String in = "title=Java: The Complete Reference;" + "author=Schildt;" + "publisher=McGraw-Hill;" + "copyright=2014"; public static void main(String args[]) { StringTokenizer st = new StringTokenizer(in, "=;"); while(st.hasMoreTokens()) { String key = st.nextToken(); String val = st.nextToken(); System.out.println(key + "t" + val); } } }
  • 45. import java.util.StringTokenizer; class STDemo { static String in = "title=Java: The Complete Reference;" + "author=Schildt;" + "publisher=McGraw-Hill;" + "copyright=2014"; public static void main(String args[]) { StringTokenizer st = new StringTokenizer(in, "=;"); while(st.hasMoreTokens()) { String key = st.nextToken(); String val = st.nextToken(); System.out.println(key + "t" + val); } } }
  • 46. 1. Inheritance Basics 2. Using super 3. Creating a Multilevel Hierarchy 4. Method Overriding 5. Dynamic Method Dispatch 6. Using Abstract Classes 7. Using final with Inheritance INHERITANCE
  • 47. Inheritance  In the terminology of Java, a class that is inherited is called a superclass.  The class that does the inheriting is called a subclass.  Therefore, a subclass is a specialized version of a superclass.  It inherits all of the members defined by the superclass and adds its own, unique elements..
  • 48. 1. Inheritance Basics  To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword.  To see how, let’s begin with a short example.  The following program creates a superclass called A and a subclass called B.  Notice how the keyword extends is used to create a subclass of A.
  • 49. // Create a superclass class A { int i, j; void showij() { System.out.println("i and j: " + i + " " + j); } } // Create a subclass by extending class A class B extends A { int k; void showk() { System.out.println("k: " + k); }
  • 50. void sum() { System.out.println("i+j+k: " + (i+j+k)); } } class SimpleInheritance { public static void main(String args []) { A superOb = new A(); B subOb = new B();
  • 51. // The superclass may be used by itself superOb.i = 10; superOb.j = 20; System.out.println("Contents of superOb: "); superOb.showij(); System.out.println(); // The subclass has access to all public members of its superclass subOb.i = 7; subOb.j = 8; subOb.k = 9; System.out.println("Contents of subOb: "); subOb.showij(); subOb.showk(); System.out.println(); System.out.println("Sum of i, j and k in subOb:"); subOb.sum(); } }
  • 52. Contents of superOb: i and j: 10 20 Contents of subOb: i and j: 7 8 k: 9 Sum of i, j and k in subOb: i+j+k: 24  As you can see, the subclass B includes all of the members of its superclass, A.  This is why subOb can access i and j and call showij( ). Also, inside sum( ), i and j can be referred to directly, as if they were part of B.
  • 53. Member Access and Inheritance  Although a subclass includes all of the members of its superclass, it cannot access those members of the superclass that have been declared as private.  For example, consider the following simple class hierarchy:
  • 54. // In a class hierarchy, private members remain private to their class // This program contains an error and will not compile // Create a superclass class A { int i; // public by default private int j; // private to A void setij(int x, int y) { i = x; j = y; } }
  • 55. // A's j is not accessible here class B extends A { int total; void sum() { total = i + j; // ERROR, j is not accessible here } } class Access { public static void main(String args[]) { B subOb = new B(); subOb.setij(10, 12); subOb.sum(); System.out.println("Total is " + subOb.total); } }
  • 56. Access.java:22: error: j has private access in A total = i + j; // ERROR, j is not accessible here ^ 1 error  This program will not compile because the use of j inside the sum( ) method of B causes an access violation.  Since j is declared as private, it is only accessible by other members of its own class.  Subclasses have no access to it.
  • 57. A More Practical Example  Box class developed is extended to include a fourth component called weight.  Thus, the new class will contain a box’s width, height, depth, and weight. class Box { double width; double height; double depth;
  • 58. // construct clone of an object Box(Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; }
  • 59. // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; }
  • 60. // compute and return volume double volume() { return width * height * depth; } } // Here, Box is extended to include weight class BoxWeight extends Box { double weight; // weight of box
  • 61. // constructor for BoxWeight BoxWeight(double w, double h, double d, double m) { width = w; height = h; depth = d; weight = m; } } class DemoBoxWeight { public static void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); double vol;
  • 62. vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println(); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + mybox2.weight); } } Volume of mybox1 is 3000.0 Weight of mybox1 is 34.3 Volume of mybox2 is 24.0 Weight of mybox2 is 0.076
  • 63. 2. Using Super  Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword super.  super has two general forms.  The first calls the superclass’ constructor.  The second is used to access a member of the superclass that has been hidden by a member of a subclass.
  • 64. Using super to Call Superclass Constructors  A subclass can call a constructor defined by its superclass by use of the following form of super: super(arg-list);  Here, arg-list specifies any arguments needed by the constructor in the superclass.  super( ) must always be the first statement executed inside a subclass’ constructor.
  • 65. // BoxWeight now uses super to initialize its Box attributes class BoxWeight extends Box { double weight; // weight of box // initialize width, height, and depth using super() BoxWeight(double w, double h, double d, double m) { super(w, h, d); // call superclass constructor weight = m; } }
  • 66.  In the preceding example, super( ) was called with three arguments. Since constructors can be overloaded, super( ) can be called using any form defined by the superclass.  The constructor executed will be the one that matches the arguments.  For example, here is a complete implementation of BoxWeight that provides constructors for the various ways that a box can be constructed.  In each case, super( ) is called using the appropriate arguments.  Notice that width, height, and depth have been made private within Box.
  • 67. class Box { private double width; private double height; private double depth; // construct clone of an object Box(Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; }
  • 68. // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box }
  • 69. // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } }
  • 70. // BoxWeight now fully implements all constructors class BoxWeight extends Box { double weight; // weight of box // construct clone of an object BoxWeight(BoxWeight ob) { // pass object to constructor super(ob); weight = ob.weight; }
  • 71. // constructor when all parameters are specified BoxWeight(double w, double h, double d, double m) { super(w, h, d); // call superclass constructor weight = m; } // default constructor BoxWeight() { super(); weight = -1; }
  • 72. // constructor used when cube is created BoxWeight(double len, double m) { super(len); weight = m; } } class DemoSuper { public static void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); BoxWeight mybox3 = new BoxWeight(); // default BoxWeight mycube = new BoxWeight(3, 2); BoxWeight myclone = new BoxWeight(mybox1); double vol;
  • 73. vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println(); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + mybox2.weight); System.out.println(); vol = mybox3.volume(); System.out.println("Volume of mybox3 is " + vol); System.out.println("Weight of mybox3 is " + mybox3.weight); System.out.println();
  • 74. vol = myclone.volume(); System.out.println("Volume of myclone is " + vol); System.out.println("Weight of myclone is " + myclone.weight); System.out.println(); vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); System.out.println("Weight of mycube is " + mycube.weight); System.out.println(); } }
  • 75. Volume of mybox1 is 3000.0 Weight of mybox1 is 34.3 Volume of mybox2 is 24.0 Weight of mybox2 is 0.076 Volume of mybox3 is -1.0 Weight of mybox3 is -1.0 Volume of myclone is 3000.0 Weight of myclone is 34.3 Volume of mycube is 27.0 Weight of mycube is 2.0
  • 76.  Notice that super( ) is passed an object of type BoxWeight—not of type Box. This still invokes the constructor Box(Box ob).  As mentioned earlier, a superclass variable can be used to reference any object derived from that class. Thus, we are able to pass a BoxWeight object to the Box constructor. Of course, Box only has knowledge of its own members.  Let’s review the key concepts behind super( ). When a subclass calls super( ), it is calling the constructor of its immediate superclass.  Thus, super( ) always refers to the superclass immediately above the calling class. This is true even in a multileveled hierarchy.  Also, super( ) must always be the first statement executed inside a subclass constructor.
  • 77. A Second Use for super  The second form of super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used.  This usage has the following general form: super.member  Here, member can be either a method or an instance variable.  This second form of super is most applicable to situations in which member names of a subclass hide members by the same name in the superclass.  Consider this simple class hierarchy:
  • 78. // Using super to overcome name hiding class A { int i; } // Create a subclass by extending class A class B extends A { int i; // this i hides the i in A B(int a, int b) { super.i = a; // i in A i = b; // i in B }
  • 79. void show() { System.out.println("i in superclass: " + super.i); System.out.println("i in subclass: " + i); } } class UseSuper { public static void main(String args[]) { B subOb = new B(1, 2); subOb.show(); } } i in superclass: 1 i in subclass: 2
  • 80.  Although the instance variable i in B hides the i in A, super allows access to the i defined in the superclass.  As you will see, super can also be used to call methods that are hidden by a subclass.
  • 82. Single Inheritance class A { public void methodA() { System.out.println("Base or Parent class method"); } } class B extends A { public void methodB() { System.out.println("Derived or Child class method"); } }
  • 83. class SingleIn { public static void main(String args[]) { B obj = new B(); obj.methodA(); //calling super class method obj.methodB(); //calling sub class method } } Base or Parent class method Derived or Child class method
  • 84. Multilevel Inheritance class A { public void methodA() { System.out.println("class A method"); } } class B extends A { public void methodB() { System.out.println("class B method"); } }
  • 85. class C extends B { public void methodC() { System.out.println("class C method"); } } class MultilevelIn { public static void main(String args[]) { C obj = new C(); obj.methodA(); //calling grand parent class method obj.methodB(); //calling parent class method obj.methodC(); //calling child method } } class A method class B method class C method
  • 86. Hierarchical Inheritance class A { void DisplayA() { System.out.println("This is a content of parent class"); } } class B extends A { void DisplayB() { System.out.println("This is a content of child class 1"); } }
  • 87. class C extends A { void DisplayC() { System.out.println("This is a content of child class 2"); } } class HierarchicalIn { public static void main(String args[]) { System.out.println("Calling for child class B"); B b = new B(); b.DisplayA(); b.DisplayB(); System.out.println();
  • 88. System.out.println("Calling for child class C"); C c = new C(); c.DisplayA(); c.DisplayC(); } } Calling for child class B This is a content of parent class This is a content of child class 1 Calling for child class C This is a content of parent class This is a content of child class 2
  • 89. Multiple Inheritance interface A { void displayA(); } interface B { void displayB(); } class C implements A,B { public void displayA() { System.out.println("Interface A : Parent 1"); }
  • 90. public void displayB() { System.out.println("Interface B : Parent 2"); } void displayC() { System.out.println("Class C : Child of Parent1 and Parent 2"); } }
  • 91. class MultipleIn { public static void main(String args[]) { C obj = new C(); obj.displayA(); obj.displayB(); obj.displayC(); } } Interface A : Parent 1 Interface B : Parent 2 Class C : Child of Parent1 and Parent 2
  • 92. 3. Creating Multilevel Hierarchy  It is perfectly acceptable to use a subclass as a superclass of another. For example, given three classes called A, B, and C, C can be a subclass of B, which is a subclass of A.  When this type of situation occurs, each subclass inherits all of the traits found in all of its superclasses. In this case, C inherits all aspects of B and A.  To see how a multilevel hierarchy can be useful, consider the following program. In it, the subclass BoxWeight is used as a superclass to create the subclass called Shipment.  Shipment inherits all of the traits of BoxWeight and Box, and adds a field called cost, which holds the cost of shipping such a parcel.
  • 93. When Constructors Are Executed  When a class hierarchy is created, in what order are the constructors for the classes that make up the hierarchy executed?  For example, given a subclass called B and a superclass called A, is A’s constructor executed before B’s, or vice versa?  The answer is that in a class hierarchy, constructors complete their execution in order of derivation, from superclass to subclass.
  • 94.  Further, since super( ) must be the first statement executed in a subclass constructor, this order is the same whether or not super( ) is used.  If super( ) is not used, then the default or parameterless constructor of each superclass will be executed.
  • 95. 4. Method Overriding  In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass.  When an overridden method is called from within its subclass, it will always refer to the version of that method defined by the subclass.  The version of the method defined by the superclass will be hidden.
  • 96. No. Method Overloading Method Overriding 1 Method overloading is used to increase the readability of the program. Method overriding is used to provide the specific implementation of the method that is already provided by its super class. 2 Method overloading is performed within class. Method overriding occurs in two classes that have IS-A (inheritance) relationship. 3 In case of method overloading, parameter must be different. In case of method overriding, parameter must be same. 4 Method overloading is the example of compile time polymorphism. Method overriding is the example of run time polymorphism. 5 In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter. Return type must be same or covariant in method overriding.
  • 97. Java Method Overloading class OverloadingExample { static int add(int a,int b) { return a+b; } static int add(int a,int b,int c) { return a+b+c; } }
  • 98. Java Method Overriding class Animal { void eat() { System.out.println("eating..."); } } class Dog extends Animal { void eat() { System.out.println("eating bread..."); } }
  • 99. Real example of Java Method Overriding
  • 100. class Bank { int getRateOfInterest() { return 0; } } class SBI extends Bank { int getRateOfInterest() { return 8; } }
  • 101. class ICICI extends Bank { int getRateOfInterest() { return 7; } } class AXIS extends Bank { int getRateOfInterest() { return 9; } }
  • 102. class Test2 { public static void main(String args[]) { SBI s=new SBI(); ICICI i=new ICICI(); AXIS a=new AXIS(); System.out.println("SBI Rate of Interest: "+s.getRateOfInterest()); System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest()); System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest()); } } SBI Rate of Interest: 8 ICICI Rate of Interest: 7 AXIS Rate of Interest: 9
  • 103. 5. Dynamic Method Dispatch  Method overriding forms the basis for one of Java’s most powerful concepts: dynamic method dispatch.  Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time.  Dynamic method dispatch is important because this is how Java implements run-time polymorphism.  A superclass reference variable can refer to a subclass object. Java uses this fact to resolve calls to overridden methods at run time.
  • 104.  When an overridden method is called through a superclass reference, Java determines which version of that method to execute based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time.  When different types of objects are referred to, different versions of an overridden method will be called.  In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed.  Therefore, if a superclass contains a method that is overridden by a subclass, then when different types of objects are referred to through a superclass reference variable, different versions of the method are executed
  • 105. class A { void callme() { System.out.println("Inside A's callme method"); } } class B extends A { // override callme() void callme() { System.out.println("Inside B's callme method"); } }
  • 106. class C extends A { // override callme() void callme() { System.out.println("Inside C's callme method"); } } class Dispatch { public static void main(String args[]) { A a = new A(); // object of type A B b = new B(); // object of type B C c = new C(); // object of type C
  • 107. A r; // obtain a reference of type A r = a; // r refers to an A object r.callme(); // calls A's version of callme r = b; // r refers to a B object r.callme(); // calls B's version of callme r = c; // r refers to a C object r.callme(); // calls C's version of callme } } Inside A's callme method Inside B's callme method Inside C's callme method
  • 108.  This program creates one superclass called A and two subclasses of it, called B and C.  Subclasses B and C override callme( ) declared in A. Inside the main( ) method, objects of type A, B, and C are declared. Also, a reference of type A, called r, is declared.  The program then in turn assigns a reference to each type of object to r and uses that reference to invoke callme( ).  As the output shows, the version of callme( ) executed is determined by the type of object being referred to at the time of the call.  Had it been determined by the type of the reference variable, r, you would see three calls to A’s callme( ) method.
  • 109. class A { void display() { System.out.println("Displaying from class A"); } } class B extends A { public void display() { System.out.println("Displaying from class B"); } }
  • 110. class Dispatch1 { public static void main(String args[]) { A a = new A(); // A reference and object A b = new B(); // A reference but B object a.display(); // runs the method in A class b.display(); // runs the method in B class } } Displaying from class A Displaying from class B
  • 111. class Rectangle { int l=8,b=4; int area; void area() { area=l*b; System.out.println("Area of rectangle: "+area); } } class Square extends Rectangle { void area() //overridden method { area=l*l; System.out.println("Area of square: "+area); } }
  • 112. class Triangle extends Rectangle { void area() //overridden method { area=(b*l)/2; System.out.println("Area of triangle: "+area); } }
  • 113. public class Dispatch2 { public static void main(String args[]) { Rectangle r=new Rectangle(); r.area(); r=new Square(); //Rectange reference but Square object r.area(); r=new Triangle(); //Rectange reference but Triangle object r.area(); } }
  • 114. Area of rectangle: 32 Area of square: 64 Area of triangle: 16
  • 115. 6. Using Abstract Classes  To declare an abstract method, use this general form: abstract type name(parameter-list);  As you can see, no method body is present.  Any class that contains one or more abstract methods must also be declared abstract.  To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration.
  • 116.  There can be no objects of an abstract class.  That is, an abstract class cannot be directly instantiated with the new operator.  Such objects would be useless, because an abstract class is not fully defined.  Also, you cannot declare abstract constructors, or abstract static methods.  Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be declared abstract itself.
  • 117. abstract class Figure { double dim1; double dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } // area is now an abstract method abstract double area(); }
  • 118. class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } // override area for rectangle double area() { System.out.println("Inside Area for Rectangle."); return dim1 * dim2; } }
  • 119. class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } // override area for right triangle double area() { System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2; } }
  • 120. class AbstractAreas { public static void main(String args[]) { // Figure f = new Figure(10, 10); // illegal now Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; // this is OK, no object is created figref = r; System.out.println("Area is " + figref.area()); figref = t; System.out.println("Area is " + figref.area()); } }
  • 121. class AbstractAreas { public static void main(String args[]) { // Figure f = new Figure(10, 10); // illegal now Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; // this is OK, no object is created figref = r; System.out.println("Area is " + figref.area()); figref = t; System.out.println("Area is " + figref.area()); } }
  • 122. Inside Area for Rectangle. Area is 45.0 Inside Area for Triangle. Area is 40.0
  • 123. 7. Using final with Inheritance  The keyword final has three uses.  First, it can be used to create the equivalent of a named constant.  The other two uses of final apply to inheritance.  Using final to Prevent Overriding  Using final to Prevent Inheritance
  • 124. Using final to Prevent Overriding  While method overriding is one of Java’s most powerful features, there will be times when you will want to prevent it from occurring.  To disallow a method from being overridden, specify final as a modifier at the start of its declaration.  Methods declared as final cannot be overridden.
  • 125. class A { final void meth() { System.out.println("This is a final method."); } } class B extends A { void meth() { // ERROR! Can't override. System.out.println("Illegal!"); } }
  • 126. Using final to Prevent Inheritance  Sometimes you will want to prevent a class from being inherited.  To do this, precede the class declaration with final.  Declaring a class as final implicitly declares all of its methods as final, too.  As you might expect, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations.
  • 127. final class A { //... } // The following class is illegal. class B extends A { // ERROR! Can't subclass A //... }  As the comments imply, it is illegal for B to inherit A since A is declared as final.
  • 128. PACKAGES: 1. Packages 2. Access Protection 3. Importing Packages PACKAGES AND INTERFACES
  • 129. INTERFACES: 4. Defining an Interface 5. Implementing Interfaces 6. Nested Interfaces 7. Applying Interfaces 8. Variables in Interfaces PACKAGES AND INTERFACES
  • 130. 1. Packages  The name of each example class was taken from the same name space. This means that a unique name had to be used for each class to avoid name collisions.  After a while, without some way to manage the name space, you could run out of convenient, descriptive names for individual classes.  You also need some way to be assured that the name you choose for a class will be reasonably unique and not collide with class names chosen by other programmers.
  • 131. Defining a Package  To create a package is quite easy: simply include a package command as the first statement in a Java source file.  Any classes declared within that file will belong to the specified package.  The package statement defines a name space in which classes are stored.  If you omit the package statement, the class names are put into the default package, which has no name.
  • 132.  This is the general form of the package statement: package pkg;  Here, pkg is the name of the package. For example, the following statement creates a package called mypack: package mypack;  Java uses file system directories to store packages. For example, the .class files for any classes you declare to be part of mypack must be stored in a directory called mypack.  Remember that case is significant, and the directory name must match the package name exactly.
  • 133.  You can create a hierarchy of packages. To do so, simply separate each package name from the one above it by use of a period.  The general form of a multileveled package statement is shown here: package pkg1[.pkg2[.pkg3]];  A package hierarchy must be reflected in the file system of your Java development system. For example, a package declared as package java.awt.image; needs to be stored in javaawtimage in a Windows environment.  Be sure to choose your package names carefully. You cannot rename a package without renaming the directory in which the classes are stored.
  • 134. Finding Packages and CLASSPATH  As just explained, packages are mirrored by directories. This raises an important question: How does the Java run-time system know where to look for packages that you create?  The answer has three parts.  First, by default, the Java run-time system uses the current working directory as its starting point.  Thus, if your package is in a subdirectory of the current directory, it will be found.
  • 135.  Second, you can specify a directory path or paths by setting the CLASSPATH environmental variable.  Third, you can use the -classpath option with java and javac to specify the path to your classes.  For example, consider the following package specification: package mypack  In order for a program to find MyPack, one of three things must be true.  Either the program can be executed from a directory immediately above myPack, or the CLASSPATH must be set to include the path to mypack, or the -classpath option must specify the path to mypack when the program is run via java.
  • 136.  When the second two options are used, the class path must not include mypack, itself.  It must simply specify the path to mypack. For example, in a Windows environment, if the path to mypack is C:MyProgramsJavamypack then the class path to mypack is C:MyProgramsJava  The easiest way is to simply create the package directories below your current development directory, put the .class files into the appropriate directories, and then execute the programs from the development directory.
  • 137. package mypack; class Balance { String name; double bal; Balance(String n, double b) { name = n; bal = b; } void show() { if(bal<0) System.out.print("--> "); System.out.println(name + ": $" + bal); } }
  • 138. class AccountBalance { public static void main(String args[]) { Balance current[] = new Balance[3]; current[0] = new Balance("K. J. Fielding", 123.23); current[1] = new Balance("Will Tell", 157.02); current[2] = new Balance("Tom Jackson", -12.33); for(int i=0; i<3; i++) current[i].show(); } } K. J. Fielding: $123.23 Will Tell: $157.02 --> Tom Jackson: $-12.33
  • 139.  Compile the file. Make sure that the resulting .class file is also in the mypack directory.  Then, try executing the AccountBalance class, using the following command line: java mypack.AccountBalance  Remember, you will need to be in the directory above mypack when you execute this command.  AccountBalance is now part of the package mypack. This means that it cannot be executed by itself.  That is, you cannot use this command line: java AccountBalance  AccountBalance must be qualified with its package name.
  • 140. Benefits of Packages  In Java, by the use of packages, you can group a number of related classes and/or interfaces together into a single unit.  Prevents name-space collision  Provides greater control over source code  Makes it easy to find a class
  • 141.  These are the benefits of organising classes into packages  It prevents name-space collision  It indicates that the classes and interfaces in the package are related  You know where to find the classes you want if they are in a specific package  It is convenient for organising your work and separating your work from libraries provided by others
  • 142. Using Packages  Use fully qualified name java.util.Date=new java.util.Date();  You can use import to instruct Java where to look for things defined outside your program import java.util.Scanner; Scanner sc=new Scanner(System.in);  You can use * to import all classes in package import java.util.*; Scanner sc=new Scanner(System.in);
  • 143. Types of Packages Predefined Packages  Built-in Packages  They are already defined packages.  Standard packages which come as a part of JRE User defined Packages  Programmer defined packages  Programmer defined packages to bundle group of related classes
  • 144. Foundation Java Packages Package Name Description java.lang Classes that apply to the language itself, which includes the Object class, the String class, the system class and also contains classes for primitive types, strings, math functions, threads, and exception. Classes belonging to java.lang package need not be explicitly imported java.util Utility classes such as Date, as well as collection classes such as Vector and Hashtable java.io Input and output classes for writing to and reading from streams (such as standard input and output) and for handling files java.net Classes for networking support, including Socket and URL (a class to represent references to documents on the www) java.awt Classes for implementing GUI – windows, buttons, menus etc. Java.applet Classes to implement Java applets, including the Applet class itself, as well as the AudioClip interface
  • 145. Static Import  Static import enables programmers to import static members  Class name and a dot(.) are not required to use an imported static member.  Example: we always use sqrt() method of Math class by using Math class i.e. Math.sqrt(), but by using static import we can access sqrt() method directly.
  • 146. //Static Import Example import static java.lang.Math.*; import static java.lang.System.*; class StaticImportTest { public static void main(String[] args) { out.println(sqrt(4)); out.println(pow(2, 2)); out.println(abs(6.3)); } } 2.0 4.0 6.3
  • 147. Packages and Name Space Collision  Namespace collision can be avoided by accessing classes with the same name in multiple packages by their fully qualified name.
  • 148. import pack1.*; import pack2.* pack1.Student stud1; pack2.Student stud2; Teacher teacher1; Courses course1;
  • 149. 2. Access Protection  Classes and packages are both means of encapsulating and containing the name space and scope of variables and methods.  Packages act as containers for classes and other subordinate packages.  Classes act as containers for data and code.  The class is Java’s smallest unit of abstraction.
  • 150.  Because of the interplay between classes and packages, Java addresses four categories of visibility for class members:  Subclasses in the same package  Non-subclasses in the same package  Subclasses in different packages  Classes that are neither in the same package nor subclasses  The three access modifiers, private, public, and protected, provide a variety of ways to produce the many levels of access required by these categories.  While Java’s access control mechanism may seem complicated, we can simplify it as follows.
  • 151.  Anything declared public can be accessed from anywhere.  Anything declared private cannot be seen outside of its class.  When a member does not have an explicit access specification, it is visible to subclasses as well as to other classes in the same package. This is the default access.  If you want to allow an element to be seen outside your current package, but only to classes that subclass your class directly, then declare that element protected.
  • 153.  A non-nested class has only two possible access levels: default and public.  When a class is declared as public, it is accessible by any other code.  If a class has default access, then it can only be accessed by other code within its same package.  When a class is public, it must be the only public class declared in the file, and the file must have the same name as the class.  Refer Programs of packages p1 and p2
  • 154. Compiling and Running the files in p1 package C:UsersPrabuDesktop>javac ./p1/Demo.java C:UsersPrabuDesktop>java p1.Demo Compiling and Running the files in p2 package C:UsersPrabuDesktop>javac ./p2/Demo.java C:UsersPrabuDesktop>java p2.Demo
  • 155. 3. Importing Packages  Java includes the import statement to bring certain classes, or entire packages, into visibility. Once imported, a class can be referred to directly, using only its name.  In a Java source file, import statements occur immediately following the package statement (if it exists) and before any class definitions.  This is the general form of the import statement: import pkg1 [.pkg2].(classname | *);
  • 156.  Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package inside the outer package separated by a dot (.).  There is no practical limit on the depth of a package hierarchy, except that imposed by the file system.  Finally, you specify either an explicit classname or a star (*), which indicates that the Java compiler should import the entire package.  This code fragment shows both forms in use: import java.util.Date; import java.io.*;
  • 157.  All of the standard Java classes included with Java are stored in a package called java.  The basic language functions are stored in a package inside of the java package called java.lang.  Normally, you have to import every package or class that you want to use, but since Java is useless without much of the functionality in java.lang, it is implicitly imported by the compiler for all programs.
  • 158.  It must be emphasized that the import statement is optional. Any place you use a class name, you can use its fully qualified name, which includes its full package hierarchy. For example, this fragment uses an import statement: import java.util.*; class MyDate extends Date { }  The same example without the import statement looks like this: class MyDate extends java.util.Date { }  In this version, Date is fully-qualified.
  • 159.  Example: Refer the programs package: mypack class: Balance directory: Desktop class: TestBalance Compiling the files in mypack package C:UsersPrabuDesktop>javac ./mypack/Balance.java Compiling and running the files in desktop C:UsersPrabuDesktop>javac TestBalance.java C:UsersPrabuDesktop>java TestBalance
  • 160. INTERFACES: 4. Defining an Interface 5. Implementing Interfaces 6. Nested Interfaces 7. Applying Interfaces 8. Variables in Interfaces PACKAGES AND INTERFACES
  • 161. 4. Defining an Interface  Using the keyword interface, you can fully abstract a class’ interface from its implementation.  That is, using interface, you can specify what a class must do, but not how it does it.  Interfaces are syntactically similar to classes, but they lack instance variables, and, as a general rule, their methods are declared without any body.  In practice, this means that you can define interfaces that don’t make assumptions about how they are implemented.  Once it is defined, any number of classes can implement an interface. Also, one class can implement any number of interfaces
  • 162. Defining an Interface An interface is defined much like a class. This is a simplified general form of an interface: access interface name { return-type method-name1(parameter-list); return-type method-name2(parameter-list); type final-varname1 = value; type final-varname2 = value; //... return-type method-nameN(parameter-list); type final-varnameN = value; }
  • 163. Here is an example of an interface definition. It declares a simple interface that contains one method called callback( ) that takes a single integer parameter. interface Callback { void callback(int param); }
  • 164. 5. Implementing Interfaces  Once an interface has been defined, one or more classes can implement that interface.  To implement an interface, include the implements clause in a class definition, and then create the methods required by the interface.  The general form of a class that includes the implements clause looks like this: class classname [extends superclass] [implements interface [,interface...]] { // class-body }
  • 165.  If a class implements more than one interface, the interfaces are separated with a comma.  If a class implements two interfaces that declare the same method, then the same method will be used by clients of either interface.  The methods that implement an interface must be declared public.  Also, the type signature of the implementing method must match exactly the type signature specified in the interface definition.
  • 166.  Here is a small example class that implements the Callback interface shown earlier: class Client implements Callback { // Implement Callback's interface public void callback(int p) { System.out.println("callback called with " + p); } }  Notice that callback( ) is declared using the public access modifier
  • 167.  It is both permissible and common for classes that implement interfaces to define additional members of their own.  For example, the following version of Client implements callback( ) and adds the method nonIfaceMeth( ): class Client implements Callback { // Implement Callback's interface public void callback(int p) { System.out.println("callback called with " + p); } void nonIfaceMeth() { System.out.println("Classes that implement interfaces " + "may also define other members, too."); } }
  • 168. Accessing Implementations Through Interface References  You can declare variables as object references that use an interface rather than a class type.  Any instance of any class that implements the declared interface can be referred to by such a variable.  When you call a method through one of these references, the correct version will be called based on the actual instance of the interface being referred to.  This is one of the key features of interfaces. The method to be executed is looked up dynamically at run time, allowing classes to be created later than the code which calls methods on them.  The calling code can dispatch through an interface without having to know anything about the “callee.”
  • 169.  The following example calls the callback( ) method via an interface reference variable: class TestIface { public static void main(String args[]) { Callback c = new Client(); c.callback(42); } }
  • 170.  Notice that variable c is declared to be of the interface type Callback, yet it was assigned an instance of Client.  Although c can be used to access the callback( ) method, it cannot access any other members of the Client class.  An interface reference variable has knowledge only of the methods declared by its interface declaration.  Thus, c could not be used to access nonIfaceMeth( ) since it is defined by Client but not Callback.
  • 171. 6. Nested Interfaces  An interface can be declared a member of a class or another interface. Such an interface is called a member interface or a nested interface.  A nested interface can be declared as public, private, or protected. This differs from a top-level interface, which must either be declared as public or use the default access level, as previously described.  When a nested interface is used outside of its enclosing scope, it must be qualified by the name of the class or interface of which it is a member.  Thus, outside of the class or interface in which a nested interface is declared, its name must be fully qualified.
  • 172. // This class contains a member interface class A { // this is a nested interface public interface NestedIF { boolean isNotNegative(int x); } } // B implements the nested interface class B implements A.NestedIF { public boolean isNotNegative(int x) { return x < 0 ? false: true; } }
  • 173. class NestedIFDemo { public static void main(String args[]) { // use a nested interface reference A.NestedIF nif = new B(); if(nif.isNotNegative(10)) System.out.println("10 is not negative"); if(nif.isNotNegative(-12)) System.out.println("this won't be displayed"); } } 10 is not negative
  • 174. 7. Applying Interfaces  In Java 9 version, a new feature is added that allows us to declare private methods inside the interface.  The purpose of private method is just to share some task between the non-abstract methods of the interface.  An interface IDemo is created that has a default method and a private method as well. Since private methods are not accessible outside to interface. So, it is called from the default method.
  • 175. interface IDemo { // Default method default void msg() { greet(); } // Private method private void greet() { System.out.println("This is private method"); } }
  • 176. public class Demo implements IDemo { public static void main(String[] args) { Demo d = new Demo(); // calling default method d.msg(); } } This is private method
  • 177. 8. Variables in Interfaces  Interfaces can be used to import shared constants into multiple classes by simply declaring an interface that contains variables that are initialized to the desired values.  When that interface is included in a class (that is, when you “implement” the interface), all of those variable names will be in scope as constants.  If an interface contains no methods, then any class that includes such an interface doesn’t actually implement anything.  It is as if that class were importing the constant fields into the class name space as final variables.
  • 178. import java.util.Random; interface SharedConstants { int NO = 0; int YES = 1; int MAYBE = 2; int LATER = 3; int SOON = 4; int NEVER = 5; } class Question implements SharedConstants { Random rand = new Random();
  • 179. int ask() { int prob = (int) (100 * rand.nextDouble()); if (prob < 30) return NO; else if (prob < 60) return YES; else if (prob < 75) return LATER; else if (prob < 98) return SOON; else return NEVER; } }
  • 180. class AskMe implements SharedConstants { static void answer(int result) { switch(result) { case NO: System.out.println("No"); break; case YES: System.out.println("Yes"); break; case MAYBE: System.out.println("Maybe"); break;
  • 182. public static void main(String args[]) { Question q = new Question(); answer(q.ask()); answer(q.ask()); answer(q.ask()); answer(q.ask()); } } Later Soon No Yes
  • 183. References 1. Herbert Schildt, “Java The Complete Reference”, 9th Edition, McGraw-Hill Education, New Delhi, 2017.