0% found this document useful (0 votes)
5 views21 pages

Object Oriented Programming For Sem

The document provides an overview of Java programming concepts, including byte code, JVM, and the reasons Java is platform-independent. It explains object-oriented programming features such as inheritance, polymorphism, and encapsulation, along with the differences between procedure-oriented and object-oriented programming. Additionally, it covers constructors, method overloading, garbage collection, and thread states, highlighting Java's capabilities and design principles.

Uploaded by

sahoozu567
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)
5 views21 pages

Object Oriented Programming For Sem

The document provides an overview of Java programming concepts, including byte code, JVM, and the reasons Java is platform-independent. It explains object-oriented programming features such as inheritance, polymorphism, and encapsulation, along with the differences between procedure-oriented and object-oriented programming. Additionally, it covers constructors, method overloading, garbage collection, and thread states, highlighting Java's capabilities and design principles.

Uploaded by

sahoozu567
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/ 21

Object Oriented prOgramming

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.

Q2. Why is Java called compiled-interpreted language? [3]


Java is called a compiled-interpreted language because:
1. First, Java code is compiled by the Java compiler into byte code.
2. Then, the JVM interprets or executes that byte code on any machine.
3. So it uses both compiling and interpreting, making it a compiled-interpreted language.

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()".

Q7. Java is platform-independent and portable. – Justify. [5]


• "Write Once, Run Anywhere" (WORA): Java's goal is that you write your code once, and it can
run on any device.
• Java Compiler and Bytecode: When you write Java code, it's compiled into "bytecode," not
directly into machine code that a specific computer understands. This bytecode is like a universal
language for Java.
• Java Virtual Machine (JVM): Every device that wants to run Java needs a JVM. The JVM acts as a
translator, taking the bytecode and converting it into the machine's specific language. Because the
JVM is made for each operating system, the same bytecode can be used on any operating system that
has a JVM.
• Platform Independence: Because of the JVM, your Java code doesn't care what operating system
it's on. It's "independent" of the platform.
• Portability: Because the compiled java code is in byte code, that byte code can be moved, or is
portable, to any device that has a JVM.

Q8. Why String is immutable in Java?


In Java, the String class is immutable for several reasons:
• Security: Since strings are widely used for file paths, URLs, and network connections, immutability
helps in avoiding security risks that may arise if a string were to be modified unexpectedly.
• Performance: String immutability allows for String Pooling (also known as the string constant
pool). When you create a new string, the JVM can reuse strings that have already been created,
saving memory and improving performance.
• Thread Safety: Immutability makes strings inherently thread-safe. Multiple threads can safely share
the same string without the need for synchronization because once created, the content of the string
cannot be changed.
• Hashing: Immutable objects can be used as keys in hash-based collections like HashMap because
their hash code cannot change once they are created. If the content of the string were mutable, the
hash code could change, leading to inconsistent behaviour.

Q9. What is the use of args array in the main function?


The args array in the main function is used to accept command-line arguments passed to a Java program.
String[] args: This is an array of String objects that holds the arguments passed to the program when it's run
from the command line.

Q10. Write a program in Java to explain the working of ‘this’.


class Person{
int id;
String name;
Person(int id, String name){
this.id =id;
this.name=name;
}
void display(){
System.out.println("The name is "+name+" and the id is "+id);
}
}
public class Test1 {
public static void main(String[] args) {
Person p= new Person(1, "Ram");
p.display();
}
}
Explanation:
This to refer to instance variable: In the constructor Person(int id, String name), the keyword this is used to
distinguish between the instance variables id and name and the constructor parameter id and name.

Q11. What is function overloading, explain with an example.

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

Q12. What is Constructor? What does the finalize method do?

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.

Parametric Constructor in Java: A parametric constructor (also known as a parameterized constructor) is


a constructor that accepts one or more parameters. These parameters are used to initialize the attributes
(fields) of an object when the object is created. This type of constructor allows you to pass specific values to
initialize the object’s fields.
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.

A class hides data using private access modifiers.


This means variables inside a class can’t be accessed directly from outside — only through methods
(getters/setters).
This protects the data from being changed accidentally.
Feature POP (Procedure-Oriented OOP (Object-Oriented
Programming) Programming)
Focus On functions and procedures On objects and classes
Data Security Less secure (data is often global) More secure (data hidden in objects)
Reusability Harder to reuse code Easier using inheritance and classes
Structure Programs are divided into functions Programs are divided into objects
Real-world Doesn’t model real-world well Models real-world problems better
Mapping

Q15. Explain the Final Keyword in Java? Give an example.


The final keyword in java is used to restrict the user. The java final keyword can be used in many contexts.
Final can be:
1. variable
2. method
3. class
Java final variable:- If you make any variable as final, you cannot change the value of final variable(It will
be constant).
Java final method:- If you make any method as final, you cannot override it.
Java final class:- If you make any class as final, you cannot extend it.
Example:-
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
Output- compile time error

Q16. What is message passing? Differentiate between aggregation and association.


Message passing means objects send messages (method calls) to each other to perform tasks. It allows
communication between objects, like one object asking another to do something.
Example: student.study(); — the student object is told to study.

Difference between the Association and Aggregation:


Feature Association Aggregation
Meaning A general link between two classes A special form of association (has-a)
Relation "uses" or "works with" relationship "has-a" relationship
Dependency Objects may or may not depend on each other Objects can exist independently
Example A doctor works with a hospital A library has books
Q17. What is the difference between final, finally and finalize in Java? What do you mean by Garbage
Collection in Java?
Final Keyword:- A final is a keyword used to restrict changes. A final variable cannot be reassigned, a final
method cannot be overridden, and a final class can't be subclassed. It ensures immutability and is often used
for constants.

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.

Garbage Collection in java:-

Garbage collection is an automatic memory management process in programming.

1. Memory Allocation: When a program runs, it uses memory to store data.


2. Unused Memory: Sometimes, the program no longer needs certain pieces of data, leaving that
memory unused.
3. Garbage: This unused memory is called "garbage."
4. Automatic Cleanup: The garbage collector identifies and reclaims this garbage memory
automatically.
5. Prevents Leaks: This prevents "memory leaks," where unused memory accumulates and slows
down or crashes the program.

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

Feature throw throws

Purpose Used to explicitly throw an exception Used to declare exceptions a method might
throw

Declaration Inside method body In method signature

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.

Example throw new ArithmeticException("Divide public void myMethod() throws


by 0"); IOException

Q19. What is the difference between ‘error and exception’? What are the benefits of organizing classes into
packages?

Aspect Error Exception

Meaning Serious problems in the program or Problems during program execution


system

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

Examples OutOfMemoryError, IOException, ArithmeticException,


StackOverflowError NullPointerException

Benefits of organizing classes into packages:

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

Q20. What are the “thread state”.


In Java, a thread goes through different states during its life cycle. Here are the main thread states in
simple words:
1. New
o Thread is created but not started yet.
o Example: Thread t = new Thread();
2. Runnable
o Thread is ready to run and waiting for CPU time.
o It may be running or just waiting in the queue.
3. Running
o Thread is actively executing code.
o CPU is working on it.
4. Blocked/Waiting
o Thread is paused, waiting for something (like a lock or signal).
o It can't continue until it gets what it’s waiting for.
5. Terminated (Dead)
o Thread has finished running or stopped due to an error.
o It can't be started again.

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]

Difference between Method overloading and Method Overriding


Feature Method Overloading Method Overriding
Definition Same method name, different Same method name and parameters in child
parameters class
Class Involved Happens in same class Happens in parent-child classes
Polymorphism Compile-time polymorphism Run-time polymorphism
Type
Purpose To do similar tasks in different ways To change behaviour of inherited method
Inheritance Not required Required (uses inheritance)
Needed

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden


method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference variable.

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.

Static Variable and static Method


class Student {
static String schoolName = "ABC High School";
String studentName;
Student(String name) {
studentName = name;
}
static void showSchoolName() {
System.out.println("School: " + schoolName);
}
void showStudentName() {
System.out.println("Student: " + studentName);
}
}
public class Main {
public static void main(String[] args) {
Student.showSchoolName();
Student s1 = new Student("Rahul");
Student s2 = new Student("Amit");
s1.showStudentName();
s2.showStudentName();
System.out.println("Accessing static variable: " + Student.schoolName);
}
}

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.

Override a method without any declare any exception:-


No, you cannot override a method to throw a new checked exception if the original method does not declare
any exception.
• You can throw unchecked exceptions (like RuntimeException).
• But checked exceptions are not allowed unless the parent method declares them.
Example:-
class Parent {
void show() {
System.out.println("Parent class method");
}
}
class Child extends Parent {
@Override
void show() {
System.out.println("Child class method");
}
}
public class Main {
public static void main(String[] args) {
Child c = new Child();
c.show(); // Outputs: Child class method
}
}

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.

Program: Main thread and child thread running together


class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Child Thread: " + i);
try { Thread.sleep(500); } catch (Exception e) {}
}
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread(); // Create child thread
t.start(); // Start child thread

// Main thread work


for (int i = 1; i <= 5; i++) {
System.out.println("Main Thread: " + i);
try { Thread.sleep(500); } catch (Exception e) {}
}
}
}

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

class MyThread2 extends Thread {


Table t;
MyThread2(Table t) { this.t = t; }
public void run() { t.printTable(10); }
}
public class Main {
public static void main(String args[]) {
Table obj = new Table(); // shared object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
}
}

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

Q34. What are the benefits of organizing classes into packages?


❖ Better Organization
1. Packages help group related classes together, just like folders organize files.
2. Makes large projects easier to manage and understand.
❖ Avoids Name Conflicts
1. You can have classes with the same name in different packages without errors.
2. Example: com.bank.Account and com.school.Account can both exist.
❖ Access Control
1. You can control visibility of classes, methods, and variables using access modifiers (public,
protected,

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.

// Creating a package for student…………


package school.student;
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void displayStudentInfo() {
System.out.println("Student Name: " + name);
System.out.println("Student Age: " + age);
}
}

//Creating a package for staff……………..


package school.staff;
public class Staff {
private String name;
private String role;
public Staff(String name, String role) {
this.name = name;
this.role = role;
}
public void displayStaffInfo() {
System.out.println("Staff Name: " + name);
System.out.println("Staff Role: " + role);
}
}

// Creating the main class and import the package…………………….


import school.student.Student;
import school.staff.Staff;

public class Main {


public static void main(String[] args) {
Student student1 = new Student("Alice", 16);
Staff staff1 = new Staff("Mr. Smith", "Teacher");
student1.displayStudentInfo();
System.out.println();
staff1.displayStaffInfo();
}
}

Q36. Difference between class and Interface.


Feature Class Interface
Definition A class is a blueprint to create objects. An interface is a blueprint for methods only
(no body).
Contains Can have variables and methods (with Can have only method signatures (until Java
code). 8).
Inheritance Supports single inheritance only. Supports multiple inheritance (via interfaces).
Object You can create an object from a class. You can’t create an object from an interface.
Creation
Keyword Used Use class keyword. Use interface keyword.

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

// Step 2: Connect to the database using DSN (Data Source Name)


Connection con = DriverManager.getConnection("jdbc:odbc:MyDSN");

// Step 3: Create a statement


Statement stmt = con.createStatement();

// Step 4: Execute SELECT query


ResultSet rs = stmt.executeQuery("SELECT * FROM Students");

// Step 5: Process the result


while (rs.next()) {
System.out.println("ID: " + rs.getInt(1) + ", Name: " + rs.getString(2));
}
// Step 6: Close connection
rs.close();
stmt.close();
con.close();

} 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.*;

public class Server {


public static void main(String[] args) {
try {
// Step 1: Create server socket on port 5000
ServerSocket ss = new ServerSocket(5000);
System.out.println("Server is waiting...");

// Step 2: Accept client connection


Socket s = ss.accept();
System.out.println("Client connected.");

// Step 3: Read data from client


DataInputStream dis = new DataInputStream(s.getInputStream());
String message = dis.readUTF();
System.out.println("Message from client: " + message);

// Step 4: Send response to client


DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Hello from server!");
// Step 5: Close resources
dis.close();
dos.close();
s.close();
ss.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Client Program (Client.java)


import java.net.*;
import java.io.*;

public class Client {


public static void main(String[] args) {
try {
// Step 1: Connect to server on localhost and port 5000
Socket s = new Socket("localhost", 5000);

// Step 2: Send message to server


DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Hello from client!");

// Step 3: Read response from server


DataInputStream dis = new DataInputStream(s.getInputStream());
String reply = dis.readUTF();
System.out.println("Message from server: " + reply);

// Step 4: Close resources


dis.close();
dos.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

-: ALL OF YOU STUDY THE AWT PORTION BY YOURSELF:-

You might also like