GROUP-B
What do you mean by object oriented programming ? How it differs
from conventional procedural Programming ?[WBUT 2008, 2010]
Ans:
Object oriented programming(OOP) is 2 programming lan
organized around objects rather than “actions” and data rather than
s of
age model
cept of a data class makes it possible to define subclasse
data objects that share some or all of the main class characteristics.
this property of OOP forces a more thorough data
Called inheritance,
coding.
e Since a class defines only the data it needs to be concerned with,
when an instance of that class(an object) is run, the code will be able
her program data. The characteristics of data
N
to accidentally access ot
hiding provides greater system secur ty.
—_—_—»
The definition of a class is reuseable not onl 9
€ definition « ly by the program for
which it is initially created but also by other object-oriented programs %
»
(and, for this reason, can be more easily distributed for use in
networks).
Procedural programming
It is divided into smaller parts known as functions.
Here, importance is not given to
of actions to be done.
It follows top down approach.
In procedural programming, data can move freely from one function to
another.
Most functions uses global data for sharing that can be accessed freely from
‘one function to another.
It does not have the data hiding property, so data is less secure.
Overloading is not possible in procedural programming.
ut to functions as well as sequence
It is divided into parts called objects. :
Here, importance is given to the data rather than procedure or function.
because it works as a real world.
It follo ttom up approach.
In OOP, objects can move and communicate with each other through
In OOP, data can not move easily from function to function, it can be kept
public or private so we can control the access of data.
vides Data Hiding so provides more security.
In OOP, overloading is possible in the form of Function Overloading and
Operator Overloading.
a af OOP are : C++, JAVA, VB.NBT, C#.NET. . |
5
»’
»
%
%
%
Object oriented programming 9
9
®
9
9
8
q
‘
/ Explain OOPs properties of Java. “Java is a platform independent
language” — Explain with tne help of JVM.[WBUT 2009]
Ans.
The properties of OOP are given as follows:
« Encapsulation:
It is a process of binding or wrapping the data and the codes that
operates on the data into a single entity. This keeps the data safe from
outside interface and misuse. Cne way to think about encapsulation is as
‘a protective wrapper that prevents code and data from being arbitrarily
accessed by other code defined outside the wrapper. .
¢ Abstraction:
Abstraction is way of converting real world objects in terms of class. For
example creating a class Vehicle and injecting properties into it. E.g
public ciass Vehicle { :
public String colour;
public String model;
\
}.
Inheritance is t
nce is the is
saben 2€ property which allows a Child class to inheri
iene S from its Parent class. In Java this is achiever yi reat
= rae nly properties with access modifier public and moe
=£€ssed in child class. —
Public class Parent{ ,
Public String parentName;
Public int parentage;
eee String familyName;
Public class Child extends Parent{
public String childName;
Public int childAge;
Public void printMyName(){
System.out.printIn(“ My name is “+ chidName+” “ +familyName)
}
In above example the child has inherit its family name from the parent
class just by inheriting the class.
* Polymorphism:
Polymorphism gives us the ultimate flexibility in extensibility. The abiltiy
to define more than one function with the same name is called
Polymorphism. In java,c++ there are two type of polymorphism: compile
time polymorphism (overloading) and runtime polymorphism (overriding).
Programs written in Java are interpreted by Java itself, which is installed
a platform. The language is platform-independent because programs
written in it will work on any computer that has Java installed on it,
regardless of operating system. Java programs run in a “virtual machine"
“(sometimes called the Java Ruritime Environment [JR]. The "virtual
machine" acts like an operating system unto itself, so your program
ways acts the same, regardless of the computer platform it is using.
al
X y What are the types of inheritances in JAVA? Give example. What is
the use of super() keyword in JAVA? [WBUT 2009]
Ans.
There are various types of inheritances in JAVA:
° Single inheritance:
When a class extends another one ciass only then we call it a single
inheritance. The below flow di lass B extends only one_
“lags which is A. Here A is a parent class of B and B would be a child
Glass of A.
Class A
‘
{
public void methodA()
‘ System.out.println("Base class method");
1
1
'Class B extends A
i
public void methodB()
( Ff ny.
System.out.printin("Child class method");
} :
public static void main(String args[])
{
B obj = new BO);
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
¢ Multiple inheri ie aio
“Multiple Inheritance’ refers to the concept of one class extendin; (Or
inheritance we learnt earlier had the
inherits) more than one base class. The at it ear 2 £
concept of one base class or parent. The problem with “multiple inheritance’
is th: iil have to manage the dependency on two base_
classes.
Bl 6)
l
i
pH
Le] .
(0) Multiple inheritance
¢ Multilevel inheritance:
Multifevel inheritance refers to a mechanism in OO technology where one
éaninhent from a derived class, thereby making this derived class the base
Class for the new class. As you can see in below flow diagram C is subclass
‘or child class of B and B is a child class of A.
(d) Multilevel inheritance
« Hierarchial inheritance:
In_such kind of inheritance one class is inherited by many sub classes. [n
below example cla > and D inherits the sam
e cli
ime clas) of BC class A. A is parent class
4
ne eo © © 0-6 o-oo 9-5-9 IIIS IT ITS SE CE EYa
{¢) Hierarchical Inheritance
* Hybrdine
In simpjg eomheritance:
‘€ terms you
)
{e) Hybrid Inheritance
falf your method overrides one of its erclass's »ds, you can invoke the
overridden method through the use ofthe keywunl super: You conalor mee
super to reler to a hidden field (although hiding felis ve discourceed)
Consider this class, Superclass:
public class Superclass {
public void printMethod() {
System.out.printIn("Printed in Superclass.");
}
}
Here is a subclass, called Subclass, that overrides printMethod():
public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod(); ; .
System.out.println("Printed in Subclass’);
1
public static void main(String|} args) {
Subclass s = new Subclass();
s.printMethod();\ te What ia abstract class? Explain with, a short program to illustrate this.
IWHUT 2009)
Ana
AlLabstract elags is a clase that is declared abstract—it may or may not_
Include abstract methods, Abstract classes cannot be instantiated, but they
can be subclansed,
Wirst, you declare an abstract class, Gra, hicObject, to provide member
variables and methods that are wholly shared by all subclasses, such as the
Current position and the moveTo method. GraphicObject also declares
Rbstrac re thee eee OT ae draw or resize, that need to be
ract methods for methods, such as at ne
implemented _by all subc — but must be imp! lemented in different ways.
¢ GraphicObject class can look. something like this:
abstract class GraphicObject {
int x, y;
void moveTo(int newX, int new)) {
}
}
abstract void draw/();
abstract void resize();
}
Each nonabstract subclass of GraphicObject, such as Circle and Rectangle,
‘must provide implementations for the draw and resize methods:
class Circle extends GraphicObject {
void draw() {
a
void resize() {
}
} .
class Rectangle extends GraphicO!ject {
void draw() {
}
void resize() {
+ What is garbage collection? What is static variable? Give e
{[WBUT 2010]
Ans.
Xample of both
wvuwvveuvuwuwwe oo
c
we
’
— a oPca
— a a ee ae
=
ay
— ea
YAVA has a built in garbage collection facility. The heap is the area of
emory used for dynamic allocation. In most configurations the operating
system allocates the heap in advance to be managed by the JVM while the
program is running. This has a couple of important ramifications:
1 because global synchronization with the
* Object creation is faste: T
Operating system is not needed for every single object. An allocation
simply claims some portion of a memory array and moves the offset
pointer forward. The next ‘allocation starts at this offset and claims the
next portion of the c
e collector reclaims the
+ When an object is no longer us
it for future object allocation. This
underlying memory and reuses alloc:
means there is no explicit deletion ‘and no memory is given back to the
operating system. 7
Static variables are referenced by their classes. This fact makes them de
facto GC roots. Classes themselves can be > garbage-collected, which would
X remove all referenced static variables. This is of special importance when we
use application servers, OSGi containers or Class loaders in general.
6.”Objects are passed by reference in JAVA”- Explain with example. [WBUT
2011]
Ans.
Everything in Java is pass-by-value. There is no such thing as "pass-by-
Teference’ in Java. The key to understanding this is that something like
‘Dog myDog;
ee
is not a Dog; it's actually a pointer to a Dog.
7.What is the difference between ‘default and public’ modifier and ‘protected
and private’ access modifier?[WBUT 2011]
Ans.
Default access modifier means we do not explicitly declare an access
A variable or method declared without any access control modifier is
available to any other class in the same package. The fields in an interface
are implicitly public static final and the methods in an interface are by
default public
Private Access Modifier - private:
Methods, Variables and Constructors that are declared private can only be
accessed within the declared class itsel-~
accessed within th Errore
Private access modifier is the most restrictive access level. Class and
interfaces cannot be private. ee
interlacss oresVariables that are declared private can be accessed outside the Class ip |
public getter methods are present in the class.
Using the private modifier is the main way that an object encaj
PSulates itseip
and hide data from the outside world. :
Public Access Modifier - public:
A class, method, constructor, interface etc declared public can be acces,
from any other class. Therefore fields, methods, blocks declared inside
public class can be accessed from any class belonging to the Java Unj
sed
a
verse,
>
»
»
»
»
)
d
d
However if the public class we are trying to access is in a different Package, )
then the ublic class still need tc be imported. :
)
)
y
y
’
)
’
)
’
Because of class inheritance, all public methods and variables of a class are
inherited by its subclasses.
Protected Access Modifier - protected:
Variables, methods and constructors which are declared protected in a
Superclass can be accessed
ay the subclasses in other package or any
class within the package of the
protected members' class.
The protected access modifier car
Methods, fields can be declared Plotected, however m
interface cannot be declared protected.
ee ee ee Eee
ss and interfaces.
ethods and fields in a
Protected access gives the subclass a chance to use the helper method or
variable, while preventing a nonrelated class from trying to use it.
8.a) Write a program to convert given number of days into month and
days.[WBUT 2013]
Ans. |
class DayMonthDemo
{ ao '
public static void main(String argsj})
£
i
int num = Integer. parselnt(args|[0]
int days = num%30;
int month = num/30; .
System.out.printIn(num+" days = "~month+" Month
and "+days+" day
b) How are this and super used?[W3UT 2013]
Ans: 9.Exphain inheritance,
Within an instance method or a constructor. this is reference 10
current object — th i inane
can refer to any member of the current object from within an instance
Using this with a Field
The most common reason for usin} the this keyword is because a field is
structor arameter.
. shadowed by a method or con:
For example, the Point class was written like this
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
}
c) What is the main difference bet
platforms?[WBUT 20 13]
Ans.
Java platform is a software-only platform, which runs on top of other
hardware-based platforms like UNIX, NT ete.
( on eee AVA Comply aiid SVM”
ween JAVA platforms and other
Individual program is keeded
‘and run in JVM
JAVA compiler
javac fit
Translated by
The Java platform has 2 components:
‘VM is a software that can be ported onto
“Java Virtual Machine (JVM) =
yarious hardware platforms. Byte codes are the machine language of the
JVM
2
encapsulation concept. [WBUT 2013]
Ans
Refer to ques 2 of Group BF Constn
Dd Method
Dd b) Writ
. 14%
> Ans.
: » class |
\ {
d public
GROUP -C > {
os : int m
1. Write a program in JAVA to input a number and check whether it is > daub
prime or not.[WBUT 2008] > while
Ans. resul
import java.util.*; » num
class Prime » Syst
{
Public static void main(String args|}) » Sal
{ Ss
int n, i, res; » Sin
boolean flag=true; : »
Scanner scan= new Scanner(System.in); . |
System.out.printin("Please Enter a No.");
n=scan.nextint(); >
3
d
> Se
flay=false; >
break;
} >
} >
if(flag) .
System.out.printin(n +" is Prime Number"); >
else ’
System.out.printIn(n +" is not Prime Number’);
}
}
}
2.a) Describe the structure of
Ans.
3
>
typical Java program.[WBUT 2008] >
A Typical Java class would have the following. :
Package statement 3
import statements >
Class comments (Optional
Class Declaration { 3
Instance variable declarations >Constructor declaration
Method declarations }
out the sum of harmonic series =
b) Write a java program to find
term , for any value of n.[WBUT 2008]
1+ %4+1/3+....... Up to nth
Ans.
class HarmonicSeries
{
public static void main(String args|))
{
int num = Integer.parseInt(args(0});
double result = 0.0;
while(num > 0){
result = result + (double) 1 / num;
num--; }
System.out.printin(
“Output of Harmonic Series is "+result) }
3.a)Briefly discuss the features of JAVA language.[WBUT 2009)
Ans.
Simple :
jnore readable and eye catching.
. Java is Easy to write and
e set of features that makes it easy to learn
. Java has a concise, cohesiv:
and use. _¥
« Most of the concepts are drew fron C++ thus making Java learning.
Secure:
rogram cannot harm other system thus making it secure.
+ Java program cannot harm coe eating Int
re means of creating Internet applications.
« Java provides a secu)
to access web applications.
- Java provides secure way
Portable :
. Java programs can execute in any environment for which there is a
Java run-time system (JVM)
Jatform (Linux,Window,Mac)
» Java programs can be run on an)
. Java programs can be transferred over world wide web (e.g applets) -
°
Object-oriented :
. Java programming is object-oriented programming language.
Like C++ java provides most of the object oriented features.
Java is pure OOP. Language. (while C++ is semi object oriented)
* ahRobust :
+ Java encourages error-free programming by bein; Strictly typed and
performing run-time checks. SERENE Dy Rem sity typed and |
Multithreaded :
+ Java provides integrated support for multithreaded Programming.
b) Explain the each term of the fcilowing statement :
Public static void main ( String args | | )|WBUT 2008, 2009]
Ans.
The public keyword is an acce: specifier, which allows the programmer to
control the visibility of class members. When a class membe! ceded b
public, then that member can be accessed by code outside the class in
which it is declared.In this case, main( ) must be declared as public, since it
must be called by code outside of its class when the program is started,
The keyword static allows main( ) to be called without having to instantiate
a partic i
the Java interpreter before any objects are made.
we vava interpreter before any objects are made.
Che keyword void simply tells the compiler that main() does not return a
Value. As you will see, methods may also return values.
As stated, main() is thé method called when a Java application begins. Keep
in mind that Java is case-sensitive. Thus, Main is different from main. It is
important to understand that the Java compiler will compile classes that do
these classes. So, if you had typed Main instead of main, the compiler would
still compile your program. However, the Java interpreter would report an
error because it would be unable to find the main() method.
av information that you need to pass to a method Teese sa by variables
Specified within the set of parentheses that follow the name of the method.
These variables are called parametirs. If there are no arameters required
for a given method, you still need to include the empty parentheses. In
main( ), there is only one parameter, albeit a complicated one-
String args[ ] declares a parameter named args, which isa y
dostances of the class Sicing Objects of type String store chaacies ings
in th a ares nts presen?
ram is executes iCarguments present when the
program is executed. _ :
yy
dt
wi
c) Define different types of inheritance with ®xample.|WBUT 2009]
Ans.
This is,necessary since main() iScalled by
l
sia licn
wwe oo
wy we
wr
)Refer to ques 3 of Group B.
4.Explain the usage of ‘this’ and ‘super’ keywords in Java program.{WBUT
2009]
Ans.
1. this keyword can be used to refer current class instance variable.
2. this() can be us invoke current class constructor.
3. this ke} ‘ed to invoke current class method (implicitly)
4. this can be passed as an argument in the method call.
‘t in the constructor call.
" this can be passed as argumen’
d to return the current class instance.
5.
6. this keyword can also be use:
Refer to ques b of group b.
5. a) What are the features of java language ? Describe.[WBUT 2010]
Ans.
Simple :
+ Java is Easy to write and more readable and eye catching.
» Java has a concise, cohesive set of features that makes it easy to learn
and use.
« Most of the concepts are drew from C++ thus making Java Jearning
simpler.
aa
Secure :
+ Java program. cannot harm other system thus making it secure.
. Java provides a secure means of creating Internet applications.
Java provides secure way to access web applications.
Portable :
« Java programs can execute in any environment for which there is a
avarun-time system.[J My
. Java programs can be run on any platform (Linux, Window,Mac)
Java programs can be transferred over world wide web (e.g applets)
Object-oriented :
mming is object-oriented programming language.
des most of the object oriented features.
hile C++ is semi object oriented)
» Java progral
Like C++ java provi
Java is pure OOP. Language. (wRobust :
« Java encourages error-free programming by being ‘i
= ~ ig Stricth
Performing run-time checks. ‘ped and
Multithreaded :
+ Java provides integrated support for multithreaded programmin;
>
b) What do you mean by command line argument ?[WBUT 2010]
Ans.
Public static void main(String args[])
String args[ ] declares a parameter named args, which is an array of
instances of the class String. Objects of type String store character strings.
In this case, args receives any command-line arguments present when the
program is executed.
¢) Explain operators with reference to java. [WBUT 2010]
Ans.
Java provides a rich set of operators to manipulate variables. We can divide
all the Java operators into the following groups:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
« Misc Operators
The Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way
that théy are used in algebra. The following table lists the arithmetic
operators:
Assume integer variable A holds 10 and variable B holds 20, then:
Show Examples
Operator Description Example
my)
a
SECECEETEL SECEEE ST puss sdss sesvssrsss
é+ Addition - add ‘: i
's values on either side of ill gi
ea le of the ae B will give
Subtraction - Subtracts right hand operand from A - B will give
left hand operand -10
* Multiplication - Multiplies values on either side of A * B will give
200
the operator
/ Division - Divides left hand operand by right hand _ B / A will give
operand 2
Modulus - Divides left hand operand by right hand B % A will give
%
operand and returns remainder 0
++ Increment - Increases the value of operand by 1 Bt+ gives 21
B-- gives 19
Decrement - Decreases the value of operand by 1
The Relational Operators:
There are following relational operators supported by Java language
Assume variable A holds 10 and variable B holds 20, then:
Show Examples
Operator Description Example
(A == B) is not
Checks if the values of two operands are equal or
true.
a not, if yes then condition becomes true.
Checks if the values of two operands are equal or
not, if values are not equal then condition becomes (A != B) is true.
true. ie
Checks if the value of left oper:nd is greater than ai
>
the value of right operand, if yes then condition : ) is not
rue.
becomes true.
Checks if the value of left operand is less than the
alue of right operand, if yes then condition (A < B)is true
becomes true.
I9es Checks if the value of left operand is greater than
or equal to the value of right operand, if yes then (A >= B) is not
condition becomes true. ee
a Checks if the value of left operand is less than or
equal to the value of right operand, if yes then (A <= Bhis
condition becomes true. ‘ue.
The Bitwise Operators:
Java defines several bitwi i
5 wise operators, which can be i i
types, long, int, short, char, ond byte. Pence
Bitwise operator works on bit i i i
eee s and performs bit-by-bit operation. Assume i
a = 60; and b = 13; now in binary format they will be as follows: sa
a=0011 1100
b = 0000 1101
ab = 0000 1100
a/b = 0011 1101
ab = 0011 0001
~a = 11000011
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13 then:
Show Examples
Ads by OffersWizardAd Options
Operator Description Example
i oO s a bit to the result if it (A&B) will
& Binary AND Operator copies a bit to the r Pit ive 12 which
exists IN both operands. +s 0000 1100
Binary OR Operator copies & bit if it exists in either ‘a1 B) will
operand. give 61 whicha a ae
~~
Tee
oe [6 SlhUh SY US UYU
weve erelwrmlUrlClUcLTTrTmhUCUOOCUL
<<
>>
is 0011 1101
Binary XOR Operator copies the bit if it is set in (A ae) =
one operand but not both. give 49 which
is 0011 0001
(~A) will give -
61 which is
1100 0011 in
2's
complement
form due to a
signed binary
number.
Binary Ones Complement Operator is unary and
has the effect of ‘flipping’ bits-
Left Shift Operator. The left operands value A<< 2 will give
Binary
is moved left by the number of bits specified by the 240 which is
right operand. 1111 0000
Binary Right Shift Operator. The left operands A >> 2 will give
value is moved right by the number of bits specified 15 which is
1111
by the right operand.
r. The left operands value oo alll
beret is saat te give 15 which
P is 0000 1111
Shift right zero fill operato:
is moved right by the num!
the right operand and shifted val
with zeros.
The Logical Operators:
The following table lists the logical operat
Assume Boolean vari
ors:
ables A holds true and variable B holds false, then:
Show Examples
Description Example
Operator
88s
Called Logical AND operator. I! both the operands (A && B) is
are non-zero, then the condition becomes true. false.
(A || B) is
Called Logical OR Operator. If any of the two
true.
operands are non-zero, then the condition becomestrue.
Called Logical NOT Operz.tor. Use to reverses the
\ :
logical state of its operand. If a condition is true ‘ a B) is
then Logical NOT operator will make false. .
The Assignment Operators:
There are following assignment operators supported by Java language:
Show Examples
Operator Description Example
Simpl : i i f C=A+Bwill
= ae 7 assignment aioe Assigns a lues from assign value of
right side operands to left side operan A+BintoCc
Add AND assignment operator, It adds right C+ Ais
+=
operand to the left operand and assign the result to equivalent to C
left operand =C+A
Subtract AND assignmen: operator, It subtracts C-=Ais
right operand from the left operand and assign the equivalent to C
result to left operand =C-A
Multiply AND assignment operator, It multiplies _C *= A is
right operand with the left operand and assign the equivalent to C
result to left operand
=CfA
Divide AND assignment operator, It divides left C/=Ais
/= operand with the right operand and assign the equivalent to C
result to left operand =C/A
Modulus AND assignment operator, It takes C%= Ais
%= modulus using two operands and assign the result equivalent to C
to left operand =C%HA
C <<= 2is
<<= Left shift AND assignment operator same as C=C
<<2
Doe Right shift AND assignment operator C >>= 2is
same as C=C
,
g
a a IEE.
iy
pasEEA ESS BLOSOOOCE BEEBE AEE ELIE TEI
a ae
>>2
_ = C &= 2is
Bitwise AND assignment operator same as C = C
&2
= :
. bitwise exclusive O) ssi cece
Si ment operato!
e OR and assign: pererer asC=CA2
7 ken). ¢ ‘ i Gina
I bitwise inclusive OR and assignment operator Bra . C i
Misc Operators
There are few other operators supported by Java Language.
Conditional Operator (? : ):
Conditional operator is also known as the ternary operator. This operator
to evaluate Boolean expressions. The
consists of three operands and is used
goal of the operator is to decide which value should be assigned to the
variable. The operator is written as:
variable x = (expression) ? value if true : value if false
cance of final keyword used as a modifier before a
6.a) What is the signifi
d for a method or a class?[WBUT 2011]
variable? How it is use
Ans.
r reserved word in java and can be applied to member
class and local variables in Java. Once you make a
ange that reference and compiler
rif you try to re-initialized final
Final is a keyword o}
variables, methods,
reference final you are not allowed to ch
will verify this and raise compilation erre
variables in java.
Re
able either member variable or local variable (declared inside
Any vari
alled final variable. Final
method or block) modified by final keyword is c
Variables are often declare with static keyword in java and treated as
constant. Here is an example of final variable in Java
public static final String LOAN = "loan";
LOAN = new String("loan") //invalid compilation error
Final variables are by default read-only.b) Explain about this keyword. Explain with a suitable example.[WBUT
2011)
Ans.
class ThisDemo1
{
int a= 0;
int b = 0;
ThisDemol(int x, inty)
{
this.a = x;
this.b = y;
public static void main(String [] args)
eee td = new ThisDemol (10,12);
ThisDemol tdl = new ThisDemo1(100,23);
System.out.println(td.a); // prints 10
System.out.printIn(td.B)/>; // prints 12
System.out.printin(td1.a);// prints 100
System.out.printIn(td1.B)/>;// prints 23
}
c) What is the difference between private and static modifiers in a
class?[(WBUT 2011]
Ans.
Static modifier is used to create vzriables and methods that will exist
independently of any instance created for the class. Static members exists
before any instance of the class is created.
Also there will be only one copy of the static member.
—— re only one copy ofthe static member.
To call a static method displayRuns() of the class named Cricket we write
Cricket.displayRuns();
Class name is used to invoke the static method as static member does not
depend on any instance of the class. ae
Private static method means you can not invoke the method from outside
the class as the method is private to the class,
eee
7.a) What is a wrapper class? Illustrate through example. Is string a :
wrapper class? [WBUT 2011]
oo oo woo oo ee 9 OO SCC COCO CCC EE?
oS eee o-o-e-o oowza@wwvewew@et © ¢OEGDCSGHFE EES EE
ee ee
— oo eel wll Tre rhe ULC hlULhCOCUmh]h
4
Ans.
Wrapper
clas: sed onvert any data type into an ct. 1 7
to conve: Pp object. A wrappe:
class wray
Wheceabs Lencloses arol ives i
herever, the dave i ar und a data type and gives it an object appearance.
‘Wrapper Classes ing vps is required as an object, this object can be used,
le i i ¢
ata type-It oar methods to unwrap the object and give back the
cata ty an be compared with a chocolate. The manufacturer wraps the
chocolate wi i
thes a with some foil or paper to prevent from pollution. The user takes
: late, removes an rows the wrapper and éats it.
intk= 100;
Integer itl = new Integer(k);
Thi :
ae data type k is converted into an object, itl using Integer class. The
okiccea | can be used in Java programming wherever k is required an
The following code can be i
: used to unwrap (getting back int from Integer
object) the object it1. au 7
int m = it1.intValue();
System.out.println(m*m); // prints 10000
intValue() is a method of Integer class that returns an int data type;
Wrapper classes are used to "wrap" the primitives data types into objects so
that they can be included in the activities which are reseved for the objects.
String class wraps the string literals to an object.
a (primitive) wrapper class in Java is one of those eight classes that wrap a
(=one) primitive value. String wraps a c.1ar|] so according to this it is nota
(primitive) wrapper class.
Oe ee ee
t is abstract base class? What is concrete derive classes?Can there
b) Wha
ethods in it?[WBUT 2011]
be an abstract class with no abstract m'
Ans.
ss that is declared abstract—it may or may not
An abstract class is a cla’
Ses cannot be instantiated, but they
jnclude abstract methods. Abstract clas:
can be subclassed.
an
thod is a method that is declared without an implementation
An abstract me
‘followed by a semicolon), like this:
(without braces, and
abstract void moveTo(double deltaX, double deltaY);
“If a class includes abstract methods, then the class itself must be declareg
abstract, as i
Public abstract class GraphicObject (
// declare fields
// declare nonabstract methods
abstract void draw();
} :
When an abstract class is subclassed, the subclass usually provides
implementations for all of the abstract methods in its parent class. Howeve,
iit does not, then the subclass must also be declaw} abstract. 2
A concrete derived class has no virtual functions, It Provides functions for
its inherited pure virtual functions. This is to say, it Provides all missing
functionalities of the abstract class.
The derived class that implements the missing functionality of an abstract
class is the concrete derived class.
SASS IS the concrete derived class
Declaring a class abstract only means that you don't allow it to be
instantiated on its own.
Uistantiated on its own.
Declaring a method abstract means that subclasses have to Provide an
implementation for that method.
ee omen
The two are separate concepts, bui obviously you can't have an abstract
method in a non-abstract class. You can even have abstract classes with
final methods but never the other way around.
ess Sut never the other way around
c) Does JAVA support static or dynamic binding? Explain.[WBUT 201 y
Ans.
1) Static binding in Java occurs during Compile time while D: namic binding
occurs during Runti
2) private, final and static methods and variables uses Static binding and
bonded by compiler while virtual rethods are bonded during runtime based
upon runtime object.
etme object.
3) Static binding uses Type(Class in Java) information for binding while
ee oincing uses Type mation for binding while
Dynamic binding uses Object to resolve bindin
4) Overloaded methods are bonded using static binding while overridden
methods are bonded using dynamic binding at runtime. Here is an example
which will help you to understand both static and dynamic binding in Java,This is directly related to execution of code. If you have more than one
method of same name (method overriding) or two variable of same name in
some class hierarchy it gets tricky to find out which one is used during
runtime as a result of there reference in code. This problem is resolved using
static and dynamic binding in Java. For those who are not familiar with
link which method or variable to be
binding operation, its process used to
called as result of there reference in code. Most of the references is resolved
during compile time but some references which depends upon Object an
ed during runtime when actual object is
polymorphism in Java is resolve
available.
ghee biol
that demonstrates a three level inheritance.
8.a) Write a program in JAVA
Is for the same. [WBUT 2011]
Use the various access control
Ans.
class A
{
void disp()
{
System.out.printIn("Hello m Dikaoo kya’);
}
class B extends A
void moll()
system.out-printin(‘nye nye item chiye kya);
}
}
class Multilnheri extends B
{
void china()
{
system.out println("sara ka sara mall kharab hai’);
}
public static void main(String args(])
i!
Multilnheri ab=new Multilnheri();
ab.disp();
ab.moll();
ab.china();
,
flerence between object oriented programming and
b) What is the di
amming paradigm? [WBUT 2011]
procedural progtAns.
Refer to group b.
©) What is the role of JVM? How it is different from JRE? (WBUT 2011)
Ans.
A Java Virtual Machine (JVM) is a set of computer software programs and
‘data structures that use a virtual machine model for the execution of oth
computer programs and scripts. The model used by aJVM accepts a forms sp
computer inte iate language commonly referred to as Java bytecode
This language conceptually represents the instruction set of a stack-
oriented, capability architecture. Java Virtual Machines operate on Java
code, which is normally (but not necessarily) generated from Java
source code; a JVM can also be used to implement programming languages
JVMs are available for many hardware and software platforms. The use of
the Same bytecode for all platfor-as allows Java to be described as compile
once, run anywhere", as opposed to “write once, compile anywhere", which
describes cross-platform compiled Tanguages. The JVM also enables such
features as Automated Exception Handling that provides 'root-cause'
debugging information for every
lock and catch clause(s) execute
before the statements followin; the try statement. It always executes,
pul ee r not an exception was thrown or caught.
regardless of whether ©
tatements. If nner try statement does not
more U
can nest one OF
you “Jause, the enclosing try statement’s catch clause is entered,
ave a catchb) Explain inheritance, encapsu!ation concept. [WBUT 2012} “te
rw
Ass &
Refer to group b.
c) What is the superkey in JAVA? What is wrapper class? [WBUT 2012)
Ans.
9. a) What are adapter classes? [WBUT 2013]
Ans.
An adapter class provides the default implementation of all methods in an
event listener interface. Adapter classes are very useful when you want to
process only few of the events that are handled by a particular event listener
interface. You can define a new class by extending one of the adapter classes
and implement only those events relevant to you. Hs
eer Event relevant to you
b) What is multithreading? What are the two different ways to create
multithreaded program? [WBUT 2013]
Ans.
Java is amultithreaded programming language which means we can develop
multithreaded Program using Java. A multithreaded program contains two
or more parts that can run concurrently and each part can handle different
task at the same time making optimal use of the available resources
specially when your computer has multiple CPUs.
By definition multitasking is when multiple processes share common
processing resources such as a CPU. Multithreading extends the idea of
multitasking into applications where you can subdivide specific Operations
ithi: i . Each of the threads can
ot only among different
an application.
Multithreading enables vou to write ina way where multiple activities can
roceed concurrently in the same program, oo te
c) Discuss each part of the statement: System.out printin()
run in parallel. The OS divides Processing time n
applications, but also among each thread within
); (WBUT 2013]
Ans.
Refer to group b f
Refer to group c
»
p
S
Ssn
* System i ates
> “on vs = built class present in java.lang package. This class has
. re- i
na arse ess
* out is a static final field (ie, variable)in System class which is of the
type PrintStream (a built-in class, contains methods to print the
different data values). static fields and methods must be accessed by
using the class name, so ( System.out ).
: out here denotes the reference variable of the type PrintStream class.
Banta is a public method in PrintStream class to print the data
x ues. Hence to access a method in PrintStream class, we use
ut.printin() (as non static methods and fields can only be accessed by
Using the refrence varialble)
10. :
0.a) How does JAVA implement platform independence?[WBUT 2013]
Ans.
fhe compiled code is the exact set of instructions the CPU requires to
ae 'e" the program. In Java, the compiled code is an exact set of
ctions for a "virtual CPU" which is required to work the same on every
physical machine.
So, in a sense, the designers of the Java language decided that the language
and the compiled code was going to be platform independent, but since the
code eventually has to run on a physical platform, they opted to put all the
platform dependent code in the JVM.
ntrast to your Turbo C example. With
latform dependent code, and there is no
This requirement for a JVM is in co
‘bo C program can be
Turbo C, the compiler will produce p
need for a JVM work-alike because the compiled Tur!
executed by the CPU directly.
With Java, the CPU executes the JVM, which is platform dependent. This
running JVM then executes the Java bytecode which is platform
independent, provided that you have a JVM availble for it to execute upon.
You might say that writi you don't program for the code to be
cuted on the
executed on the physical
The only way that all this Ja’
‘ing Java code,
T machine, you write the code to be exer
va bytecode works on all Java virtual machines
is that a rather strict standard has been written for how Java virtual
machines work. This means that no matter what physical platform you are
using, the part where the Java bytecode interfaces with the JVM is
guaranteed to work only one way. Since all the JVMs work exactly the same.
ily the same everywhere without recompiling. If :
the same code works exact!
ass the tests to make sure it's the same, you're not allowed to call
you can't pi ;
four virtual machine a “Java virtual machine". Lb) What is the differe: i
nce between
member?[WBUT 2013] ee eee
Ans.
When you declare a member variable such as aFloat in MyClass:
class MyClass {
float aFloat;
}
you declare an instance. variable. Every time you create an in:
class, the runtime “system creates one COPY of each the class's instance
variables for the instance.
stance of a
bles (which you declare
ss variables once
e
are in constrast to class varial
tem allocates cla:
of that class.
Instance variables
difier). The runti
stances create!
me it encounters the
using the static mo jhe runtime system allocates Co ass. The —
syst class variables the first ti
ces share the same copy of the class's class variables. You
ugh an instance or through the class itself.
lass
class. All instan
can access class variables thro
an have instance methods and cl:
on the current ‘object's instance
‘ss variables. Class methods, on the
Tiables declare’ within the class
s them through the object). Also,
uu don't need an instance to
Your classes ©
thods operace
ccess to the cla’
The instance va
t and acces:
n the class, yO
Methods are similar:
methods. Instance me
variables but also have a
other hand cannot access
(anless they create 4 new objec’
class methods can be invoked 0}
ed within a class is
zall a class methoc-
By default, unless ot! d, a member declar ;
an instance member. T! S' elow has one instance variable--an
x--and two instance q setX--that let other
ue of x:
integer named
objects set a
e! erNamedX {
class Anint
int x:
iblic int x! {
return X;
} ablic void setX! int newX) {
= newX;
Cite
get
ociated Ww!
medX objectfrom the
Class
» You
17 ntegerNamedx ches New copy of x that is associated with the new
c) What ig
Polymorph: f :
Polymorphism Wweun Fein between compile time and run time
Ans.
Refer to group b.
d) Write a
Pro; i
them.[WBUT 2013] to input three number and print the highest among
Ans.
import java.util. Scanner;
ree LargestOfThreeNumbers
ee Static void main(String args[})
int x, y, z;
System.out.printin("Enter three integers ");
Scanner in = new Scanner(System.in);
in.nextint();
y = in.nextInt();
z = in.nextInt();
if (x > y @@ x >z)
System.out.println("First number is largest.");
else if (y > x && y>z)
System.out.printIn("Second number is largest.");
else if (z> x &&z>y)
System.out.printin("Third number is largest.");
else
System.out.printIn("Entered numbers are not distinct.");
}
i
I
11. Write short notes on:
a) Abstract class.
b) Exception handling.
c) Interface
d) JVM