Oop Important Questions
Oop Important Questions
Program:
import java.util.Scanner;
marks1 = scanner.nextInt();
marks2 = scanner.nextInt();
marks3 = scanner.nextInt();
System.out.println("Grade: A");
System.out.println("Grade: B");
} else if (average >= 50) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: D");
COMPILATION:
C:\jdk1.6.0\bin>javac StudentGrade.java
C:\jdk1.6.0\bin>java StudentGrade
Grade: B
3.Explain Inheritance and give example. (any two types)
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of the parent class. Moreover, you can add new methods and fields in your current class
also.
1.Simple
2. Multilevel
3.hybrid
4.Hierarchical
The forms of inheritance are shown. Java does not directly Implement multiple inheritance.
However, this concept is implemented using a secondary inheritance path is the form of
interface.
Syntax: -
Public class A
{
….
}
Public class B extends A
{
…..
}
class a
{
a()
{
System.out.println("Hello");
}
}
class b extends a
{
}
class sinh1
{
public static void main(String args[])
{
b obj=new b();
}
}
Compile:
F:\jdk\bin>javac sinh1.java
F:\jdk\bin>java sinh1
Output:-
Hello
Multilevel inheritance:-
When there is a chain of inheritance, it is known as multilevel inheritance
Syntax: -
Public class A
{
….
}
Public class B extends A
{
….
}
Public class c extends B
{
….
}
class one
{
public void print_sara()
{
System.out.println("sara");
}
}
class two extends one
{
public void print_for()
{
System.out.println("for");
}
}
class three extends two
{
public void print_sara()
{
System.out.println("sara");
}
}
public class mlinh2
{
public static void main(String[] args)
{
three g = new three();
g.print_sara();
g.print_for();
g.print_sara();
}
}
Compile:
F:\jdk\bin>javac mlinh2.java
F:\jdk\bin>java mlinh2
Output:-
sara
for
Sara
Advantages:
Inheritance promotes reusability. When a class inherits or derives another class, it can
access all the functionality of inherited class.
Reusability enhanced reliability. The base class code will be already tested and
debugged.As the existing code is reused, it leads to less development and maintenance
costs.
Disadvantages:-
Syntax: -
interface interfacename
{
Static final datatype variablename=value;
returntype methodname(parameter list);
}
An interface is basically a kind of class like classes, interfaces contain methods and final
fields. This means that interfaces do not specify any code to implement these methods
and data fields contain only constants.
Therefore, it is the responsibility of the class that implements an interface to define the
code for implementation of these methods. The syntax for defining an interface is very
similar to that for defining a class. The general form of an interface definition is:
Interface interfacename
{
variable declaration;
method declaration;
Here interface is the keyword, and interface is any valid java variable (just like class names).
Implementing the interface
Interfaces are used in super class, whose properties are acquired or inherited by classes.
Syntax: -
variable declaration;
method codes();
In the above syntax the interface is used as a superclass (or) inherited by class.
The various implementation figures are below.
interface In1
void display();
System.out.println("Hello");
t.display();
System.out.println(a); // System.out.println(t.a);
}}
Compile:
F:\jdk\bin>javac inf1.java
F:\jdk\bin>java inf1
Output:-
Hello
10
Packages:-
Java packaging is a concept similar to class libraries in other languages. Packages provides
reusability of another program classes, without physically copying it or without declaring it
again.
The java packages are divided into two types.
1.Built-in Packages:
Built-in packages or predefined packages are those that come along as a part of JDK (Java
Development Kit) to simplify the task of Java programmer.Some of the commonly used built-
in packages are java.lang, java.io, java.util, java.applet, etc.
User-defined packages are those which are developed by users in order to group related
classes, interfaces, and sub packages. With the help of an example program, let’s see how
to create packages, compile Java programs inside the packages and execute them.
dot method:-
This method is the easiest way when you access only the class.
Syntax:-
import packagename.classname;
Naming method:-
All the packages in lowercase letters and classes are in uppercase letters.
The system packages are accessed in a program by using import keywords like system
packages user defined packages are imported.
Syntax:-
Import package1.package2.classname;
Here, package2 is inside the package1 and class is inside the package2.
cd\
cd program files
cd jdk-13.0.1\bin
make a directory as md package name
change a directory as cd package name
set path in java as set path
D:\program files\jdk-13.0.1\bin
Javac
The path is specified.
In Notepad
Write the package program
Save the program in packagename.
Compile the program in command prompt
Compile should be javac filename.java
In Notepad (second note pad window)
Write the class program
Save the program in bin.
Compile the program in command prompt
cd..
javac filename.java
java filename
output will be displayed.
Note: -
Normal path like,
D:\jdk-13.0.1\bin>
Then md package name
Cd package name
Set path= “D:\jdk-13.0.1\bin”
Compile :-
F:\jdk-13.0.1\bin>cd xyz
F:\jdk-13.0.1\bin\xyz>javac pack1.java
import xyz.pack1;
class pac1
{
public static void main(String args[])
{
pack1 p=new pack1();
p. identity();
}
}
Store the file in sub directory then it will compile and run.
Compile:
F:\jdk-13.0.1\bin>javac pac1.java
F:\jdk-13.0.1\bin>java pac1
Output: -
He is a Software Engineer
(Exception) Errors are the common problem in programming and error may produce
unexpected result and abnormal termination or even crush. The system these errors may be
classified into 2 types as follows
1. Compile time Error
2. Runtime Error
This type of errors are caused during compilation like missing of semicolon, misspelling of
identifiers and keywords, missing double quotes in string, type assignments, and etc…
Whenever the complier causes an error, so it is necessary to edit the errors and recompile
it.
Runtime Error
After the successful compilation, class file created due to the wrong logic or stack overflow.
We cannot get the correct result during the runtime. This error are called Runtime Error like
dividing by zero, Converting invalid string into numbers, etc…
Java Exceptions
Array Store Exception When you store the wrong type of data in an
array
Try-catch Exception
The keyword try is used to preface a block of statements which may generate exceptions.
This block of statements is known as try block.
The catch block that allows/catches an exception must immediately follow the try block that
throws the exception. The general form of these 3 blocks is as follows
--------
try
{
--------
Throws Exception;
}catch(type arg)
{
--------
}
--------
Compile:
F:\jdk-13.0.1\bin>javac tep1.java
F:\jdk-13.0.1\bin>java tep1
Output:
Division by Zero
After catch statement
throws Exception
A throws class lists the types of exception that a method might throw. It is a general rule that
any method that might throw an exception must declare the fact. This is a form of enforced
documentation.
Throw is necessary for all exceptions. Except those of type error or runtime exception or any
of their subclass all other exceptions that a method can throw must be declared in the
throws clause if they do not compile time error will result.
Syntax:
{
//body of method
Compile:
F:\jdk-13.0.1\bin>javac throws1.java
F:\jdk-13.0.1\bin>java throws1
Output:
Inside throwing one
Caught java.lang.IllegalAccessException: Exception
try-catch-finally Exception
Suppose there is some action you absolutely many perform, no matter whatever happens
while executing a group of statements.
Syntax:
--------
--------
Try
{
--------
//a group of statements
--------
}
Finally Flow chart for try-catch-Finally
{
--------
//absolutely must do it
--------
}
import java.lang.Exception;
class my extends Exception
{
my(String message)
{
super(message);
}
}
class finally1
{
public static void main(String ar[])
{
int x=5,y=1000;
try
{
float z=(float)x/(float)y;
if(z<0.01)
{
throw new my("Number is too small");
}
}catch(my e)
{
System.out.println("Caught my exception");
System.out.println(e.getMessage());
}
finally
{
System.out.println("I am always here...");
}
}
}
Compile:
F:\jdk-13.0.1\bin>javac finally1.java
F:\jdk-13.0.1\bin>java finally1
Output:
Caught my exception
Number is too small
I am always here...
7. Explain wrapper class and give an example program
Wrapper classes
Primitive datatypes may be converted into object types by using wrapper classes
contained in java.lang.packages.
(or)
A Wrapper class is a class whose object wraps or contains a primitive data type. When we
create an object to a wrapper class, it contains a field and, in this field, we can store a
primitive data type. In other words, we can wrap a primitive value into a wrapper class
object.
class wrap5
byte a = 1;
int b = 10;
double d = 250.5;
char e='a';
Character charobj=e;
byte bv = byteobj;
int iv = intobj;
float fv = floatobj;
double dv = doubleobj;
char cv = charobj;
}}
Compile:
F:\jdk\bin>javac wrap5.java
F:\jdk\bin>java wrap5
Output:
8.Explain in detail about Method Overloading and Method Over Riding with example
In Java, Method Overloading allows different methods to have the same name, but
different signatures where the signature can differ by the number of input parameters or
type of input parameters, or a mixture of both.
// overloading in Java
return (x + y);
return (x + y + z);
return (x + y);
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10.5, 20.5));
Output
30
60
31.0
Using method overloading, programmers can perform a task efficiently and effectively.
Method Overriding:
• Conditions: The method in the subclass must have the same name, return type, and
parameters as the method in the superclass.
• Example: In Java, overriding method supports runtime polymorphism, where the
overridden method version used depends on the object's type at runtime.
PROGRAM:
class Animal {
void sound() {
@Override
void sound() {
System.out.println("Dog barks");
OUTPUT:
Dog barks
CHECKBOX: -
A checkbox is a control that is used to turn an option on or off. It consists of a small box
that can either contain a check mark or not. There is 2 labels associated with each
checkbox that describe what option the box represents. You change the state of a
checkbox by clicking on it. Checkboxes can be used individually or as part of a group.
Checkboxes are objects of the checkbox class.
CONSTRUCTORS: -
1. checkbox()
2. checkbox(String s)
import java.awt.*;
cb1()
checkbox1.setBounds(100,100, 50,50);
checkbox2.setBounds(100,150, 50,50);
f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
new cb1();
}}
Compile:
F:\jdk-1.0.6\bin>javac cb1.java
Run:
F:\jdk-1.0.6\bin>java cb1
Output:-
Generic Methods and Classes allow you to create methods and classes that can operate
on different data types while providing type safety. They’re used in Java to make code more
reusable and flexible.
Generic Classes
A generic class defines a class with one or more type parameters. This allows the class to
operate on objects of various types, specified when an instance is created.
public T getContent() {
return content;
}
}
Generic Methods
A generic method has a type parameter (like <T>) that appears before the return type in
the method signature. It can be used with any type of data, making it flexible.
Example:
printArray(intArray); // Output: 1 2 3
printArray(strArray); // Output: A B C
}
}
OUTPUT:
123
ABC
Advantages of Generics
PROGRAM:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
double num1;
double num2;
double ans;
char op;
Scanner reader = new Scanner(System.in);
System.out.print("Enter two numbers: ");
num1 = reader.nextDouble();
num2 = reader.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
op = reader.next().charAt(0);
switch(op) {
case '+': ans = num1 + num2;
break;
case '-': ans = num1 - num2;
break;
case '*': ans = num1 * num2;
break;
case '/': ans = num1 / num2;
break;
default: System.out.printf("Error! Enter correct operator");
return;
}
System.out.print("The result is given as follows:");
System.out.printf(num1 + " " + op + " " + num2 + " = " + ans);
}
}
OUTPUT:
Enter two numbers: 10.0 7.0
Enter an operator (+, -, *, /): -
The result is given as follows:
10.0 - 7.0 = 3.0
12.Explain in detail about file input stream and file output stream
FileOutputStream class
import java.io.*;
class Test{
public static void main(String args[]){
try{
FileOutputstream fout=new FileOutputStream("abc.txt");
String s="java is my favourite language";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){system.out.println(e);}
}
}
Output:success...
FileInputStream class
Java FileInputStream class obtains input bytes from a file.It is used for reading
streams of raw bytes such as image data. For reading streams of characters, consider
using FileReader.
It should be used to read byte-oriented data for example to read image, audio,
video etc.
Example of FileInputStream class
import java.io.*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("abc.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.println((char)i);
}
fin.close();
}catch(Exception e){system.out.println(e);}
}
}
Output: java is my favourite language
FileInputStream
Advantages:
1. Direct Byte Reading: Reads data directly as bytes, suitable for binary files like
images and audio.
2. Efficient for Raw Data: Good for handling low-level file operations, useful for raw
data manipulation.
Disadvantages:
FileOutputStream
Advantages:
1. Direct Byte Writing: Writes bytes directly, useful for binary data.
2. File Creation: Can create new files if they don't exist, making it suitable for file
generation tasks.
Disadvantages:
In Java, a layout manager is an object that controls the size, position, and arrangement of
components (like buttons, text fields, labels, etc.) within a container (such as a frame,
panel, or applet). Layout managers help organize components in a way that adjusts
automatically when the window is resized or when components are added/removed.
FlowLayout
Places components in a row, from left to right.
BorderLayout
Divides the container into five regions: North, South, East, West, and Center.
Each region can hold only one component, and the component is stretched to fill that
region.
Example: A header at the top (North), footer at the bottom (South), sidebars (East and
West), and main content in the center.
GridLayout
Each cell of the grid is of equal size, and components are stretched to fill their cells.
GridBagLayout
A flexible, complex layout manager that arranges components in a grid of rows and
columns.
Allows components to span multiple rows or columns and provides more control over
spacing and alignment.
Example: A form layout where labels and input fields are aligned in rows but with varying
sizes.
CardLayout
Manages components as layers (or "cards") in the same area; only one card is visible at a
time.
Example: A tabbed navigation interface where different tabs show different components.
PROGRAM:
import java.applet.Applet;
import java.awt.*;
import javax.swing.*;
/* applet code = "layouteg.java"width=700 eight = 900></applet>*/
setSize(300, 200);
setVisible(true);
}
Responsive Design:
Layout managers adapt to different screen sizes and resolutions, allowing the GUI to be
resized without losing the arrangement of components. This is especially useful for
building cross-platform applications.
Reduced Complexity:
They reduce the need to calculate and set specific positions for each component. You can
simply add components to a container, and the layout manager arranges them according
to the rules of the chosen layout.
Layout managers can be restrictive if you need precise positioning of components. For
applications that require exact control over layout (e.g., games or graphics-intensive apps),
layout managers may not be suitable.
Advanced layouts like GridBagLayout have complex configurations that can be challenging
for beginners. This can lead to a steeper learning curve and longer development times.
Performance Overhead:
Layout managers add a small performance overhead because they calculate positions and
sizes dynamically. While usually minor, this overhead can impact performance in complex
GUIs with many components.
Layout managers may limit creativity in designs that require unique or non-standard
arrangements, making them less ideal for highly customized or artistic interfaces.
14.Explain menu listener,keyboard listener,window listener with example
1. MenuListener in Java
The MenuListener interface in Java is used with JMenu components to detect interactions
specifically with menus in a GUI application. Menu interactions are important for user
navigation and executing specific tasks.
• Purpose: MenuListener tracks events that occur on menus, such as when a menu
is selected, deselected, or canceled. This enables developers to perform specific
actions as the user interacts with the menu.
• Methods:
o menuSelected(MenuEvent e): Invoked when the user selects a menu. This
could be used to dynamically update menu items based on the application’s
state.
o menuDeselected(MenuEvent e): Called when a menu is deselected. This
is useful for resetting menu options or performing clean-up tasks.
o menuCanceled(MenuEvent e): Triggered when the menu selection is
canceled, usually by clicking outside the menu. This helps to stop certain
actions if the user decides not to proceed.
• Example:
The KeyListener interface captures keyboard events such as key presses, key releases,
and character typing. This is useful for real-time processing of keyboard inputs, particularly
in forms or games.
• Purpose: KeyListener is used when you need to track user inputs from the
keyboard directly, often to respond to commands or shortcuts in an application.
• Methods:
o keyPressed(KeyEvent e): Called when a key is pressed down. It’s
typically used for actions that should happen immediately when a key is
pressed.
o keyReleased(KeyEvent e): Invoked when a key is released. This can be
used to stop actions that were started when the key was pressed.
o keyTyped(KeyEvent e): Called when a key is typed, meaning a character
key is input (e.g., letters, numbers). This is useful for character validation in
text fields.
• Example:
textField.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed: " + e.getKeyChar());
}
public void keyReleased(KeyEvent e) {
System.out.println("Key Released: " + e.getKeyChar());
}
public void keyTyped(KeyEvent e) {
System.out.println("Key Typed: " + e.getKeyChar());
}
});
The WindowListener interface monitors events that impact the state of a window, such
as opening, closing, and minimizing actions. This listener is crucial for applications where
resource management and state changes need to be handled as the window state
changes.
frame.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {
System.out.println("Window Opened");
}
public void windowClosing(WindowEvent e) {
System.out.println("Window Closing");
System.exit(0); // Closes the program
}
public void windowClosed(WindowEvent e) {
System.out.println("Window Closed");
}
public void windowIconified(WindowEvent e) {
System.out.println("Window Minimized");
}
public void windowDeiconified(WindowEvent e) {
System.out.println("Window Restored");
}
public void windowActivated(WindowEvent e) {
System.out.println("Window Activated");
}
public void windowDeactivated(WindowEvent e) {
System.out.println("Window Deactivated");
}
});
• Purpose: To initialize new objects with initial values or perform any setup required
when an object is created.
• Naming: The constructor's name must match the class name exactly, including
case.
• No Return Type: Constructors do not return any value, not even void.
• Types of Constructors:
o Default Constructor: A constructor with no parameters. Java provides a
default constructor automatically if no constructors are defined in the class.
o Parameterized Constructor: A constructor that takes parameters, allowing
you to set initial values for object fields at the time of creation.
// Default constructor
public Book() {
title = "Unknown";
price = 0.0;
}
// Parameterized constructor
public Book(String title, double price) {
this.title = title;
this.price = price;
}