[Go to site: main page, start]

0% found this document useful (0 votes)
4 views15 pages

Java

The document provides an overview of the StringTokenizer class in Java, detailing its methods, constructors, and examples of tokenizing strings. It also introduces dynamic polymorphism and interfaces, explaining method overriding and providing examples of how dynamic method dispatch works in Java. Additionally, it includes practice and viva questions related to the concepts discussed.

Uploaded by

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

Java

The document provides an overview of the StringTokenizer class in Java, detailing its methods, constructors, and examples of tokenizing strings. It also introduces dynamic polymorphism and interfaces, explaining method overriding and providing examples of how dynamic method dispatch works in Java. Additionally, it includes practice and viva questions related to the concepts discussed.

Uploaded by

vipvinaytanwar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

EXPERIMENT- 2

Aim :- Write a program to produce tokens from a given string .


Theory :-
StringTokenizer:
The StringTokenizer class helps us split Strings into multiple tokens.
StreamTokenizer provides similar functionality but the tokenization method of StringTokenizer is much
simpler than the one used by the StreamTokenizer class. Methods of StringTokenizer do not distinguish
among identifiers, numbers, and quoted strings, nor recognize and skip comments.
The [Link] class allows you to break a String into tokens. It is simple way to break a
String. It is a legacy class of Java. It doesn't provide the facility to differentiate numbers, quoted strings,
identifiers etc. like StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O
chapter.
The set of delimiters (the characters that separate tokens) may be specified either at the creation time or
on a per-token basis.

Constructors of the StringTokenizer Class :-

There are 3 constructors defined in the StringTokenizer class.

21
Methods of the StringTokenizer Class

The six useful methods of the StringTokenizer class are as follows:

Example of StringTokenizer Class

Let's see an example of the StringTokenizer class that tokenizes a string "my name is khan" on the basis of
whitespace.

[Link]

import [Link];

public class Simple{

public static void main(String args[]){

StringTokenizer st = new StringTokenizer("my name is khan"," ");

while ([Link]()) {

[Link]([Link]());

} } }

The above Java code, demonstrates the use of StringTokenizer class and its methods hasMoreTokens() and
nextToken().

Example of nextToken(String delim) method of the StringTokenizer class

[Link]

import [Link].*;

public class Test {

public static void main(String[] args)

22
StringTokenizer st = new StringTokenizer("my,name,is,khan");

// printing next token

[Link]("Next token is : " + [Link](","));

Output:

Note: The StringTokenizer class is deprecated now. It is recommended to use the split() method of the String
class or the Pattern class that belongs to the [Link] package.

Example of hasMoreTokens() method of the StringTokenizer class

This method returns true if more tokens are available in the tokenizer String otherwise returns false.

[Link]
import [Link];

public class StringTokenizer1

/* Driver Code */

public static void main(String args[])

/* StringTokenizer object */

StringTokenizer st = new StringTokenizer("Demonstrating methods from StringTokenizer class"," ");

/* Checks if the String has any more tokens */

while ([Link]())

[Link]([Link]());

} } }

Output:-

The above Java program shows the use of two methods hasMoreTokens() and nextToken() of StringTokenizer
class.

Example of hasMoreElements() method of the StringTokenizer class

23
This method returns the same value as hasMoreTokens() method of StringTokenizer class. The only
difference is this class can implement the Enumeration interface.
[Link]
import [Link];
public class StringTokenizer2
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer("Hello everyone I am a Java developer"," ");
while ([Link]())
{
[Link]([Link]());
}
}
}
Output:

The above code demonstrates the use of hasMoreElements() method.


Example of nextElement() method of the StringTokenizer class
nextElement() returns the next token object in the tokenizer String. It can implement Enumeration
interface.
[Link]
import [Link];
public class StringTokenizer3
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Hello Everyone Have a nice day"," ");
/* Checks if the String has any more tokens */
while ([Link]())
{
/* Prints the elements from the String */
[Link]([Link]());
}
}
}

24
OUTPUT

The above code demonstrates the use of nextElement() method.


Example of countTokens() method of the StringTokenizer class
This method calculates the number of tokens present in the tokenizer String.
[Link]
import [Link];
public class StringTokenizer3
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Hello Everyone Have a nice day"," ");
/* Prints the number of tokens present in the String */
[Link]("Total number of Tokens: "+[Link]());
}
}

OUTPUT

The above Java code demonstrates the countTokens() method of StringTokenizer() class.

PRACTICE QUESTIONS

Q1. Java Program to check whether two Strings are anagram or not.

Q2. Java program to find the percentage of uppercase, lowercase, digits and special characters in a
String

Q3. Write a java program reverse tOGGLE each word in string?

Viva Questions :-
Q1. What is the difference between equals() method and == operator?

Q2. Is String class final?

25
Q3. What is the difference between String and StringBuffer in java?

Q4. What is the difference between StringBuffer and StringBuilder in java?

Q5. What does intern() method in java

26
EXPERIMENT-3
Aim:-Write a java package to show dynamic polymorphism and interfaces.
Theory:- In Java, polymorphism is a concept of object-oriented programming that allows us to perform
a single action in different forms. The word polymorphism is a combination of two words i.e. ploy and
morphs. The word poly means many and morphs means different forms. In short, a mechanism by which
we can perform a single action in different ways.
There are two types of polymorphism in Java:
1. Static Polymorphism (Compile Time Polymorphism)
2. Dynamic Polymorphism (Run Time Polymorphism)

Fig 3.1 Polymorphism types in Java


Dynamic Polymorphism - Dynamic polymorphism is a process or mechanism in which a call to an
overridden method is to resolve at runtime rather than compile-time. It is also known as runtime
polymorphism or dynamic method dispatch. Dynamic polymorphism can be achieved by using the
method overriding.
In this process, an overridden method is called through a reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.
Method overriding is one of the ways in which Java supports Runtime Polymorphism.
Properties of Dynamic Polymorphism
1. It decides which method is to execute at runtime.
2. It can be achieved through dynamic binding.
3. It happens between different classes.
4. It is required where a subclass object is assigned to a super-class object for dynamic
polymorphism.
5. Inheritance involved in dynamic polymorphism.
Method Overriding
It provides a specific implementation to a method that is already present in the parent class. It is used
to achieve run-time polymorphism. Remember that, it is not possible to override the static method.
Hence, we cannot override the main() method also because it is a static method.

27
Rules for Method Overriding
The name of the method must be the same as the name of the parent class method.
The number of parameters and the types of parameters must be the same as in the parent class.
There must exist an IS-A relationship (inheritance).
We call an overridden method through a reference of the parent class. The type of object decides which
method is to be executed and it is decided by the JVM at runtime.
Dynamic Method Dispatch is the mechanism by which a call to an overridden method is resolved at
run time, rather than compile time.
When an overridden method is called through a superclass reference, Java determines which
version(superclass/subclasses) of that method is to be executed based upon the type of the object being
referred to at the time the call occurs. Thus, this determination is made at run time.
At run-time, it depends on the type of object being referred to (not the type of the reference variable)
that determines which version of an overridden method will be executed.
A superclass reference variable can refer to a subclass object. This is also known as upcasting. Java uses
this fact to resolve calls to overridden methods at run time.

Fig.3.2- Upcasting in Java


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.
Here is an example that illustrates Dynamic Method Dispatch:
// A Java program to illustrate Dynamic Method Dispatch using hierarchical inheritance
class A
{ void m1()
{
[Link]("Inside A's m1 method");
}

28
}
class B extends A
{ // overriding m1()
void m1()
{ [Link]("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
[Link]("Inside C's m1 method");
}
}
// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
// obtain a reference of type A
A ref;
// ref refers to an A object
ref = a;
// calling A's version of m1()
ref.m1();

29
// now ref refers to a B object
ref = b;
// calling B's version of m1()
ref.m1();
// now ref refers to a C object
ref = c;
// calling C's version of m1()
ref.m1();
}
}
Explanation :
The above program creates one superclass called A and it’s two subclasses B and C. These subclasses
overrides m1( ) method.
Inside the main() method in Dispatch class, initially objects of type A, B, and C are declared.
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C

Now a reference of type A, called ref, is also declared, initially it will point to null.
A ref; // obtain a reference of type A
Now we are assigning a reference to each type of object (either A’s or B’s or C’s) to ref, one-by-
one, and uses that reference to invoke m1( ). As the output shows, the version of m1( ) executed is
determined by the type of object being referred to at the time of the call.
ref = a; // r refers to an A object
ref.m1(); // calling A's version of m1()

30
ref = b; // now r refers to a B object
ref.m1(); // calling B's version of m1()

ref = c; // now r refers to a C object


ref.m1(); // calling C's version of m1()

In the following example, we have created two classes named Sample and Demo. The Sample class is
a parent class and the Demo class is a child or derived class. The child class is overriding the dispaly()
method of the parent [Link] have assigned the child class object to the parent class reference. So, in
order to determine which method would be called, the type of object would be decided by the JVM at
run-time. It is the type of object that determines which version of the method would be called (not the
type of reference).
[Link]

31
//parent class
class Sample
{
//method of the parent class
public void display()
{
[Link]("Overridden Method");
}
}
//derived or child class
public class Demo extends Sample
{
//method of child class
public void display()
{
[Link]("Overriding Method");
}
public static void main(String args[])
{
//assigning a child class object to parent class reference
Sample obj = new Demo();
//invoking display() method
[Link]();
}
}

Example 3- Example of Method Overriding


public class DynamicPolymorphismExample

32
{
public static void main(String args[])
{
//assigning a child class object to a parent class reference
Fruits fruits = new Mango();
//invoking the method
[Link]();
}
}
//parent class
class Fruits
{
public void color()
{
[Link]("Parent class method is invoked.");
}
}
//derived or child class that extends the parent class
class Mango extends Fruits
{
//overrides the color() method of the parent class
@Override
public void color()
{
[Link]("The child class method is invoked.");
}
}

33
In the above example, we have used an annotation @Override. It indicates that the child class method
is over-writing its base class method.
INTERFACES
Interfaces are very similar to classes. They have variables and methods but the interfaces allow only
abstract methods(that don’t contain the body of the methods).
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the
Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
In other words, interfaces can have abstract methods and variables. It cannot have a method body.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
Since Java 8, we can have default and static methods in an interface.
Since Java 9, we can have private methods in an interface.
An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final
by default. A class that implements an interface must implement all the methods declared in the
interface.
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}

PRACTICE QUESTIONS-
Q1. Write a program to show interface inheritance .
Q2. Write a program to showcase the implementation of super keyword .

VIVA QUESTIONS
Q1. Why use Java interface?

Q2. How static binding and dynamic binding differ ?

34
Q3. Can we override a super class method without throws clause as a method with throws
clause in the sub class?

Q4. How do you refer super class version of overridden method in the sub class?

Q5. Can we override private methods?

35

You might also like