0% found this document useful (0 votes)
36 views32 pages

Java All Papers Sol

Uploaded by

patilkrushna280
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)
36 views32 pages

Java All Papers Sol

Uploaded by

patilkrushna280
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/ 32

Abhishek Khatri

THIS PDF CONTAINS SOLUTIONS FOR CA-1,CA-2,MIDSEM,CA-3 AND


PREVIOUS YEAR PAPER

CA-1

1)CODE:
int x = 5;
____ (x==5){
System.__.println(“Yeah”);}
Ans: if, out

2)Not a property of JAVA OOPs:


Ans: Procedure Oriented

3)An if statement can contain how many else if statement?


Ans: As many as you want

4)print “in a loop” 7 times using while:-


CODE:
int x = 1;
while (x <= __){
System.out.println(“in a loop”);
__ ++;}
Ans: 7, x

5)Print greater number


CODE:
int x = 10; int y = 5;
___ (x > y){
System.out.println(__);}
___ {
System.out.println(__);}
Ans: if, x, else, y

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

Q.1.A)When does Exception in Java arises in code sequence?


Ans: Can occur any time (Both Run and Compile time)

B)Which keyword is not a part of exception handling?


Ans: thrown

C)Which can be used to fully abstract a class from it’s implementatio?


Ans: Interface

D)Mechanism for naming and visibility control of a class and it’s contents?
Ans: Packages

E)What will be the output of this Java program


class EH{
public static void main(String[] args) {
try{
System.out.println(“Hello” + “” + 1/0);
}
catch(ArithemeticException e){
System.out.println(“World”);
}
}
}
Ans: World

Q.2.1)Explain user defined and predefined packages with example


Ans:
Packages in Java are a mechanism to encapsulate a group of classes, interfaces, and sub-packages.
In Java, it is used for making search/locating and usage of classes, interfaces, enumerations, and
annotations easier. It can be considered data encapsulation also. In other words, we can say a
package is a container of a group of related classes where some of the classes are accessible are
exposed, and others are kept for internal purposes.
Types of Packages
Packages are categorized into two parts. These are:
Built-in packages: The already defined package like java.io.*, java. lang.* etc., are known as built-
in packages.
User-defined packages: As the name propose, user-defined packages in Java are essentially
packages that are defined by the programmer. Whenever we want to add a class to the package, we
have to mention the package name and the “package” keyword at the top of the program.
CODE:
package example;
// Class
public class gfg {
public void show()
{
System.out.println("Hello geeks!! How are you?");
}
public static void main(String args[])
Abhishek Khatri

{
gfg obj = new gfg();
obj.show();
}
}
Output:

Hello geeks!! How are you?


import example.gfg;

public class GFG {


public static void main(String args[])
{
gfg obj = new gfg();
obj.show();
}
}
Output:
Hello geeks!! How are you?

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

(1)Built-in Exceptions: ArithmeticException, IOException, FileNotFoundException,


ArrayIndexOutOfBoundsException, ClassNotFoundException, FileNotFoundException,
InterruptedException, NoSuchFieldException, NoSuchMethodException, NullPointerException,
NumberFormatException, RuntimeException, StringIndexOutOfBoundsException,
IllegalArgumentException, IllegalStateException.
Example(1):-
CODE:
// Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}
Output
Can't divide a number by 0

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

public static void main(String args[])


{
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}
Output
StringIndexOutOfBoundsException

(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

// This program throws an exception whenever balance


// amount is below Rs 1000
class MyException extends Exception
{
//store account information
private static int accno[] = {1001, 1002, 1003, 1004};

private static String name[] =


{"Nish", "Shubh", "Sush", "Abhi", "Akash"};

private static double bal[] =


{10000.00, 12000.00, 5600.0, 999.00, 1100.55};

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

// display the actual account information


Abhishek Khatri

for (int i = 0; i < 5 ; i++)


{
System.out.println(accno[i] + "\t" + name[i] +
"\t" + bal[i]);

// display own exception if balance < 1000


if (bal[i] < 1000)
{
MyException me =
new MyException("Balance is less than 1000");
throw me;
}
}
} //end of try

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

1)Correct way to declare array?


Ans: datatype[] arrayname = new datatype[size];
(NOTA in the paper)

2)Predicate the output:


class Amount{
int Amount = 20;
Amount(){
t = 40;
}
}
class Demo{
public static void main(String[] args){
Amount t1 = new Amount();
System.out.println(t1.t);
}
}
Ans:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
t cannot be resolved or is not a field
at Demo.main(Test.java:10)
(NOTA in the paper)

3)Type of inheritance that is not supported in JAVA


Ans: Multiple inheritance using classes

4)if class B is subclassed from class A then enter the correct syntax:
Ans: class B extends A{}

5)Inheritance is used for:


Ans: To avoid redundancy of the code

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.

Example of Constructor vs Method:


public class JavaTester {
int num;
JavaTester(){
num = 3;
System.out.println("Constructor invoked. num: " + num);
}
public void init(){
num = 5;
System.out.println("Method invoked. num: " + num);
}
public static void main(String args[]) {
JavaTester tester = new JavaTester();
tester.init();
}
}
Output
Constructor invoked. num: 3
Method invoked. Num: 5

c)Write a program for method overloading.


Ans:
There are two ways to overload the method in java
Abhishek Khatri

By changing number of arguments


By changing the data type

1) Method Overloading: changing no. of arguments


CODE:
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
Output:
22
33

2) Method Overloading: changing data type of arguments


CODE:
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}
Output:
22
24.9

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

public class Test{


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of mobile phones: ");
int totalItems = scanner.nextInt();
Mobile[] records = new Mobile[totalItems];
for (int i = 0; i < totalItems; i++) {
System.out.println("Enter details for mobile phone " + (i+1) + ":");
System.out.print("Enter product ID: ");
int productId = scanner.nextInt();
System.out.print("Enter company name: ");
String companyName = scanner.next();
System.out.print("Enter price: ");
double price = scanner.nextDouble();
records[i] = new Mobile(productId, companyName, price);
}
double totalPrice = 0;
for (Mobile record : records) {
totalPrice += record.price;
}
double averagePrice = totalPrice / totalItems;
System.out.println("The average price of the mobile phones is: " + averagePrice);
}
}
Output:
Enter the number of mobile phones: 2
Enter details for mobile phone 1:
Enter product ID: 111
Enter company name: A1
Enter price: 10000
Enter details for mobile phone 2:
Enter product ID: 222
Enter company name: A2
Enter price: 20000
The average price of the mobile phones is: 15000.0

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

InputStream in = new FileInputStream("test.txt");


System.out.println(in.available());
in.read(dataBytes);
String s1 = new String(dataBytes);
System.out.println(s1);
in.close();
} catch (Exception e) {
e.printStackTrace();
}

}
}
Output:
Data written.
32
This is the new line in the file
Abhishek Khatri

Previous Year Endsem Paper

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.

Step by step Execution of Java Program:


Whenever, a program is written in JAVA, the javac compiles it.
The result of the JAVA compiler is the .class file or the bytecode and not the machine native code
(unlike C compiler).
The bytecode generated is a non-executable code and needs an interpreter to execute on a machine.
This interpreter is the JVM and thus the Bytecode is executed by the JVM.
And finally program runs to give the desired output.

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

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter the total number of values: ");
int n = sc.nextInt();
int[] arr = new int[n];
for(int i=0;i<n;i++){
System.out.println("Enter number");
int x = sc.nextInt();
arr[i] = x;
}
int max = 0;
int min = arr[0];
for(int i : arr){
if(i>max){
max = i;
}
if(i<min){
min = i;
}
}
System.out.println("The maximum value is "+ max + " and the minimum value is "+
min);
}
}
Output:
3
Enter number
1
Enter number
2
Enter number
3
The maximum value is 3 and the minimum value is 1

C)Explain operators in JAVA and give an example of each


Ans:
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.

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 Unary Operator Example: ++ and --


public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
Output:
10
12
12
10

Q.2.A)Explain constructor and it’s types with example


Ans: In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the
memory.It is a special type of method which is used to initialize the object.Every time an object is
created using the new() keyword, at least one constructor is called.It calls a default constructor if
there is no constructor available in the class. In such case, Java compiler provides a default
constructor by default.

There are two types of constructors in Java:


Default constructor (no-arg constructor)
Parameterized constructor
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);}

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan

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

int[] esalary = new int[n];


for(int i=0;i<n;i++){
System.out.println("Enter employee id");
eid[i] = sc.nextInt();
System.out.println("Enter employee ename");
ename[i] = sc.next();
System.out.println("Enter employee salary");
esalary[i] = sc.nextInt();
}
double total = 0;
for(int i : esalary){
total+=i;
}
System.out.println("The average salary of all the employees is "+total/n);
}
}
Output:
Enter the total number of employees:
2
Enter employee id
111
Enter employee ename
name1
Enter employee salary
20000
Enter employee id
222
Enter employee ename
name2
Enter employee salary
30000
The average salary of all the employees is 25000.0

3)What is function overloading give an example


Ans:Refer MIDSEM Q.2.c)

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

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:Hello
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.

Threads can be created by using two mechanisms :


Extending the Thread class
Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread class. This class overrides the run() method
available in the Thread class. A thread begins its life inside run() method. We create an object of our
new class and call start() method to start the execution of a thread. Start() invokes the run() method
on the Thread object.
CODE:
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
Abhishek Khatri

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

Life cycle of a Thread (Thread States)


In Java, a thread always exists in any one of the following states. These states are:
New
Active
Blocked / Waiting
Timed Waiting
Terminated

Explanation of Different Thread States


New: Whenever a new thread is created, it is always in the new state. For a thread in the new state,
the code has not been run yet and thus has not begun its execution.

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.

Java AWT Hierarchy

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:

2)Use ActionListner in JAVA Swing


Ans:
CODE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test{
JFrame mainFrame;
JLabel headerLabel;
JLabel statusLabel;
JPanel controlPanel;
Test(){
mainFrame = new JFrame("Java SWING Examples");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("", JLabel.CENTER);
statusLabel.setSize(350, 100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
Test swingListenerDemo = new Test();
swingListenerDemo.showActionListenerDemo();
}
private void showActionListenerDemo() {
headerLabel.setText("Listener in action: ActionListener");
JPanel panel = new JPanel();
JButton okButton = new JButton("OK");
okButton.addActionListener(new CustomActionListener());
panel.add(okButton);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
class CustomActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Ok Button Clicked.");
}
}
}
Abhishek Khatri

Output:

3)Give example of Graphics


class methods from AWT
package
Ans:Graphics is an abstract
class provided by Java AWT
which is used to draw or
paint on the components. It
consists of various fields
which hold information like components to be painted, font, color, XOR mode, etc., and methods
that allow drawing various shapes on the GUI components. Graphics is an abstract class and thus
cannot be initialized directly.
CODE:
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MyFrame extends Frame {
public MyFrame()
{
setVisible(true);
setSize(300, 200);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
g.drawRect(100, 100, 100, 50);
}
public static void main(String[] args)
{
new MyFrame();
}
}
Output:
Abhishek Khatri

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.

C)What is vector and its methods with example:


Ans: (Out of syllabus)

You might also like