We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 45
KHARAT ACADEMY
Subject - Java Programming (JPR - 22412)
(IMP Questions with Answers)
1 Scheme - MSBTE
Branches: CO0/CM/CW/IF
(Weightage - 10 Marks)
1. List any eight features of Java.
Answer:
Features of Java:
1) Data Abstraction and Encapsulation
2) Inheritance
3) Polymorphism
4) Platform independence
5) Portability
6) Robust
7) Supports multithreading
8) Supports distributed applications
9) Secure
10) Architectural neutral
11) Dynamic
2. Enlist the logical operators in Java.
Answer:
&&: Logical AND
||: Logical OR
!: Logical NOT
3. Define array. List its types.
Answer;
An array is a homogeneous data type where it can hold only abjects of one data type.
Types of Array:
1) One-Dimensional
2) Two-Dimensional
EteKHARAT ACADEMY
4. Explain any four features of Java.
Answer:
1) Object Oriented: In Java, everything is an Object. Java can be easily extended since
itis based on the Object model.
2) 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.
3) Simple: Java is designed to be easy to learn. If you understand the basic concept
of OOP Java, it would be easy to master.
4) Secure: With Java's secure feature it enables to develop virus-free, tamperfree
systems. Authentication techniques are based on public-key encryption.
5) Architecture-neutral: Java compiler generates an architecture-neutral abject file
format, which makes the compiled code executable on many processors, with the
presence of Java runtime system.
6) Multithreaded: With Java's multithreaded feature it is possible to write programs
that can perform many tasks simultanequsly. This design feature allows the
developers to construct interactive applications that can run smoothly.
5. Explain the concept of platform independence and portability with respect to
Java language.
Answer:
1) Java is a platform independent language. This is possible because when ajava
program is compiled, an intermediate code called the byte code is obtained rather
than the machine code.
2) Byte code is a highly optimized set of instructions designed to be executed by the
JVM which is the interpreter for the byte code. Byte code is not a machine specific
code. Byte code is a universal code and can be moved anywhere to any platform.
3) Therefore javais portable, as it can be carried to any platform. JVM is a virtual
machine which exists inside the computer memory and is a simulated computer
thin acomputer which does all the functions of a computer.
4) Only the JVM needs to be implemented for each platform. Although the details of
the JVM will defer from platform to platform, all interpret the same byte cade.KHARAT ACADEMY
Source Code Java Virtual Lp Window Operating
Machine (VM) ‘System
i Java Virtual Linux Operating
BERR: Machine (JVM) System
6. Define type casting. Explain its types with syntax and example.
Answer:
1) The process of converting one data type to another is called casting or type
casting.
2) If the two types are compatible, then java will perform the conversion
automatically.
3) Itis possible to assign an int value to long variable.
4) However, if the two types of variables are nat compatible, the type conversions
are not implicitly allowed, hence the need for type casting.
‘There are two types of conversion:
1. Implicit type-castin,
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:
inti=3;
double f;
f=i;
output:
F230
Widening Conversion: The rule is to promote the smaller type to bigger type to prevent
loss of precision, known as Widening Conversion.
2. Explicit type-casting:
Explicit type-casting performed via a type-casting operator in the prefix form of (new-
type) operand.KHARAT ACADEMY
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: newValue = (typecast) value;
Example:
double f = 3.5;
inti;
i=(int)f; // it cast double value 3.5 to int 3.
Narrowing Casting: Explicit type cast is requires to Narrowing conversion to inform.
the compiler that you are aware af the possible loss of precision,
7. Explain any two logical operator in java with example.
Answer:
Logical Operators: Logical operators are used when we want to form compound
conditions by combining two or more relations. Java has three logical operators as
shown in table:
Program demonstrating logical Operators
public class Test {
public static void main(String args[J) {
boolean a = true;
boolean b = false;
System.outprintin("a && b = "+ (a&&b));
System.outprintin(“a |b =" + (al{b) );
System.out-printin("!(a && b) =" +!(a && b));
}
}
Output: a && b = false a|| b = true !(a && b) = true
8. Explain switch case and conditional operator in java with suitable example.
Answer:
switch,..case statement:
1) The switch...case statement allows us to execute a block of code among many
alternatives.
2) Syntax :
switch (expression) {
case value]:
Jf code
break;
case value2:
fiKHARAT ACADEMY
f/f code
break;
default
// default statements
J
The expression is evaluated once and compared with the values of each case.
3) If expression matches with valuel, the code of case valuel are executed.
Similarly, the code of case value? 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.
4) Otherwise even after executing a case, if break is not given, it will go for the next
case. If there is no match, the cade of the default case is executed.
Example:
// Java Program to print day of week
#/ using the switch..case statement
class test {
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 printin(day);KHARAT ACADEMY
)
Conditional Operator:
The Conditional Operator Is used to select one af 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: expression! ? expression?:expression3;
The above syntax means that if the value given in Expression] is true, then Expression2
will be evaluated;
otherwise, expression3 will be evaluated.
Example
class test {
public static void main(String[] args) {
String result;
inta=6,b=12;
b ? “equal”:"Not equal");
System.out.printin("Both are "+result);
}
9. List any four methods of string class and state the use of each.
Answer:
The java.lang.String class provides alot of methods to work on string. By the help of
these methods, We can perform operations on string such as trimming, concatenating,
converting, comparing, replacing strings etc.
1) toLowercase (): Converts all of the characters in this String to lower case. Syntax:
s1.toLowerCase()
Example:
String s="Sachin";
System. out. printin(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 printin(s.toUpperCase(});
ii mt)KHARAT ACADEMY
Output: SACHIN
3) trim Q): Returns a copy of the string, with leading and trailing whitespace omitted.
Syntax: s1.trim))
Example:
String s=" Sachin ";
System. out.printin(s.trim());
Output:Sachin
4) replace (): Returns a new string resulting from replacing all occurrences of old Char
in this string with new Char, Syntax: s1.replace('x’;y')
Example:
String s1="Java is a programming language. Javais a platform.”;
String s2=s1.replace("Java","Kava"); //replaces all occurrences of "Java" to "Kava"
System. out printin(s2);
Output: Kava is a programming language. Kava is a platform,
10. Differentiate between array and vector.
_—
ig Aoace
An array is a structure that The Vector is similar to array holds
holds multiple values of the multiple objects and like an array; it
same type contains components that can be
accessed using an integer index
An array is a homogeneous data Vectors are heterogeneous. You can
type where it can hald only
objects of one data type
Array can store primitive type
data element.
Array is the static memory
allocation
After creation, an array isa
fixed-length structure,
11. Write a Java Program to find out the even numbers from 1 to 100 using for
loop.
have objects of different data types
inside a Vector
The size of a Vector can grow or
shrink as needed to accommodate
adding and removing items after
the Vector has been created
Vector are store nonprimitive type
data element.
Vector is the dynamic memory
allocationKHARAT ACADEMY
Answer:
class test {
public static void main(String args{)) {
System.out printin("Even numbers from 1 to 100 :");
for(int i=1;i<=100; i++) {
if(i%2==0)
System.out print(i+
12. Write a java program to sort an 1-d array in ascending order using bubble-
sort.
Answe
public class BubbleSort {
public static void main(String[] args) {
int arr[] ={3,60,35,2,45,320,5};
System.out.printin(“Array Before Bubble Sort");
for(int i=0; i< nj i++) {
for(int j=1; j < (m-i); [+4
{
if(arr[j-1] >arr{i])
{
//swap elements
temp=are[[-1);
arr[j-1) = arr[j];
are{j] = temp;
System.outprintin("Array After Bubble Sort");
for(int i=0; i< arr.length; i++) {
System.outprint(are[i] + "”);
ee et)KHARAT ACADEMY
}
13. Write a program to create a vector with five elements as (5, 15, 25, 35, 45).
Insert new element at 2nd position. Remove 1st and 4th element from vector.
Answer:
import java.util";
class VectarDemo {
public static void main ng] args) {
Vector v = new Vector();
v.addElement(new Integer(5));
v.addElement(new Integer(15));
y.addElement(new Integer(25));
y.addElement(new Integer(35));
v.addElement(new Integer(45));
System.out.printin("Original array elements are“);
for(int i=0;i< v.size();i++) {
System.out printIn(v.elementat(i));
}
v.insertElementAt(new Integer(20),1); // insert new element at 2nd position
v.removeElementat(0); //remove first element
v.removeElementat(3); //remove fourth element
System.out.printin(“Array elements after insert and remove operation ");
for(int i=0;i< w.size();i++) {
System out printin(v.elementAt(i));
fiKHARAT ACADEMY
Subject - Java Programming (JPR - 22412)
(IMP Questions with Answers)
Scheme - MSBTE
Branches: CO/CM/CW/IF
(Weightage - 18 Marks)
1. Define Constructor. List its types.
Answer:
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 itis
syntactically similar to any method. When a constructor is not defined, java executes a
default constructor which initializes all numeric members to zero and other types to
null or spaces. 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
2, Define Class and Object.
Answer:
Class: A class isa user defined data type which groups data members and its associated
functions together.
Object: Itis a basic unit of Object Oriented Programming and represents the real life
entities. A typical Java program creates many objects, which as you know, interact by
invoking methods.
3. State use of finalize( ) method with its syntax.
Answer:
Use of finalize():
1) Sometimes an object will need to perform some action when itis destroyed. Eg. If
an object holding some non java resources such as file handle or window
character font, then before the object is garbage collected these resources should
be freed.
SdKHARAT ACADEMY
2) To handle such situations java provide a mechanism called finalization. In
finalization, specific actions that are to be done when an object is garbage
collected can be defined.
3) To add finalizer to a class define the finalize() method. The java run-time calls
this method whenever it is about to recycle an object.
4) Syntax:
protected void finalize() {
4. on the syntax and example for the following functions i) min ( ) ii) Sqrt ()
Answer:
i) min)
Syntax: static int min(int x, int y) Returns minimum of x and y
Example: int y= Math.min(64,45);
ii)Sqrt()
Syntax: static double sqrt(double arg) Returns square root of arg.
Example: double y= Math.sqrt(64);
5. Describe final variable and final method.
Answer:
Final method: making a method final ensures that the functionality defined in this
method will never be altered in any way, ie a final method cannot be overridden.
Syntax:
final void findAverage() {
//implementation
}
Example of declaring a final method:
class A {
final void show() {
System.out.printin("in show of A");
)
}
class B extends A {
void show() // can not override because it is declared with final
{
System.out printin(“in show of B”);KHARAT ACADEMY
}
Final variable: the value of a final variable cannot be changed. Final variable behaves
like class variables and they do not take any space on individual objects of the class.
Example of declaring final variable: final int size = 100;
6. Name the wrapper class methods for the following:
(i) To convert string objects to primitive int
(ii) To convert primitive int to string objects.
Answer;
To convert string objects to primitive int:
String str="5"; int value = Integer.parselnt(str);
To convert primitive int to string objects:
int value=5; String str=Integer.toString(value);
7. Explain the types of constructors in Java with suitable example.
OR
8. What is constructor? List types of constructor. Explain parameterized
constructor with suitable example.
Answer:
Constructors are used to initialize an object as soon as itis created. Every time an
object is created using the ‘new’ keyword, a constructor is invoked. If no constructor is
defined in a class, java compiler creates a default constructor. Constructors are similar
to methods but with to differences, constructor has the same name as that of the class
and it does not return any value.
The types of constructors are:
1. Default constructor
2. Constructor with no arguments
3. Parameterized constructor
4. Copy constructor
a. Default constructor: Java automatically creates default constructor if there is
no default or parameterized constructor written by user. Default constructor
in Java initializes member data variable to default values (numeric values are
initialized as 0, Boolean is initialized as false and references are initialized as
null).
class testl {
inti;
boolean b;
byte bt;
float ft;KHARAT ACADEMY
String s;
public static void main(String args[]) {
test1 t = new test / default constructor is called.
System.out printin(ti
System.out printIn(ts);
System.out.printin(t.b);
System.out.printIn(t-bt);
System.out printin(t-ft);
. Constructor with no arguments: Such constructors does not have any
parameters. All the objects created using this type of constructors has the
same values for its datamembers.
Eg:
class Student {
int roll_na;
String name;
Student() {
roll_n i
name="ABC";
}
void displayQ) {
System.out.printin("Roll no is: "+follno);
System.out.printin("Name is : "+name);
}
public static void main(String af]}) {
Student s = new Student();
sdisplay();
c. Parametrized constructor: Such constructor consists of parameters. Such
constructors can be used to create different objects with datamembers having
different values.
class Student {
int roll_no;
String name;
Student(int r, String n) {
roll_no = r; name=n;
J
void display() {
System.out printin("Roll no '+roll_no);
System.out printin("Name is : "+name);KHARAT ACADEMY
public static void main(String a[]) {
Student s = new Student(20,"ABC");
s.display();
d. Copy Constructor: A copy constructor is a constructor that creates anew
object using an existing object of the same class and jalizes each instance
variable of newly created object with corresponding instance variables of the
existing abject passed as argument. This constructor takes a single argument
whose type is that of the class containing the constructor.
class Rectangle {
int length;
int breadth;
Rectangle(intl, int b) {
length = |; breadth= b;
}
//copy constructor
Rectangle(Rectangle obj) {
length = obj.length;
breadth= obj.breadth;
)
public static void main(String[] args) {
Rectangle r1= new Rectangle(5,6);
Rectangle r2= new Rectangle(r1);
System.out printIn(“Area of First Rectangle : “+ (r1.length*r1.breadth));
System .outprintin("Area of First Second Rectangle :
“+(r1Jength*r1.breadth));
)
}
9, Describe instance Of and dot (.) operators in Java with suitable example.
Answer:
Instance of operator: The java instance of operator is used to test whether the object is
an instance of the specified type (class or subclass or interface).
The instance of in java is also known as type comparison operator because it compares
the instance with type. It returns either true or false. If we apply the instance of
operator with any variable that has null value, it returns false.
Example
class Simple1{
public static void main(String args[]) {
Simple1 s=new Simple1();
PieKHARAT ACADEMY
System.out printin(sinstanceofSimple1);//true
)
}
dot (.) operator: The dot operator, also known as separator ar periad used to separate a
variable or method from a reference variable. Only static variables or methods can be
accessed using class name. Code that is outside the object's class must use an object
reference or expression, followed by the dot (.) operator, followed by a simple field
name.
Example
this.name="john"; //where name is a instance variable referenced by ‘this’ keyword
c.getdata(); //where getdata() is a method invoked on object ‘c’
10. Explain the command line arguments with suitable example.
Answer:
Java Command Line Argument: The java command-line argument is an argument i.e.
passed at the time of running the java program.
1) The arguments passed from the console can be received in the java program and
it can be used as an input.
2) 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.
3) Command Line Arguments can be used to specify configuration information while
launching your application. There is norestriction on the number of java
command line arguments.
4) You can specify any number of arguments Information is passed as Strings. They
are captured into the String args of your main method Simple example of
command-line argument in java In this example, we are receiving only one
argument and printing it.
5) To run this java program, you must pass at least one argument from the
command prompt.
class CommandLineExample {
public static void main(String args[]){
System.out.printin("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
11. Differentiate between String and String Buffer.KHARAT ACADEMY
String is a major class String Buffer isa peer class of String
aa Length is fixed (immutable) Length is flexible (mutable)
Contents of object cannot be Contents of object can be modified
modified
Object can be created by Objects can be created by calling
assigning String constants constructor of String Buffer class
enclosed in double quotes using “new"
12. Define a class circle having data members pi and radius. Initialize and display
values of data members also calculate area of circle and display it.
Answer:
class abe {
float pi,radius; abc(float p, float r) {
pi=p; radius=r; } void area() {
float ar=pi*radius*radius;
System.out.printin(“Area="+ar);
}
void display) {
System.out prinun( "Pi:
System.out-printin("Radius="+radius);
}
class area {
public static void main(String args[]) {
abe a=new abc(3.14£,5.00);
a.display();
aarea(];KHARAT ACADEMY
Subject - Java Programming (JPR - 22412)
(IMP Questions with Answers)
y CUE eC:
I Scheme - MSBTE
Branches: CO/CM/CW/IF
(Weightage - 12 Marks)
1. List the types of inheritances in Java.
Answer:
Types of inheritances in Java:
1) Single level inheritance
2) Multilevel inheritance
3) Hierarchical inheritance
4) Multiple inheritance
5) Hybrid inheritance
2. Define the interface in Java.
Answer:
Interface is similar to a class.
It consist of only abstract methods and final variables. To implement an interface a
class must define each of the method declared in the interface. It is used to achieve fully
abstraction and multiple inheritance in Java
3. List any four Java API packages.
Answer:
1) java.lang
2) java.util
3) javi
4) javaawt
5) java.net
6) ava.applet
4, Explain single and multilevel inheritance with proper example.
eea4
KHARAT ACADEMY
Answer:
1) Single level inheritance: In single inheritance, a single subclass extends froma
single superclass.
ferry
terre)
Example :
class A{
void display() {
System.out printin(“In Parent class A");
}
}
class B extends A //derived class B from A
{
void show() {
System.out.printin("In child class B");
}
public static void main(String args[]) {
B b= new BO);
b.display(); //super class method call
bshow(); //'sub class method call
)
2) 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.
Class A
Class B
Example:
class A {KHARAT ACADEMY
void display(){
System.out.printIn(“In Parent class A”);
)
}
class B extends A //derived class B from A
{
void show(] {
System.out.printin("In child class B");
)
}
class C extends B //derived class C fram B
{
public void print() {
System.out.printIn(“In derived from derived class C”);
}
public static void main(String args[]) {
Cc=new CQ);
c.display(); //super class method call
c.show(); // sub class method call
c.print(); //sub-sub class method call
}
5. Explain the four access specifiers in Java.
OR
6. Explain any four visibility controls in Java.
Answer:
There are 4 types of java access modifiers:
1, private
2. default
3. protected.
4. public
1) private access modifier: The private access modifier is accessible only within class.
2) default access specifier: If you don’t specify any access control specifier, it is default,
Le. it becomes implicit public and it is accessible within the program.KHARAT ACADEMY
3) protected access specifier: The protected access specifier is accessible within
package and outside the package but through inheritance only.
4) public access specifier: The public access specifier is accessible everywhere. It has
the widest scope among all other modifiers.
Access Modifier
Access Location
Public
Protected
Friendly
(default)
Private
protected
private
Same Class
Yes
Yes
es
Sub class in same
package
Other classes in
Yes
Yes
Yes
Yes
Yes
s
Ye
Yes
same package
Sub class in other Yes
packages
Yes
Non sub classes in Yes No
other packages
Ye!
Yes
No
No
No
|
7 [| %
7. Differentiate between class and interfaces.
vet
doesn't Supports
inheritance
extend keyword is used to
inherit
class contain method body
contains any type of variable
Ey can have constructor
8. =
BE
On
1 Applets run in web pages
Eee vu alias
Applets are not full featured
application programs.
3 | Applets are the small programs
Applet starts execution with its
init().
=~ Sy
ae
multiple Supports multiple inheritance
implements
inherit
interface contains abstract method
contains only final variable
cannot have constructor
keyword is used to
n Stet overloading and method overriding.
Java Application
Applications run on standalone
systems.
Applications are full
programs.
featured
Applications are larger programs:
Application starts execution with
its main ()KHARAT ACADEMY
Applets are event driven Applications are control driven
9. Explain dynamic method dispatch in Java with suitable example.
Answer:
Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time.
1) When an overridden method is called through a superclass reference, Java
determines which version (superclass/subclasses) of that method is tobe
executed based upon the type of the object being referred to at the time the call
occurs. Thus, this determination is made at run time.
2) At run-time, it depends on the type of the object being referred to (not the type of
the reference variable) that determines which version of an overridden method
will be executed
3) A superclass reference variable can refer to a subclass object. This is also known
as upcasting. Java uses this fact to resolve calls to overridden methods at run
time. Therefore, if a superclass contains a method thatis overridden bya
subclass, then when different types of objects are referred to through a
superclass reference variable, different versions of the method are executed.
Here is an example that illustrates dynamic method dispatch:
// A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
class A {
void m1) {
System.out printin("Inside A's m1 method");
}
}
class B extends A {
// overriding m1Q)
void m1(){
System.out printin("Inside B's m1 method");
}
}
class. C extends A {
/foverriding m1()
void m10) {
System.out.printin("Inside C's m1 method");
}
}
// Driver class class Dispatch {
lava Programming Pages