Object Oriented Programming For Sem
Object Oriented Programming For Sem
Q1. What is byte code? What does the JVM do? Why Java is called platform independent language?
[1+2+2]
Byte Code:- Byte code is a set of instructions that is generated after Java code is compiled. It is not machine
code but a special code that the Java Virtual Machine (JVM) can understand.
What does the JVM do?
• JVM reads and runs the byte code.
• It converts byte code into machine code for your specific system, so the program can run.
Why is Java called platform independent?
• Because the same byte code can run on any system (Windows, Linux, Mac) that has a JVM.
• You write code once and run it anywhere, thanks to JVM.
Q3. What is JVM. Explain the process of compilation and interpretation in Java. [5]
JVM is a software that runs Java programs. It reads byte code and converts it into machine code so your
computer can understand and run the program.
Compilation and Interpretation Process in Java:
1. Compilation:
o Java source code (.java) is written by the programmer.
o The Java compiler (javac) converts this code into byte code (.class file).
o Byte code is not system-specific.
2. Interpretation:
o The JVM takes this byte code and interprets or executes it.
o It converts byte code into machine code for the specific system (Windows, Linux, etc.).
Q4. Explain “public static void main (String args[ ])”. [5]
Class: This keyword is used to declare a class in java.
Public: This keyword is an access modifier that represents visibility. It means it is visible to all.
Static: It is a Keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create any object.
Void: It is return type of the method. It means it doesn’t return any value.
Main: it represents the starting point of the program.
String args[]: It is used for command line arguments.
Q5. What is command line argument? Compare string and stringBuffer class. [2+3]
The java command-line argument is an argument i.e. passed at the time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an input.
So, it provides a convenient way to check the behaviour of the program for the different values. You can
pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Feature String StringBuffer
Mutability Immutable (cannot be changed) Mutable (can be changed)
Performance Less efficient for frequent changes More efficient for frequent changes
Memory Creates new objects for each change Modifies the same object
Thread Safety Thread safe. Thread safe.
Use Case For constant strings, no changes For strings that need frequent modifications
Q6. Briefly explain the features of object oriented programming with example [5]
Inheritance: When one object acquires all the properties and behaviours of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Ex- A "SportsCar" class could inherit from a "Car" class, gaining all the basic car features, and then add its
own, like a "turbo()" function.
Polymorphism: If one task is performed in different ways. Poly means "many forms." It lets objects of
different classes respond to the same method call in their own way. It is called polymorphisim.
Ex-Both a "Dog" and a "Cat" object might have a "makeSound()" method, but the dog barks, and the cat
meows.
Abstraction: Hiding internal implementation and showing functionality only to the user is known as
abstraction.
For example, phone call, we do not know the internal processing.
Encapsulation: Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, A "Car" object might encapsulate data like "color" and "speed" and functions like "start()" and
"accelerate()".
Function overloading is feature in Java that allows multiple methods with the same name to exist in the same
class but with different parameter lists. This allows the same function to behave differently based on the
arguments passed to it.
Key point of function overloading:
• Same function name but different parameter lists (in terms of type, number, or both).
• Overloading is resolved at compile time.
• It enhances code readability and allows flexibility.
Example:-
class Calculator{
public void add(int a, int b){
int c =a+b;
System.out.println("The sum is: "+c);
}
public void add(int a, int b, int c){
int sum=a+b+c;
System.out.println("The sum is: "+sum);
}
public void add(double a, double b){
double c=a+b;
System.out.println("The sum is: "+c);
}
}
public class Test2 {
public static void main(String[] args) {
Calculator c= new Calculator();
c.add(2, 3);
c.add(2, 4, 5);
c.add(2.5, 3.5);
}
}
Constructor in Java: A constructor in Java is a special type of method used to initialize objects. It is called
when an object of a class is created. Constructors have the same name as the class and do not have a return
type (not even void). They are primarily used to set initial values for the object's fields or to perform setup
tasks when an object is created.
Two types of constructos is:
Default constructor: Provided by Java if no other constructor is defined. It doesn't
take parameters and does nothing except calling the parent class's constructor.
Parameterized constructor: A constructor that takes arguments to initialize object properties.
• The finalize() method is called by the Garbage Collector before an object is removed from memory.
o It gives the object a chance to clean up resources (like closing files or database connections).
o It runs automatically, not manually.
o Mostly used for cleanup work, but not commonly used in modern Java.
Q13. What is parametric and non-parametric constructor? Explain with suitable example.
class Student{
String name;
int age;
public void getinfo(){
System.out.println("The name is: "+this.name);
System.out.println("The age is: "+this.age);
}
Student(String name, int age){
this.name= name;
this.age= age;
}
}
public class parametrized {
public static void main(String[] args) {
Student s1 = new Student("Amit",18);
s1.getinfo();
}
}
Non-Parametric Constructor in Java: A non-parametric constructor (also known as a default constructor
or no-argument constructor) is a constructor that does not take any parameters. It is either provided
automatically by the Java compiler if no other constructors are defined or explicitly defined by the
developer. This constructor initializes the object with default or pre-defined values.
Example-
class Student{
String name;
int age;
Student(){
System.out.println("Constructor called");
}
public void getinfo(){
System.out.println("The name is: "+this.name);
System.out.println("The age is: "+this.age);
}
}
public class nonparametrized {
public static void main(String[] args) {
Student s1= new Student();
s1.name="Rahul";
s1.age=18;
s1.getinfo();
}
}
Q14. How does a class accomplish data hiding? List out the differences between Procedure Oriented
programming and Object-Oriented programming.
Finally Block:- A finally is a block used with try-catch statements to execute important code like closing
resources. It always runs whether an exception occurs or not, ensuring cleanup actions are performed.
Finalize method:- A finalize() is a method called by the garbage collector before an object is destroyed. It's
used to perform cleanup operations like releasing resources, but it is deprecated and not recommended in
modern Java.
Q18. What is the base class of Error and Exception? Differentiate between throw and throws.
The base class of the Error and Exception in java is “Throwable”.
Purpose Used to explicitly throw an exception Used to declare exceptions a method might
throw
Internal We are allowed to throw only one We can declare multiple exceptions using
Implementation exception at a time i.e. we cannot throw throws keyword that can be thrown by the
multiple exceptions. method.
Q19. What is the difference between ‘error and exception’? What are the benefits of organizing classes into
packages?
Fixable Usually not fixable by the programmer Can be handled using code (try-catch)
Cause Happens due to system failure Happens due to programming mistakes or invalid
input
Handling Not handled using try-catch normally Can be handled using try-catch blocks
• Better organization – Packages help you keep related classes together, like putting files into folders.
• Avoid name conflicts – You can have classes with the same name in different packages.
• Easier to find and reuse code – You know where to look for certain functionality.
• Access control – Packages help you control which classes can be accessed from where using access
modifiers like public, private, and protected.
Q21. What are the two methods to create threads? Compare them. Explain them with an example java
program.
Two method to create threads:
1. By extending Thread class
2. By implementing Runnable interface
Compare between the Extending Thread and Implementing Runnable Thread
Feature Extending Thread Implementing Runnable
Inheritance Can’t extend another class Can extend another class (more flexible)
Code Separation Code and thread are tightly coupled Logic is separate from thread
Reusability Less reusable More reusable and cleaner
Memory Usage Uses more memory (creates full Thread Uses less memory (shares the same
object) Thread class)
Recommended Simple or quick thread examples Larger or real-world applications
For
Q22. Explain with the help of an example, how java gets benefitted by using interfaces? [6]
Benefit of interface:-
1. Multiple Inheritance: Allows a class to implement multiple interfaces.
2. Loose Coupling: Reduces dependencies between classes.
3. Abstraction: Defines what a class should do without specifying how.
4. Polymorphism: Enables different classes to behave in different ways with the same interface.
5. Flexibility and Reusability: Promotes code reuse across different class hierarchies.
6. Decoupling: Classes can depend on interfaces, not concrete implementations.
7. Improved Testability: Interfaces make it easier to mock dependencies during testing.
Example:-
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
System.out.println("Woof! Woof!");
}
}
class Cat implements Animal {
public void sound() {
System.out.println("Meow! Meow!");
}
}
public class Test10 {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.sound(); // Outputs: Woof! Woof!
myCat.sound(); // Outputs: Meow! Meow!
}
}
Q23. How can you create your own package and add classes in that? Explain with the help of an example.
[6+3]
Steps to Create Your Own Package in Java:
1. Create a package using the package keyword.
2. Save the class file in a folder with the same name as the package.
3. Compile the class with the correct folder structure.
4. Import and use the package in another class.
Example:-
// creating a package……………..
package mypackage;
public class MathOperations {
public int add(int a, int b) {
return a + b;
}
}
// write the program in main class…………
import mypackage.*;
public class Main {
public static void main(String[] args) {
MathOperations math = new MathOperations();
int result = math.add(5, 10);
System.out.println("Sum: " + result);
}
}
Q24. (a) What are the differences between Method Overloading and Method Overriding?
(b) Explain Dynamic Method Dispatch with suitable example.
(c) Write a program to access static variable and static method to explain ‘static’ keyword properly. [4+4+7]
Example-
class Bike{
void run(){
System.out.println("running");
}
}
class Splendor extends Bike{
void run(){
System.out.println("running safely with 60km");
}
public static void main(String args[]){
Bike b = new Splendor();//upcasting
b.run();
}
}
Explanation- This Java sample uses method overriding to illustrate runtime polymorphism. While the
Splendour class extends Bike and overrides the run() method to output "running safely with 60km," the Bike
class provides a method called run() that prints "running." Because of upcasting, a Bike reference variable
called b is generated in the main method that points to a Splendour object. Runtime polymorphism is
demonstrated by the overridden method from the Splendour class, which is called when the run() method is
called using this reference variable. The JVM determines which method to call based on the actual object
type at runtime.
Explanation:-
• static means the variable or method belongs to the class, not the object.
• schoolName and showSchoolName() are static – shared by all objects.
• studentName and showStudentName() are non-static – unique for each student.
• We access static stuff using class name, not object.
Q25. When do we use finally block? What is run time exception? Explain ‘this’ and ‘super’ keyword.
The finally block is used after try-catch to run important code like closing files or database connections. It
always runs, whether an exception happens or not.
EX:-
try {
// risky code
} catch(Exception e) {
// handle error
} finally {
// always runs
}
A run-time exception is an error that happens while the program is running. These are unchecked
exceptions — not checked by the compiler.
Examples:
• ArithmeticException (e.g., divide by zero)
• NullPointerException
Keyword Meaning
this Refers to the current object of the class. Used to access variables or methods in the same
class.
super Refers to the parent class. Used to call parent class’s constructor or method.
Q26. What is Inheritance? How many types of inheritance Java supports are there? Discuss it. Given a
method that does not declare any exception, can I override that method in a subclass to throw an
exception?
Inheritance:- Inheritance is a feature in Java where one class (child) can use the properties and methods of
another class (parent). It helps in code reuse and building hierarchical relationships.
Example:-
class Animal {
void eat() { System.out.println("Eating..."); }
}
class Dog extends Animal {
void bark() { System.out.println("Barking..."); }
}
Types of Inheritance:-
Type Description
Single One child class inherits one parent class.
Multilevel A class inherits a child class which itself inherits another class.
Hierarchical Multiple child classes inherit one parent class.
Hybrid Not supported directly but can be achieved using interfaces.
Multiple Not supported with classes, but achievable using interfaces.
Q27. What is multi-threading? Write a program that can run a main thread and a child thread simultaneously.
What does synchronized keyword do? Briefly describe with example.
Multithreading is a process of running multiple threads at the same time in a single program. It makes
programs faster and more efficient, especially when doing many tasks like downloading, printing, etc.
Synchronized keyword :-
synchronized makes a block or method thread-safe, meaning only one thread can access it at a time.
It prevents data conflict when multiple threads try to access the same object.
Example:-
class Table {
synchronized void printTable(int n) { // synchronized method
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
try { Thread.sleep(400); } catch (Exception e) {}
}
}
}
class MyThread1 extends Thread {
Table t;
MyThread1(Table t) { this.t = t; }
public void run() { t.printTable(5); }
}
Q28. What are the different characteristics of abstract keyword? Explain abstract class through a program.
Characteristics of the abstract keyword:-
➢ Used with classes or methods
o A class or method can be marked abstract.
➢ Abstract class
o Cannot be directly used to create objects.
o Meant to be inherited by other classes.
➢ Abstract method
o A method without a body (no code).
o Must be overridden in the child class.
➢ Helps in defining rules
o Abstract classes give a common structure but leave details for subclasses.
➢ Can have both abstract and normal methods
o Abstract class can include implemented methods too.
Example:-
abstract class Animal {
abstract void sound();
void eat() {
System.out.println("Animal eats food");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
d.eat();
}
}
Q29. Write a Java program to create a class called Shape with methods called getPerimeter() and getArea().
Create a subclass called Circle that overrides the getPerimeter() and getArea() methods to calculate the area
and perimeter of a circle.
class Shape{
double getPerimeter(){
return 0;
}
double getArea(){
return 0;
}
}
class Circle extends Shape{
double radius;
Circle(double radius){
this.radius=radius;
}
double getPerimeter() {
return 2*3.14*radius;
}
double getArea(){
return 2*3.14*radius*radius;
}
}
public class Shapedemo {
public static void main(String[] args) {
Circle c=new Circle(5);
System.out.println("The Perimeter of the circle is: "+c.getPerimeter());
System.out.println("The Area of the Circle is: "+c.getArea());
}
}
Output: The Perimeter of the Circle is: 31.40000000002
The Area of the Circle is: 157.0
Q30. Define an interface perimeter using java that contains a method to calculate the perimeter of an object.
Define two classes circle and Rectangle with suitable fields and methods. Implement the interface
“perimeter” in these classes. Write the appropriate main() method to create object of each class and test all
the methods.
interface Perimeter{
double calPerimeter();
}
class Circle implements Perimeter {
double radius;
Circle(double radius){
this.radius=radius;
}
public double calPerimeter(){
return 2*3.14*radius;
}
}
class Recatangle implements Perimeter{
double height, width;
Recatangle(double height, double width){
this.height=height;
this.width=width;
}
public double calPerimeter(){
return 2*(height+width);
}
}
public class Test6 {
public static void main(String[] args) {
double radius = Double.parseDouble(args[0]);
double height = Double.parseDouble(args[1]);
double width = Double.parseDouble(args[2]);
Circle ob = new Circle(radius);
Recatangle ob1= new Recatangle(height,width);
System.out.println("The Perimeter of the Circle is: "+ob.calPerimeter());
System.out.println("The Perimeter of Rectangle is: "+ob1.calPerimeter());
}
}
Q31. Write a java program that will handle multiple exception at the same time. Use nested try catch
block.
public class Test7 {
public static void main(String[] args) {
try {
int[] numbers = {10, 20, 30};
int result = numbers[1]/0;
try {
System.out.println("Number: " + numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Inner Catch: Array index is out of bounds!");
}
} catch (ArithmeticException e) {
System.out.println("Outer Catch: Cannot divide by zero!");
} catch (Exception e) {
System.out.println("Outer Catch: Some other exception occurred.");
}
System.out.println("Program continues after exception handling.");
}
}
Q32. Define a user defined exception handling program which will throw exceptions if you entered a
negative number.
class NegativeNumberException extends Exception {
public NegativeNumberException(String message) {
super(message);
}
}
public class Test8 {
static void checkNumber(int number) throws NegativeNumberException {
if (number < 0) {
throw new NegativeNumberException("Negative number is not allowed: " + number);
} else {
System.out.println("Valid number: " + number);
}
}
public static void main(String[] args) {
try {
int num=Integer.parseInt(args[0]);
checkNumber(num);
} catch (NegativeNumberException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
System.out.println("Program ends.");
}
}
Q33. Define an exception called “NotEqualException” that is thrown when a float value is not equal to
3.14. Write a program that uses that user defined exception.
class NotEqualException extends Exception {
public NotEqualException(String message) {
super(message);
}
}
public class Test9{
static void checkValue(float value) throws NotEqualException {
if (value != 3.14) {
throw new NotEqualException("Value is not equal to 3.14");
} else {
System.out.println("Value is exactly 3.14");
}
}
public static void main(String[] args) {
float num = Float.parseFloat(args[0]);
try {
checkValue(num);
} catch (NotEqualException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
System.out.println("Program ends.");
}
}
Q35. Create a package named “school”. Create two sub package named student package and staff package
within “school”. Implement a simple school system that makes use of classes provided by these two
packages.
Q37. Write a program to execute SQL select query using JDBC. Storing data is your choice and use JDBC -
ODBC bridge driver as your driver.
import java.sql.*;
public class SelectExample {
public static void main(String[] args) {
try {
// Step 1: Load JDBC-ODBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (Exception e) {
System.out.println(e);
}
}
}
Q38. Write a client server based application using Java socket programming.
Server Program (Server.java)
import java.net.*;
import java.io.*;