0% found this document useful (0 votes)
13 views

Java 1stut Qb Ans

The document is a Java question bank for the 1st Unit Test, covering various topics such as features of Java, control structures like switch-case and conditional operators, type casting, exception handling, and inheritance. It includes explanations, syntax, examples, and Java programs for concepts like constructors, classes, and built-in exceptions. Additionally, it discusses user-defined packages and the importance of exception handling in robust programming.

Uploaded by

vedantwalanj18
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Java 1stut Qb Ans

The document is a Java question bank for the 1st Unit Test, covering various topics such as features of Java, control structures like switch-case and conditional operators, type casting, exception handling, and inheritance. It includes explanations, syntax, examples, and Java programs for concepts like constructors, classes, and built-in exceptions. Additionally, it discusses user-defined packages and the importance of exception handling in robust programming.

Uploaded by

vedantwalanj18
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Java Question bank 1st UT

(ANSWERS)

4Marks
1) Explain Four Features of Java.
I. Object Oriented: In Java, everything is an Object. Java can be easily
extended since it is based on the Object model.
II. Platform Independent: Unlike many other programming languages
including C and C++, when Java is compiled, it is not compiled into
platform specific machine, rather into platform independent byte code.
This byte code is distributed over the web and interpreted by the
Virtual Machine (JVM) on whichever platform it is being run on.
III. Simple: Java is designed to be easy to learn. If you understand the
basic concept of OOP Java, it would be easy to master.
IV. Secure: With Java's secure feature it enables to develop virus-free,
tamper free systems. Authentication techniques are based on public-
key encryption.

2) Explain Switch Case and Conditional Operator In Java With Suitable


Example.
Switch case statement: The switch case statement allows us to execute a
block of code among many alternatives.
Syntax : switch (expression)
{
case value1:
// code
break;
case value2: // code
break;
default: // default statements
}
The expression is evaluated once and compared with the values of each case.
If expression matches with value1, the code of case value1 are executed.
Similarly, the code of case value2 is executed if expression matches with
value2. break is a required statement, which is used to take break from
switch block, if any case is true. Otherwise even after executing a case, if
break is not given, it will go for the next case. If there is no match, the code
of the default case is executed.
Example :
// Java Program to print day of week
// using the switch...case statement
class test1{
public static void main(String[] args)
{
int number = 1;
String day;
switch (number)
{
case 1: day = "Monday";
break;
case 2: day= "Tuesday";
break;
case 3: day = "Wednesday";
break;
case 4: day= "Thursday";
break;
case 5: day = "Friday";
break;
case 6: day= "Saturday";
break;
case 7: day = "Sunday";
break;
default: day= "Invalid day";
}
System.out.println(day);
}
}

Conditional Operator:
The Conditional Operator is used to select one of two expressions for
evaluation, which is based on the value of the first operands. It is used to
handling simple situations in a line.
Syntax: expression1 ? expression2:expression3;
The above syntax means that if the value given in Expression1 is true, then
Expression2 will be evaluated; otherwise, expression3 will be evaluated.
Example
class test {
public static void main(String[] args)
{
String result;
int a = 6, b = 12;
result = (a==b ? "equal":"Not equal");
System.out.println("Both are "+result);
}
}

3) Describe Concept of Type Casting and Explain its Types With proper
syntax and example.
I. The process of converting one data type to another is called casting or type
casting.
II. If the two types are compatible, then java will perform the conversion
automatically.
III. It is possible to assign an int value to long variable.
IV. However, if the two types of variables are not compatible, the type conversions
are not implicitly allowed, hence the need for type casting.
There are two types of conversion:
1.Implicit type-casting.
2.Explicit type-casting.
1. Implicit type-casting:
Implicit type-casting performed by the compiler automatically; if there will be no loss of
precision.
Example:
int i = 3;
double f;
f = i;
output: f = 3.0
2. Explicit type-casting:
• Explicit type-casting performed via a type-casting operator in the prefix form of (new-
type) operand.
• Type-casting forces an explicit conversion of type of a value. Type casting is an
operation which takes one operand, operates on it and returns an equivalent value in the
specified type.
Syntax:
new Value = (typecast)value;

Example: double f = 3.5;


int i;
i = (int)f;
// it cast double value 3.5 to int 3.
4).Write A Java program to display all the odd numbers between 1 to 30 using
for loop & if statement.

public class OddNumbers


{
public static void main(String[] args)
{
for (int i = 1; i <= 30; i++)
{
if (i % 2 != 0)
{
System.out.println(i);
}
}
}
}
Output:
1
3
5
7
9
11
13
15
17
19
21
23
25
27
29

5.Define a class employee with data members ‘empid’, ‘name’,’salary’.accept


data for three objects and display it.
class employee
{
int empid;
String name;
double salary;
void getdata()
{
BufferedReader obj=
new BufferedReader (new InputStreamReader(System.in));
System.out.print("Enter Emp number : ");
empid=Integer.parseInt(obj.readLine());
System.out.print("Enter Emp Name : ");
name=obj.readLine();
System.out.print("Enter Emp Salary : ");
salary=Double.parseDouble(obj.readLine());
}
void show()
{
System.out.println("Emp ID : " + empid);
System.out.println(“Name : " + name);
System.out.println(“Salary : " + salary);
}
}
classEmpDetails
{
public static void main(String args[])
{
employee e[] = new employee[3];
for(inti=0; i<3; i++)
{
e[i] = new employee(); e[i].getdata();
}
System.out.println(" Employee Details are : ");
for(inti=0; i<3; i++)
e[i].show();
}
}

6.Define a class circle having data members Pi and radius.Initialize and


display values of data members also calculate are of circle and display it.

class abc{
float pi,radius;
abc(float p, float r)
{
pi=p;
radius=r;
}
void area()
{
float ar=pi*radius*radius;
System.out.println("Area="+ar);
}
void display()
{
System.out.println("Pi="+pi);
System.out.println("Radius="+radius);
}
}
class area
{
public static void main(String args[])
{
abc a=new abc(3.14f,5.0f);
a.display();
a.area();
}
}

7.Develop a program to create a class ‘Book’ having data members


author,title and price.Derive a class ‘BookInfo’ having data member ‘stock
position’ and method to initialize and display the information for three object.
class Book
{
String author, title, publisher;
Book(String a, String t, String p)
{
author = a;
title = t;
publisher = p;
}
}
class BookInfo extends Book
{
float price;
int stock_position;
BookInfo(String a, String t, String p, float amt, int s)
{
super(a, t, p);
price = amt;
stock_position = s;
}
void show()
{
System.out.println("Book Details:");
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Publisher: " + publisher);
System.out.println("Price: " + price);
System.out.println("Stock Available: " + stock_position);
}
}
class Exp6_1
{
public static void main(String[] args)
{
BookInfo ob1 = new BookInfo("Herbert Schildt", "Complete Reference", "ABC
Publication", 359.50F,10);
BookInfo ob2 = new BookInfo("Ulman", "system programming", "XYZ
Publication", 359.50F, 20);
BookInfo ob3 = new BookInfo("Pressman", "Software Engg", "Pearson
Publication", 879.50F, 15);
ob1.show();
ob2.show();
ob3.show();
}
}
OUTPUT:
Book Details:
Title: Complete Reference
Author: Herbert Schildt
Publisher: ABC Publication
Price: 2359.5
Stock Available: 10
Book Details:
Title: system programming
Author: Ulman
Publisher: XYZ Publication
Price: 359.5
Stock Available: 20
Book Details:
Title: Software Engg
Author: Pressman
Publisher: Pearson Publication
Price: 879.5
Stock Available: 15

8.Explain single and multilevel inheritance with proper example.


Single level inheritance:
In single inheritance, a single subclass extends from a single
superclass.

Example :
class A {
void display()
{
System.out.println(“In Parent class A”);
}
}
class B extends A //derived class B from A
{
void show()
{
System.out.println(“In child class B”);
}
public static void main(String args[])
{
B b= new B();
b.display(); //super class method call
b.show(); // sub class method call
}
}
Multilevel inheritance:
In multilevel inheritance, a subclass extends from a superclass and
then the same subclass acts as a superclass for another class.
Basically it appears as derived from a derived class.

Example:
class A
{
void display()
{
System.out.println(“In Parent class A”);
}
}
class B extends A //derived class B from A
{
void show()
{
System.out.println(“In child class B”);
}
}
class C extends B //derived class C from B
{
public void print()
{
System.out.println(“In derived from derived class C”);
}
public static void main(String args[])
{
C c= new C();
c.display(); //super class method call
c.show(); // sub class method call
c.print(); //sub-sub class method call
}
}
9.Define an Exception Called “No Match Exception” that is thrown when
the password accepted is not equal to “MSBTE”. Write the program.

import java.io.*;
class NoMatchException extends Exception
{
NoMatchException(String s)
{
super(s);
}
}
class test1
{
public static void main(String args[]) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in) );
System.out.println("Enter a word:");
String str= br.readLine();
try
{
if (str.compareTo("MSBTE")!=0) // can be done with equals()
throw new NoMatchException("Strings are not equal");
else
System.out.println("Strings are equal");
}
catch(NoMatchException e)
{
System.out.println(e.getMessage());
}
}
}
10.Define Exception. State Built-In Exceptions.
An exception is a problem that arises during the execution of a
program.
Java exception handling is used to handle error conditions in a program
systematically by taking the necessary action
Built-in exceptions:
• Arithmetic exception: Arithmetic error such as division by
zero.
• Class Not Found Exception
• File Not Found Exception: Caused by an attempt to access
a nonexistent file.
• IO Exception: Caused by general I/O failures, such as
inability to read from a file.
• NullPointerException: Caused by referencing a null object.
• SecurityException: Caused when an applet tries to perform
an action not allowed by the browser’s security setting.
• StackOverflowException: Caused when the system runs out
of stack space.

6Marks

1) What is constructor? List types of constructor .Explain paramaterized


constructor with suitable example.
Constructor:
A constructor is a special member which initializes an object
immediately upon creation.
• It has the same name as class name in which it resides and it is
syntactically similar to any method.
• Once defined, constructor is automatically called immediately after
the object is created before new operator completes.
Types of constructors:
1. Default constructor
2. Parameterized constructor
3. Copy constructor
4. Constructor with no arguments
Parameterized constructor:
When constructor method is defined with parameters inside it, different value sets can be
provided to different constructor with the same name.
Example
class Student {
int roll_no;
String name;
Student(int r, String n) // parameterized constructor
{
roll_no = r;
name=n;
}
void display()
{
System.out.println("Roll no is: "+roll_no);
System.out.println("Name is : "+name);
}
public static void main(String a[])
{
Student s = new Student(20,"ABC"); // constructor
with parameters
s.display();
}
}
2) Explain the difference between String class and String Buffer
class.Explain any four methods of String class.

Methods of string class


1)toLowercase ():
Converts all of the characters in this String to lower case.
Syntax: s1.toLowerCase()
Example: String s="Sachin";
System.out.println(s.toLowerCase());
Output: sachin

2) toUppercase():
Converts all of the characters in this String to upper case
Syntax: s1.toUpperCase()
Example: String s="Sachin";
System.out.println(s.toUpperCase());
Output: SACHIN

3)trim ():
Returns a copy of the string, with leading and trailing whitespace
omitted.
Syntax: s1.trim()
Example: String s=" Sachin ";
System.out.println(s.trim());
Output:Sachin
5. length():
Syntax: int length()
It is used to return length of given string in integer.
Eg. String str=”INDIA”
System.out.println(str.length()); // Returns 5

3) Write a program to define class Emplyoee with members as id and salary .Accept data for
five employees and display details of employees getting highest salary.

4) Compare array and vector .Explain elementAT() and addElement()


methods
elementAT( ):
The elementAt() method of Java Vector class is used to get the element at the specified
index in the vector. Or The elementAt() method returns an element at the specified index.
addElement( ):
The addElement() method of Java Vector class is used to add the specified element to the
end of this vector. Adding an element increases the vector size by one.
5) How to create user defined package in java. Explain with an suitable
example.
A java package is a group of similar types of classes, interfaces and
sub-packages
It also provides access protection and removes name collisions.

Creation of user defined package:


To create a package a physical folder by the name should be created
in the computer.
Example: we have to create a package myPack, so we create a folder
d:\myPack
The java program is to be written and saved in the folder myPack. To
add a program to the package, the first line in the java program
should be package <name>; followed by imports and the program
logic.
package myPack;
import java.util;
public class Myclass {
//code
}
Example:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
System.out.println("Volume is:"+(l*b*h));
}
}
Source file:
import package1.Box;
class volume {
public static void main(String args[])
{
Box b=new Box();
b.display(); }
}
6) Explain the concepts of exception handling in java and it’s importance in robust
programming.Provide an example to illustrate the implementation and benefits of
exception handling
7) Implement the following inheritance
Interface:Salary Class:Emplyoee
Basic_salary
Basicsal() Name,age

Display()

Class:Gross_salary
TA,DA,HRA
Total_sal()

You might also like