You are on page 1of 16

URR-18 “Write your Roll number”

KAKATIYA INSTITUTE OF TECHNOLOGY & SCIENCE, WARANGAL-506015


(An Autonomous Institute under Kakatiya University, Warangal)
B.Tech. (ECE, ECI & EIE) III-Semester
II-Mid Semester Examination
Course Name: OBJECT ORIENTED PROGRAMMING
Course Code: U18OE303A

Date: 15/12/2020 Note: 1. Answer all the questions.


Time: 2hrs] [Max. Marks: 30

1. Answer the following in brief. M


CD
ar
LL CO
k
*
s
a. Define abstract class?
Answer:
A class which is declared with the abstract keyword is known as an abstract
class in Java. It can have abstract and non-abstract methods (concrete
methods). It needs to be extended to a class to override/implement the
abstract method. 1 R CO3
Points about abstract class
 An abstract class must be declared with an abstract keyword.
 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the
body of the method.
b. Discuss the types of polymorphism.
Answer:
The word polymorphism means having many forms. In simple words, we U-
can define polymorphism as the ability of a message to be displayed in more
than one form. 1 CP CO3
There are two types of polymorphism in java: 2
1) Static Polymorphism also known as compile time polymorphism
Example: Overloading
2) Dynamic Polymorphism also known as runtime polymorphism
Example: Overriding
c. Explai Java API
Answer:
Java application programming interface (API) is a list of all classes that are
part of the Java development kit (JDK). It includes all Java packages, classes,
and interfaces, along with their methods, fields, and constructors. These
prewritten classes provide a tremendous amount of functionality to a 1 U CO3
programmer. A programmer should be aware of
these classes and should know how to use them.
d. Draw the Exception hierarchy in java.
Answer:

R-
1 CR CO4
P2

e. Discuss join method in String class?


Answer:
The java.lang.string.join() method concatenates the given elements with the
delimiter and returns the concatenated string. The join() method is included
in java string since JDK 1.8.
Syntax of join method is
public static String join(CharSequence deli, CharSequence... ele)
1 U CO4
Example:
String str = String.join(" < ", "Four", "Five", "Six", "Seven");
System.out.println(str);

Output will be: Four < Five < Six < Seven

f Define Stream and explain the input stream classes.


Answer:
A stream is a flow of data or a stream is a path along which the data flows.
Every stream has a source and a destination. We can build a complex file 1 U CO4
processing sequence using a series of simple stream operations. Two
fundamental types of streams are Output Stream (Writing
streams) and InputStream(Reading streams).
While an Output streams writes data into a source(file) , an Input streams is
used to read data from a source(file).
2. a. Explain method overloading with suitable example.
Answer:
Method Overloading is a feature that allows a class to have more than one
method having the same method name, with different signatures.

In order to overload a method, the argument lists of the methods must


differ in either of these:
1. Number of parameters.
2. Type of parameters.
3. Sequence of parameters.

Example program:
class DisplayOverloading
{
public void display(char ch)
{
System.out.println("Displaying a character ch="+ch);
4 U CO3
}
public void display(int num, char ch)
{
System.out.println("Displaying int and char => "+num+","+ch );
}
public void display(char ch, int num)
{
System.out.println("Displaying char and int => "+ch+","+num );
}

}
class OverloadingDemo
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.display('K');
obj.display(2, 'R');
obj.display('S',1);
}
}

Output:
Displaying a character ch=K
Displaying int and char => 2,R
Displaying char and int => S,1
b. Write a java program to demonstrate an interface with suitable example.
Answer:
interface Shape
{
void area();
}
class Rectangle implements Shape
{
int l,b;
Rectangle(int l,int b)
{
this.l=l;
this.b=b;
}
public void display()
{
System.out.println("length="+l+
", Breadth="+b); 4 Ap CO3
}
public void area()
{
System.out.println("Rectangle Area="+(l*b));
}
}

class InterfaceDemonsration {
public static void main(String args[])
{
Rectangle robj=new Rectangle(32,11);
robj.display();
robj.area();
}
}
Output:
length=32, Breadth=11
Rectangle Area= 352
(OR)
c. Describe the process of creating and accessing of classes in a package
Answer:
Important points while creating a package
 Package statement must be first statement in the program even
before the import statement.
 A package is always defined as a separate folder having the same
name as the package name.
 Store all the classes in that package folder.
 All classes of the package which we wish to access outside the
package must be declared public.
 All classes within the package must have the package statement as
its first line.
 All classes of the package must be compiled before use.
 A class which uses the class/interface of a package should import
the class in either of the following ways.
 import packagename.ClassName;
or
 import packagename.*;
 A class can even use the class/interface of a package without
import statement i.e using fully qualified name of the class using
package name.

Method-1: Execution of packages


1. Compile all Package files one by one with the following command
javac -d . ClasssName1.java
javac -d . ClassName2.java

Note--- if u want to compile all package classes at ones


javac -d . *.java 4 U CO3
2.Compile the MainClass.java which is using package Class
javac MainClass.java

3. Execute MainClass.java
java MainClass
--
Method-2: Execution of packages
1. Create a folder with package name
Syntax: md packageName
Ex: md mypack
2. Copy all packageFile.java to the packageFolder
Move to the package folder and compile the java program
cd mypack
javac packageFile.java
4. Moving/changing to the parent directory
cd ..
Note: Here " .."( double dot) indicates parent directory
5. Compile the MainClass.java which is using the classs of a package
javac MainClass.java
6. Execute MainClass.java
java MainClass

Note: If the package itself contains MainClass then we can follow the following
steps
javac -d . packageFile.java
java packagename.ClassName
d. Write a java program to demonstrate dynamic method dispatch.
Answer:
Definition of Dynamic method dispatch: Dynamic method dispatch is
the mechanism by which a call to an overridden method will be resolved
at run-time rather than at compile time.

class Figure
{
double dim1;
double dim2;
Figure(double a, double b)
{
dim1 = a;
dim2 = b;
}
double area()
{
System.out.println("Area for Figure is undefined.");
return 0;
}
}

class Rectangle extends Figure


{
//here we need not to declare variables for Rectangle.
//because we can use the variables declared in super class.
Rectangle(double a, double b)
{ 4 Ap CO3
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 DMD_Demo
{
public static void main(String args[])
{
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);

Figure figref; //super class reference variable.

figref = f;
System.out.println("Area is " + figref.area());
System.out.println("-------------------------");

figref = r;
System.out.println("Area is " + figref.area());
System.out.println("-------------------------");

figref = t;
System.out.println("Area is " + figref.area());
}
}

Output:
Area for Figure is undefined.
Area is 0.0
-------------------------
Inside Area for Rectangle.
Area is 45.0
-------------------------
Inside Area for Triangle.
Area is 40.0

3. a. Describe try, catch and finally blocks.


Answer:
 Java try, catch and finally blocks helps in writing the application code
which may throw exceptions in runtime and gives us a chance to either
recover from exception by executing alternate application logic
or handle the exception gracefully to report back to the user. Exception
handling helps in preventing abnormal termination of the programs.
Flow of control in try/catch/finally blocks:
 If exception occurs in try block’s body then control immediately
transferred (skipping rest of the statements in try block) to the catch block.
Once catch block finished execution then finally block will be executed 4 U CO4
and that after rest of the program will be executed.
 If there is no exception occurred in the code which is present in try
block then first, the try block gets executed completely and then control
gets transferred to finally block (skipping catch blocks).
 If a return statement is encountered either in try or catch block. In this
case finally block runs. Control first jumps to finally and then it
returned back to return statement.
Syntax :

try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb1)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb2)
{
// exception handler for ExceptionType2
}
// ...
.
.
.
finally
{
// block of code to be executed before try block ends
}

b. Write a java program to create a file using byte stream classes


Answer:
import java.io.*;
import java.util.Scanner;
class CreateFileFOS
{
public static void main(String args[]) throws IOException
{
String fileName="";
FileOutputStream fout=null;
Scanner sobj=null;
try
{
sobj=new Scanner(System.in);

System.out.println("Enter the file name:");


fileName=sobj.nextLine();
4 Ap CO4
fout= new FileOutputStream(fileName);

// If u want to create a file object in append mode


//fout = new FileOutputStream("myfile.txt",true);

System.out.println("enter text(To stop give '@'):");


char ch;
while((ch=(char)System.in.read())!='@')
{
fout.write(ch);
}

System.out.println("Given file:"+fileName+
" is created successfully.");
}
catch(FileNotFoundException e)
{
System.out.println("Exception caught- File Unable to create");
System.out.println("Exception details:"+e);
}
catch(Exception e)
{
System.out.println("Exception caught:"+e);
}
finally
{
if(fout!=null)
fout.close();
if(sobj!=null)
sobj.close();
}
}
}
(OR)
c. Explain reading and writing using character stream classes.
Answer:
Character Streams − These handle data in 16-bit Unicode. Using these you
can read and write text data only.
The Reader and Writer classes (abstract classes) are the super classes of all
the character stream classes: classes that are used to read/write character
streams. Following are the character array stream classes provided by Java

Reader Writer
BufferedReader BufferedWriter
CharacterArrayReader CharacterArrayWriter
StringReader StringWriter
InputStreamReader OutputStreamWriter
FileReader FileWriter

FileReader : This class is used to read the data from the file.
BufferedReader: This class is a buffered version of FileReader, using the
method readLine() in BufferedReader we can read a line of text from the 4 U CO4
file. This is also used to read the characters from a specific stream.
CharacterArrayReader: This class is used to read the characters from the
character array.
StringReader: This class is used to read the data from the String object
InputSreamReader: An InputStreamReader is a bridge from byte streams
to character streams: It reads bytes and decodes them into characters using
a specified charset .

FileWriter: This class is used to write the data to the file.


BufferedWriter: This class is a buffered version of FileWriter. This is also
used to write the characters to a specific stream.
CharacterArrayWriter: This class is used to write the characters to the
character array.
StringWriter: This class is used to write the data to the String object
OutputSreamWriter: OutputStreamWriter is a class which is used to
convert character stream to byte stream, the characters are encoded into
byte using a specified charset. write() method calls the encoding converter
which converts the character into bytes.
d. Write a java program to demonstrate string comparison & Character
extraction operations with suitable example.
Answer:
String Comparison:
There are three ways to compare string in java:
1. By equals() method
2. By = = operator
3. By compareTo() method
1) String compare by equals() method
The String equals() method compares the original content of the string.
It compares values of string for equality. String class provides two
methods:
o public boolean equals(Object another) compares this string to
the specified object.
o public boolean equalsIgnoreCase(String another) compares this
String to another string, ignoring case.

2) String compare by == operator


The = = operator compares references not values.

3) String compare by compareTo() method


The String compareTo() method compares values lexicographically and
returns an integer value that describes if first string is less than, equal to
or greater than second string.
Suppose s1 and s2 are two string variables. If:
s1 == s2 : 0 (zero)
s1 > s2 :positive value 4 Ap CO4
s1 < s2 :negative value
There are two types of compareTo()
1. public int compareTo(String anotherString)
2. public int compareToIgnoreCase(String anotherString)

String Character Extraction Methods


1. charAt()
To extract a single character from a String, we can refer directly to
an individual character via the charAt( ) method
public char charAt(int index)

2. getChars()
If we need to extract more than one character at a time, you can
use the getChars( ) method
public void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

3. getBytes()
This method converts the characters in string to byte array
byte[] getBytes();

4. toCharArray()
This method converts this string to a new character array.
char[] toCharArray()
Example on String Comparsion:
public class StringCompareDemo{
public static void main(String args[]){
String s1 = "Hello";
String s2 = "java";
String s3 = new String("java");
String s4="Hello";
String s5="JAVA";

System.out.println("s1="+s1);
System.out.println("s2="+s2);
System.out.println("s3="+s3);
System.out.println("s4="+s4);
System.out.println("s5="+s5);
System.out.println();

if(s1==s4)
System.out.println("s1==s4");
else
System.out.println("s1!=s4");

if(s2==s3)
System.out.println("s2==s3");
else
System.out.println("s2!=s3");

if(s2.equals(s3))
System.out.println("s2 & s3 contains same content");
else
System.out.println("s2 & s3 contains different content");

if(s2.equalsIgnoreCase(s5))
System.out.println("s2 &s5 contains same content-Ignoring the case");
else
System.out.println("s2 &s3 contains different content");

System.out.println("s1.compareTo(s2)="+
s1.compareTo(s2));

System.out.println("s2.compareTo(s3)="+
s2.compareTo(s3));

System.out.println("s2.compareTo(s5)="+
s2.compareTo(s5));

System.out.println("s2.compareToIgnorecase(s5)="+
s2.compareToIgnoreCase(s5));
}
}
Output:
s1=Hello
s2=java
s3=java
s4=Hello
s5=JAVA
s1==s4
s2!=s3
s2 & s3 contains same content
s2 &s5 contains same content-Ignoring the case
s1.compareTo(s2)=-34
s2.compareTo(s3)=0
s2.compareTo(s5)=32
s2.compareToIgnorecase(s5)=0

Example on String Extraction:

public class StringExtractionDemo{


public static void main(String args[]){
String s1 = "ABCDToJAVA";
System.out.println("s1="+s1);

char ch=s1.charAt(4);
System.out.println("\ns1.charAt(4)="+ch);

System.out.println("\nChars from 6 to 9");


char chArray[]=new char[4];
s1.getChars(6,s1.length(),chArray,0);
for(char cv:chArray)
System.out.println(cv);

System.out.println("\nChars from 0 to 4 in bytes");


String subStr=s1.substring(0,4);
byte bArray[]=subStr.getBytes();
for(byte bv:bArray)
System.out.println(bv);

System.out.println("String to char array:");


char characters[]=s1.toCharArray();
for(char cv:characters)
System.out.print(cv+" ");
}
}

Output:
s1=ABCDToJAVA

s1.charAt(4)=T

Chars from 6 to 9
J
A
V
A

Chars from 0 to 4 in bytes


65
66
67
68
String to char array:
ABCDToJAVA
4. a. Justify, how an ambiguity to call the method in multiple inheritance is res
olved by using interface in java.
Answer:
Multiple Inheritance is a feature of object-oriented concept, where a
class can inherit properties of more than one parent class. The problem occ
urs when there exist methods with same signature in both the super classe
s. On calling the method, the compiler cannot determine which class meth
od to be called so generates a compile time error.

This problem can be solved with the help of interfaces as interface will gen
erally have function declarations

Example:
interface Address
{
void printAddress();
}
interface MyMath
{
void add(int a,int b);
}

class SingleClass implements Address, MyMath


{
public void printAddress()
{
System.out.println("My House is located at Hanamkonda");
}
public void add(int a,int b) 4 E CO3
{
System.out.println("Addition of("+a+"+"+b+")="+(a+b));
}
public void nonInterfaceMethod()
{
System.out.println("Concrete methods of SingleClass"+
", not an interface method");
}

}
public class MultipleInterfacesInSingleClass
{
public static void main(String s[])
{
SingleClass obj=new SingleClass();
obj.printAddress();
obj.add(3,2);
obj.nonInterfaceMethod();

System.out.println("---------------------------");

System.out.println("Address ref is now pointing to"


+"implementation class object");
}
}
b. Differentiate throw and throws keywords with suitable example.
Answer:

4 An CO4

Example program:
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
throwOne();
}
catch(IllegalAccessException e)
{
System.out.println("caught " +e);
}
}
}

(OR)
c. Justify the uses of interfaces over abstract classes.
Answer:
Interface solves multiple inheritance problem compared to abstract class
and the other differences on interfaces over abstract class are as follow.

Abstract class Interface

1) Abstract class can have Interface can have only


abstract and non- abstract methods. Since Java 8, it
abstract methods. can have default and static
methods also.

2) Abstract class doesn't Interface supports multiple


support multiple inheritance. inheritance.

3) Abstract class can have Interface has only static and


final, non-final, static and final variables.
non-static variables.

4) Abstract class can provide Interface can't provide the


the implementation of implementation of abstract
interface. class.

5) The abstract keyword is The interface keyword is used


4 E CO3
used to declare abstract class. to declare interface.

6) An abstract class can An interface can extend another


extend another Java class and Java interface only.
implement multiple Java
interfaces.

7) An abstract class can be An interface can be


extended using keyword implemented using keyword
"extends". "implements".

8) A Java abstract class can Members of a Java interface are


have class members like public by default.
private, protected, etc.

9)Example: Example:
public abstract class Shape public interface Drawable
{ {
public abstract void draw(); void draw();
} }
d. Discriminate string searching methods.
Answer:
Following are the different methods used in string searching methods.
int indexOf(int ch)
int lastIndexOf(int ch)

int indexOf(String str)


int lastIndexOf(String str)

int indexOf(int ch, int startIndex)


int lastIndexOf(int ch, int startIndex)

int indexOf(String str, int startIndex)


int lastIndexOf(String str, int startIndex)
=================================
Example program on indexOf() and lastIndexOf().

class indexOfDemo {
public static void main(String args[]) {
String s = "Now is the time for all good men " +
"to come to the aid of their country.";
System.out.println(s); 4 An CO4
System.out.println("indexOf(t) = " + s.indexOf('t'));
System.out.println("lastIndexOf(t) = " + s.lastIndexOf('t'));
System.out.println("indexOf(the) = " + s.indexOf("the"));
System.out.println("lastIndexOf(the) = " + s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " + s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " + s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " + s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " + s.lastIndexOf("the", 60));
}
}

Here is the output of this program:


Now is the time for all good men to come to the aid of their
country.
indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55

---Question Paper Ends---


Question Paper Set by: Dr.V. Chandra Shekhar Rao , Sri. I. Sai Rama Krishna,
Sri. B.Sridhra Murthy , Dr. Kumar Dorthi, Sri. K. Johnson

You might also like