Java All Papers Sol
Java All Papers Sol
CA-1
1)CODE:
int x = 5;
____ (x==5){
System.__.println(“Yeah”);}
Ans: if, out
Q.2
A) Ajay bought N books from the book store. Write a program to accept price of N books and print
average price of the books using array.
Ans:
CODE:
import java.util.*;
class Test{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of books: ");
int n = sc.nextInt();
double[] allPrices = new double[n];
for(int i=0;i<n;i++){
System.out.println("Enter price: ");
double price = sc.nextDouble();
Abhishek Khatri
allPrices[i] = price;
}
double totalPrice = 0;
for(int i=0;i<n;i++){
totalPrice+=allPrices[i];
}
double n1 = n;
System.out.println("The average price of all books is: "+totalPrice/n1);
}
}
Output:
Enter the number of books:
3
Enter price:
1
Enter price:
2
Enter price:
3
The average price of all books is: 2.0
2)Ajay want to buy N products, each product is of price Rs. 210. if the number of products are
greater then 5 then Ajay will get 10% discount on total price. Write a program to calculate final
price.
Ans:
CODE:
import java.util.*;
public class Test{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of products:");
int N = sc.nextInt();
int price = 210; // price of each product
int discount = 0; // discount percentage
if (N > 5) {
discount = 10;
}
int totalPrice = N * price;
int finalPrice = totalPrice - (totalPrice * discount) / 100;
System.out.println("Final price: Rs." + finalPrice);
}
}
Output:
Enter the number of products:
6
Final price: Rs.1134
Abhishek Khatri
CA-2
D)Mechanism for naming and visibility control of a class and it’s contents?
Ans: Packages
{
gfg obj = new gfg();
obj.show();
}
}
Output:
2)b)What is exception in java. Write programs for demostrating any 3 exceptions in JAVA
Ans:
Exception Handling in Java is one of the effective means to handle the runtime errors so that the
regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle
runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException,
etc.
Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e.
at run time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught
and handled by the program. When an exception occurs within a method, it creates an object. This
object is called the exception object. It contains information about the exception, such as the name
and description of the exception and the state of the program when the exception occurred.
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc. Errors
are usually beyond the control of the programmer, and we should not try to handle errors.
Error: An Error indicates a serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
Types of Exceptions
Java defines several types of exceptions that relate to its various class libraries. Java also allows
users to define their own exceptions.
Exceptions can be categorized in two ways:
(1)Built-in Exceptions
-Checked Exception
-Unchecked Exception
(2)User-Defined Exceptions
Abhishek Khatri
Example(2):-
CODE:
B. NullPointer Exception
//Java program to demonstrate NullPointerException
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
Output
NullPointerException..
Example(3):-
CODE:
C. StringIndexOutOfBound Exception
// Java program to demonstrate StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo
{
Abhishek Khatri
(2)User Defined:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases,
the user can also create exceptions which are called ‘user-defined Exceptions’.
Example:-
CODE:
// Java program to demonstrate user defined exception
// default constructor
MyException() { }
// parameterized constructor
MyException(String str) { super(str); }
// write main()
public static void main(String[] args)
{
try {
// display the heading for the table
System.out.println("ACCNO" + "\t" + "CUSTOMER" +
"\t" + "BALANCE");
catch (MyException e) {
e.printStackTrace();
}
}
}
Runtime Error
MyException: Balance is less than 1000
at MyException.main(fileProperty.java:36)
Output:
ACCNO CUSTOMER BALANCE
1001 Nish 10000.0
1002 Shubh 12000.0
1003 Sush 5600.0
1004 Abhi 999.0
Abhishek Khatri
MIDSEM
4)if class B is subclassed from class A then enter the correct syntax:
Ans: class B extends A{}
6)Keyword that makes a variable belong to class, rather than being defined for each instance
Ans: static
Q.2.a)What are drawbacks of procedural languages? Explain the need for object oriented
programming with suitable program.
Ans:A procedural language is a sort of computer programming language that has a set of functions,
instructions, and statements that must be executed in a certain order to accomplish a job or program.
In general, procedural language is used to specify the steps that the computer takes to solve a
problem.
The disadvantages of PP are:
-Bad code-ruse. Not like class and objects that resemble the real world model, functions in PP are
task-oriented and cannot be reused when meeting a different one. Except for some commonly used
library functions, we need to write many repetitive code for similar problems.
Abhishek Khatri
-Hard to expand the application. The entire process in PP is coded directly into the application,
very-task related. For example, an application in PP for registering the user will not be used for
logging on and off. Difficult to create new data types.
-Hard to maintain. It will be a timing consuming solution to make changes. If one function
accidentally changes value of the global data, all the functions who access to this global data must
change their values.
No information hiding. Data is exposed to the whole program, so no security for data.
-Hard to design. For example, in designing graphical user interface, we'd better mainly concentrate
on how to design a menu, a button etc. since people will see them at first sight, not actions behind.
Programs made with object-oriented programming are well organized. Since relative data and
functions are grouped in the same object, it is easier to find what you are looking for and get a basic
idea of the code's purpose. Developers new to the project or those revisiting code they have not seen
in a while can get their bearings more quickly. Since the code is divided into manageable pieces,
you can avoid the overwhelming monolith files that become unwieldy and unnecessarily
complicated.
OOP follows four basic principles:
Encapsulation: Data and methods that interact with that data are bundled into one unit. This allows
you to control access to the data within each object.
Abstraction: When creating an object, the coder reduces complexity by showing only essential
information and "hiding" everything else, including implementation mechanisms.
Inheritance: A programmer can derive a new object with all or some of the properties of an existing
object. For example, a child class will inherit properties and behaviors from a parent class.
Polymorphism: This allows us to use child and parent classes in precisely the same way while
maintaining each class's unique attributes.
CODE:
abstract class Car {
Car() {
System.out.println("Car is built. ");
}
abstract void drive();
void gearChange() {
System.out.println("Gearchanged!!");
}
}
class Tesla extends Car {
void drive() {
System.out.println("Drive Safely");
}
}
class Test {
public static void main(String args[]) {
Car obj = new Tesla();
obj.drive();
obj.gearChange();
Abhishek Khatri
}
}
Output:
Car is built.
Drive Safely
Gearchanged!!
b) How constructors are different from method in JAVA? Illustrate with example
Ans: Constructors are special methods used to initialize objects whereas methods are used to
execute certain statements. Following are the important differences between Constructors and
Methods.
Q.3.A)Write a program to keep record for N mobile phone details and find average cost of N
mobiles.(Details to store: total_items, product_id,comapny_name, price), using classes objects and
methods.
Ans:
import java.util.Scanner;
class Mobile{
public int productId;
public String companyName;
public double price;
public Mobile(int productId, String companyName, double price){
this.productId = productId;
this.companyName = companyName;
this.price = price;
}
}
Abhishek Khatri
B)Define Inheritance. List types of inheritance. Create classes with methods to accept an integer
value, to calculate factorial of a number and display the result using multilevel inheritance.
Ans:
Inheritance is a mechanism of driving a new class from an existing class. The existing (old) class is
known as base class or super class or parent class. The new class is known as a derived class or sub
class or child class. It allows us to use the properties and behavior of one class (parent) in another
class (child).
A class whose properties are inherited is known as parent class and a class that inherits the
properties of the parent class is known as child class. Thus, it establishes a relationship between
parent and child class that is known as parent-child or Is-a relationship.
Suppose, there are two classes named Father and Child and we want to inherit the properties of the
Father class in the Child class. We can achieve this by using the extends keyword.
Abhishek Khatri
Types of Inheritance
Java supports the following four types of inheritance:
Single Inheritance
Multi-level Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties and
behavior of a single-parent class. Sometimes it is also known as simple inheritance.
CODE:
class Employee
{
float salary=34534*12;
}
public class Executive extends Employee
{
float bonus=3000*6;
public static void main(String args[])
{
Executive obj=new Executive();
System.out.println("Total salary credited: "+obj.salary);
System.out.println("Bonus of six months: "+obj.bonus);
}
}
Output:
Total salary credited: 414408.0
Bonus of six months: 18000.0
Multi-level Inheritance
In multi-level inheritance, a class is derived from a class which is also derived from another class is
called multi-level inheritance. In simple words, we can say that a class that has more than one
parent class is called multi-level inheritance. Note that the classes must be at different levels.
Hence, there exists a single base class and single derived class but multiple intermediate base
classes.
Abhishek Khatri
CODE:
class Student {
int reg_no;
void getNo(int no) {
reg_no=no;
}
void putNo() {
System.out.println("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student {
float marks;
void getMarks(float m) {
marks=m;
}
void putMarks() {
System.out.println("marks= "+marks);
}
}
//derived class
class Sports extends Marks {
float score;
void getScore(float scr) {
score=scr;
}
void putScore() {
System.out.println("score= "+score);
}
}
public class MultilevelInheritanceExample{
public static void main(String args[]) {
Sports ob=new Sports();
ob.getNo(0987);
ob.putNo();
ob.getMarks(78);
Abhishek Khatri
ob.putMarks();
ob.getScore(68.7);
ob.putScore();
}
}
Output:
registration number= 0987
marks= 78.0
score= 68.7
Hierarchical Inheritance
If a number of classes are derived from a single base class, it is called hierarchical inheritance.
CODE:
class Student {
public void methodStudent() {
System.out.println("The
method of the class Student
invoked.");
}
}
class Science extends Student
{
public void methodScience() {
System.out.println("The method of the class Science invoked.");
}
}
class Commerce extends Student {
public void methodCommerce() {
System.out.println("The method of the class Commerce invoked.");
}
}
class Arts extends Student {
public void methodArts() {
System.out.println("The method of the class Arts invoked.");
}
}
public class HierarchicalInheritanceExample {
public static void main(String args[]) {
Science sci = new Science();
Commerce comm = new Commerce();
Arts art = new Arts();
sci.methodStudent();
comm.methodStudent();
art.methodStudent();
}
Abhishek Khatri
}
Output:
The method of the class Student invoked.
The method of the class Student invoked.
The method of the class Student invoked.
Hybrid Inheritance
Hybrid means consist of more than one. Hybrid inheritance is the combination of two or more types
of inheritance.
CODE:
class GrandFather {
public void show() {
System.out.println("I am grandfather.");
}
}
class Father extends GrandFather {
public void show() {
System.out.println("I am father.");
}
}
class Son extends Father {
public void show() {
System.out.println("I am son.");
}
}
public class Daughter extends Father {
public void show() {
System.out.println("I am a daughter.");
}
public static void main(String args[]) {
Daughter obj = new Daughter();
obj.show();
}
}
Output:
I am daughter.
Multiple Inheritance (not supported)
Java does not support multiple inheritances due to ambiguity.
Abhishek Khatri
CA-3
Q.1)Write a program to accept the value from user and find it’s square using swing JFrame,
JTextField, Jlabel and Jbutton. Display result on Jlabel.
Ans: CODE:
import java.awt.event.*;
import javax.swing.*;
public class Test implements ActionListener{
JFrame f1;
JTextField t1;
JLabel l1;
JButton b1;
Test(){
f1 = new JFrame();
t1 = new JTextField();
t1.setBounds(50, 50, 100, 20);
b1 = new JButton("Square");
b1.setBounds(50, 80, 100, 20);
l1 = new JLabel();
l1.setBounds(20, 100, 300, 100);
l1.setText("Get Square of a number");
b1.addActionListener(this);
f1.add(t1);f1.add(b1);f1.add(l1);
f1.setSize(300,300);
f1.setLayout(null);
f1.setVisible(true);
}
public void actionPerformed(ActionEvent e){
String s1 = t1.getText();
int x1 = Integer.parseInt(s1);
if(e.getSource() == b1){
int square = x1*x1;
l1.setText(String.valueOf(square));
}
}
public static void main(String[] args) {
new Test();
}
}
Output:
Abhishek Khatri
2)Write a program to accept two numbers from user to find the addition of the numbers and store
the result into the text file using I/O OutputStream class.
Ans:CODE:
import java.util.*;
import java.io.*;
public class Test{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int total = 0;
System.out.println("Enter 2 numbers to write there sum in file");
for(int i=0;i<2;i++){
System.out.println("Enter the "+ (i+1) +" number: ");
total+=sc.nextInt();
}
try {
OutputStream out = new FileOutputStream("test.txt");
byte[] dataBytes = String.valueOf(total).getBytes();
out.write(dataBytes);
System.out.println("Data written.");
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Enter 2 numbers to write there sum in file
Enter the 1 number:
2
Enter the 2 number:
2
Data written.
And 4 is written in the given file
C)Write a program to store and retrive the data in text file using java I/O classes
Ans: CODE:
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
byte[] dataBytes = new byte[100];
try {
OutputStream out = new FileOutputStream("test.txt");
dataBytes = "This is the new line in the file".getBytes();
out.write(dataBytes);
System.out.println("Data written.");
out.close();
Abhishek Khatri
}
}
Output:
Data written.
32
This is the new line in the file
Abhishek Khatri
1)A) What are the properties of Object Oriented Programming? Why JAVA is platform
independent?
Ans:
Refer Q.2.a) of midsem for OOPs
The meaning of platform-independent is that the java compiled code(byte code) can run on all
operating systems.
A program is written in a language that is a human-readable language. It may contain words,
phrases, etc which the machine does not understand. For the source code to be understood by the
machine, it needs to be in a language understood by machines, typically a machine-level language.
So, here comes the role of a compiler. The compiler converts the high-level language (human
language) into a format understood by the machines. Therefore, a compiler is a program that
translates the source code for another program from a programming language into executable code.
This executable code may be a sequence of machine instructions that can be executed by the CPU
directly, or it may be an intermediate representation that is interpreted by a virtual machine. This
intermediate representation in Java is the Java Byte Code.
B) Write a program to accept the N numbers from user in array and find the greatest and smallest
element and print it.
Ans:CODE:
import java.util.*;
class Test{
Abhishek Khatri
There are many types of operators in Java which are given below:
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
Abhishek Khatri
Java Default Constructor: A constructor is called "Default Constructor" when it doesn't have any
parameter.
CODE:
class Bike1{
Bike1(){
System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Output:
Bike is created
Java Parameterized Constructor: A constructor which has a specific number of parameters is called
a parameterized constructor.
CODE:
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
B)Write a program to accept details of N employee(eid, ename, esalary) and find the average salary
of N employees using arrays.
Ans:
CODE:
import java.util.*;
class Test{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the total number of employees: ");
int n = sc.nextInt();
int[] eid = new int[n];
String[] ename = new String[n];
Abhishek Khatri
4)Define Interface. Design a program that uses interface to achive multiple inheritance.
Ans: An interface in Java is a blueprint of a class. It has static constants and abstract methods.The
interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the
Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.In
other words, you can say that interfaces can have abstract methods and variables. It cannot have a
method body.Java Interface also represents the IS-A relationship.It cannot be instantiated just like
the abstract class.
There are mainly three reasons to use interface. They are given below.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.
Multiple inheritance in Java by interface
CODE:
Abhishek Khatri
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
4)A)Define thread and multithreading? Explain the life cycle of thread in detail
Ans:
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program
for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-
weight processes within a process.
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
Output
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
Active: When a thread invokes the start() method, it moves from the new state to the active state.
The active state contains two states within it: one is runnable, and the other is running.
Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state,
the thread may be running or may be ready to run at any given instant of time. It is the duty of the
thread scheduler to provide the thread time to run, i.e., moving the thread the running state.
Running: When the thread gets the CPU, it moves from the runnable to the running state. Generally,
the most common change in the state of a thread is from runnable to running and again back to
runnable.
Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then, either
the thread is in the blocked state or is in the waiting state.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is A)
has entered the critical section of a code and is not willing to leave that critical section. In such a
scenario, another thread (its name is B) has to wait forever, which leads to starvation. To avoid such
scenario, a timed waiting state is given to thread B.
Abhishek Khatri
Terminated: A thread reaches the termination state because of the following reasons:
When a thread has finished its job, then it exists or terminates normally.
Abnormal termination: It occurs when some unusual events such as an unhandled exception or
segmentation fault.
B)What are the types of exception in java. Give an example with program
Ans:Refer CA-2 Q.2.B)
C)Create two threads printing number 1 to 5 and write a program using runnable interface.
Ans:CODE:
import java.util.*;
class Multi implements Runnable{
public void run(){
for(int i=1;i<=5;i++){
System.out.println(i);
}
}
}
class Test{
public static void main(String[] args) {
Multi m1 = new Multi();
Thread t1 = new Thread(m1);
Multi m2 = new Multi();
Thread t2 = new Thread(m2);
t1.start();
t2.start();
}
}
Output:
1
2
3
4
5
1
2
Abhishek Khatri
3
4
5
Q.5.A)What is AWT? What are the AWT components we use for designing?
Ans:
AWT stands for Abstract Window Toolkit.
It is a platform-dependent API to develop GUI (Graphical User Interface) or window-based
applications in Java. It was developed by Sun Microsystem In 1995. It is heavy-weight in use
because it is generated by the system’s host operating system. It contains a large number of classes
and methods, which are used for creating and managing GUI.
Characteristics:
It is a set of native user interface components.
It is very robust in nature.
It includes various editing tools like graphics tool and imaging tools.
It uses native window-system controls.
It provides functionality to include shapes, colors and font classes.
Components: All the elements like the button, text fields, scroll bars, etc. are called components.
Container: It is a component in AWT that can contain another components like buttons, textfields,
labels etc. The classes that extends Container class are known as container such as Frame, Dialog
and Panel.It is basically a screen where the where the components are placed at their specific
locations. Thus it contains and controls the layout of components.
Example CODE:
import java.awt.*;
public class AWTExample1 extends Frame {
AWTExample1() {
Button b = new Button("Click Me!!");
b.setBounds(30,100,80,30);
add(b);
setSize(300,300);
setTitle("This is our basic AWT example");
setLayout(null);
setVisible(true);
}
public static void main(String args[]) {
AWTExample1 f = new AWTExample1();
Abhishek Khatri
}
}
Output:
Output:
Q.6.A)Define InputStream. Write a program to read the content from the file using Input stream
class in java.
Ans: InputStream class is the superclass of all the io classes i.e. representing an input stream of
bytes. It represents input stream of bytes. Applications that are defining subclass of InputStream
must provide method, returning the next byte of input.
A reset() method is invoked which re-positions the stream to the recently marked position.
Example:
Suppose we have a file named input.txt with the following content.
This is a line of text inside the file.
CODE:
import java.io.FileInputStream;
import java.io.InputStream;
class Main {
public static void main(String args[]) {
byte[] array = new byte[100];
try {
InputStream input = new FileInputStream("input.txt");
System.out.println("Available bytes in the file: " + input.available());
input.read(array);
System.out.println("Data read from the file: ");
String data = new String(array);
System.out.println(data);
input.close();
} catch (Exception e) {
e.getStackTrace();
}
}
}
Output:
Available bytes in the file: 39
Data read from the file:
This is a line of text inside the file
B)Define OutputStream. Write a program to write the content of the file using OutputStream Class.
Ans:The OutputStream class of the java.io package is an abstract superclass that represents an
output stream of bytes.Since OutputStream is an abstract class, it is not useful by itself. However,
its subclasses can be used to write data.
Example CODE:
import java.io.FileOutputStream;
import java.io.OutputStream;
public class Main {
public static void main(String args[]) {
String data = "This is a line of text inside the file.";
Abhishek Khatri
try {
OutputStream out = new FileOutputStream("output.txt");
byte[] dataBytes = data.getBytes();
out.write(dataBytes);
System.out.println("Data is written to the file.");
out.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
Output:
When we run the program, the output.txt file is filled with the following content.
This is a line of text inside the file.