Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Systools Demo: Solved By: - Rajesh & Ashish

Download as pdf or txt
Download as pdf or txt
You are on page 1of 77

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

1. Why JAVA known as platform-neutral language? How JAVA is more secured than
other language.

A "platform" usually refers to an Operating System (OS), such as Windows or


Mac. "Platform-independent" means that the same Java code can run on different
platforms. This is achieved by using the Java Virtual Machine (VM) - a layer between
the Java code and the OS. The VM takes a piece of Java code, translates it into the

O
native code the OS can understand and feeds the code to the OS. Then it interprets
the result or further request from the OS and passes it back to the Java
component. Therefore, Java code is said to be "interpreted". Because of the extra
steps involved, Java code runs slower than the native code of the OS.

EM
Plateform neutral or platform independence, means that programs written in the Java
language must run similarly on any supported hardware/operating-system platform.
One should be able to write a program once, compile it once, and run it anywhere.
Java was designed to not only be cross-platform in source form like C, but also in
compiled binary form. Since this is frankly impossible across processor architectures
Java is compiled to an intermediate form called byte-code. A Java program never really
executes natively on the host machine. Rather a special native program called the

D
Java interpreter reads the byte code and executes the corresponding native machine
instructions. Thus to port Java programs to a new platform all that is needed is to port
the interpreter and some of the library routines. Even the compiler is written in Java.
The byte codes are precisely defined, and remain the same on all platforms.

Java is more secure than other programming languages because of it's use of a virtual
LS
machine on the host computer. Essentially, when you run a Java program on your
computer, it runs on the JVM (Java Virtual Machine.) This JVM translates the code
from the java file you downloaded into native machine code specific for your computer.
Therefore, the JVM can control all aspects of how the code is executed, and is able to
block any security breaches before they even reach your computer. This is much more
secure than running a program directly on your computer, although there is a slight
performance drop due to the fact that the Virtual Machine must run along with the
O

java program.

2. What is multithreading? How does it improve the performance of java ?


O

Ans from book:- In a multithreading environment, a thread is the smallest unit of


dispatchable code. This means that a single program can perform two or more tasks
simultaneously. For instance a text editor can format text at the same time that it is
printing.
ST

The benefit of Java's multithreading is that the main loop/polling mechanism is


eliminated. One thread can pause without stopping other parts of the program. For
example, the idle time created when a thread reads data from a network or waits for
user input can be utilized elsewhere. When a thread blocks in a Java program, only
the single thread that is blocked pauses. All other threads continue to run.
SY

Ans From Web:- Multithreading enables we to write programs that contain two or
more separate paths of execution that can execute concurrently. Each path of

1 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

vi. Java does not have a preprocessor, and as such, does not have macros like # define.
vii. Constants can be created by using the final modifiers when declaring class and
instances variables.
viii. In Java, all methods are tied to classes. Java does not support stand-alone
methods.
ix. Java does not include the const keyword as present in C or the ability to pass by
const reference explicitly.

O
x. In Java strings are implemented as objects and not as an array of null-terminated
characters.
xi. Java has some additional primitive data types like byte and Boolean. Data types in
Java have a fixed size regardless of the operating system used.

EM
xii. In Java, arrays are real objects because you can allocate memory using the new
operator In Java, arrays are real objects because you can allocate memory using the
new operator

4. Explain briefly features of Java language.


1.Simple 2. Object-oriented 3. Statically typed
4. Compiled 5. Multitreaded 6. Garbage Collected

D
7. Robust 8. Secure 9. Extensible
10. Well understood

 Simple. Java's developers deliberately left out many of the unnecessary features of
other high-level programming languages. For example, Java does not support pointer
math, implicit type casting, structures or unions, operator overloading, templates,
LS
header files, or multiple inheritance.
 Object-oriented. Just like C++, Java uses classes to organize code into logical
modules. At runtime, a program creates objects from the classes. Java classes can
inherit from other classes, but multiple inheritance, wherein a class inherits methods
and fields from more than one class, is not allowed.
 Statically typed. All objects used in a program must be declared before they are used.
This enables the Java compiler to locate and report type conflicts.
O

 Compiled. Before you can run a program written in the Java language, the program
must be compiled by the Java compiler. The compilation results in a "byte-code" file
that, while similar to a machine-code file, can be executed under any operating system
that has a Java interpreter. This interpreter reads in the byte-code file and translates
O

the byte-code commands into machine-language commands that can be directly


executed by the machine that's running the Java program. You could say, then, that
Java is both a compiled and interpreted language.
 Multi-threaded. Java programs can contain multiple threads of execution, which
ST

enables programs to handle several tasks concurrently. For example, a multi-threaded


program can render an image on the screen in one thread while continuing to accept
keyboard input from the user in the main thread. All applications have at least one
thread, which represents the program's main path of execution.
 Garbage collected. Java programs do their own garbage collection, which means that
programs are not required to delete objects that they allocate in memory. This relieves
programmers of virtually all memory-management problems.
SY

 Robust. Because the Java interpreter checks all system access performed within a
program, Java programs cannot crash the system. Instead, when a serious error is

3 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

 In POP, adding of data and function is difficult and in OOP it is easy.

In POP, there is no access specifier and in OOP there are public, private and protected
specifier.

O
 In POP, operator cannot be overloaded and in OOP operator can be overloaded.

EM
6. What are the advantages of object oriented programing.
 Advantages of OOP:
 Reusability: Elimination of redundant code and use of existing classes through
inheritance. Thus provides economy of expression.
 Modularity: Programs can be the built from standard working modules.
 Security: Principle of information hiding helps programmer to build secure programs.
 Easy mapping: Object in the problem domain can be directly mapped to the objects in
the program.

D
 Scalability: Can be easily upgraded from small programs to large programs. Object-
oriented systems are also resilient to change and evolve over time in a better way.
 Easy management: Easy management of software complexity.
LS
7. How are data and method organized in an object oriented program ? Illustrate the
same for car object.

In an object-oriented program, a set of variables and functions used to describe an


object constitutes a "class".
A class defines the structure and behavior (data and method) that will be shared by a
set of objects. Each object of a given class contains the structure and behavior defined
O

by the class, as if it were stamped out of a mould in the shape of a class. A class is a
logical construct. An object has physical reality. When you create a class, you will
specify the code and data that will constitute that class. Collectively, these elements
are called the members of the class. Specifically, the data defined by the class are
O

referred to as member variables or instance variables. The code that operates on that
data is referred to as member methods or just methods, which define the use of the
member variables.
ST

8. Describe inheritance as applied to OOP.


Inheritance is one of the OOPS concepts(the OOPS concepts are Abstraction,
Encapsulation, Polymorphism and Inheritance). Java is purely a OOP language.
Inheritance means a class of objects can inherit properties from another class of
objects. A class that inherits the attributes from another class is called subclass or
child class or derived class. The class from which the attributes are derived is called
SY

base class or super class or parent class. Derived class can modify the some or all
attributes derived from the base class. Inheritance enables easy maintenance and
reusability of code which saves time and efforts.

5 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

modifiers define varying levels of access between class members and other objects.
Access modifiers are declared immediately before the type of a member variable or the
return type of a method. There are four access modifiers
 The default access modifier
 Public
 Protected
 Private

O
The default access modifier specifies that only classes in the same file or package have
access to a class’s variables and methods. There is no actual keyword for declaring the
default access modifier; it is applied by default in the absence of any other modifier.

EM
For example, in our MotorMain program all the variables and methods in the
MotorCycle class had default access because no access modifiers were specified. The
class MotorMain could however see and use all these variables and methods because
the two classes are part of the same file (and hence the same default package).

The public access modifier specifies that class variables and methods are accessible to
anyone, both inside and outside the class. This means that public class members have
global visibility and can be accessed by any other object. For example: if you declared

D
the variable named x as public int x = 20; then the value of x will be visible to all the
other classes of the same program.
public int count;
public Boolean isActive;

The protected access modifier specifies that class members are accessible only to
LS
methods in that class and subclasses (don’t worry we deal with subclasses later) of
that class. This is same, as Public but it will give more protection than the public. If
Protected is used then all the methods and attributes of the base class will be
available to all its derived classes
Protected int count;
Protected Boolean isActive;
O

The private access modifier is the most restrictive; it specifies that class members are
accessible only by the class in which they are defined. this means that no other class
has access to private class members. For example: private int y = 100; means the
value of y will be visible only to the class it is defined. If you try to access the variable
O

in other classes then the compiler will return an error.

10.What is inheritance? Show how subclass can invoke constructor of super class. With
example
ST

Definitions:
A class that is derived from another class is called a subclass (also a derived class,
extended class, or child class). The class from which the subclass is derived is called a
superclass (also a base class or a parent class).

Excepting Object, which has no superclass, every class has one and only one direct
SY

superclass (single inheritance). In the absence of any other explicit superclass, every
class is implicitly a subclass of Object.

7 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

Subclass which invokes the superclass constructor

public class Subaru extends Car{


int wheels;

public Subaru(){

O
super(4,"Subaru Impreza");
wheels=4;
}
}

EM
Here the constructor of superclass is invoked by the method call super(4,"Subaru
Impreza") and you can call the default constructor by placing your call super().By
following the way you can invoke the superclass constructor which can be helpful in
many tasks in your application.

11.Explain continue and break statements in Java with an example

D
In certain situations, it may be necessary for the flow of control to exit a loop
statement and start the next iteration of the loop statement. An example of such a
situation is a password verification program where the user is given three chances to
enter the correct password.
LS
If the user enters an incorrect password, the counter variable in the program is
incremented and the control is returned to the start of the loop statement. This saves
time because the remaining statements in the loop will not be executed. For this
purpose, Java provides the continue statement.
The continue statement stops the current iteration of a loop and immediately starts
the next iteration of the same loop. When the current iteration of a loop stops, the
statements after the continue statement in the loop are not executed.
O

The continue statement is written as continue;.

You can use the continue statement in the while, do-while, and for statements but not
O

in the switch statement. Use of continue statements is illustrated in the following


program.

//The program displays all even numbers between 1 and 20.


ST

Class EvenNum20
{
public static void main(String args[])
{
int j, k;
for(j=1, k=0; j<=20; j++)
{
SY

k=j%2;
If(k!=0)

9 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

Type Casting refers to changing an entity of one datatype into another. This is
important for the type conversion in developing any application. If we will store a int
value into a byte variable directly, this will be illegal operation. For storing your
calculated int value in a byte variable we ll have to change the type of resultant data
which has to be stored.

Type casting means treating a variable of one type as though it is another type.

O
When up casting primitives as shown below from left to right, automatic conversion
occurs. But if you go from right to left, down casting or explicit casting is required.
Casting in Java is safer than in C or other languages that allow arbitrary casting. Java
only lets casts occur when they make sense, such as a cast between a float and an int.

EM
However we can’t cast between an int and a String (is an object in Java).
byte -> short -> int -> long -> float -> double
int i = 5;
long j = i; //Right. Up casting or implicit casting
byte b1 = i; //Wrong. Compile time error “Type Mismatch”.
byte b2 = (byte) i ; //Right. Down casting or explicit casting is required.

Other example:

D
Long a=99L
Int b=a; //Wrong, needs a cast
Int b=(int) a //OK

13. Explain the Bit-wise operators available in JAVA with an example to


LS
each.
Bit manipulation operations, including logical and shift operations, perform low-level
operation directly on the binary representations used in integers. These operations are
not often used in enterprise-type systems but might be critical in graphical, scientific,
or control systems. The ability to operate directly on binary might save large amounts
of memory, might enable certain computations to be performed very efficiently, and
can greatly simplify operations on collections of bits, such as data read from or written
O

to parallel I/O ports.

Java defines several bitwise operators which can be applied to the integer types, long,
int, short, char, and byte. These operators act upon the individual bits of their
O

operands.
They are summarized in the following table:
OPERATOR RESULT
~ Bitwise unary NOT or Bitwise complement
ST

& Bitwise AND


| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
SY

The ~ Operator (NOT)

11 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

System.out.println("Result : " + Integer.toBinaryString(result));


}
}

/*
The output of this example will be:

O
Operand1 : 1101
Operand2 : 1100
Result : 1100
*/

EM
The | Bitwise inclusive or Operator

A bitwise OR takes two bit patterns of equal length, and produces another one of the
same length by matching up corresponding bits (the first of each; the second of each;
and so on) and performing the logical inclusive OR operation on each pair of
corresponding bits. In each pair, the result is 1 if the first bit is 1 OR the second bit is
1 OR both bits are 1, and otherwise the result is 0. For example:

D
0101 (decimal 5)
OR 0011 (decimal 3)
= 0111 (decimal 7)
LS
The ^ Bitwise exclusive or

A bitwise exclusive or takes two bit patterns of equal length and performs the logical
XOR operation on each pair of corresponding bits. The result in each position is 1 if
the two bits are different, and 0 if they are the same. For example:

0101
O

XOR 0011
= 0110

Bit Shifts
O

The bit shifts are sometimes considered bitwise operations, since they operate on the
binary representation of an integer instead of its numerical value; however, the bit
shifts do not operate on pairs of corresponding bits, and therefore cannot properly be
ST

called bit-wise operations. In this operation, the digits are moved, or shifted, to the left
or right. Registers in a computer processor have a fixed number of available bits for
storing numerals, so some bits will be "shifted out" of the register at one end, while the
same number of bits are "shifted in" from the other end; the differences between bit
shift operators lie in how they compute the values of those shifted-in bits.

The Left-Shift Operator<<


SY

The operator << performs a left shift. The result of this shift is that the first operand is
multiplied by two raised to the number specified by the second operand ; for example:

13 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

O
EM
D
On the left we have a class called Tree. This class defines a type of Java Object -- a
Tree -- that will serve as the blueprint from which all Tree Objects will be created. The
class itself is not a Tree; it is merely a description of what a Tree is, or what all Trees
have in common. In this example, our Tree class indicates that all Trees have a
property called 'height'.
LS
On the right, we have two actual Tree Objects. These are Trees, and they were created
based on the blueprint provided by the Tree class. These Objects are said to be
instances of the Tree class, and the process of creating them is called instantiation.
Thus, we can say that by instantiating the Tree class twice, we have created two
instances of the Tree class, two Objects based on the Tree class, or just two Trees.
Notice that in creating these Objects we have assigned a value to their height property.
O

The first Tree is 2 meters high and the second is 5 meters high. Although the values of
these properties differ, this does not change the fact that both objects are Trees. They
are simply Trees with different heights.
O

Classes don't only define properties of Objects; they also define operations that may be
performed by those Objects. Such operations are called methods in object-oriented
languages like Java
ST

15.What is function overloading? What are the two rules apply to overloaded methods?
Illustrate the same with example.

Function overloading is the process of using the same name for two or more functions in
the same class. Each time the same function name is used it must be used with different
types of parameters, sequence of parameters or number of parameters. The type of
parameter, sequence of parameter or number of parameter is called the function
SY

signature. When the name of the function is same then the compiler identifies the
function based on the parameters.

15 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

Output

The value is 50

The value is 4200

O
16.What is a constructor? What are its special properties? What are the different types of
constructors? Explain with an example.

EM
A constructor is a special type of method that is invoked when an object of a class is
created. A constructor is used to initialize the members of a class.
Properties of a constructor:
The name of the constructor is same as the name of the class.
Constructor does not have any return type.
Constructor cannot be inherited.
Constructor can be of various kinds. Java provides us with default constructor,
parameterized constructor and subclass constructor. When any constructor is not

D
defined for a class then java provides us with a default constructor without any
parameter. A subclass can invoke the constructor of super class using the keyword
super().
Example of different kinds of constructors:
//Default Constructor
class Test
LS
{
void TestFunction()
{
String name = "RAJ";
System.out.println(name);
}
public static void main(String[] args)
O

{
System.out.println("Default constructor is invoked");
Test t = new Test();// default constructor is invoked
t.TestFunction();
O

}
}
// Parameterized constructor
class Test
ST

{
public Test()
{
System.out.print("Constructor is called without any arguments");
}
public Test(int x)
{
SY

System.out.println(" ");
System.out.print("constructor is called with one arguments." + " ");
System.out.print("Passed argument is" + " " + x);

17 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

17.What is a class? How does it accomplish data hiding? How do you create objects from
the class?
Class is a template, declaration or a blueprint that can be used to classify the objects.
A class contains variables and functions. A class uses encapsulation and abstraction
for accomplishing data hiding. Abstraction is the process of providing only the relevant
information means it provides us with that information what we are looking for.
Encapsulation is the process of enclosing one or more items within a physical or

O
logical package. It prevents access to non essential details. A class uses access
modifiers for implementing encapsulation which defines the scope of a member
variable and function of a class. Different types of access modifiers are Default, public,
private and protected.

EM
Default: A variable, method or class has default accessibility if no any access modifier
is defined for them. It is accessible anywhere within the same class and same package.

Public: A variable or method marked as public is accessible any where in the same
class, same package, subclass and different class.

Private: A private variable or method is accessible only by the methods and variable of

D
the same class.

Protected: Protected variables and methods are accessible anywhere in the same class,
same package and derived class but it is not accessible to the different class.
LS
18.What is an array? Why arrays are easier to use compared to bunch orelated variables?

An array is a sequence of logically related data items. It is a kind of row made of boxes,
with each box holding a value. The number associated with each box is the index of
the item. Each box can be accessed by, first box, second box, third box, and so on, till
the nth box. The first box, or the lowest bound of an array is always zero, which
means, the first item in an array is always at position zero of that array. Position in an
O

array is called index. So the third item in an array would be at index 2 (0, 1,2).
An array is a sequence of logically related data items. It is a kind of row made of boxes,
with each box holding a value.
O

Arrays have following advantages over bunch of related variables:


o Arrays of any type can be created. They can have one or more dimensions.
o Any specific element can be indexed in an array by its index.
o All like type variables in an array can be referred by a common name.
ST

 What is an exception? Explain with a program.


Ans:
An exception is an erroneous situation that occurs during the execution of a program.
When an exception occurs in an application then java throws an error. The error is
handled through the exception handler. When error occurs, runtime creates an
exception object and sends it to the program. The exception object contains
information about the error. Java use try and catch for handling exceptions. The part
SY

of the program which is likely to throw exceptions is kept with try and each try is at
least preceded by one catch blocks. There can be any number of catch for a try block.

19 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

Allocating Memory to Arrays


The new operator is used to allocate memory to an array.
Syntax to allocate memory
array_name = new type[size];
For e.g.
anArray = new int[10]; //size of the array is 10.
Alternatively, we can use the shortcut syntax to create and initialize an array:

O
int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};

EM
D
Each item in an array is called an element, and each element is accessed by its
numerical index. As shown in the above illustration, numbering begins with 0. The 9th
element, for example, would therefore be accessed at index 8.
Two-dimensional Arrays
LS
In additions to one-dimensional arrays, we can create two-dimensional arrays. To
declare two-dimensional arrays, we need to specify multiple square brackets after the
array name.
Syntax to declare a two dimensional array
type array_name = new type[rows][cols];
For e.g.
int multidim[] = new int[3][];
O

Creating an Array of Objects


O

To create an array of objects means that every element in an array is an object, or


instance of another class. For example, if you wanted to make an array filled with
Circle objects (suppose we have Circle class), we would do it in the following way:
ST

Circle[] c = new Circle[5];

The above statement has created an array called c, with 5 Circle elements. At the
moment, each object is null. You have just created the following:
SY

21 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

public void display(){


System.out.println( it is a firest class method );
}
}
class overiding extends a{
public void display(){
System.out.println( it is a Second class method );

O
}
public static void main(String []anil){
overiding obj new overiding();

EM
obj.display();

}
}
output: it is a Second class method

Some more differences:

D
Overloading methods
1.They appear in the same class or a subclass
2.They have the same name but, have different parameter lists, and can have different
return types.
An example of an overloaded method is print() in the java.io.PrintStream class
LS
Overriding methods
It allows a subclass to re-define a method it inherits from it's superclass
overriding methods:
1. It appears in subclasses
2. They have the same name as a superclass method
3. They have the same parameter list as a superclass method
4. They have the same return type as as a superclass method
O

5. They have the access modifier for the overriding method may not be more restrictive
than the access modifier of the superclass method
·If the superclass method is public, the overriding method must be public
·If the superclass method is protected, the overriding method may be protected or
O

public
·If the superclass method is package, the overriding method may be packagage,
protected, or public
·If the superclass methods is private, it is not inherited and overriding is not an issue
ST

21. Explain final keyword with suitable example.


Any field that you never expect to be changed should generally be declared final. In the
Java programming language, the final keyword is used in several different contexts to
define an entity which cannot later be changed.

Final classes:- A final class cannot be subclassed. This is done for reasons of security
SY

and efficiency. Accordingly, many of the Java standard library classes are final, for

23 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

private long createid{


return…//generate new id
}
…//more declarations
}

22. What is stream? List out the different stream classes in java, explain how

O
input or output is handled in java?
A stream is a sequence of data. A stream is in Java is a path along which data flows. It
has a source of data and a destination for the data. Both the source and the

EM
destination may be physical devices or programs or other streams in same program.
Java uses the concept of streams to represent the ordered sequence of data, a
common characteristic shared by all the input/output devices as stated above. A
stream presents a uniform, easy-to-use, object-oriented interface between the program
and the input/output devices.

Java includes a particularly rich set of I/O classes in the core API, mostly in the
java.io packages. These packages support several different styles of I/O. One

D
distinction is between byte-oriented I/O, which is handled by input and output
streams, and character-I/O, which is handled by readers and writers. These all have
their place and are appropriate for different needs and use cases.

All classes are basically divided into two types of categories:


1. Byte Stream classes
LS
2. Character stream classes

1. Byte Stram classes:- Byte streams are defined by using two class hierarchies. At the
top are two abstract classes: InputStream and OutputStream. Each of these abstract
classes has severalconcrete subclasses, that handle the differences between various
devices, such as disk files, network connections, and even memory buffers. The
abstract classes InputStream and OutputStream define several key methods that the
O

other stream classes implement. Two of the most important are read( ) and write( ),
which, respectively, read and write bytes of data. Both methods are declared as
abstract inside InputStream and OutputStream. They are overridden by derived
stream classes.
O

2. Character Stream Classes:- Character streams are defined by using two class
hierarchies. At the top are two abstract classes, Reader and Writer. These abstract
classes handle Unicode character streams. Java has several concrete subclasses of
ST

each of these. The abstract classes Reader and Writer define several key methods that
the other stream classes implement. Two of the most important methods are read( )
and write( ), which read and write characters of data, respectively. These methods are
overridden by derived stream classes.

Handling the input or output in Java:


Java provide java.io package to handle input and output of any type of data. There are
SY

two classes based on data which these classes can handle. The name of the classes

25 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

}
}

24. Explain if else statement with syntax and with an examples.


The syntax of if else statement is given below.
If (test expression)

O
{
True block statement(s)
}
else

EM
{
False block statement(s)
}
In if else statement if the condition given in test expression evaluates to true then
immediately true block statement is executed otherwise the false block statement is
executed. There can be number of if else in a if else statement.
//program to find the greatest of two numbers
public class Greater {

D
public static void main(String [ ] args) {
int x=10,y=20;
if (x > y)
{
System.out.println(x + “ is greater than “ + y);
}
LS
else
{
System.out.println(y + “ is greater than “ + x);
}
System.out.println( );
}
25.List the eight basic data types used in java given examples.—
O

I. Boolean: Logical values are represented using the Boolean data types The Boolean
data type has two values either true or false. Example: boolean truth=true
II. Char: Single characters are represented by using the char data type. A char represents
a 16-bit unsigned Unicode character. A char is enclosed within a single quote.
O

Example: char a=’A’


III. String: A sequence of characters are stored using String data type. A String is
enclosed within double quote marks. Example: “happy”
IV. Byte: The length of Byte data type is 8 bits and it ranges between -27 to 27-1. Example
ST

of Byte data type is 2.


V. Short: The length of Short data type is 16 bits and it ranges between -215 to 215-1.
Example of Srt data type is -62699.
VI. Long: The length of Long data type is 64 bits and it ranges between -263 to 263-1.
Example of Long data type is 775, 808L1L.
VII. Int: The length of int data type is 32 bits and it ranges between -231 to 231-1. Example
of int data type is 147.
SY

VIII. Float: The length of Float data type is 32 bits used to store values to the right of
decimal point. Example of float data type is 99F.

27 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

28. Explain thread priority with simple program?


The thread is controlled by their priority. Java executes threads based on their
priority. Only one thread is executed at one time. The thread which are in runnable
state waits for their chance to be executed by the CPU. Java uses setPriority property
for setting the priority of a thread and getPriority to get the priority of a thread.
import java.io.*;

O
class Test extends Thread
{
public void FirstThread()
{

EM
for (int T = 0; T < 11; T++)
{
for (int cnt = 0; cnt < 100; cnt++)
{
System.out.print(".");
}
System.out.print(T);
}

D
}
public void SecondThread()
{
for (int T = 11; T < 20; T++)
{
for (int cnt = 0; cnt < 100; cnt++)
LS
{
System.out.print(".");
}
System.out.print(T);
}
}
public static void main(String[] args)
O

{
Test t = new Test();
t.FirstThread();
t.SecondThread();
O

Thread t1 = new Thread(t);


Thread t2 = new Thread(t);
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
ST

t1.start();
t2.start();

}
}

29. What is scope of a variable?


SY

29 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

case 9: System.out.println("September");
break;

case 10: System.out.println("October");


break;

O
case 11: System.out.println("November");
break;

EM
case 12: System.out.println("December");
break;
}

31. Describe the structure of a typical Java program

D
A Java program may contain many classes of which only one class defines a main
method. Classes contain data members and methods. Methods of a class operate on
the data members of the class. Methods may contain data type declarations and
executable statements. To write a Java program, we first define classes and then put
them together.
LS
A Java program may contain one or more sections as shown in the following figure:
Documentation Section Suggested

Package Statement Optional


O

Import Statements Optional


O

Interface Statements Optional

Class Definitions Essential


ST

Main Method class

Main Method Definition Essential


SY

31 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

simplifies code writing thus making programs easier to maintain and debug. It allows
reusability of the code
A subclass is defined as follows:
class subclass extends superclass {
Variables declaration;

O
Methods declaration;
}
The keyword extends signifies that the properties of the superclass are extended to the

EM
subclass. The subclass will now contain its own variables and methods as well those
of the superclass. This kind of situation occurs when we want to add some more
properties to existing class without actually modifying it.

33. What is a constructor & parameterized constructor? Explain its usage with an
example.
A constructor creates an Object of the class that it is in by initializing all the instance

D
variables and creating a place in memory to hold the Object. It is always used with the
keyword new and then the Class name. For instance, new String(); constructs a new
String object.

Sometimes in a few classes you may have to initialize a few of the variables to values
LS
apart from their predefined data type specific values. If java initializes variables it
would default them to their variable type specific values. For example you may want to
initialize an integer variable to 10 or 20 based on a certain condition, when your class
is created. In such a case you cannot hard code the value during variable declaration.
such kind of code can be placed inside the constructor so that the initialization would
happen when the class is instantiated.
O

Constructor name is class name. A constructors must have the same name as the
class its in.

 Default constructor. If you don't define a constructor for a class, a default


O

parameterless constructor is automatically created by the compiler. The default


constructor calls the default parent constructor (super()) and initializes all instance
variables to default value (zero for numeric types, null for object references, and false
for booleans).
 Default constructor is created only if there are no constructors. If you define any
ST

constructor for your class, no default constructor is automatically created.


 Differences between methods and constructors.
o There is no return type given in a constructor signature (header). The value is this
object itself so there is no need to indicate a return value.
o There is no return statement in the body of the constructor.
o The first line of a constructor must either be a call on another constructor in the same
class (using this), or a call on the superclass constructor (using super). If the first line
SY

is neither of these, the compiler automatically inserts a call to the parameterless super
class constructor.

33 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

height = 10;
}
Cube1(int l, int b, int h) {
length = l;
breadth = b;
height = h;

O
}
public static void main(String[] args) {
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();

EM
cubeObj2 = new Cube1(10, 20, 30);
System.out.println(”Volume of Cube1 is : ” + cubeObj1.getVolume());
System.out.println(”Volume of Cube1 is : ” + cubeObj2.getVolume());
}
}

34. What is polymorphism? Explain method overriding with example and

D
prove that it is a polymorphism.

Polymorphism: It is a key concept in object-oriented programming. Poly means many,


morph means change (or 'form'). Polymorphism (from the Greek, meaning “many
forms”) is a feature that allows one interface to be used for a general class of actions.
LS
The specific action is determined by
the exact nature of the situation. Consider a stack (which is a last-in, first-out list).
You might have a program that requires three types of stacks. One stack is used for
integer values, one for floating-point values, and one for characters. The algorithm
that implements each stack is the same, even though the data being stored differs.
More generally, the concept of polymorphism is often expressed by the phrase “one
interface, multiple methods.” This means that it is possible to design a generic
O

interface to a group of related activities. This helps reduce complexity by allowing the
same interface to be used to specify a general class of action. It is the compiler’s job to
select the specific action (that is, method) as it applies to each situation. You, the
programmer, do not need to make this selection manually. You need only remember
and utilize the
O

general interface.

A simple crude example for polymorphism in real-world could be ...


1. Every dog has a nose . Dog is a system. Nose is the interface of the system to detect
ST

smell. Based on the kind of smell, dog (system) reacts differently..may be it will bark at
you, wag its tail, chase you etc.,

So eventhough dog-system has a single nose-interface, it behaves differently based on


the smell (or data/parameters fed to the interface).

You can consider one another a computer-systems related example...


SY

2. Every ATM has a single interface(slot) to login to the bank-system by feeding in the
ATM-card(data). But based on what sort of account user holds, a different screen is

35 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

class Triangle extends Figure {


Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");

O
return dim1 * dim2 / 2;
}
}
class FindAreas {

EM
public static void main(String args[]) {
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;

D
System.out.println("Area is " + figref.area());
figref = f;
System.out.println("Area is " + figref.area());
}
}
The output from the program is shown here:
LS
Inside Area for Rectangle.
Area is 45
Inside Area for Triangle.
Area is 40
Area for Figure is undefined.
Area is 0
O

Through the dual mechanisms of inheritance and run-time polymorphism, it is


possible to define one consistent interface that is used by several different, yet related,
types of objects. In this case, if an object is derived from Figure, then its area can be
obtained by calling area( ). The interface to this operation is the same no matter what
O

type of figure is being used.

35. List and explain different types of loops in Java


ST

Loop is the control statement of any language in which whenever you want to perform
the repetitious work then you use the Loop control statement. There are mainly three
types of loops. Loop repeats a statement or a process multiple times according to the
specified conditions. It allows the multiple statements or process to be run for the
specified time or it also follows the certain conditions. Loop makes our program
readable, flexible and reliable. Three loops in java these are while,do while and for
SY

37 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

The do...while Loop:

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed
to execute at least one time.

Syntax:

O
The syntax of a do...while loop is:
do
{
//Statements

EM
}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in
the loop execute once before the Boolean is tested.

If the Boolean expression is true, the flow of control jumps back up to do, and the
statements in the loop execute again. This process repeats until the Boolean

D
expression is false.

Example:
public class Test {
public static void main(String args[]){
int x= 10;
LS
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
O

This would produce following result:


O

value of x : 10
value of x : 11
value of x : 12
value of x : 13
ST

value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
SY

39 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

O
36. Explain the various control of statements of Java programming language with
syntax and an example for each.
A programming language uses control statements to cause the flow of execution to
advance and branch based on changes to the state of a program. Java’s program

EM
control statements can be put into the following categories: selection, iteration, and
jump. Selection statements allow your program to choose different paths of execution
based upon the outcome of an expression or the state of a variable. Iteration
statements enable program execution to repeat one or more statements (that is,
iteration statements form loops). Jump statements allow your program to execute in a
nonlinear fashion. All of Java’s control statements are examined here.

D
1- Selection Statements :- (if-then, if-then-else and switch)
2- Repetition or iteration Statements:- while, do-while and for
3- Branching or jupm Statements :- break, continue and return

Selection statements:
LS
1. If Statement:
This is a control statement to execute a single statement or a block of code,
when the given condition is true and if it is false then it skips if block and rest
code of program is executed .
O

Syntax:
if(conditional_expression){
<statements>;
...;
O

...;
}

Example: If n%2 evaluates to 0 then the "if" block is executed. Here it evaluates
ST

to 0 so if block is executed. Hence "This is even number" is printed on the


screen.

int n = 10;

if(n%2 = = 0){
SY

System.out.println("This

41 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

3. Switch Statement:
This is an easier implementation to the if-else statements. The keyword
"switch" is followed by an expression that should evaluates to byte, short, char
or int primitive data types ,only. In a switch block there can be one or more
labeled cases. The expression that creates labels for the case must be unique.
The switch expression is matched with each case label. Only the matched case

O
is executed ,if no case matches then the default statement (if present) is
executed.

Syntax:

EM
switch(control_expression){
case expression 1:
<statement>;
case expression 2:
<statement>;
...
...
case expression n:

D
<statement>;
default:
<statement>;
}//end switch
LS
Example: Here expression "day" in switch statement evaluates to 5 which
matches with a case labeled "5" so code in case 5 is executed that results to
output "Friday" on the screen.

int day = 5;
O

switch (day) {
case 1:
System.out.println("Monday");
break;
O

case 2:
System.out.println("Tuesday");
break;
case 3:
ST

System.out.println("Wednesday");
break;
case 4:
System.out.println("Thrusday");
break;
case 5:
SY

System.out.println("Friday");
break;
case 6:

43 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

2. do-while loop statements:


This is another looping statement that tests the given condition past so you can
say that the do-while looping statement is a past-test loop statement. First the
do block statements are executed then the condition given in while statement is

O
checked. So in this case, even the condition is false in the first attempt, do
block of code is executed at least once.

Syntax:

EM
do{
<statement>;
...;
...;
}while (expression);

Example: Here first do block of code is executed and current value "1" is
printed then the condition i<=10 is checked. Here "1" is less than number "10"

D
so the control comes back to do block. This process continues till value of i
becomes greater than 10.

int i = 1;
LS
do{

System.out.println("Num:
" + i);

i++;
O

}while(i <= 10);


O

3. for loop statements:


This is also a loop statement that provides a compact way to iterate over a
range of values. From a user point of view, this is reliable because it executes
ST

the statements within this block repeatedly till the specified conditions is true .

Syntax:
for (initialization; condition; increment or decrement){
<statement>;
...;
...;
SY

}
initialization: The loop is started with the value specified.

45 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

O
EM
D
2. Continue statements:
This is a branching statement that are used in the looping statements (while,
do-while and for) to skip the current iteration of the loop and resume the next
iteration .
LS
Syntax:
continue;

Example:
O
O
ST
SY

47 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

O
EM
37. Define programming. What are the types of programming? Explain.

Programming is the art and science of translating a set of ideas into a program - a list
of instructions a computer can follow. The person writing a program is known as a

D
programmer (also a coder).

The exact form the instructions take depend on the Programming Language used.
Languages run the spectrum from very low level like Machine Language or Assembly,
to a very high level like Java. Lower level languages are more closely tied to the
platform they are targeted for, while Higher level languages abstract an increasing
LS
amount of the platform from the programmer.

In other words, low level programming languages represent the instructions in a


manner that resembles more closely the way the computer actually works. High level
languages do resemble more the way the human mind works. Each type is a good fit
depending on the particular case. Whenever speed and resource consumption are
important, low level languages can provide an advantage since they cause much less
O

"translation" and are less generic, thus causing less load on the computer[1]. High level
languages have much more abstraction and thus are better suited for tasks where
maintenance and complex design is required.
O

After a programmer has finished writing the program, it must be executed.


Traditionally, some languages (like Basic) are interpreted, while others (like C) are
compiled prior to execution. Interpreted languages are executed "on the fly" at run
time, while compiled languages have a separate compilation step that must be
ST

completed prior to running. Compilers are able to make certain optimizations that are
unavailable to interpreters.

The program may fail to compile or execute due to syntax errors. These are errors
caused by doing something that is unknown or illegal according to the language they
have used. These errors have to be corrected before the program will execute.
SY

49 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

O
EM
Procedures, also known as functions, subroutines, or methods, are small sections of
code that perform a particular function. A procedure is effectively a list of
computations to be carried out. Procedural programming can be compared to
unstructured programming, where all of the code resides in a single large block. By

D
splitting the programmatic tasks into small pieces, procedural programming allows a
section of code to be re-used in the program without making multiple copies. It also
makes it easier for programmers to understand and maintain program structure.

Two of the most popular procedural programming languages are FORTRAN and
LS
BASIC.

Modular Programming
With modular programming procedures of a common functionality are grouped
together into separate modules. A program therefore no longer consists of only one
single part. It is now divided into several smaller parts which interact through
O
O
ST
SY

51 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

ask them to perform what they do by sending the messages. OOP paradigm helps us
to organize the inherent complexities of software systems.

Definition

It is a method of implementation in which programs are organized as co-operative


collection of objects, each of which represents an instance of some class and whose

O
classes all members of a hierarchy of classes united in inheritance relationships.

EM
D
LS
O
O
ST

38. What is JVM ? How does it help to achieve platform independence? If


JVM is available for windows then can we run program written on Unix
platform ?
SY

53 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

For example, establishing a socket connection from a workstation to a remote


machine involves an operating system call. Since different operating systems
handle sockets in different ways, the JVM translates the programming code so
that the two machines that may be on different platforms are able to connect.

Ans from Book of this Question:-

O
All language compilers translate source code into machine code for a specific
computer. Java compiler

EM
produces an intermediate code known as bytecode for a machine that does not exist.
This machine is called the Java Virtual Machine and it exists only inside the computer
memory. The following Figure 3.4 illustrates the process of compiling a Java program
into bytecode which is also referred to as virtual machine code.

D
LS
O

The virtual machine code is not machine specific. This machine specific code ( known
O

as machine code) is generated by the Java interpreter by acting as an intermediary


between the virtual machine and the real machine as shown in the Figure3.5.
Interpreter is different for different machines
ST
SY

55 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

}
}

O
2. Write a Java programm to implement recursive binary search.
Ans:
class RecursiveBinary
{
static int[] a ={ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };

EM
public void BinarySearch(int[] a, int k, int low, int high)
{
if (low <= high)
{
int mid = (low + high) / 2;
if (a[mid] == k)
{
System.out.println(k + " " + "is found at index" + " " + mid);
}

D
else if (k < a[mid])
{
BinarySearch(a, k, low, mid - 1);
}
else
{
LS
BinarySearch(a, k, mid + 1, high);
}
}
}
public static void main(String[] args)
{
RecursiveBinary r = new RecursiveBinary();
O

r.BinarySearch(a, 14, 0, 9);


}
}
O

3. Write a program in Java to implement Binary Search.


ST

Ans:
class Binary_Search
{
int[] a ={ 2, 4, 6, 8, 10, 12, 14, 16, 18 };
int k = 16;
void Search()
{
int low = 0;
SY

int high = 8;
while (low <= high)
{

57 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

System.out.println("Enter the setup costs(per order)");


SetupCosts=Double.parseDouble(br.readLine());
System.out.println("Enter the holding costs(per item per unit time)");
HoldingCost=Double.parseDouble(br.readLine());
}
catch(Exception e)
{

O
}
}
void Calculate()
{

EM
try
{
EOQ=Math.sqrt((2*DemandRate*SetupCosts)/HoldingCost);
System.out.println("EOQ:"+" "+EOQ);
TBO=Math.sqrt((2*SetupCosts)/(DemandRate*HoldingCost));
System.out.println("TBO:"+" "+TBO);
}
catch(Exception e)

D
{

}
}
public static void main(String[]args)
{
LS
InventoryManagement IM=new InventoryManagement();
IM.getdata();
IM.Calculate();
}
}
O

5. Write a Java program to sort a list strings using bubble sort technique.
//may be some error plz check
Ans:
class Test
O

{
public void BubbleSort()
{
try
ST

{
int length;
String temp;
String[] array;
System.out.println("Enter the size of array");
length = Integer.parseInt(br.readLine());
array = new String[length];
SY

System.out.println("Enter the element for the array");


for (int i = 0; i < length; i++)
{

59 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

System.out.println("enter the length of array");


length = Integer.parseInt(br.readLine());
a = new int[length];
System.out.println("Enter the array elements");
for (int p = 0; p < length; p++)
{
a[p] = Integer.parseInt(br.readLine());

O
}
for (int q = 0; q < length; q++)
{
if (a[q] % 2 == 0)

EM
{
sumeven = sumeven + a[q];
}
else
{
sumodd = sumodd + a[q];
}
}

D
System.out.println("Sumeven:" + " " + sumeven);
System.out.println("Sumodd:" + " " + sumodd);
}
catch (Exception e)
{
System.out.println(e);
LS
}
}
public static void main(String[] args)
{
Test t = new Test();
t.Addition();
}
O

7. Write a Java programme to sort a list of numbers.


Ans:
O

import java.io.*;
class Sort
{
int length;
ST

int[] a;//
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void Sorting()
{
try
{
System.out.println("Enter the length of array");
SY

length = Integer.parseInt(br.readLine());
a = new int[length];

61 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

public Box()
{
width = 10;
height = 10;
depth = 10;
}
public void Volume()

O
{
double result = width * height * depth;
System.out.println("The volume of the box is " + " " + result);
}

EM
public static void main(String args[])
{
Box b = new Box();
b.Volume();
}
}
9. Write a Java programme to find whether the given string is palindrome or not.
Ans:

D
import java.io.*;
class Test
{
String str;
boolean Test;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
LS
public void PalinTest()
{
try
{
System.out.println("Enter the string");
str = br.readLine();
int startindex = 0;
O

int lastindex = str.length() - 1;


while (startindex < lastindex)
{
if (str.charAt(startindex) == str.charAt(lastindex))
O

{
Test = true;
startindex++;
lastindex--;
ST

}
else
{
Test = false;
System.out.println(str + " " + "is not a palindrome");
return;
}
SY

}
if (Test == true)
{

63 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
public void DiscountTest()
{
try
{

O
double PurchaseAmount;
double MillDiscount, HandloomDiscount;
String Choice, Item;
System.out.println("Enter the purchase amount");

EM
PurchaseAmount = Float.parseFloat(br.readLine());
System.out.println("Enter the Item type");
Item = br.readLine();
if (PurchaseAmount <= 100)
{
if (Item.equals("Millcloth"))
{
MillDiscount = (PurchaseAmount * 0) / 100;

D
System.out.println("MillDiscount:" + " " + MillDiscount);
}
else
{
HandloomDiscount = (PurchaseAmount * 5) / 100;
System.out.println("HandloomDiscount:" + " " +
LS
HandloomDiscount);
}
}
else if (PurchaseAmount > 100)
{
if (PurchaseAmount <= 200)
{
O

if (Itemequals("Millcloth"))
{
MillDiscount = (PurchaseAmount * 5) / 100;
System.out.println("MillDiscount:" + " " +
O

MillDiscount);
}
else
{
ST

HandloomDiscount = (PurchaseAmount * 7.5) / 100;


System.out.println("HandloomDiscount:" + " " +
HandloomDiscount);
}
}
}
else if (PurchaseAmount > 200)
SY

{
if (PurchaseAmount <= 300)
{

65 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

String FirstName = "Raj";


String LastName = "Singh";
String FullName = FirstName + " " + LastName;
System.out.println("My Name is" + " " + FullName);
}
public static void main(String[] args)
{

O
Test t = new Test();
t.MyFunction();
}
}

EM
13. Write a program to create a thread by extending the thread class. 8
Marks

class MyThread extends Thread


{
public void run()

D
{
for (int i = 0; i <= 5; i++)
{
System.out.println("Raj");
}
LS
}
public static void main(String[] args)
{
MyThread t = new MyThread();
t.start();
}
}
O

SOME SHORT EXPLANATION:-

1. Explain the methods


O

Trim- The Trim method returns a copy of the invoking string from which any
leading and trailing white space are removed. The general form of Trim method
ST

is String.trim().
Example of trim method:
class Test
{
String str="Rajesh kumar";
void TrimTest()
{
SY

str=str.trim();
System.out.println(str);
}

67 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

class Test
{
String str="Rajesh kumar";
void SubStringTest()
{

O
str=str.substring(0,7);
System.out.println(str);
}
public static void main(String[]args)

EM
{
Test t=new Test();
t.SubStringTest();
}
}

Length.

D
Length : The number of character contained in a string is called the length of
the string. Java uses length() method to know the length of a string. The general
form of length method is String.length().
class Test
{
LS
String str="Kalpana Kumari";
void LengthTest()
{
int j=str.length();
System.out.println(j);
}
public static void main(String[]args)
O

{
Test t=new Test();
t.LengthTest();
}
}
O
ST

OOP Language :- OOPL The use of a class of programming languages and


techniques based on the concept of an "object" which is a data structure
(abstract data type) encapsulated with a set of routines, called "methods",
which operate on the data. Operations on the data can __only__ be performed
via these methods, which are common to all objects that are instances of a
particular "class". Thus the interface to objects is well defined, and allows the
code implementing the methods to be changed so long as the interface remains
SY

the same.Each class is a separate module and has a position in a "class

69 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

statements take the control back to the loop. The keywords used to declaring
continue statement is “continue”.
Example of continue statement:
class Test
{
public static void main(String[]args)

O
{
for(int i=0;i<10;i++)
{
if (i == 8)
{

EM
continue;
}
System.out.println(i+”.”+”rAJ”);
}
}
}

D
While and do while
 While:
While statement consists of a condition and a loop body. The condition is enclosed
within the parenthesis. All the variables used in condition of while loop should be
LS
initialized before the while loop begins. The value of variables used in condition must
change in the loop body. Otherwise condition will always remains true causing loop to
run infinitely. Single or multiple statements can be written within the loop body.
Multiple statements should be enclosed within braces. Otherwise the code may
generate an unexpected output. Condition is evaluated first if the condition holds true
then only the loop body is executed. After loop body is executed condition is evaluated
O

again. The process of evaluating condition and executing loop body continues until the
condition becomes false.
Syntax of while loop is
While (Test Condition)
O

{ body of the loop};.

 Do While:
ST

Do while loop performs certain repetitive action depending on a condition. All the
variables used in condition of while loop should be initialized before the while loop
begins. The value of variables used in condition must change in the loop body.
Otherwise condition will always remains true causing loop to run infinitely. Single or
multiple statements can be written within the loop body. Multiple statements should
be enclosed within braces. Otherwise the code may generate an unexpected output. In
SY

do while loop the loop body is executed at least once regardless of condition being true
or false. After loop body is executed the condition is checked. If the condition evaluates

71 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

Distinguish between the following terms:


 Objects and classes
 Data abstraction and data encapsulation
 Inheritance and polymorphism
 Dynamic binding and message passing

O
Ans.
 Objects and classes: Object is a physical entity which represents
a person, vehicle or a conceptual entity (thing in existence) like bank account,

EM
company etc.
A set of variables and functions used to describe an object is a "class".
A class defines the structure and behavior (data and code) that will be shared by a set
of objects. Each object of a given class contains the structure and behavior defined by
the class, as if it were stamped out of a mould in the shape of a class. A class is a
logical construct. An object has physical reality. When you create a class, you will
specify the code and data that will constitute that class. Collectively, these elements
are called the members of the class. Specifically, the data defined by the class are

D
referred to as member variables or instance variables. The code that operates on that
data is referred to as member methods or just methods, which define the use of the
member variables.

 Data abstraction and data encapsulation: Abstraction - the act


or process of leaving out of consideration one or more qualities of a complex object so
LS
as to attend to others. Solving a problem with objects requires you to build the
objects tailored to your solution. We choose to ignore its inessential details, dealing
instead with the generalized and idealized model of the object.
Encapsulation - The ability to provide users with a well-defined interface to a set of
functions in a way, which hides their internal workings. In object-oriented
programming, the technique of keeping together data structures and the methods
(procedures) which act on them. The easiest way to think of encapsulation is to
O

reference phones. There are many different types of phones, which consumers can
purchase today. All of the phones used today will communicate with each other
through a standard interface. For example, a phone made by GE can be used to call a
phone made by Panasonic. Although their internal implementation may be different,
O

their public interface is the same. This is the idea of encapsulation.

 Inheritance and polymorphism: Inheritance in object-oriented


programming means that a class of objects can inherit properties from another class
ST

of objects. When inheritance occurs, one class is then referred as the 'parent class' or
'superclass' or 'base class'. In turn, these serve as a pattern for a 'derived class' or
'subclass'.
Inheritance is an important concept since it allows reuse of class definition without
requiring major code changes. Inheritance can mean just reusing code, or can mean
that you have used a whole class of object with all its variables and functions.
Polymorphism: It is a key concept in object-oriented programming. Poly means many,
SY

morph means change (or 'form').

73 Solved by: - Rajesh & Ashish [ AshuRaj ]


[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

}
Example - Creation of Thread by extending the
Thread class.

When the run method ends, the thread is supposed to "die". The next example shows
the creation of thread by implementing the Runnable interface.

O
public class ThreadExample2 implements Runnable {
public void run() {
.../* Code which gets executed when

EM
thread gets executed. */
}
public static void main(String args[]) {
ThreadExample2 Tt = new ThreadExample2();
Thread t = new Thread(Tt);
t.start();
}
}

D
Example - Creating thread by implementing Runnable

States of thread
A thread can be in one of the following states - ready, waiting for some action,
running, and dead. These states are explained below.
LS
Running State A thread is said to be in running state when it is being executed. This
thread has access to CPU.
Ready State A thread in this state is ready for execution, but is not being currently
executed. Once a thread in the ready state gets access to the CPU, it gets converted to
running state.
Dead State A thread reaches "dead" state when the run method has finished
O

execution. This thread cannot be executed now.


Waiting State In this state the thread is waiting for some action to happen. Once that
action happens, the thread gets into the ready state. A waiting thread can be in one of
the following states - sleeping, suspended, blocked, waiting for monitor. These are
O

explained below.

Yielding to other processes


A CPU intensive operation being executed may not allow other threads to be executed
ST

for a "large" period of time. To prevent this it can allow other threads to execute by
invoking the yield() method. The thread on which yield() is invoked would move from
running state to ready state.
Sleep state of a thread
A thread being executed can invoke the sleep() method to cease executing, and free
up the CPU. This thread would go to the "sleep" state for the specified amount of
time, after which it would move to the "ready" state. The sleep method has the
SY

following prototypes.

public static void sleep (long millisec)

75 Solved by: - Rajesh & Ashish [ AshuRaj ]


SY
ST
O
O
LS
D
EM
O

You might also like