0% found this document useful (0 votes)
3 views60 pages

Java PYQ

The document contains a series of questions and answers related to Object-Oriented Programming (OOP), Java, and C++. It covers topics such as inheritance, method overloading, exception handling, and the differences between various programming concepts. The content is structured into groups, with each group addressing specific questions and providing concise answers suitable for exam preparation.

Uploaded by

shubho5629
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)
3 views60 pages

Java PYQ

The document contains a series of questions and answers related to Object-Oriented Programming (OOP), Java, and C++. It covers topics such as inheritance, method overloading, exception handling, and the differences between various programming concepts. The content is structured into groups, with each group addressing specific questions and providing concise answers suitable for exam preparation.

Uploaded by

shubho5629
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

Group-A Questions with Answers

1. Which feature of OOPS describes the reusability of code?

Answer: Inheritance

2. A function in C language is similar to what in Java?

Answer: Method

3. Which method is used to determine the name of a class represented by the class object
as a String?

Answer: getName()

4. Which of the following is a mutable class in Java?

Answer: StringBuilder

5. What is multithreaded programming?

Answer: A process in which two or more parts of the same process run simultaneously.

6. Which are the common security restrictions in applets?

Answer: Both A and B

7. An overridden method is the method of _____ class and the overriding method is the
method of _____ class.

Answer: sub, super

8. Which among the following is not a valid data type in Java?

Answer: Bool

9. The combination of abstraction of data and code is viewed in _____.

Answer: Object

10. String args[] in main() method are used for?

Answer: Passing arguments at run time

11. Choose the correct statement about Java.

Answer: JIT Compiler takes bytecode as input and produces executable code.

12. What happens if two threads of the same priority are called simultaneously?

Answer: It depends on the operating system.


Group-B Questions with Answers

2. Define State, Data Member, Attribute and Property.

Answer:

• State: Current condition of an object.

• Data Member: Variable declared inside a class.

• Attribute: Characteristic or feature of an object.

• Property: Value of an attribute.

Example: A student has attributes like name and age.

3. Explain Public and Private Access Specifiers.

Answer:

Public

• Accessible from anywhere in the program.

• No access restriction.

Private

• Accessible only inside the same class.

• Used for data hiding and security.

Difference: Public members can be accessed by all classes, while private members can only
be accessed within their own class.

4. Difference Between Array and ArrayList.

Answer:

Array ArrayList

Fixed size Dynamic size

Faster Slower

Stores primitive values Stores objects


Array ArrayList

Length cannot change Size can change

5. Identify the output of the program and justify.

Output:

Welcome to InterviewBit
Welcome to Scaler Academy
Welcome to Scaler Academy 2

Justification:

• super() calls the parent class constructor.

• this() calls the default constructor of the same class.

• Then the parameterized constructor prints the final statement.

6. Can Java be said to be a complete Object-Oriented Programming language? Why does


Java not use pointers?

Answer:

No, Java is not a complete Object-Oriented language because it supports primitive data
types such as int, char, float, and boolean, which are not objects.

Java does not use pointers because:

1. It improves security.

2. It prevents direct memory access.

3. It reduces programming errors.

4. Memory is managed automatically by Garbage Collection.

Conclusion: Java is mostly object-oriented and safer because it does not use pointers.

Group-C (Long Questions) Easy Answers

7. What is Method Overloading? What is Method Overriding? Difference between them.

Method Overloading
When multiple methods have the same name but different parameters in the same class.

class Test {
void add(int a, int b){}
void add(int a, int b, int c){}
}

Method Overriding

When a subclass provides its own implementation of a method already defined in the parent
class.

class Animal{
void sound(){
[Link]("Animal Sound");
}
}
class Dog extends Animal{
void sound(){
[Link]("Bark");
}
}

Differences

Overloading Overriding

Same class Parent and child class

Different parameters Same parameters

Compile-time polymorphism Run-time polymorphism

Inheritance not required Inheritance required

8. How to Resolve Naming Conflict in Multiple Inheritance? Compare Class and Struct.
Define Process Abstraction.

Resolving Naming Conflict

Java avoids multiple inheritance of classes. It uses interfaces to remove ambiguity.

Class vs Struct
Class Struct

Supports methods and data Mainly stores data

Supports inheritance Limited inheritance

Used in Java Used in C/C++

Process Abstraction

Process abstraction means hiding implementation details and showing only essential
features to the user.

Example: ATM machine hides internal processing from users.

9. Garbage Collection, Minor/Major/Full GC, Mark-and-Sweep

Garbage Collection

Garbage Collection (GC) automatically removes unused objects from memory.

Types of GC

Minor GC

• Cleans Young Generation memory.

• Fast process.

Major GC

• Cleans Old Generation memory.

• Slower than Minor GC.

Full GC

• Cleans entire heap memory.

• Slowest GC.

When Object Becomes Eligible for GC?

• When it has no reference pointing to it.

Student s = new Student();


s = null;

Mark-and-Sweep

1. Mark: Find unused objects.


2. Sweep: Remove those objects from memory.

10. Applets Communication, Attributes of Applet Tag, Daemon Thread

Can Two Applets Communicate?

Yes.

They can communicate using:

• AppletContext

• Public methods

• Shared data

Attributes of <applet> Tag

<applet code="[Link]"
width="300"
height="200">
</applet>

Important attributes:

• code

• width

• height

• align

• name

Daemon Thread

A daemon thread runs in the background and supports other threads.

Examples:

• Garbage Collector

• Background services

Is Garbage Collector a Daemon Thread?

Yes. Garbage Collector runs as a daemon thread.

11. Explain [Link] Class. Write Program for Ascending Sort.


[Link] Class

Objects class provides utility methods for object operations.

Important methods:

• equals()

• hash()

• isNull()

• nonNull()

• toString()

Program to Sort an Array in Ascending Order

import [Link];

class SortDemo {
public static void main(String args[]) {
int arr[] = {5, 2, 8, 1, 3};

[Link](arr);

[Link]("Ascending Order:");
for(int i : arr)
[Link](i + " ");
}
}

Output:

12358

These answers are written in simple MAKAUT exam style and are suitable for 5+5+5 mark
long questions.

Group-A Questions with Easy Answers (2023)

1. What is Aggregation?
Answer: Aggregation is a "has-a" relationship where one class contains another class as a
member.

2. What is Inheritance?

Answer: Inheritance is the process by which one class acquires properties and methods of
another class.

3. What is the name of the Java file?

import myLibrary.*;
public class ShowSomeClass
{
}

Answer: [Link]

4. What is Bytecode?

Answer: Bytecode is the intermediate code generated by the Java compiler and executed by
the JVM.

5. What is Default Access Specifier?

Answer: If no access specifier is specified, it is called default access. It is accessible within


the same package.

6. Difference between Exception and Error?

Exception Error

Can be handled Cannot usually be handled

Occurs during program execution Serious system problem

7. What is Link?

Answer: Link is a relationship between two objects or classes in UML.

8. What is Data Hiding?

Answer: Data hiding means restricting direct access to data using private members.

9. Difference between Object and Object Reference?

• Object: Actual instance of a class.

• Object Reference: Variable that stores the address of an object.

10. What value of X prints all array elements?


int values[] = {1,2,3,4,5,6,7,8};
for(int i=0; i<X; i++)
[Link](values[i]);

Answer: X = 8

11. What is Message Passing?

Answer: Communication between objects through method calls is called message passing.

12. Output of the Program

public class Trial{


int x;
public static void main(String args[]){
x = 8;
[Link](x);
}
}

Answer: Compilation Error


Because a non-static variable (x) cannot be accessed directly inside a static method (main).

Group-B Questions with Easy Answers (2023)

2. Differentiate Major and Minor Elements with Example

Major Elements

• Classes

• Objects

• Inheritance

• Polymorphism

Minor Elements

• Abstraction

• Encapsulation

• Message Passing

Example: In a Student Management System, Student class and Student object are major
elements.
3. Differences Between OOP and Conventional Programming

OOP Conventional Programming

Object-based Function-based

Reusable code Less reusable

Data security Less secure

Uses classes and objects Uses functions

4. What is an Exception? How are Exceptions Handled?

Exception

An exception is a runtime error that interrupts normal program execution.

Handling

Java handles exceptions using:

• try

• catch

• finally

• throw

Example:

try{
int a=10/0;
}
catch(Exception e){
[Link]("Error");
}

5. Difference Between Abstract Class and Interface

Abstract Class Interface

Can have abstract and normal methods Contains abstract methods


Abstract Class Interface

Uses extends Uses implements

Can have constructors Cannot have constructors

6. "Java does not support destructors". Discuss. What is this keyword?

Destructors

Java does not support destructors because memory is managed automatically by the
Garbage Collector.

this Keyword

this refers to the current object of a class.

Example:

class Student{
int age;
Student(int age){
[Link] = age;
}
}

Use of this:

• Refers to current object.

• Resolves variable name conflicts.

• Calls another constructor using this().

Group-C Questions with Easy Answers (2023)

7(a). Differentiate Generalization and Specialization with Example

Generalization

Combining similar classes into one parent class.

Example:

• Car, Bike → Vehicle


Specialization

Creating child classes from a parent class.

Example:

• Vehicle → Car, Bike

Generalization Specialization

Bottom to Top approach Top to Bottom approach

Creates parent class Creates child class

7(b). Explain Degree of Association with Example

Degree of Association means the number of classes involved in a relationship.

Types:

1. Unary Association – One class

2. Binary Association – Two classes

3. Ternary Association – Three classes

Example: Student enrolls in Course (Binary Association).

7(c). Explain Cardinality of Association with Example

Cardinality specifies how many objects participate in a relationship.

Types:

• One-to-One (1:1)

• One-to-Many (1:M)

• Many-to-One (M:1)

• Many-to-Many (M:M)

Example:
One Teacher teaches many Students (1:M).

8(a). Explain Polymorphism with Example

Polymorphism means "many forms".


A single method can perform different tasks.

Example

class Shape{
void draw(){
[Link]("Drawing Shape");
}
}

class Circle extends Shape{


void draw(){
[Link]("Drawing Circle");
}
}

Advantages

• Code reusability

• Flexibility

• Easy maintenance

8(b). Advantages and Disadvantages of OOP

Advantages

1. Code Reusability

2. Data Security

3. Easy Maintenance

4. Modularity

5. Flexibility

Disadvantages

1. Larger program size

2. More memory usage

3. Slower execution

4. Complex design
8(c). Difference Between Abstraction and Encapsulation

Abstraction Encapsulation

Hides implementation details Hides data

Focuses on what to do Focuses on how to protect data

Achieved using abstract class/interface Achieved using access modifiers

9(a). What is a Thread?

A thread is the smallest unit of execution in a program.

It allows multiple tasks to run simultaneously.

Example:

• Playing music while downloading a file.

9(b). How to Set Priority of Thread?

Thread priority is set using:

[Link](5);

Priority values:

• MIN_PRIORITY = 1

• NORM_PRIORITY = 5

• MAX_PRIORITY = 10

9(c). Program for Synchronization Between Two Threads

class Table{
synchronized void printTable(int n){
for(int i=1;i<=5;i++){
[Link](n*i);
}
}
}

Synchronization ensures only one thread accesses shared resources at a time.


10(a). Explain Method Overloading with Example

Method overloading means multiple methods having the same name but different
parameters.

class Demo{
void add(int a,int b){}
void add(int a,int b,int c){}
}

Benefits

• Improves readability

• Supports compile-time polymorphism

10(b). Explain Autoboxing and Unboxing

Autoboxing

Converting primitive data type into wrapper object.

int a = 10;
Integer i = a;

Unboxing

Converting wrapper object into primitive type.

Integer i = 10;
int a = i;

11(a). Uses of Exception Handling in Java

1. Prevents abnormal program termination.

2. Maintains normal flow of program.

3. Handles runtime errors.

4. Improves reliability.

11(b). Program for Negative Age Exception


class AgeException{
public static void main(String args[]){
int age = -5;

try{
if(age < 0)
throw new Exception("Negative Age");
}
catch(Exception e){
[Link]("Negative age entered");
}
}
}

11(c). Program to Generate Square Roots of First 30 Natural Numbers

class Root implements Runnable{


public void run(){
for(int i=1;i<=30;i++){
[Link](i+" = "+[Link](i));
}
}

public static void main(String args[]){


Thread t = new Thread(new Root());
[Link]();
}
}

11(d). What is Synchronization? Why is it Needed?

Synchronization

Synchronization is a process that controls access to shared resources by multiple threads.

Need

1. Prevents data inconsistency.

2. Avoids thread interference.

3. Ensures correct output.


4. Improves thread safety.

Example: Bank account transactions by multiple users.

Group-A Questions with Answers (2020)

1. Which statement(s) is/are true?

Answer: Both I and II

2. Identify the user-defined types.

Answer: Both enumeration and classes

3. What are mandatory parts in a function declaration?

Answer: Return type and function name

4. Which operator cannot be overloaded?

Answer: ?: (Conditional operator)

5. If a class is derived privately from a base class then?

Answer: All members are inherited but become private in the derived class.

6. Streams performing both input and output operations must be declared as?

Answer: iostream

7. Most significant feature of template classes?

Answer: Code Reusability

8. An inline function is expanded during?

Answer: Compile Time

9. Inline functions are avoided when?

Answer: All of these

• Static variables

• Recursive calls

• Loops

10. Which statement catches all exceptions?

Answer:
catch(...)

11. Which statement is correct?

Answer: C++ allows both static and dynamic type checking.

12. A virtual function having no definition in the base class is called?

Answer: Pure Virtual Function

Group-B Questions with Answers (2020)

2. Define a Date Object with Constructor. Write a Function to Swap Two Date Objects.

Date Class

class Date
{
int d,m,y;
public:
Date(int dd,int mm,int yy)
{
d=dd;
m=mm;
y=yy;
}
};

Swap Function

void swapDate(Date &a, Date &b)


{
Date temp=a;
a=b;
b=temp;
}

Explanation: Constructor initializes date values. Swap function exchanges two date objects.

3. Differentiate Between if-else and switch-case


if-else switch-case

Used for complex conditions Used for multiple choices

Can use relational operators Uses constant values only

Slower Faster

More flexible Easier for menu-driven programs

Example

if(a>0)
cout<<"Positive";
else
cout<<"Negative";

switch(ch)
{
case 1: cout<<"One";
break;
}

4. What is Exception? Explain Exception Handling in C++.

Exception

An exception is an error that occurs during program execution.

Exception Handling

C++ uses:

• try

• throw

• catch

Example

try
{
throw 10;
}
catch(int x)
{
cout<<"Exception Caught";
}

Advantage: Prevents abnormal program termination.

5. Special Properties of Constructor Functions. Order of Constructor and Destructor Calls.

Properties of Constructor

1. Same name as class.

2. No return type.

3. Called automatically.

4. Initializes objects.

5. Can be overloaded.

Order of Calls

Constructor Order

Base Class → Derived Class

Destructor Order

Derived Class → Base Class

6. Explain Data Abstraction with Example.

Data Abstraction

Data abstraction means hiding implementation details and showing only essential features.

Example

class ATM
{
public:
void withdraw();
};

The user only knows how to withdraw money, not the internal processing.

Advantages

• Security
• Reduced complexity

• Easy maintenance

Definition: Data abstraction hides unnecessary details and exposes only important
information to the user.

Group-C Questions with Easy Answers (2020)

7(a). How are Derived Class Constructors Used to Pass Parameters to Base Class in
Multilevel Inheritance?

In multilevel inheritance, the derived class constructor passes values to the base class
constructor using an initializer list.

Example

class A{
public:
A(int x){
cout<<"A = "<<x;
}
};

class B: public A{
public:
B(int x,int y):A(x){
cout<<" B = "<<y;
}
};

Explanation: First the base class constructor is called, then the derived class constructor.

7(b). Program to Demonstrate Multiple Inheritance

#include<iostream>
using namespace std;

class A{
public:
void showA(){
cout<<"Class A"<<endl;
}
};

class B{
public:
void showB(){
cout<<"Class B"<<endl;
}
};

class C: public A, public B{


};

int main(){
C obj;
[Link]();
[Link]();
return 0;
}

Output

Class A
Class B

Definition: Multiple inheritance means one class inherits properties from more than one
base class.

8(a). Class Matrix and Function to Read Matrix Elements

#include<iostream>
using namespace std;

class Matrix{
int a[10][10],m,n;

public:
void read(){
cin>>m>>n;

for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
cin>>a[i][j];
}
};

Explanation: Reads all elements of an m × n matrix.

8(b). Friend Function, Merits and Demerits

Friend Function

A function declared with the keyword friend can access private members of a class.

Example

class Test{
private:
int x=10;

public:
friend void show(Test);
};

void show(Test t){


cout<<t.x;
}

Merits

1. Access private data.

2. Increases flexibility.

3. Useful for operator overloading.

Demerits

1. Reduces data security.

2. Breaks encapsulation.

8(c). Friend Class with Example

A friend class can access private members of another class.

class A{
private:
int x=10;

friend class B;
};

class B{
public:
void show(A a){
cout<<a.x;
}
};

9(a). Pure Virtual Function

A virtual function with no definition in the base class.

virtual void display() = 0;

Uses

• Achieves abstraction.

• Forces derived classes to implement the function.

9(b). Abstract Base Class

A class containing at least one pure virtual function is called an abstract base class.

class Shape{
public:
virtual void draw() = 0;
};

Features

• Cannot create objects.

• Used as a base class.

9(c). Dynamic Binding

Dynamic binding means a function call is resolved at run time.

Example
Base *p;
p = new Derived();
p->show();

Advantage

Supports runtime polymorphism.

10(a). Stream Classes Required for Opening Files

ifstream

Used for reading files.

ofstream

Used for writing files.

fstream

Used for both reading and writing files.

10(b). File Pointer Manipulation

File pointers are used to move within a file.

Functions

seekg() // move input pointer


seekp() // move output pointer
tellg() // current input position
tellp() // current output position

Uses

• Random file access

• Reading/Writing at specific locations

10(c). Copy Contents of One File to Another

#include<iostream>
#include<fstream>
using namespace std;

int main(){
ifstream fin("[Link]");
ofstream fout("[Link]");

char ch;
while([Link](ch))
[Link](ch);

[Link]();
[Link]();
}

11(a). What is STL? Explain STL Programming Model.

STL (Standard Template Library)

STL is a collection of reusable classes and functions in C++.

Components

1. Containers (vector, list)

2. Algorithms (sort, search)

3. Iterators

Advantages

• Reusable code

• Faster development

• Efficient programming

11(b). Vector Class Operations

Create Vector

vector<float> v;

Insert Elements

v.push_back(10.5);
v.push_back(20.5);

Display Vector
for(int i=0;i<[Link]();i++)
cout<<v[i];

11(c). Methods of String Class

Important string functions:

length()
size()
append()
compare()
substr()
find()
replace()
empty()

Example

string s="Hello";
cout<<[Link]();

Output

These are short, easy-to-memorize MAKAUT-style answers for Group-C (2020 OOP with
C++).

Group-A (Easy Answers) – Java 2016

1. Return type of a constructor method is


Answer: No return type (d)

2. Which is used as a part of method signature in Java?


Answer: throws (c)

3. Which one is not true about an interface?


Answer: It can be partially implemented by a class (d)

4. StringBuffer differs from String because


Answer: StringBuffer allows text to be changed after creation (b)

5. Which cannot be used as a method modifier?


Answer: generic (b)
6. Which is not a reserved word in Java?
Answer: include (c)

7. A top-level class without any modifier is accessible to


Answer: Any class within the same package (b)

8. Output of the method for input 2

return 0 * 100 + ++n;

Answer: 3

9. Which listener detects selection in a Choice component?


Answer: ItemListener (b)

10. Contract of a class means


Answer: None of these (d)

Group-B (Easy Answers) – Java 2016

2(a) What is meant by specific import?

Answer:
Specific import imports only one class from a package.

Example:

import [Link];

2(b) Why is String called a reference type?

Answer:
String is a class in Java. Objects of String are stored through references, so String is a
reference type and not a primitive type.

Example:

String s = "Hello";

2(c) Difference between Abstract Class and Interface


Abstract Class Interface

Can have abstract and normal methods Contains abstract methods

Uses extends Uses implements

Can have constructors No constructors

3(a) Explain private, protected and package-private modifiers

Private

• Accessible only within the same class.

Protected

• Accessible within package and subclasses.

Package-Private (Default)

• Accessible only within the same package.

3(b) What is the function of finally?

Answer:
finally block executes whether an exception occurs or not.

Example:

try{
// code
}
finally{
[Link]("Always executed");
}

4(a) Different States in Applet Life Cycle

1. Initialization (init())

2. Starting (start())

3. Running (paint())

4. Stopping (stop())
5. Destruction (destroy())

4(b) Sketch the Life Cycle of Applet

init()

start()

paint()

stop()

destroy()

5(a) Difference Between Application and Applet

Application Applet

Runs independently Runs inside browser

Has main() method No main() method

Can access local files Restricted access

5(b) What are Local Applet and Remote Applet?

Local Applet

Applet stored on the local computer.

Remote Applet

Applet downloaded from another computer through the internet.

6(a) What is Private Constructor?

Answer:
A constructor declared with the private keyword is called a private constructor.

class Test{
private Test(){}
}
6(b) Utility of Private Constructor

Answer:

1. Prevents object creation from outside the class.

2. Used in Singleton Design Pattern.

3. Provides better control over object creation.

Group-C (Easy Answers) – Java 2016

7(a) Program to Check Palindrome String

A palindrome string reads the same forward and backward.

import [Link];

class Palindrome {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
String s = [Link]();

String rev = "";


for(int i=[Link]()-1; i>=0; i--)
rev += [Link](i);

if([Link](rev))
[Link]("Palindrome");
else
[Link]("Not Palindrome");
}
}

7(b) How to Call One Constructor from Another?

Use the this() keyword.

class Test{
Test(){
this(10);
[Link]("Default");
}

Test(int x){
[Link](x);
}
}

7(c) If Constructor is Private, How Can We Create an Object?

Object can be created using a public static method inside the same class.

class Test{
private Test(){}

static Test getObject(){


return new Test();
}
}

7(d) Variables are Initialized Before Constructor Execution

When an object is created:

1. Variables get default values.

2. Instance variables are initialized.

3. Constructor executes.

class Demo{
int x = 10;

Demo(){
[Link](x);
}
}

Output: 10

8(a) Program to Print Binary and Hexadecimal of a Number


import [Link];

class Convert{
public static void main(String args[]){
Scanner sc = new Scanner([Link]);
int n = [Link]();

[Link]("Binary: " +
[Link](n));

[Link]("Hex: " +
[Link](n));
}
}

8(b) Difference Between Interface and Abstract Class

Interface Abstract Class

Uses implements Uses extends

Only abstract methods (traditional Java) Abstract and normal methods

No constructor Constructor allowed

Supports multiple inheritance Does not support multiple inheritance

8(c) What is Autoboxing?

Autoboxing is the automatic conversion of a primitive type into its wrapper class.

int a = 10;
Integer i = a;

8(d) Advantages of Vector Class

1. Dynamic size.

2. Stores objects.

3. Supports synchronization.

4. Easy insertion and deletion.


9(a) What is Thread? How to Create a Thread?

Thread

A thread is a lightweight process.

Methods to Create Thread

1. Extending Thread class.

2. Implementing Runnable interface.

class MyThread extends Thread{


public void run(){
[Link]("Thread Running");
}
}

9(b) Need of Synchronized Block

Synchronization prevents multiple threads from accessing shared resources simultaneously.

synchronized(this){
// critical section
}

Advantages

• Prevents data inconsistency.

• Ensures thread safety.

9(c) Overriding toString() Method

class Student{
int id=1;

public String toString(){


return "Student ID = " + id;
}
}

Purpose: Returns meaningful object information.


10(a) Program to Sort an Array

import [Link];

class Sort{
public static void main(String args[]){
int a[]={5,2,8,1,3};

[Link](a);

for(int i:a)
[Link](i+" ");
}
}

Output:

12358

10(b) Difference Between Character Stream and Byte Stream

Character Stream Byte Stream

Handles characters Handles bytes

Uses Reader/Writer Uses InputStream/OutputStream

Suitable for text files Suitable for binary files

10(c) How Does Garbage Collector Work?

• Removes unused objects from memory automatically.

• Frees heap memory.

• Runs in the background.

Example:

Student s = new Student();


s = null;

Now the object becomes eligible for garbage collection.


10(d) What is Object Serialization?

Serialization is the process of converting an object into a byte stream for storage or
transmission.

class Student implements Serializable{


int id=1;
}

Advantages

1. Saves object state.

2. Used in file handling.

3. Used in network communication.

11. Short Notes

(a) StringTokenizer

Used to break a string into tokens.

StringTokenizer st =
new StringTokenizer("Java OOP");

(b) Vector Class

A dynamic array that can grow or shrink automatically.

(c) Wrapper Class

Converts primitive data types into objects.

Examples:

• Integer

• Double

• Character

(d) Command Line Arguments

Arguments passed while running a Java program.


java Test Hello

(e) Abstract Class

A class declared using the abstract keyword.

abstract class Shape{


abstract void draw();
}

It cannot be instantiated and is used to achieve abstraction.

Group-A (Easy Answers) – Java 2015

1. Which is a reserved word in Java?

Answer: Native

2. What is bytecode in Java?

Answer: The code generated by the Java compiler.

3. Which statement is correct?

Answer: The try block should be followed by either a catch block or a finally block.

4. JVM stands for?

Answer: Java Virtual Machine

5. To inherit a class from another class, we use:

Answer: extends

6. An interface can define only:

Answer: Abstract methods and final fields

7. In Java Applet, start() method may be invoked:

Answer: Many times

8. An exception is a/an:

Answer: Runtime problem

9. Which keyword is used to define a constant?

Answer: final
10. Output of:

String s = "WBUT";
[Link]([Link](2));

Answer: U

Group-B (Easy Answers) – Java 2015

2. Differentiate between final, finally and finalize

final finally finalize()

Keyword Block Method

Used to make constant Executes always Called before object destruction

Cannot be changed Used in exception handling Used by garbage collector

3. How is Multilevel Inheritance Done in Java?

When one class inherits another class and a third class inherits the second class.

class A{}
class B extends A{}
class C extends B{}

Constructor Calling Sequence

A() → B() → C()

(Base class constructor executes first.)

4. Difference Between Function Overloading and Function Overriding

Overloading Overriding

Same method name, different parameters Same method name and parameters

Same class Parent and child class

Compile-time polymorphism Run-time polymorphism

Example
void add(int a,int b){}
void add(int a,int b,int c){}

5. "Java is Platform Independent" – Justify. What is super? What is final?

Platform Independent

Java source code is converted into bytecode which runs on any JVM.

Rule: Write Once, Run Anywhere (WORA).

super

super refers to the parent class.

super();

final

final is used to make constants or prevent inheritance/overriding.

final int MAX = 100;

6(a). Describe Applet Life Cycle

Methods

1. init() – Initialization

2. start() – Starts applet

3. paint() – Displays output

4. stop() – Stops applet

5. destroy() – Terminates applet

Flow

init()

start()

paint()

stop()

destroy()
6(b). What is a Wrapper Class?

A wrapper class converts primitive data types into objects.

Examples

Primitive Wrapper Class

int Integer

char Character

double Double

float Float

Example

int x = 10;
Integer obj = x;

This process is called Autoboxing.

Group-C (Easy Answers) – Java 2015

7(a) Importance of Inheritance with Example

Inheritance

Inheritance allows one class to acquire properties and methods of another class.

Advantages

1. Code Reusability

2. Easy Maintenance

3. Reduces Code Duplication

Example

class Animal{
void eat(){
[Link]("Eating");
}
}
class Dog extends Animal{
void bark(){
[Link]("Barking");
}
}

7(b) Program to Find Area of a Circle

import [Link];

class Circle{
public static void main(String args[]){
Scanner sc = new Scanner([Link]);

double r = [Link]();
double area = 3.14 * r * r;

[Link]("Area = " + area);


}
}

7(c) Difference Between Abstract Class and Interface

Abstract Class Interface

Can have abstract and normal methods Contains abstract methods

Uses extends Uses implements

Can have constructors No constructors

Single inheritance Multiple inheritance

Difference Between throws and throw

throws throw

Used in method declaration Used to throw exception

Can declare multiple exceptions Throws one exception at a time

Example:
void show() throws IOException
{
}

throw new ArithmeticException();

7(d) Properties of Constructor and Overloaded Constructor

Properties of Constructor

1. Same name as class.

2. No return type.

3. Called automatically.

4. Initializes objects.

Overloaded Constructor

class Test{
Test(){
[Link]("Default");
}

Test(int x){
[Link](x);
}
}

Benefit: Objects can be initialized in different ways.

8(a) Dynamism in OOP

Dynamism

Ability of an object to behave differently at different times.

Types

1. Compile-Time Dynamism

Achieved through Method Overloading.

void add(int a,int b){}


void add(int a,int b,int c){}
2. Run-Time Dynamism

Achieved through Method Overriding.

class A{
void show(){}
}

class B extends A{
void show(){}
}

8(b) Program for Abstraction and Runtime Polymorphism

abstract class Shape{


abstract void draw();
}

class Circle extends Shape{


void draw(){
[Link]("Circle");
}
}

class Square extends Shape{


void draw(){
[Link]("Square");
}
}

class Test{
public static void main(String args[]){
Shape s;

s = new Circle();
[Link]();

s = new Square();
[Link]();
}
}
9(a) What is Destructor?

A destructor is a method used to destroy objects and release resources.

Note: Java has no explicit destructor. Garbage Collector performs memory cleanup.

Example:

Student s = null;

Object becomes eligible for garbage collection.

9(b) How are Exceptions Handled in Java?

Java handles exceptions using:

• try

• catch

• finally

• throw

• throws

Example

try{
int a = 10/0;
}
catch(Exception e){
[Link]("Error");
}

9(c) When Do We Design an Interface?

Use an interface when:

1. Multiple classes need the same behavior.

2. Multiple inheritance is required.

3. Complete abstraction is needed.

Example:
interface Shape{
void draw();
}

10(a) Program to Print Fibonacci Series

class Fibonacci{
public static void main(String args[]){
int a=0,b=1,c;

[Link](a+" "+b+" ");

for(int i=1;i<=8;i++){
c=a+b;
[Link](c+" ");
a=b;
b=c;
}
}
}

Output:

0 1 1 2 3 5 8 13 21 34

10(b) Difference Between Java and C++

Java C++

Platform Independent Platform Dependent

No pointers Supports pointers

No multiple inheritance of classes Supports multiple inheritance

Uses JVM No JVM

10(c) Importance of Naming Conventions in Packages

1. Avoids name conflicts.

2. Makes code readable.


3. Organizes classes properly.

Local Applet

A local applet is stored and executed on the local computer.

11. Short Notes

(a) Dynamic Method Dispatch

Runtime mechanism where overridden method is called based on object type.

A obj = new B();


[Link]();

(b) Abstract Window Toolkit (AWT)

Java GUI package used to create windows, buttons, labels, etc.

Components:

• Button

• Label

• TextField

• Frame

(c) Garbage Collection

Automatic process that removes unused objects from memory.

Benefits:

• Frees memory

• Prevents memory leaks

(d) Thread Priority

Priority decides which thread gets CPU first.

Values:

• MIN_PRIORITY = 1
• NORM_PRIORITY = 5

• MAX_PRIORITY = 10

Example:

[Link](10);

(e) Serialization and Deserialization

Serialization

Converting an object into a byte stream.

Deserialization

Converting byte stream back into an object.

class Student implements Serializable{


int id;
}

Uses:

• File storage

• Network communication

• Object transfer between systems

Group-A (Easy Answers) – Java 2014

1. Same method name with different parameters is called

Answer: Method Overloading

2. Which keyword is used to define a constant?

Answer: final

3. Which method keeps a thread in running state?

Answer: run()

4. Color clr = new Color([Link]);

This statement produces the same red color on any monitor.


Answer: False

5. Most expensive phase of software development life cycle?

Answer: Maintenance

6. Width of line drawn by drawLine() method?

Answer: 1 Pixel

7. Java was developed by

Answer: Sun Microsystems

8. Which keyword is used to invoke the current object?

Answer: this

9. Default return type of main()?

Answer: void

10. Method overloading is one way Java supports

Answer: Polymorphism

Group-B (Easy Answers) – Java 2014

2. Method Overloading and Method Overriding

Method Overloading

Same method name but different parameters.

void add(int a,int b){}


void add(int a,int b,int c){}

Method Overriding

Child class provides its own version of parent class method.

class A{
void show(){}
}

class B extends A{
void show(){}
}
Difference

Overloading Overriding

Same class Parent & Child class

Different parameters Same parameters

Compile-time Run-time

3. What is an Interface? Why Do We Need It?

Interface

An interface is a collection of abstract methods.

interface Shape{
void draw();
}

Need of Interface

1. Achieves abstraction.

2. Supports multiple inheritance.

3. Improves flexibility.

Abstract Class vs Interface

Abstract Class Interface

Can have normal methods Only abstract methods (traditional Java)

Uses extends Uses implements

Can have constructors No constructors

4. What is Dynamic Method Dispatch?

Dynamic Method Dispatch is a mechanism where the method to be executed is decided at


runtime.

A obj = new B();


[Link]();

How Achieved?
By method overriding and inheritance.

5. Difference Between Compile-Time and Run-Time Polymorphism

Compile-Time Run-Time

Method Overloading Method Overriding

Decided by compiler Decided during execution

Faster Slower

6. What is Garbage Collection? What is Static Variable?

Garbage Collection

Removes unused objects from memory automatically.

Student s = new Student();


s = null;

Static Variable

A variable shared by all objects of a class.

class Test{
static int count=0;
}

7. What is Wrapper Class? Utility of final

Wrapper Class

Converts primitive data types into objects.

Examples:

• Integer

• Double

• Character

Integer obj = 10;

Utility of final
1. Create constants.

2. Prevent method overriding.

3. Prevent class inheritance.

final int MAX = 100;

8. Checked and Unchecked Exceptions

Checked Exception

Checked at compile time.

Examples:

• IOException

• SQLException

Unchecked Exception

Occurs at runtime.

Examples:

• ArithmeticException

• NullPointerException

9. How to Define a Class That Cannot Be Inherited?

Use the final keyword.

final class Test{


}

A final class cannot be extended by another class.

Group-C (Easy Answers) – Java 2014

10(a) What is OOP? Difference Between OOP and POP

OOP (Object-Oriented Programming)


A programming approach based on objects and classes.

Features

• Encapsulation

• Inheritance

• Polymorphism

• Abstraction

OOP vs POP

OOP POP

Object-based Function-based

More secure Less secure

Code reusable Less reusable

Uses classes Uses functions

10(b) What is an Exception? How to Handle It?

Exception

An exception is an error that occurs during program execution.

Handling Methods

• try

• catch

• finally

• throw

• throws

Example

try{
int a = 10/0;
}
catch(Exception e){
[Link]("Error");
}
10(c) Multiple Inheritance in Java

Java does not support multiple inheritance through classes but supports it through
interfaces.

interface A{
void showA();
}

interface B{
void showB();
}

class C implements A,B{


public void showA(){}
public void showB(){}
}

11. What is Polymorphism? Types of Polymorphism

Polymorphism

Polymorphism means one interface, many forms.

Types

1. Compile-Time Polymorphism

Achieved through Method Overloading.

void add(int a,int b){}


void add(int a,int b,int c){}

2. Run-Time Polymorphism

Achieved through Method Overriding.

class A{
void show(){}
}

class B extends A{
void show(){}
}
Overloading vs Overriding

Overloading Overriding

Same class Parent & Child

Different parameters Same parameters

Compile-time Run-time

12. Short Notes

(a) Interface

An interface contains abstract methods.

interface Shape{
void draw();
}

Advantages

• Abstraction

• Multiple inheritance

• Flexibility

(b) Package

A package is a collection of related classes and interfaces.

package mypack;

Advantages

• Organizes code

• Avoids name conflicts

(c) Container Class

A container class stores multiple objects.

Examples:

• Vector
• ArrayList

• HashMap

(d) Exception Handler

Exception handler catches and manages errors during execution.

try{
}
catch(Exception e){
}

Benefit

Prevents abnormal program termination.

(e) Abstraction

Abstraction means hiding implementation details and showing only essential features.

abstract class Shape{


abstract void draw();
}

Advantage

Reduces complexity.

(f) Garbage Collection

Garbage Collection automatically removes unused objects from memory.

Student s = new Student();


s = null;

Advantages

• Frees memory

• Prevents memory leaks

13(a) What is a Thread? Life Cycle of Thread

Thread
A thread is a lightweight process.

Life Cycle

New

Runnable

Running

Blocked/Waiting

Dead

13(b) Ways to Create Thread & Set Priority

Create Thread

1. Extending Thread class

class MyThread extends Thread{


public void run(){}
}

2. Implementing Runnable interface

class MyThread implements Runnable{


public void run(){}
}

Set Priority

[Link](10);

Priority Range:

• MIN_PRIORITY = 1

• NORM_PRIORITY = 5

• MAX_PRIORITY = 10

Need of Synchronized Block

synchronized(this){
// critical code
}
Prevents multiple threads from accessing shared resources simultaneously.

13(c) What is an Applet? Life Cycle and Demerits

Applet

A Java program that runs inside a web browser.

Life Cycle

init()

start()

paint()

stop()

destroy()

Demerits

1. Requires browser support.

2. Security restrictions.

3. Slower than applications.

14(a) Program to Check Palindrome String

import [Link];

class Palindrome{
public static void main(String args[]){
Scanner sc=new Scanner([Link]);
String s=[Link]();

String rev="";

for(int i=[Link]()-1;i>=0;i--)
rev+=[Link](i);

if([Link](rev))
[Link]("Palindrome");
else
[Link]("Not Palindrome");
}
}

14(b) Program for Series


1 1 1
1+ + + ⋯+
2 3 𝑛

class Series{
public static void main(String args[]){
int n=10;
double sum=0;

for(int i=1;i<=n;i++)
sum=sum+1.0/i;

[Link](sum);
}
}

14(c) Serialization and Deserialization

Serialization

Converting an object into a byte stream.

Deserialization

Converting byte stream back into an object.

class Student implements Serializable{


int id;
}

Uses

• File storage

• Network communication

• Data transfer
15. Features of Java & Role of JVM

Features of Java

1. Platform Independent

2. Object Oriented

3. Secure

4. Robust

5. Multithreaded

Role of JVM

• Executes bytecode.

• Provides platform independence.

• Manages memory.

What is Unicode?

Unicode is a standard character encoding system that supports all languages.

Example:

char ch = 'A';

Use of super Keyword

super refers to the parent class.

class A{
A(){
[Link]("Parent");
}
}

class B extends A{
B(){
super();
}
}

Uses of super

1. Call parent constructor.


2. Access parent variables.

3. Access parent methods.

You might also like