Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Java Programming 2021

Department of Computer Applications


Java Programming- 5 BCA B
Important Questions with answers

Each Question carries 5 marks:

1. Explain the features of Java.

Vasantha,Presidency College Page 1


Java Programming 2021

Vasantha,Presidency College Page 2


Java Programming 2021

2. Explain static variables and static methods with examples.

The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to
the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

Static variable: If you declare any variable as static, it is known as a static variable.

o The static variable gets memory only once in the class area at the time of class
loading.

//Java Program to demonstrate the use of static variable

class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){

Vasantha,Presidency College Page 3


Java Programming 2021

Student s1 = new Student(111,"Karan");


Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}

Output:

111 Karan ITS


222 Aryan ITS

Advantages of static variable


It makes your program memory efficient (i.e., it saves memory).

2. Java static method:

 If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 A static method can access static data member and can change the value of it.

Example:

Vasantha,Presidency College Page 4


Java Programming 2021

class Student{
int rollno;
String name;
static String college = "ITS";

//static method to change the value of static variable


static void change(){
college = "BBDIT";
}
}

public class TestStaticMethod{


public static void main(String args[]){
Student.change();//calling change method
}

3. Differentiate between Method overloading and method overriding

OR explain method overloading/method overriding with a program.

Differences between Method overloading and method overriding:

Vasantha,Presidency College Page 5


Java Programming 2021

Explain method overloading with a program.

If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

Vasantha,Presidency College Page 6


Java Programming 2021

1.By changing number of arguments

2.By changing the data type

//Write a program to find area of geometrical figures using method

import java.io.*;

import java.util.Scanner;

class lab5geo

float areasq,arearect,areacir;

void area(int side)

areasq=side*side;

System.out.println("The area of square is:"+areasq);

void area(float length,float breadth)

arearect=length*breadth;

System.out.println("The area of rectangle is :"+arearect);

void area (float radius)

areacir=3.14f*radius*radius;

System.out.println("The area of circle is:"+areacir);

public static void main(String args[])

Vasantha,Presidency College Page 7


Java Programming 2021

Scanner input = new Scanner(System.in);

lab5geo obj=new lab5geo();// creating object

System.out.println("enter side of a square");

int side = input.nextInt();

obj.area(side);// calling method

System.out.println("enter length and bredth of a rectangle");

float L = input.nextFloat();

float B = input.nextFloat();

obj.area(L,B);

System.out.println("enter radius of a circle");

float rad = input.nextFloat();

obj.area(rad);

} //end public

}//end class

Explain method overriding with a program.

 If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.

Rules for Java Method Overriding

1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Example:

class Vehicle{

Vasantha,Presidency College Page 8


Java Programming 2021

//defining a method

void run()

System.out.println("Vehicle is running");}

//Creating a child class

class Bike2 extends Vehicle{

//defining the same method as in the parent class

void run()

System.out.println("Bike is running safely");

public static void main(String args[])

Bike2 obj = new Bike2();//creating object

obj.run();//calling method

Output:

Bike is running safely

4. What is Inheritance? Explain any three types with an example.

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Vasantha,Presidency College Page 9


Java Programming 2021

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.

Types of inheritance in java

Vasantha,Presidency College Page 10


Java Programming 2021

Single Inheritance
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}

Output:

barking...
eating...

Vasantha,Presidency College Page 11


Java Programming 2021

Multilevel Inheritance
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output:

weeping...
barking...
eating...

Hierarchical Inheritance
When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.

class Animal{

void eat(){System.out.println("eating...");}

Vasantha,Presidency College Page 12


Java Programming 2021

class Dog extends Animal{

void bark(){System.out.println("barking...");}

class Cat extends Animal{

void meow(){System.out.println("meowing...");}

class TestInheritance3{

public static void main(String args[]){

Cat c=new Cat();

c.meow();

c.eat();

//c.bark();//C.T.Error

}}

Output:

meowing...
eating...

5. What is String? Explain string methods with an example.

In Java, string is basically an object that represents sequence of char values.

Example:

char[] ch={'j','a','v','a','t','p','o','i','n','t'};

String s=new String(ch);

is same as:

String s="javatpoint";

Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.

Vasantha,Presidency College Page 13


Java Programming 2021

Example:

import java.io.*;
class lab3
{
public static void main(String arg[])
{
String s1 = "COMPUTER SCIENCE";
String s2 = "COMPUTER SCIENCE";
System.out.println("First String is:" +s1);
System.out.println("Second String is:" +s2);
System.out.println("String converted into lowercase:" +s1.toLowerCase());
System.out.println("String converted into uppercase:"+s2.toUpperCase());
System.out.println("Substring is:"+s1.substring(4,5));
System.out.println("String length:"+s1.length());
System.out.println("comparison of 2 strings:"+s1.equals(s2));
System.out.println("the first occurance of 'e' is:" + s1.indexOf('E'));

Vasantha,Presidency College Page 14


Java Programming 2021

System.out.println("the last occurance of 'e' is:" + s1.lastIndexOf('E'));


System.out.println("the letter 'i' is replaced by:" +s2.replace('I','a'));
System.out.println("The char of position 4 is:" +s1.charAt(4));
}
}

6. Explain Life cycle of a thread with a neat diagram.

A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.

The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:

New

Runnable

Running

Non-Runnable (Blocked)

Vasantha,Presidency College Page 15


Java Programming 2021

Terminated

1) New

The thread is in new state if you create an instance of Thread class but before the invocation of start() meth

2) Runnable

The thread is in runnable state after invocation of start() method, but the thread scheduler has
not selected it to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.

7. What is Graphics class? Explain the methods with an example.

The graphics class defines a number of drawing functions, Each shape can be drawn edge-
only or filled. To draw shapes on the screen, we may call one of the methods available in the
graphics class.

Drawing Methods of the Graphics Class

Sr.No Method Description


1. clearRect() Erase a rectangular area of the canvas.
2. copyAre() Copies a rectangular area of the canvas to another area
3. drawArc() Draws a hollow arc
4. drawLine() Draws a straight line
5 drawOval() Draws a hollow oval
6 drawPolygon() Draws a hollow polygon
7 drawRect() Draws a hollow rectangle
8. drawRoundRect() Draws a hollow rectangle with rounded corners
9. drawString() Display a text string
10. FillArc() Draws a filled arc
11. fillOval() Draws a filled Oval
12. fillPolygon() Draws a filled Polygon
13. fillRect() Draws a filled rectangle

Vasantha,Presidency College Page 16


Java Programming 2021

14. fillRoundRect() Draws a filled rectangle with rounded corners


15. getColor() Retrieves the current drawing color
16. getFont() Retrieves the currently used font
17. getFontMetrics() Retrieves the information about the current font
18. setColor() Sets the drawing color
19. setFont() Sets the font

Lines and Rectangles

Lines are drawn by means of the drawLine() method.

Syntax
void drawLine(int startX, int startY, int endX, int endY)

drawLine() displays a line in the current drawing color that begins at (start X, start Y) and
ends at (endX, end Y).

Example: g.drawLine(0,0,100,100);

Rectangle

The drawRect() and fillRect() methods display an outlined and filled rectangle, respectively.

Syntax

void drawRect(int top, int left, int width, int height)

void fillRect(int top, int left, int width, int height)

The upper-left corner of the rectangle is at(top,left). The dimensions of the rectangle are
specified by width and height.

Use drawRoundRect() or fillRoundRect() to draw a rounded rectangle. A rounded rectangle


has rounded corners.

Syntax

void drawRoundRect(int top, int left, int width, int height int Xdiam, int YDiam)

void fillRoundRect(int top, int left, int width, int height int Xdiam, int YDiam)

Circles and Ellipses

Vasantha,Presidency College Page 17


Java Programming 2021

The Graphics class does not contain any method for circles or ellipses. To draw an ellipse,
use drawOval(). To fill an ellipse, use fillOval().

Syntax

void drawOval(int top, int left, int width, int height)

void fillOval(int top, int left, int width, int height)

Drawing Arcs

An arc is a part of oval. Arcs can be drawn with draw Arc() and fillArc() methods.

Syntax

void drawArc(int top, int left, int width, int height, int startAngle, int sweetAngle)

void fillArc(int top, int left, int width, int height, int startAngle, int sweetAngle)

8. Write a program to demonstrate user defined exceptions.

User Defined Exception or custom exception is creating your own exception class and throws
that exception using ‘throw’ keyword. This can be done by extending the class Exception.

class JavaException{

public static void main(String args[]){

try{

throw new MyException(2);

// throw is used to create a new exception and throw it.

catch(MyException e){

System.out.println(e) ;

class MyException extends Exception{

int a;

Vasantha,Presidency College Page 18


Java Programming 2021

MyException(int b) {

a=b;

public String toString(){

return ("Exception Number = "+a) ;

9. Explain life cycle of an applet with a neat diagram.

1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.

Vasantha,Presidency College Page 19


Java Programming 2021

public void init(): is used to initialized the Applet. It is invoked only once.

public void start(): is invoked after the init() method or browser is maximized. It is used to
start the Applet.

public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.

public void destroy(): is used to destroy the Applet. It is invoked only once.

10. What is interface? Write a program to implement an interface.

 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.

There are mainly three reasons to use interface. They are given below.

 It is used to achieve abstraction.


 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling. achieve abstraction and multiple inheritance
in Java.

Syntax:
interface <interface_name>{

// declare constant fields

// declare methods that abstract

// by default.

Example:

interface printable{

void print();

class A6 implements printable{

public void print(){System.out.println("Hello");}

Vasantha,Presidency College Page 20


Java Programming 2021

public static void main(String args[]){

A6 obj = new A6();

obj.print();

Output:

Hello

11. Explain the ways of extending a thread with a program as an example.

Extends Thread class

Create a thread by a new class that extends Thread class and create an instance of that class.
The extending class must override run() method which is the entry point of new thread.

Example

public class MyThread extends Thread{

public void run()

System.out.println("Thread started running..");

public static void main( String args[] )

MyThread mt = new MyThread();

mt.start();

Output :
Thread started running..

Vasantha,Presidency College Page 21


Java Programming 2021

12. What is exception? Explain how exceptions are handled in java.

 In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
 Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

 The core advantage of exception handling is to maintain the normal flow of the
application.
 An exception normally disrupts the normal flow of the application that is why we use
exception handling.

There are 5 keywords which are used in handling exceptions in Java.

Keyword Description

try The "try" keyword is used to specify a block where we should place exception code. The
try block must be followed by either catch or finally. It means, we can't use try block alone.

catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the important code of the program. It is executed
whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It
specifies that there may occur an exception in the method. It is always used with method
signature.

13. Explain Final method, final class and final variables in java OR

Explain final keyword in java.

Using the final keyword means that the value can’t be modified in the future.

Vasantha,Presidency College Page 22


Java Programming 2021

Final variables:

If a variable is declared with the final keyword, its value cannot be changed once initialized.
Note that the variable does not necessarily have to be initialized at the time of declaration.

Example: final int var = 50;

Final methods:

A method, declared with the final keyword, cannot be overridden or hidden by subclasses.

Example:

public final void finalMethod(){


System.out.print("Base");
}

Final classes:

A class declared as a final class, cannot be subclassed

Example:

// declaring a final class

final class FinalClass {

//...

class Subclass extends FinalClass{ //attempting to subclass a final class throws an error

//...

14. What is stream? Explain the types of streams with example.

 Stream represents a sequence of objects from a source, which supports aggregate


operations.
 In Java a stream is composed of bytes.
 It's called a stream because it is like a stream of water that continues to flow.

Vasantha,Presidency College Page 23


Java Programming 2021

• In java, 3 streams are created for us automatically. All these streams are attached with
console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

import java.io.FileInputStream;

import java.io.InputStream;

public class Main {

public static void main(String args[]) {

Vasantha,Presidency College Page 24


Java Programming 2021

byte[] array = new byte[100];

try {

InputStream input = new FileInputStream("input.txt");

System.out.println("Available bytes in the file: " + input.available());

// Read byte from the input stream

input.read(array);

System.out.println("Data read from the file: ");

// Convert byte array into string

String data = new String(array);

System.out.println(data);

// Close the input stream

input.close();

catch (Exception e) {

e.getStackTrace();

15. Differentiate between String and String buffer in java.

Vasantha,Presidency College Page 25


Java Programming 2021

16. Define Constructor Overloading? Write a program to demonstrate the same.

 In Java, a constructor is a block of codes similar to the method. It is called when an


instance of the class is created. At the time of calling constructor, memory for the
object is allocated in the memory.
 It is a special type of method which is used to initialize the object.
 Every time an object is created using the new() keyword, at least one constructor is
called.

Rules for creating Java constructor

1. There are two rules defined for the constructor.


2. Constructor name must be the same as its class name
3. A Constructor must have no explicit return type
4. A Java constructor cannot be abstract, static, final, and synchronized.

Write a program to implement constructor overloading by passing different number of


parameter of different types.

class lab5overload

public static void main(String args[])

Vasantha,Presidency College Page 26


Java Programming 2021

overload a = new overload (5.6f); //area of circle

overload b = new overload (5,6); //area of rectanagle

overload c = new overload (5); //area of square

class overload

overload(float r)

float ar;

ar=3.14f * r * r;

System.out.println("Area of circle "+ar);

overload (int a,int b)

int ar=a*b;

System.out.println("Area of Rectange "+ar);

overload (int a)

int ar=a*a;

System.out.println("Area of Square "+ar);

} //end class

17. Explain package with the steps to create a user defined package with an example.

Vasantha,Presidency College Page 27


Java Programming 2021

Packages can have collection of classes, interfaces and sub packages. Each sub packages can
in turn have classes and interfaces.

•Packages are used to reuse the classes written in one program into another program without
physically copying them into the program under development.

•Packages act as containers.

•It has both a naming and a visibility control mechanism.

Vasantha,Presidency College Page 28


Java Programming 2021

Refer to lab manual for example -Program

18. Differentiate between arrays and vectors.

19. Explain Data Input Stream and Data Output Stream in Java.

Java DataOutputStream Class

Java DataOutputStream class allows an application to write primitive Java data types to the
output stream in a machine-independent way.

Syntax:

public class DataOutputStream extends FilterOutputStream implements DataOutput

Methods:

Vasantha,Presidency College Page 29


Java Programming 2021

Example:

package com.javatpoint;

import java.io.*;

public class OutputExample {

public static void main(String[] args) throws IOException {

FileOutputStream file = new FileOutputStream(D:\\testout.txt);

DataOutputStream data = new DataOutputStream(file);

data.writeInt(65);

data.flush();

data.close();

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

Vasantha,Presidency College Page 30


Java Programming 2021

Java DatainputStream Class:

 Java DataInputStream class allows an application to read primitive data from the input
stream in a machine-independent way.
 Java application generally uses the data output stream to write data that can later be
read by a data input stream.

Syntax:

public class DataInputStream extends FilterInputStream implements DataInput

Methods:

Example:

package com.javatpoint;

import java.io.*;

public class DataStreamExample {

public static void main(String[] args) throws IOException {

Vasantha,Presidency College Page 31


Java Programming 2021

InputStream input = new FileInputStream("D:\\testout.txt");

DataInputStream inst = new DataInputStream(input);

int count = input.available();

byte[] ary = new byte[count];

inst.read(ary);

for (byte bt : ary) {

char k = (char) bt;

System.out.print(k+"-");

20. Write a program to demonstrate method overriding in java.

Refer to Question No.3 for answer.

21. Explain Wrapper class with an example.

 The wrapper class in Java provides the mechanism to convert primitive into object
and object into primitive.
 Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and
objects into primitives automatically. The automatic conversion of primitive into an
object is known as autoboxing and vice-versa unboxing.

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

Vasantha,Presidency College Page 32


Java Programming 2021

long Long

float Float

double Double

Example:

//PART -B PROGRAM 15. Write a program to implement wrapper classes.

class wrapperdemo

public static void main(String args[])

byte a = 1;

Byte byteobj = new Byte(a); // wrapping around Byte object

int b = 10;

Integer intobj = new Integer(b);

float c = 18.6f;

Float floatobj = new Float(c);

double d = 250.5;

Double doubleobj = new Double(d);

char e='a';

Character charobj=e;

// printing the values from objects

System.out.println("Values of Wrapper objects (printing as objects)");

System.out.println("Byte object " + byteobj);

System.out.println("Integer object " + intobj);

System.out.println("Float object " + floatobj);

System.out.println("Double object " + doubleobj);

Vasantha,Presidency College Page 33


Java Programming 2021

System.out.println("Character object " + charobj);

// objects to data types (retrieving data types from objects)

// unwrapping objects to primitive data types

byte bv = byteobj;

int iv = intobj;

float fv = floatobj;

double dv = doubleobj;

char cv = charobj;

// printing the values from data types

System.out.println("Unwrapped values (printing as data types)");

System.out.println("byte value " + bv);

System.out.println("int value " + iv);

System.out.println("float value " + fv);

System.out.println("double value " + dv);

System.out.println("char value " + cv);

22. Differentiate between a java applet and a java application.

Vasantha,Presidency College Page 34


Java Programming 2021

23. Explain visibility control in java.

 There are two types of modifiers in Java: access modifiers and non-access modifiers.
 The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class.
 We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.

 There are four types of Java access modifiers:

 Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
 Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
 Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
 Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.

Vasantha,Presidency College Page 35


Java Programming 2021

24. Explain with an example: a) abstract method

b) Abstract class

Abstract class:

 A class which is declared as abstract is known as an abstract class. It can have


abstract and non-abstract methods. It needs to be extended and its method
implemented. It cannot be instantiated.
 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.

Vasantha,Presidency College Page 36


Java Programming 2021

Example of abstract class

abstract class A{}

Abstract Method:

A method which is declared as abstract and does not have implementation is known as an
abstract method.

Example of abstract method

abstract void printStatus();//no method body and abstract

Example:

abstract class Bike{

abstract void run();

Vasantha,Presidency College Page 37


Java Programming 2021

class Honda4 extends Bike{

void run(){System.out.println("running safely");}

public static void main(String args[]){

Bike obj = new Honda4();

obj.run();

Output:

running safely

25. Explain how parameters are passed to an applet.

 Parameters are passed to applets in NAME=VALUE pairs in <PARAM> tags


between the opening and closing APPLET tags.
 Inside the applet, you read the values passed through the PARAM tags with the
getParameter() method of the java.applet.Applet class.
 The getParameter() method of the Applet class can be used to retrieve the parameters
passed from the HTML page.

import java.awt.*;

import java.applet.*;

public class MyApplet extends Applet

String n;

String a;

public void init()

n = getParameter("name");

a = getParameter("age");

Vasantha,Presidency College Page 38


Java Programming 2021

public void paint(Graphics g)

g.drawString("Name is: " + n, 20, 20);

g.drawString("Age is: " + a, 20, 40);

/*

<applet code="MyApplet" height="300" width="500">

<param name="name" value="Ramesh" />

<param name="age" value="25" />

</applet>

*/

Output of the above program is as follows:

26. Differentiate container and component classes(4m)

container component

Vasantha,Presidency College Page 39


Java Programming 2021

1.It has group of components. It is an independent visual control such as push


button or slider

2. ex: JPanel,JWindow

Vasantha,Presidency College Page 40


Java Programming 2021

Vasantha,Presidency College Page 41

You might also like