You are on page 1of 19

Question Bank PT-1 Examination 2023-24

Chapter 1

1. Explain features of Java.(any four)


Object Oriented:
In Java, everything is an Object. Java can be easily extended since it is based on the Object model.
Platform Independent:
Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into
platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and
interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
Simple:
Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to master.
Secure:
With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based
on public-key encryption.
Architecture-neutral:
Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many
processors, with the presence of Java runtime system.
Multithreaded:
With Java's multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This
design feature allows the developers to construct interactive applications that can run smoothly.
Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The
development process is more rapid and analytical since the linking is an incremental and light-weight process.

2. Write a program to ………………………………using ‘?:’ operator.

3. Define JDK. List the tools available in JDK explain any one in detail.
A Java Development Kit (JDK) is a collection of
1) JRE
2) tools which are used for developing, designing, debugging, executing and running java programs.
Tools of jdk:---
appletviewer: use to run java applets
java(java interpreter): runs applets and applications by reading and interpreting byte code files
javac( java compiler): translate java source code to bytecode files that the interpreter can understand
javadoc(java documentation): create HTML-format documentation from java source code files.
javah(java header): produces header files
javap: (java disassemble): convert bytecode files into a program description
jdb: (java debugger): helps us to find errors in our programs.

4. Write general syntax of any two decision making statements and also give its examples
1. if statement
This is the statement that permits you to do something when a condition is satisfied.
Syntax:
if(condition)
{
statement;
}
Program
class IfStatement
{
public static void main(String[] args)
{
int number = 10;
if (number > 0)
{
System.out.println("Number is positive.");
}
System.out.println("This statement is always executed.");
}
}
2. if -else statement
This is an extension of the if statement. In this statement, you can say what to do if the condition is satisfied and also
what to do if the condition is not satisfied.
Syntax:
if (condition)
{
statement;
}
else
{
statement;
}
Program
class IfElse
{
public static void main(String[] args)
{
int number = 10;
if (number > 0)
{
System.out.println("Number is positive.");
}
else
{
System.out.println("Number is not positive.");
}
System.out.println("This statement is always executed.");
}
}

5. Explain break and continue statement with example.


Break
It terminates the loop immediately. Control moves to the next statement following the loop.
For nested loops-break out of the innermost loop, the outer loop remains unaffected
Syntax:
break;
Program
class BreakDemo
{
public static void main(String args[])
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++)
{
if (i == 5)
break;
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}

continue:
It causes continue running a loop, but stop processing the remaining loop body for that particular iteration.
Syntax:
continue;
Program
class ContinueDemo
{
public static void main(String args[])
{
for (int i = 1; i < 10; i++)
{
if (i%2 == 0)
continue;
System.out.print(i + " ");
}
}
}

6.)Give syntax and example of following math functions


a)sqrt() b)pow() c)max() d)pow()
Ans)
i)sqrt()
Syntax:
Math.sqrt(value/variable);
Example:
double y= Math.sqrt(64);
ii)pow()
Syntax:
Math.pow(value/variable);
Example:
double y= Math.pow(2,3);
iii)max()
Syntax:
Math.max(value/variable,value/variable)
Example:
iv)exp()
Syntax:
Math.pow(value/variable)
Example:
System.out.println(Math.exp(2));

7. Write a program to …………………………………………using bitwise shift operator.

8. Describe types of variables in Java with their scope.


There are three types of variables in java
1. Local variables.
2. Instance variables.
3. Static variables.
Local variables
The variables which are declare inside a method or constructor or blocks are called local variables.
It is possible to access local variables only inside the method or constructor or blocks only, it is not possible to
access outside of method or constructor or blocks.
For the local variables memory allocated when method starts and memory released when method completed.
The local variables are stored in stack memory.
Instance variables (non-static variables)
The variables which are declare inside a class but outside of methods are called instance variables.
The scope (permission) of instance variable is inside the class having global visibility.
For the instance variables memory allocated during object creation & memory released when object is destroyed.
Instance variables are stored in heap memory.
Static variables (class variables)
The variables which are declared inside the class but outside of the methods with static modifier are called static
variables.
Scope of the static variables with in the class global visibility.
Static variables memory allocated during .class file loading and memory released at .class file unloading time.
Static variables are stored in non-heap memory.
9. Describe instance Of and dot (.) operators in Java with suitable example.
instanceof operator
It is used to test whether the object is an instance of the specified type (class or subclass or interface).
It returns either true or false. If we apply the instanceof operator with any variable that has null value, it returns false.
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}
output:true

dot operator
Also known as member operator, separator or period used to separate a variable or method from a reference variable
Used to access the member of a package or a class.
objectName.variableName;
objectName.methodName(argument);
className.MethodName();
Example:
a1.y ;
a1.m2();
Math.sqrt(x);
Question Bank PT-1 Examination 2023-24
Chapter 2

1. State use of finalize( ) method with its syntax and example.


Finalize() method is used to specify those actions that must be performed before an object is destroyed. The Java runtime
mechanism calls this method whenever it is about to reclaim the space for that object.
finalize() method is called prior to garbage collection.
We can override the finalize() method to keep those operations you want to perform before an object is destroyed.
Syntax:
protected void finalize()
{
finalization code
}
Example:
class FinalizeMethod
{
public void finalize()
{
System.out.println("all work done");
}
public static void main(String[] args)
{
FinalizeMethod t1=new FinalizeMethod();
FinalizeMethod t2=new FinalizeMethod();
System.out.println("good");
System.out.println("morning");
t1=null;
t2=null;
System.gc();
}
}

2.Explain the types of constructors in Java with suitable example


Types of Constructor
There are two types of constructors
1) Default Constructor.
a. Zero argument constructor.
2) User defined Constructor
a. zero argument constructor
b. parameterized constructor

Default Constructor:
In the java programming if we are not providing any constructor in the class then compiler provides default constructor.
Provided by the compiler at the time of compilation.
It is always zero argument constructors with empty implementation.

Page 1
Default constructor is executed by the JVM at the time of execution.
User defined constructors:
When user defines constructor in a class, it is called as user defined constructor.
Zero argument constructor: user defined constructor which doesn’t accept any parameter.
Example:
class Test
{
Test()
{
System.out.println("zero argument constructor");
}
public static void main(String[] args)
{
Test t=new Test();
}
}

Parameterized constructor: user defined constructor which takes some parameters.


Example:
class Score
{
Score(int i)
{
System.out.println(i);
}
void Remark()
{
System.out.println("Excellent");
}
public static void main(String[] args)
{
Score t=new Score(10);
t.Remark();
}
}.

3.Differentiate between String and StringBuffer class(Any4Points).


BASIS FOR
STRING STRINGBUFFER
COMPARISON

Length The length of the String object is The length of the StringBuffer can be
fixed. increased.

Modification String object is immutable. StringBuffer object is mutable.

Performance It is slower during concatenation. It is faster during concatenation.

Memory Consumes more memory. Consumes less memory.

Storage String constant pool. Heap Memory.

4.Define wrapper class. Give the following wrapper class methods with syntax and use:
a. To convert integer number to string.
b. To convert numeric string to integer number.
c. To convert object numbers to primitive numbers using typevalue() method.
Page 2
Wrapper class wraps (encloses) around a data type and gives it an object appearance.
Wrapper classes include methods to unwrap the object and give back the data type.
Each of Java's eight primitive data types has a class dedicated to it which is called as wrapper classes
The wrapper classes are part of the java.lang package, which is imported by default into all Java programs.

Primitive Wrapper Class


data type
boolean Boolean
byte Byte
char Character
int Integer
float Float
double Double
long Long
short Short
a) toString()
This method converts primitive datatype to String
Syntax:
Integer.toString(int)
Example:
int x=10;
String str;
str=Integer.toString(x);
b)Parsetype()
This method converts String to primitive datatype
Syntax:
int variablename=Integer.parseInt(string);
Example:
int i=Integer.parseInt(str);
c)typevalue()
This method converts object to its corresponding primitive type
Syntax:
int variablename=referencevariable.intValue();
Example:
int x=i.intValue();

5.Write a program to……………………….two 2-d array(3X3 matrix).

6.Differentiate vector and array


Sr. No. Vector Array
1 Vector can grow and shrink dynamically. Array can’t grow and shrink dynamically
2 Vector can hold dynamic list of objects or Array is a static list of primitive data types
primitive data types.
3 Vector class is found in java.util package Array class is found in java.lang (default) package
4 Vector can store elements of different data Array can store elements of same data type
types
5 Vector class provides different methods for For accessing element of an array no special methods
accessing and managing vector elements. are available as it is not a class, but a derived type
6 Syntax:Vector objectname=new Vector(); Syntax:datatype arrayname[]=new datatype[size];
7 Example: Vector v1=new Vector(); Example: int[] myArray={22,12,9,44};

7.Write a program to accept a number as command line argument ………………………

8.Write a program to ……………………………..vector class

9.Write a program to ………………………………using parameterized constructor.


Page 3
10. Give use of ‘this’ keyword in Java with suitable example.
This is a keyword that can be used inside any method to refer to the current object
This is always a reference to the object on which the method was invoked.
This will refer to the current object.
If instance & local variables are having same name, then to represent instance variables use this keyword.
Example:
class Student
{
int rollno;
int marks;
void setdata(int rollno,int marks)
{
this.rollno=rollno;
this.marks=marks;
}
void display()
{
System.out.println("rollno:"+rollno);
System.out.println("marks:"+marks);
}
}
class ThisKeyword
{
public static void main(String args[])
{
Student s1=new Student();
s1.setdata(1,65);
s1.display();
}
}

Page 4
Question Bank PT-1 Examination 2023-24
Chapter 3

1.List the types of inheritances in Java


1. Single level
2. Multilevel inheritance
3. Hierarchical
4. Multiple Inheritance(supported through interface only)
5. Hybrid Inheritance(supported through interface only)

2.Differentiate between method overloading and method overriding.


Method Overloading Method Overriding
Definition Methods of the same class shares the Sub class have the same method with same
same name but each method must have name and exactly the same number and type
different number of parameters or of parameters and same return type as a
parameters having different types and super class.
order.
Meaning Method Overloading means more than Method Overriding means method of base
one method shares the same name in class is re-defined in the derived class
the class but having different signature. having same signature.
Behavior Method Overloading is to “add” or Method Overriding is to “Change” existing
“extend” more to method’s behavior. behavior of method.
Polymorphism It is a compile time polymorphism. It is a run time polymorphism.
Inheritance It may or may not need inheritance in It always requires inheritance in Method
Method Overloading. Overriding.
Signature In Method Overloading, methods must In Method Overriding, methods must
have different signature. have same signature.
Relationship of In Method Overloading, relationship is In Method Overriding, relationship is there
Methods there between methods of same class. between methods of super class and sub
class.
Criteria In Method Overloading, methods have In Method Overriding, methods have same
same name different signatures but in name and same signature but in the different
the same class. class.
No. of Classes Method Overloading does not require Method Overriding requires at least two
more than one class for overloading. classes for overriding.

3.Describe the use of final keyword w. r. t. method and the variable with suitable example.
The final keyword in Java indicates that no further modification is possible. Final can be Variable, Method or Class

Final Variable
Final variable is a constant. We cannot change the value of final variable after initialization.
Sample program for final keyword in Java
class FinalVarDemo
{
final int a = 10;
void show()
{
a = 20;
System.out.println("a : "+a);
}
public static void main(String args[])
{
FinalVarDemo var = new FinalVarDemo();
var.show();
}
}
Page 1
Output:
Compile time error

Final method
When we declare any method as final, it cannot be overridden.
Sample program for final method in Java
class A
{
final void put()
{
System.out.println("put method of A class");
}
}
class B extends A
{
void put()
{
System.out.println("put method of B class");
}
public static void main(String args[])
{
B b = new B();
b.put();
}
}
Output:
Compile time error

4.Describe use of super with respect to inheritance.


It is used to refer to the immediate parent class of the object.
super () calls the parent class constructor
super() is added in each class constructor automatically by compiler as a first statement
super.methodname calls method from parents class.
Super keyword is also used to call the parents class variable.
class A
{
A(String str)
{
System.out.println("Constructor of class A:"+str);
}
void show()
{
System.out.println("show method of base class");
}
}
class B extends A
{
B()
{
super("super call from class B");
super.show();
System.out.println("Constructor of class B.");
}
}
class Super_Demo
{
public static void main(String[] a)

Page 2
{
B b = new B();
}
}

5.Write a program to define class…………….using array of objects


6.Explain dynamic method dispatch in Java with suitable example
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.
Method to execution based upon the type of the object being referred to at the time the call occurs. Thus, this
determination is made at run time. 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.
Example:
class ABC
{
//Overridden method
public void disp()
{
System.out.println("disp() method of parent class");
}
}
class Demo extends ABC
{
//Overriding method
public void disp()
{
System.out.println("disp() method of Child class");
}
public void newMethod()
{
System.out.println("new method of child class");
}
public static void main( String args[])
{
ABC obj = new ABC();
obj.disp();//method of parent class is called.
ABC obj2 = new Demo();
obj2.disp();//method of child class is called(dynamic method dispatch and runtime polymorphism)
}
}
7.Explain implementing interface with example
A class implements an interface. After that, class can perform the specific behavior on an interface.
The implements keyword is used by class to implement an interface.
Syntax:
class ClassName implements interfacename
{
// body of class
}

Example:
interface Results
{
final static float pi = 3.14f;
float areaOf(float l, float b);
}
class Rectangle implements Results
{
public float areaOf(float l, float b)

Page 3
{
return (l * b);
}
}
class Square implements Results
{
public float areaOf(float l, float b)
{
return (l * l);
}
}
class Circle implements Results
{
public float areaOf(float r, float b)
{
return (pi * r * r);
}
}
public class InterfaceDemo
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Square square = new Square();
Circle circle = new Circle();
System.out.println("Area of Rectangle: "+rect.areaOf(20.3f, 28.7f));
System.out.println("Are of square: "+square.areaOf(10.0f, 10.0f));
System.out.println("Area of Circle: "+circle.areaOf(5.2f, 0));
}
}

Output:
Area of Rectangle: 582.61
Are of square: 100.0
Area of Circle: 84.905594

8.List and explain any four built-in packages in Java


Built-in packages are supplied as a part of JDK (Java Development Kit) to simplify the task of java programmer.It starts
with java keyword. (For example: java.lang.*).
Example:
1)java.lang.*
used for convertion of data from string to fundamental data, displaying the result on to the console, obtaining the garbage
collector, etc
2)java.io.*
used for developing file handling applications, such as, opening the file in read or write mode, reading or writing the
data, etc.
3)java.util.* used for developing quality or reliable applications in java or J2EE. also known as collection framework.
4)java.awt.*(abstractwindowing toolkit)
used for developing GUI (Graphic Unit Interface) components such as buttons, check boxes, scroll boxes, etc.
5) java.text.* used for formatting date and time.
6)java.applet.* used for developing browser oriented applications
7)java.net.* used for developing client server applications.

9.Explain static import in Java


It is introduced in 1.5 version of Java. Static members of a class can be accessed directly without class name or any
object by using the concept of static import. It improve the code readability and enhance coding.
Program
import static java.lang.Math.*;

Page 4
class Test2
{
public static void main(String[] args)
{
System.out.println(sqrt(4));
System.out.println(pow(2, 2));
System.out.println(abs(6.3));
}
}
Output:
2.0
4.0
6.3
Program
import static java.lang.Math.*;
import static java.lang.System.*;
class Test3
{
public static void main(String[] args)
{
out.println(sqrt(4));
out.println(pow(2, 2));
out.println(abs(6.3));
}
}
Output:
2.0
4.0
6.3

10. Implement following inheritance………………………….:

11. Difference between class and interface


Class Interface

The keyword used to create a class is “class” The keyword used to create an interface is “interface”

A class can be instantiated i.e, objects of a class An Interface cannot be instantiated i.e, objects cannot be

can be created. created.

Classes does not support multiple inheritance. Interface supports multiple inheritance.

It can be inherit another class. It cannot inherit a class.

It can be inherited by another class using the It can be inherited by a class by using the keyword

keyword ‘extends’. ‘implements’ and it can be inherited by an interface

using the keyword ‘extends’.

It can contain constructors. It cannot contain constructors.

It cannot contain abstract methods. It contains abstract methods only.

Variables and methods in a class can be declared All variables and methods in a interface are declared as

Page 5
using any access specifier(public, private, default, public.

protected)

Variables in a class can be static, final or neither. All variables are static and final.

Page 6
PT-1 PROGRAMS CHAPTER 1-2-3(2023-24)
Ques)Implement following inheritance:

Display details of devices from loadOS() method of class Mobile.


Ans)
import java.util.Scanner;
class Device
{
String vendorName;
int ramSize;
double OSVersion;

}
interface Loader
{
// public and abstract
public abstract void loadOS();
}
class Mobile1 extends Device implements Loader
{
void getData()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Details for Vendor Name, Version and Ram Size : ");
vendorName=sc.nextLine();
OSVersion=sc.nextDouble();
ramSize=sc.nextInt();
}
public void loadOS()
{
System.out.println("Details:");
System.out.println("Vendor Name:"+vendorName);
System.out.println("Version:"+OSVersion);
System.out.println("Ram size:"+ramSize);
}
// Driver Code
public static void main (String[] args)
{
Mobile1 m= new Mobile1();
m.getData();
m.loadOS();
}
}
Ques)Write a program to find largest between two numbers using‘?:’operator.
ANS)
public class LargestNumber
{
public static void main(String args[])
{
int a,b,c;
a=10;
b=20;
c = (a>b) ? a: b;
System.out.println( "Largest number between "+a+" and "+b+" is : " + c );
}
}

Ques)Write a program to divide any positive even integer by 2 using bitwise shift operator.
ANS)
public class BitwiseDivision
{
public static void main(String args[])
{
int n=Integer.parseInt(args[0]);
// divide by 2
n = n >> 1;
System.out.println("Value after division is: " + n);
}
}

Ques)Write a program to add two 2-d array(3X3 matrix).


ANS)
public class AddingTwoMatrices{
public static void main(String args[])
{
int a[][]={{1,2,3},{4,5,6},{7,8,9}};
int b[][]={{1,1,1},{1,1,1},{1,1,1}};
int c[][]=new int[3][3];

for(int i = 0;i<3;i++)
{
for(int j = 0;j<3;j++)
{
c[i][j] = a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}
}
Write a program to accept a number as command line argument and print the number is even or
odd.
ANS)
public class EvenOdd
{
public static void main(String args[])
{
int x=Integer.parseInt(args[0]);
if (x%2 ==0)
{
System.out.println("Even Number");
}
else
{
System.out.println("Odd Number");
}
}

QUES)Write a program to implement a vector class and its any eight methods
ANS)
import java.util.Vector;
class VectorExample3
{
public static void main(String[] arg)
{
Vector v = new Vector();
v.add(2);
v.add(0, 1);
v.add("thakur");
v.add("poly");
System.out.println("Vector is " + v);
System.out.println(v.contains("poly"));
System.out.println("element at indexx 2 is: " + v.get(2));
System.out.println("index of thakur is: " + v.indexOf("thakur"));
System.out.println(v.isEmpty());
System.out.println("first element of vector is: " + v.firstElement());
System.out.println("Initial capacity: " + v.capacity());
v.clear();
System.out.println("after clearing: "+v);
}
}

QUES)Write a program to initialize object of a class student using parameterized constructor.


ANS)
class Student
{
int marks;
double perc;
student(int m,double p)
{
marks=m;
perc=p;
}
void display()
{
System.out.println("Marks=" + marks);
System.out.println("Percentage=" + perc);
}
public static void main(String args[])
{
student s1=new student(121,60.5);
s1.display();
}
}

QUES)Write a program to define class Employee with members as id and salary. Accept data
for five employees and display details of employees getting highest salary.
ANS)
import java.util.Scanner;
class Employee
{
int empid;
String name;
float salary;
void getInput()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the empid : ");
empid = in.nextInt();
System.out.print("Enter the name : ");
name = in.next();
System.out.print("Enter the salary : ");
salary = in.nextFloat();
}
void display()
{
System.out.println("Employee id = " + empid);
System.out.println("Employee name = " + name);
System.out.println("Employee salary = " + salary);
}
public static void main(String[] args)
{
float max;
int i,d=0;
Employee e[] = new Employee[5];
for(i=0; i<5; i++)
{
e[i] = new Employee();
e[i].getInput();
}
System.out.println("The details of employee with highest salary are: ");
max=e[0].salary;
for( i=0;i<5;i++)
{
if(e[i].salary>max)
{
max = e[i].salary;
d=i;
}
}
e[d].display();
}
}

You might also like