OOP (Imp)
OOP (Imp)
• Java Runtime Environment (JRE) is a software environment that runs Java bytecode.
It includes the Java Virtual Machine (JVM), core Java classes, and supporting files.
The JRE is what allows you to run Java applications on your computer.
• Java Development Kit (JDK) is a software development environment (IDE) that
contains the JRE, plus tools for developing and testing Java applications. The JDK
includes a compiler, debugger, and other tools that make it easier to write Java
programs.
• Just-in-time compiler (JIT) is a part of the JVM that optimizes the execution of Java
bytecode. The JIT compiler compiles bytecode into native machine code at runtime,
which can significantly improve the performance of Java applications.
Here is a table that summarizes the differences between JRE, JDK, and JIT:
Java
public class StaticExample {
static int count = 0;
System.out.println(count); // Prints 2
}
}
Java
public class StaticExample {
static void incrementCount() {
count++;
}
System.out.println(count); // Prints 2
}
}
OOP-1 BY: -DEEP SHAH
• Single inheritance: A subclass can inherit from only one superclass. For example, the
Dog class can inherit from the Animal class.
• Multilevel inheritance: A subclass can inherit from a superclass that also inherits
from another superclass. For example, the German Shepherd class can inherit from
the Dog class, which inherits from the Animal class.
• Hierarchical inheritance: A class can be inherited by multiple subclasses. For
example, the Animal class can be inherited by the Dog class, the Cat class, and the
Bird class.
• Hybrid inheritance: A combination of single, multilevel, and hierarchical inheritance.
For example, the Bird class can inherit from the Animal class, which inherits from the
LivingThing class, and the FlyingBird class can inherit from the Bird class.
Java
public class Animal {
public void eat() {
System.out.println("The animal is eating.");
}
}
• Any other class can call the main() method. This is useful for testing and debugging
purposes. For example, you can create a separate class to test the main() method of
another class.
• The main() method does not need to be instantiated. This saves memory and
execution time.
• The main() method can be called from the command line. This is useful for running
Java programs from the command line.
Write a program, which shows an example of function overloading.
public class OverloadingExample {
Java
class Animal {
public void makeSound() {
System.out.println("I am an animal");
}
}
Describe abstract class called Shape, which has three subclasses say
Triangle, Rectangle, and Circle. Define one method area() in the abstract
class and override this area() in these three subclasses to calculate for
specific object i.e. area() of Triangle subclass should calculate area of
OOP-1 BY: -DEEP SHAH
@Override
public double area() {
return 0.5 * base * height;
}
}
@Override
public double area() {
return length * width;
}
}
@Override
OOP-1 BY: -DEEP SHAH
@Override
public double area() {
// This will not compile because the area() method is final in the Shape class
return 0.5 * base * height;
}
}
Define Interface and explain how it differs from the class.
An interface in Java is a reference type that is used to declare a behaviour that classes must
implement. They are similar to protocols. Interfaces are declared using the interface
keyword, and may only contain method signature and constant declarations.
Here are some of the key differences between interface and class in Java:
OOP-1 BY: -DEEP SHAH
Java
class Animal {
@Override
public void speak() {
System.out.println("Woof!");
}
}
@Override
public void speak() {
System.out.println("Meow!");
}
}
Text I/O
Binary I/O
The ArrayList class in Java is a resizable array. It implements the List interface and
extends the AbstractList class. ArrayLists are dynamic, meaning that they can grow
or shrink as needed. This makes them a flexible data structure to use in Java
programs.
Java
import java.util.ArrayList;
System.out.println(cars);
}
}
What is an Exception? List out various built-in exceptions in JAVA and explain
any one Exception class with suitable example.
In Java, an exception is an event that occurs during the execution of a program that
disrupts the normal flow of the program's instructions. Exceptions can be caused by
a variety of factors, such as invalid input, accessing a nonexistent object, or dividing
by zero.
When an exception occurs, the program will typically stop executing and display an
error message. However, it is possible to handle exceptions using exception
handling.
try {
} catch (Exception e) {
System.out.println(e.getMessage());
}
OOP-1 BY: -DEEP SHAH
A generic type is a type that can be used with different types of data. This is done by
using type parameters, which are placeholder names for the actual types that will be
used.
To declare a generic type in a class, you use the <> symbol to specify the type
parameters. For example, the following code declares a generic class called Box:
Java
public class Box<T> {
private T value;
public T getValue() {
return value;
}
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
fileReader.close();
}
}
New: A newly created thread is in the new state. The thread has not yet started to
run when the thread is in this state.
Runnable: A thread that is ready to run is moved to a runnable state. In this state,
a thread might actually be running or it might be ready to run at any instant of
time.
Waiting: A thread that is waiting is waiting for some other thread to perform a
particular action. For example, a thread might be waiting for another thread to
notify it that a condition has been met.
Terminated: A thread that has terminated is in the terminated state. The thread
has finished running and will not be run again.
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
OOP-1 BY: -DEEP SHAH
• BorderPane: The BorderPane layout pane places its children in five regions:
top, bottom, left, right, and center.
• FlowPane: The FlowPane layout pane places its children in a single row or
column, depending on the orientation.
• GridPane: The GridPane layout pane places its children in a grid, with each
child occupying a single cell.
• HBox: The HBox layout pane places its children in a horizontal row.
• VBox: The VBox layout pane places its children in a vertical column.
• StackPane: The StackPane layout pane places its children on top of each
other.
• AnchorPane: The AnchorPane layout pane allows you to anchor its children to
specific positions on the pane.
• TilePane: The TilePane layout pane places its children in a grid, with each
child occupying a single cell of equal size.
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Label_Test extends Application {
@Override
OOP-1 BY: -DEEP SHAH
Example of HBox
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Label_Test extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
HBox root = new HBox();
Scene scene = new Scene(root,200,200);
root.getChildren().addAll(btn1,btn2);
primaryStage.setScene(scene);
primaryStage.show();
OOP-1 BY: -DEEP SHAH
}
public static void main(String[] args) {
launch(args);
}
}
Write importance of JAVAFX compare to AWT and Swing.
OOP-1 BY: -DEEP SHAH
public MyClass() {
// This is the default constructor.
}
Encapsulation is the hiding of data and methods within an object. This means that
the data and methods are not directly accessible from outside the object. Instead,
they can only be accessed through the object's public interface.
this.make = make;
this.model = model;
this.year = year;
return make;
return model;
return year;
Explain in detail how inheritance and polymorphism are supported in java with
necessary examples.
What is a Package? What are the benefits of using packages? Write down the
steps in creating a package and using it in a java program with an example.
A package is a named collection of classes and interfaces in Java. Packages are used to
organize code and to prevent name conflicts.
• Organization: Packages can be used to organize code into logical groups. This makes
it easier to find and understand the code.
• Name conflict prevention: Packages prevent name conflicts by allowing different
classes to have the same name, as long as they are in different packages.
• Importing: Packages can be imported into other packages, which allows the classes
in the imported package to be used in the importing package.
Here are the steps in creating a package and using it in a Java program:
1. Create a package directory. The package directory should have the same name as
the package.
Java
// Create the package directory.
mkdir mypackage
Dynamic binding is a feature of object-oriented programming (OOP) that allows the method to
be called at runtime, instead of compile time.
OOP-1 BY: -DEEP SHAH
@Override
public void makeSound() {
System.out.println("The dog is barking");
}
}
@Override
public void makeSound() {
System.out.println("The cat is meowing");
}
}
Finalization is a process in Java that allows an object to perform cleanup activities before it is
garbage collected.
public class MyClass {
@Override
protected void finalize() throws Throwable {
OOP-1 BY: -DEEP SHAH
super.finalize();
import java.util.Scanner;
class AreaCalculation
{
double area;
void circle(double r)
{
area= (22*r*r)/7;
}
}
class AreaOfCircle extends AreaCalculation
{
public static void main(String args[])
{
Scanner s= new Scanner(System.in);
System.out.println("Enter the radius:");
double rad= s.nextDouble();
AreaOfCircle a=new AreaOfCircle();
a.circle(rad);
System.out.println("Area of Circle is: " + a.area);
}
}
Java
interface Callback {
void onSuccess();
void onFailure();
OOP-1 BY: -DEEP SHAH
class MyClass {
public void doSomethingAsync(Callback callback) {
// Perform some asynchronous task.
// ...
@Override
public void onFailure() {
System.out.println("The task failed!");
}
};
With a neat diagram explain the Model view controller design pattern and list
out the advantages and disadvantages of using it in designing an application.
OOP-1 BY: -DEEP SHAH
The Model-View-Controller (MVC) design pattern is a software design pattern that separates
the application's concerns into three interconnected parts: the model, the view, and the
controller.
Model
The model represents the application's data and business logic. It is responsible for storing
and retrieving data, and for performing calculations. The model should not be concerned
with how the data is presented to the user.
View
The view is responsible for presenting the data to the user. It does not interact with the
model directly, but instead receives data from the controller. The view should not be
concerned with how the data is stored or calculated.
Controller
The controller acts as an intermediary between the model and the view. It receives requests
from the view, and then interacts with the model to get the data that is needed. The
controller then updates the view with the new data.
• Separation of concerns: The MVC pattern separates the application's concerns into
three distinct parts, which makes the application easier to understand, develop, and
maintain.
• Testability: The MVC pattern makes it easy to test the different parts of the
application independently. This is because the model, view, and controller are all
loosely coupled.
• Scalability: The MVC pattern makes it easy to scale the application by adding more
models, views, or controllers.
Disadvantages of using MVC
• Overhead: The MVC pattern can introduce some overhead, as it requires the
application to create and manage three separate objects.
• Complexity: The MVC pattern can be complex to implement, especially for large
applications.
• Communication: The MVC pattern requires the model, view, and controller to
communicate with each other. This can be a source of errors if the communication is
not done properly.
list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
OOP-1 BY: -DEEP SHAH
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object-oriented
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
import java.util.Scanner;
To compile and run this program, you can use the following commands:
javac KeywordsDemo.java
java KeywordsDemo
This will compile the program and then run it. The output of the program will be:
Here is an explanation:
• Statement (i) is a valid statement because it creates a new instance of the A class.
OOP-1 BY: -DEEP SHAH
• Statement (iii) is also a valid statement because the B class can inherit from the A
class.
• Statement (iv) is a valid statement because it creates a new instance of the B class.
• Statement (ii) is an invalid statement because it tries to create a new instance of the
A class using a reference of the B class. This is not allowed because the B class is a
subclass of the A class, and therefore cannot be used to create an instance of the A
class.
class A {
class B extends A {
}
public class Main {
public static void main(String[] args) {
B b = new A(); // This will cause a compilation error.
}
}
Write a java program to take infix expressions and convert it into prefix expressions.
import java.util.*;
public class Main
{
public static int precedence(char op) {
switch (op) {
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
}
return -1;
}
OOP-1 BY: -DEEP SHAH
if (precedence(ch) > 0) {
while (operators.isEmpty() == false && precedence(operators.peek()) > precedence(ch)) {
prefix += operators.pop();
}
operators.push(ch);
} else if (ch == '(') {
char x = operators.pop();
while (x != ')') {
prefix += x;
x = operators.pop();
}
while (!operators.isEmpty()) {
prefix += operators.pop();
}
Explain file io using byte stream with appropriate example. hint: use FileInputStream,
FileOutputStream.
OOP-1 BY: -DEEP SHAH
File I/O is the process of reading and writing data to and from files. Byte streams are a type
of I/O that work with bytes, which are the smallest unit of data in a computer.
FileInputStream and FileOutputStream are two classes in the Java API that provide methods
for reading and writing bytes to and from files.
Java
import java.io.FileInputStream;
fis.close();
}
}
Java
class Animal {
public void makeSound() {
System.out.println("Animal is making a sound");
}
}
Java
class Animal {
public abstract void makeSound();
}
}
}
FileReader and FileWriter are two classes in the Java API that provide methods for reading
and writing characters to and from files.
Java
import java.io.FileReader;
fr.close();
}
}
Java
import java.io.FileWriter;
fw.write(text);
fw.close();
}
}
• Encapsulation is the bundling of data and methods into a single unit. This allows us
to protect the data from unauthorized access and to control how the data is used.
• Access specifiers are keywords that are used to control the access to members of a
class. There are four access specifiers in Java:
o public: This is the most open access specifier. Any class can access public
members.
o protected: This is a more restricted access specifier. Only subclasses of the
class can access protected members.
o default: This is the default access specifier. Only classes in the same package
can access default members.
o private: This is the most restricted access specifier. Only the class itself can
access private members.
Java Collections is a framework that provides a set of classes and interfaces for storing and
manipulating collections of objects. The Java Collections framework is one of the most
important parts of the Java programming language. It is used in almost every Java program.
The Java Collections framework includes a wide variety of classes and interfaces, including:
Here are some of the benefits of using the Java Collections framework:
• Button: A button is a graphical element that the user can click to perform an action.
• Label: A label is a graphical element that displays text.
• TextField: A text field is a graphical element that allows the user to enter text.
• TextArea: A text area is a graphical element that allows the user to enter multiple
lines of text.
• ListView: A list view is a graphical element that displays a list of items.
• TreeView: A tree view is a graphical element that displays a hierarchical list of items.
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) {
// Create a label
Label label = new Label("Hello, World!");
// Create a button
Button button = new Button("Click me!");
// Create a scene
Scene scene = new Scene(vbox, 300, 250);
Implicit type conversion is when the compiler automatically converts a value from one data
type to another. This is done when the two data types are compatible, meaning that they
can be stored in the same amount of memory. For example, the compiler will automatically
convert a byte value to an int value, because both data types are stored in 8 bits of memory.
Explicit type conversion is when the programmer manually converts a value from one data
type to another. This is done using the cast operator.
OOP-1 BY: -DEEP SHAH
if (x > 5) {
if (y > 10) {
System.out.println("x is greater than 5 and y is greater than 10");
}
}
• Multi-way if statements, also known as else if statements, allow you to check
multiple conditions and execute different code depending on which condition is true.
For example, the following code shows a multi-way if statement:
Java
int x = 10;
if (x < 5) {
System.out.println("x is less than 5");
} else if (x == 5) {
System.out.println("x is equal to 5");
} else {
System.out.println("x is greater than 5");
}
• Final is an access modifier that can be applied to classes, methods, and variables.
A final class cannot be subclassed, a final method cannot be overridden, and a final
variable cannot be reassigned.
• Finally is a keyword that can be used to create a block of code that is always
executed, even if an exception is thrown. This is useful for performing cleanup tasks,
such as closing files or releasing resources.
• Finalize is a method that is called by the garbage collector just before an object is
destroyed. This method can be used to perform cleanup tasks, such as releasing
resources or writing data to a file.
OOP-1 BY: -DEEP SHAH
• Final class cannot be subclassed. This means that no other class can inherit from the
final class.
• Final method cannot be overridden. This means that no subclass of the class that
contains the final method can override the method.
• Final variable cannot be reassigned. This means that the value of the final variable
cannot be changed after it is initialized.
Explain Primitive data type and wrapper class data types.
Primitive data types are the basic data types that are built into the Java language. They are
simple data types that represent a single value, such as an integer, a floating-point number,
or a character. Primitive data types are declared using the following keywords:
• byte
• short
• int
• long
• float
• double
• char
• boolean
Wrapper class data types are classes that wrap the primitive data types. They provide a way
to treat primitive data types as objects. Wrapper classes are declared using the following
class names:
• Byte
• Short
• Integer
• Long
• Float
• Double
• Character
Boolean
OOP-1 BY: -DEEP SHAH
What are syntax errors (compile errors), runtime errors, and logic errors?
• Syntax errors (also known as compile errors) are errors that occur when the code
does not follow the rules of the programming language. These errors are detected by
the compiler and prevent the code from running
• Runtime errors are errors that occur when the code is running. These errors are not
detected by the compiler
• Logic errors are errors that occur when the code does not do what it is supposed to
do. These errors are not detected by the compiler or the runtime environment and
can be very difficult to find.
Explain following controls (1) Checkbox (2) Radio Button (3) Textfield (4) Label
Checkbox
A checkbox is a GUI control that allows the user to select one or more options. Checkbox
controls are typically used to allow users to select their preferences, such as their favorite
colors or their preferred method of contact.
Radio Button
A radio button is a GUI control that allows the user to select one option from a group of
options. Radio button controls are typically used to allow users to make a single selection,
such as their favorite flavor of ice cream or their preferred payment method.
Textfield
A textfield is a GUI control that allows the user to enter text. Textfields are typically used to
allow users to enter their name, address, or other personal information.
Label
A label is a GUI control that displays text. Labels are typically used to provide information to
the user, such as the name of a field or the instructions for entering data.
Garbage collection is the process of automatically managing the memory used by objects in
a Java program. The garbage collector is responsible for identifying and deleting objects that
are no longer referenced by any other object in the program. This frees up the memory that
was used by those objects so that it can be reused by other objects.
• It frees up the programmer from having to worry about memory management. This
can reduce errors and improve the performance of Java programs.
• It is a very efficient algorithm. The garbage collector typically runs in the background
and does not interfere with the execution of the Java program.
• It is a standard part of the Java language. This means that all Java programs can use
the garbage collector, regardless of the JVM that they are running on.
The Scene Graph is the foundation of JavaFX. It is a hierarchical tree of nodes that represent
all of the visual elements of the user interface. The nodes in the scene graph can be
anything from simple shapes to complex controls. The scene graph is responsible for
managing the layout of the user interface and handling user input.
The Graphics Engine is responsible for rendering the scene graph to the screen. It uses the
graphics hardware of the underlying platform to achieve high performance. The graphics
engine also supports 2D and 3D graphics.
The Media Engine is responsible for playing media files, such as audio and video. It supports
a variety of media formats, including MP3, WAV, and FLV. The media engine also supports
streaming media.
• Button : A button is a control that allows the user to interact with the application.
Buttons can be used to perform actions, such as opening a new window or closing
the application.
• Label : A label is a control that displays text. Labels are typically used to provide
instructions or information to the user.
• TextField : A text field is a control that allows the user to enter text. Text fields are
typically used to collect input from the user, such as their name or address.
OOP-1 BY: -DEEP SHAH