0% found this document useful (0 votes)
84 views41 pages

OOP (Imp)

Uploaded by

Ahetisam Malek
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)
84 views41 pages

OOP (Imp)

Uploaded by

Ahetisam Malek
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
You are on page 1/ 41

OOP-1 BY: -DEEP SHAH

 Explain JRE, JDK and JIT.

• 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:

Feature JRE JDK JIT

Develops and Optimizes the


Runs Java
Purpose tests Java execution of Java
bytecode
applications bytecode

JVM, core Java JRE, compiler,


Contains classes, debugger, other JVM
supporting files tools

Who End users,


Developers Developers
uses it developers
OOP-1 BY: -DEEP SHAH

 Explain static keyword with example


The static keyword in Java is a non-access modifier that can be used with variables,
methods, and nested classes. When a member is declared as static, it belongs to the class
itself, rather than to an instance of the class. This means that only one instance of a static
member exists, even if you create multiple objects of the class, or if you don't create any.

Here is an example of a static variable:

Java
public class StaticExample {
static int count = 0;

public static void main(String[] args) {


System.out.println(count); // Prints 0

StaticExample obj1 = new StaticExample();


StaticExample obj2 = new StaticExample();

System.out.println(count); // Prints 2
}
}

Here is an example of a static method:

Java
public class StaticExample {
static void incrementCount() {
count++;
}

public static void main(String[] args) {


StaticExample.incrementCount();
StaticExample.incrementCount();

System.out.println(count); // Prints 2
}
}
OOP-1 BY: -DEEP SHAH

 Explain inheritance with its types and give suitable example

Inheritance is a powerful feature in object-oriented programming (OOP) that allows one


class to inherit the properties and methods of another class. This can be used to reuse code
and create more complex and sophisticated classes.

There are four types of inheritance in Java:

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

Here is an example of inheritance in Java:

Java
public class Animal {
public void eat() {
System.out.println("The animal is eating.");
}
}

public class Dog extends Animal {


public void bark() {
System.out.println("The dog is barking.");
}
}
OOP-1 BY: -DEEP SHAH

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.bark();
}
}
 Compare object-oriented programming with sequential programming

 Method main is a public static method. Justify


The main() method is a public static method in Java for the following reasons:
• Public: The main() method must be public so that it can be called from outside the
class. This is because the Java Virtual Machine (JVM) calls the main() method to start
the execution of a Java program.
• Static: The main() method must be static so that it can be called without creating an
instance of the class. This is because the JVM does not create an instance of the class
when it calls the main() method.
Here are some of the implications of making the main() method public and static:
OOP-1 BY: -DEEP SHAH

• 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 {

public void sum(int a, int b) {


System.out.println(a + b);
}

public void sum(int a, int b, int c) {


System.out.println(a + b + c);
}

public static void main(String[] args) {


OverloadingExample obj = new OverloadingExample();
obj.sum(10, 20); // Prints 30
obj.sum(10, 20, 30); // Prints 60
}
}
differentiate between function overloading and overriding.
OOP-1 BY: -DEEP SHAH

 Write difference between String class and String Buffer class.

 Explain super keyword with example.


The super keyword in Java is used to refer to the parent class of a subclass. It can be used to
access the parent class's constructors, methods, and fields.

Here is an example of how to use the super keyword:

Java
class Animal {
public void makeSound() {
System.out.println("I am an animal");
}
}

class Dog extends Animal {


public void makeSound() {
// Call the parent class's makeSound() method
super.makeSound();
System.out.println("I am a dog");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.makeSound();
}
}

 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

triangle likewise for Rectangle and Circle.


abstract class Shape {

abstract double area();


}

class Triangle extends Shape {

private double base;


private double height;

public Triangle(double base, double height) {


this.base = base;
this.height = height;
}

@Override
public double area() {
return 0.5 * base * height;
}
}

class Rectangle extends Shape {

private double length;


private double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
public double area() {
return length * width;
}
}

class Circle extends Shape {

private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
OOP-1 BY: -DEEP SHAH

public double area() {


return Math.PI * radius * radius;
}
}

public class Main {

public static void main(String[] args) {


Shape triangle = new Triangle(3, 4);
System.out.println("The area of the triangle is: " + triangle.area());

Shape rectangle = new Rectangle(5, 6);


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

Shape circle = new Circle(7);


System.out.println("The area of the circle is: " + circle.area());
}
}
 How can we protect sub class to override the method of super class? Explain
with example.
Use the final keyword. The final keyword can be used to prevent a method from being overridden. For
example, the following code shows how to use the final keyword to prevent the area() method from
being overridden
final class Shape {

public final double area() {


return 0;
}
}

class Triangle extends Shape {

@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

• Abstraction: An interface is a pure abstraction, while a class can be concrete. This


means that an interface can only contain abstract methods, while a class can contain
both abstract and concrete methods.
• Inheritance: An interface can only extend other interfaces, while a class can extend
other classes and interfaces.
• Object creation: Interfaces cannot be instantiated, while classes can be instantiated.
• Polymorphism: Interfaces can be used for polymorphism, while classes can also be
used for polymorphism.
 What do you mean by run time polymorphism? Write a program to demonstrate run
time polymorphism
Runtime polymorphism, also known as dynamic method dispatch, is a feature of object-
oriented programming languages that allows the method to be called at runtime, rather
than compile time. This is achieved by overriding methods in subclasses.

Here is an example of a program to demonstrate runtime polymorphism:

Java
class Animal {

public void speak() {


System.out.println("I am an animal");
}
}

class Dog extends Animal {

@Override
public void speak() {
System.out.println("Woof!");
}
}

class Cat extends Animal {

@Override
public void speak() {
System.out.println("Meow!");
}
}

public class Main {

public static void main(String[] args) {


Animal animal = new Dog();
animal.speak();
OOP-1 BY: -DEEP SHAH

animal = new Cat();


animal.speak();
}
}
 Differentiate between Text I/O and Binary I/O.

Text I/O

• Data is interpreted as a sequence of characters.


• The newline character (\n) is used to mark the end of a line.
• This is the most common way to read and write text files, such as .txt, .csv,
and .html files.

Binary I/O

• Data is interpreted as raw binary values, usually bytes.


• No character encoding or decoding is used.
• This is the most common way to read and write binary files, such as .exe, .dll,
and .jpg files.
 Explain Array List class.

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.

Here are some of the key features of the ArrayList class:

• It can store any type of object.


• It can be accessed using an index.
• It can be iterated through using a for loop or an iterator.
• It can be sorted using the Collections.sort() method.
• It can be searched using the Collections.binarySearch() method.

Here is an example of how to create an ArrayList in Java:

Java
import java.util.ArrayList;

public class ArrayListExample {


OOP-1 BY: -DEEP SHAH

public static void main(String[] args) {


ArrayList<String> cars = new ArrayList<>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");

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.

Some of the most common built-in exceptions in Java include:

• NullPointerException - This exception is thrown when a reference to an object


is null.
• ArrayIndexOutOfBoundsException - This exception is thrown when an index
is out of bounds for an array.
• ClassCastException - This exception is thrown when an object is cast to an
incompatible type.
• ArithmeticException - This exception is thrown when an arithmetic operation
results in an error, such as dividing by zero.
• IllegalArgumentException - This exception is thrown when a method is passed
an invalid argument.

try {

// Code that might throw an exception

} catch (Exception e) {

// Handle the exception

System.out.println(e.getMessage());

}
OOP-1 BY: -DEEP SHAH

 How do you declare a generic type in a class? Explain

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 Box(T value) {


this.value = value;
}

public T getValue() {
return value;
}

public void setValue(T value) {


this.value = value;
}
}
 Write a JAVA program to read student.txt file and display the content.
import java.io.*;

public class ReadStudentFile {

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


FileReader fileReader = new FileReader("student.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);

String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}

bufferedReader.close();
fileReader.close();
}
}

 Explain Thread life cycle in detail.


OOP-1 BY: -DEEP SHAH

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.

Blocked: A thread that is blocked is waiting for a resource to become available.


For example, a thread might be blocked waiting for a lock to be acquired.

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.

The following diagram shows the thread life cycle:

 Write a program to create a child thread to print integer numbers 1 to 10.

class MyThread implements Runnable {

@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
OOP-1 BY: -DEEP SHAH

public class Main {

public static void main(String[] args) {


MyThread thread = new MyThread();
Thread t = new Thread(thread);
t.start();
}
}

 Enlist various layout panes and explain any two in detail

Here are the various layout panes in Java:

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

Example of boarder pane

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

public void start(Stage primaryStage) throws Exception {


BorderPane BPane = new BorderPane();
BPane.setTop(new Label("This will be at the top"));
BPane.setLeft(new Label("This will be at the left"));
BPane.setRight(new Label("This will be at the Right"));
BPane.setCenter(new Label("This will be at the Centre"));
BPane.setBottom(new Label("This will be at the bottom"));
Scene scene = new Scene(BPane,600,400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}

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

Define constructor. How objects are constructed? Explain constructor


overloading with an example.
A constructor is a special method that is called when an object is created. It is used to initialize
the object's state. Constructors do not have a return type.
public class MyClass {

public MyClass() {
// This is the default constructor.
}

public MyClass(String name) {


// This constructor takes a String parameter.
this.name = name;
}

private String name;


}

 Explain about Encapsulation, Abstraction.

Encapsulation and abstraction are two important concepts in object-oriented


programming (OOP).

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.

Abstraction is the process of representing essential features without including the


details. This means that the abstraction hides the implementation details of an
object. The user of the object only sees the essential features of the object, and does
not need to know how the object is implemented.

public class Car {

private String make;

private String model;

private int year;

public Car(String make, String model, int year) {


OOP-1 BY: -DEEP SHAH

this.make = make;

this.model = model;

this.year = year;

public String getMake() {

return make;

public String getModel() {

return model;

public int getYear() {

return year;

public void drive() {

System.out.println("The car is driving");

 Explain in detail how inheritance and polymorphism are supported in java with
necessary examples.

public class Animal {


OOP-1 BY: -DEEP SHAH

public void makeSound() {

System.out.println("The animal is making a sound");

public class Dog extends Animal {

public void makeSound() {

System.out.println("The dog is barking");

public class Cat extends Animal {

public void makeSound() {

System.out.println("The cat is meowing");

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

The benefits of using packages include:


OOP-1 BY: -DEEP SHAH

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

2. Create the Java classes in the package directory.

3. Import the package into another Java program.

Here is an example of how to create a package and use it in a Java program:

Java
// Create the package directory.
mkdir mypackage

// Create the Java classes in the package directory.


javac -d mypackage MyClass.java

// Import the package into another Java program.


import mypackage.MyClass;

public class Main {

public static void main(String[] args) {


MyClass myClass = new MyClass();
}
}
 What is Dynamic binding? Show with an example how dynamic binding works.

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

public class Animal {

public void makeSound() {


System.out.println("The animal is making a sound");
}
}

public class Dog extends Animal {

@Override
public void makeSound() {
System.out.println("The dog is barking");
}
}

public class Cat extends Animal {

@Override
public void makeSound() {
System.out.println("The cat is meowing");
}
}

public class Main {

public static void main(String[] args) {


Animal animal = new Dog();
animal.makeSound();

animal = new Cat();


animal.makeSound();
}
}

 Explain the concept of finalization.

Finalization is a process in Java that allows an object to perform cleanup activities before it is
garbage collected.
public class MyClass {

private File file;

public MyClass(File file) {


this.file = file;
}

@Override
protected void finalize() throws Throwable {
OOP-1 BY: -DEEP SHAH

super.finalize();

// Close the file.


if (file != null) {
file.close();
}
}
}

 Write a java program to implement the multiple inheritance concepts for


calculating area of circle and square.

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);
}
}

 Explain about callback.


A callback in Java is a function that is passed as an argument to another function
and executed when that function completes or some event happens. Callbacks are
often used in asynchronous programming.

Here is an example of a callback in Java:

Java
interface Callback {
void onSuccess();
void onFailure();
OOP-1 BY: -DEEP SHAH

class MyClass {
public void doSomethingAsync(Callback callback) {
// Perform some asynchronous task.
// ...

// Notify the callback when the task is finished.


callback.onSuccess();
}
}

public class Main {


public static void main(String[] args) {
Callback callback = new Callback() {
@Override
public void onSuccess() {
System.out.println("The task finished successfully!");
}

@Override
public void onFailure() {
System.out.println("The task failed!");
}
};

MyClass myClass = new MyClass();


myClass.doSomethingAsync(callback);
}
}

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

Advantages of using MVC


OOP-1 BY: -DEEP SHAH

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

 Explain features of Java briefly. Explain any two features.

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

Java is an object-oriented programming language. Everything in Java is an object.


Object-oriented means we organize our software as a combination of different types
of objects that incorporate both data and behaviour.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

 Write a single program which demonstrates the usage of following keywords: i)


import, ii) new, iii) this, iv) break, v) continue Show how to compile and run the
program in java.

import java.util.Scanner;

public class KeywordsDemo {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
KeywordsDemo keywordsDemo = new KeywordsDemo();
System.out.println("The value of the `this` keyword is: " + keywordsDemo);
System.out.print("Enter a number: ");
OOP-1 BY: -DEEP SHAH

int number = scanner.nextInt();


for (int i = 0; i < 10; i++) {
if (i == number) {
break;
}
System.out.println("The value of i is: " + i);
}
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println("The value of i is: " + i);
}
}
}

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:

The value of the `this` keyword is: KeywordsDemo@66772582


Enter a number: 5
The value of i is: 0
The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
The value of i is: 5

 Consider class A as the parent of class B. Explain among the


following which statement will show the compilation error.
i) A a = new A();
ii) A a = new B();
iii) B b = new A();
iv) B b = new B();
Statement (ii) will show the compilation error.

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.

Here is an example of the code that will cause a compilation error:

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

public static String infixToPrefix(String infix) {


String prefix = "";
Stack< Character> operators = new Stack< >();

for (int i = infix.length() - 1; i >= 0; --i) {


char ch = infix.charAt(i);

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();
}

} else if (ch == ')') {


operators.push(ch);
} else {
prefix += ch;
}
}

while (!operators.isEmpty()) {
prefix += operators.pop();
}

String reversedPrefix = "";


for (int i = prefix.length() - 1; i >= 0; i--) {
reversedPrefix += prefix.charAt(i);
}
return reversedPrefix;
}

public static void main (String[]args)


{
String exp = "A+B*(C^D-E)";
System.out.println ("Infix Expression: " + exp);
System.out.println ("Prefix Expression:" + infixToPrefix (exp));
}
}
Output:

Infix Expression: A+B*(C^D-E)


Prefix Expression: +A*B-^CDE

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.

Here is an example of how to use FileInputStream to read a file:

Java
import java.io.FileInputStream;

public class FileInputStreamDemo {

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


FileInputStream fis = new FileInputStream("myfile.txt");
byte[] buffer = new byte[1024];
int bytesRead;

while ((bytesRead = fis.read(buffer)) != -1) {


System.out.println(new String(buffer, 0, bytesRead));
}

fis.close();
}
}

Define types of polymorphism


Polymorphism is a feature of object-oriented programming that allows objects of different
types to be treated in a similar way. There are two main types of polymorphism in Java:

• Compile-time polymorphism: This is also known as static polymorphism or early


binding. It occurs when the compiler chooses the correct method to call based on
the type of the object at compile time.
• Run-time polymorphism: This is also known as dynamic polymorphism or late
binding. It occurs when the compiler does not know which method to call until
runtime. This is done by using virtual methods.

Here is an example of compile-time polymorphism in Java:


OOP-1 BY: -DEEP SHAH

Java
class Animal {
public void makeSound() {
System.out.println("Animal is making a sound");
}
}

class Dog extends Animal {


@Override
public void makeSound() {
System.out.println("Dog is barking");
}
}

public class PolymorphismDemo {

public static void main(String[] args) {


Animal animal = new Dog();
animal.makeSound();
}
}

Here is an example of run-time polymorphism in Java:

Java
class Animal {
public abstract void makeSound();
}

class Dog extends Animal {


@Override
public void makeSound() {
System.out.println("Dog is barking");
}
}

class Cat extends Animal {


@Override
public void makeSound() {
System.out.println("Cat is meowing");
OOP-1 BY: -DEEP SHAH

}
}

public class PolymorphismDemo {

public static void main(String[] args) {


Animal animal = new Dog();
animal.makeSound();

animal = new Cat();


animal.makeSound();
}
}

 Explain file io using character stream with


appropriate example. hint: use FileReader,
FileWriter
File I/O is the process of reading and writing data to and from files. Character streams are a
type of I/O that work with characters, which are the basic unit of data for text.

FileReader and FileWriter are two classes in the Java API that provide methods for reading
and writing characters to and from files.

Here is an example of how to use FileReader to read a file:

Java
import java.io.FileReader;

public class FileReaderDemo {

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


FileReader fr = new FileReader("myfile.txt");
char[] buffer = new char[1024];
int charsRead;

while ((charsRead = fr.read(buffer)) != -1) {


System.out.println(new String(buffer, 0, charsRead));
}
OOP-1 BY: -DEEP SHAH

fr.close();
}
}

Here is an example of how to use FileWriter to write to a file:

Java
import java.io.FileWriter;

public class FileWriterDemo {

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


FileWriter fw = new FileWriter("myfile.txt");
String text = "This is a test file.";

fw.write(text);
fw.close();
}
}

 Define Encapsulation and access specifier

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

 Write a short note on Java Collections.


OOP-1 BY: -DEEP SHAH

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:

• List: A list is an ordered collection of objects.


• Set: A set is an unordered collection of unique objects.
• Map: A map is a collection of key-value pairs.
• Queue: A queue is a collection of objects that are stored in a first-in, first-out (FIFO)
order.
• Deque: A deque is a collection of objects that can be stored in a first-in, first-out
(FIFO) or last-in, first-out (LIFO) order.

Here are some of the benefits of using the Java Collections framework:

• Efficiency: The Java Collections framework is very efficient. It uses a variety of


techniques to optimize the performance of collections.
• Reusability: The Java Collections framework is very reusable. It provides a wide
variety of classes and interfaces that can be used in a variety of different
applications.
• Extensibility: The Java Collections framework is extensible. It allows you to create
your own custom collections.

 Differentiate between Abstract class and Interfaces


OOP-1 BY: -DEEP SHAH

 Write a short note on JAVAFX controls.


JavaFX controls are graphical user interface (GUI) components that are used to create
interactive applications. They are part of the JavaFX toolkit, which is a set of classes and
interfaces that provide a platform-independent way to create GUIs.

Some of the most commonly used JavaFX controls include:

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

 Develop a GUI based application using JAVAFX controls.


import javafx.application.Application;
import javafx.scene.Scene;
OOP-1 BY: -DEEP SHAH

import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class HelloWorld extends Application {

@Override
public void start(Stage primaryStage) {
// Create a label
Label label = new Label("Hello, World!");

// Create a button
Button button = new Button("Click me!");

// Add the label and button to a VBox


VBox vbox = new VBox();
vbox.getChildren().addAll(label, button);

// Create a scene
Scene scene = new Scene(vbox, 300, 250);

// Set the scene on the stage


primaryStage.setScene(scene);

// Show the stage


primaryStage.show();
}

public static void main(String[] args) {


launch(args);
}
}
 Explain type-conversion in java
Type conversion in Java is the process of converting a value of one data type into another.
This can be done either implicitly or explicitly.

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

 Difference between Nested if and multi-way if statements


• Nested if statements are a series of if statements that are nested inside each other.
This means that the inner if statements are only executed if the outer if statements
are true. For example, the following code shows a nested if statement:
Java
int x = 10;
int y = 20;

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");
}

 Differentiate between final, finally and finalize. What will happen if we


make class and method as final?

• 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

If we make a class or method as final, the following will happen:

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

 Explain Java garbage collection mechanism.

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.

There are two main types of garbage collection algorithms:


OOP-1 BY: -DEEP SHAH

• Mark-and-sweep is the most common garbage collection algorithm


• Reference counting is a simpler garbage collection algorithm.

Here are some of the benefits of garbage collection:

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

 Explain the architecture of JavaFX

The architecture of JavaFX is divided into three main layers:

• The Scene Graph


• The Graphics Engine
• The Media Engine

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.

 List out JavaFX UI controls and explain any one in detail.

• 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

• PasswordField : A password field is a control that allows the user to enter a


password. Password fields are typically used to protect sensitive information, such as
a user's login credentials.
• Checkbox : A checkbox is a control that allows the user to select one or more
options. Checkboxes are typically used to allow the user to make choices, such as
their preferred language or their favorite color.
• RadioButton : A radio button is a control that allows the user to select one option
from a group of options. Radio buttons are typically used to allow the user to make a
single choice, such as their favorite flavor of ice cream or their preferred payment
method.
• ToggleButton : A toggle button is a control that allows the user to turn an option on
or off. Toggle buttons are typically used to allow the user to change the state of an
application, such as the sound or the visibility of a menu.
• Slider : A slider is a control that allows the user to select a value from a range of
values. Sliders are typically used to adjust the settings of an application, such as the
volume or the brightness.
• ProgressBar : A progress bar is a control that shows the progress of an operation.
Progress bars are typically used to show the user how much time is remaining until
an operation is complete.

You might also like