Sunteți pe pagina 1din 7

Why is Java known as a platform-neutral

language?
Java is known as platform-neutral language
because Java's bytecodes are designed to be read,
interpreted, and executed in exactly the same
manner on any computer hardware or operating
system that supports a Java run-time.

How is Java more secure than other languages?
One of the potential terrors of the Internet is the
possibility of security breaches- viruses that infect
your computer, or hackers who take advantage of a
software glitch to invade your personal cyberspace
and make off with confidential information.
Applets, which are Java programs, are
automatically downloaded when a Web page is
displayed. Java applets, by default, execute within
the Java executing environment and are limited to
the environment. This means, an applet cannot
access the local file system or other programs of
the system where it executes. This reduces the
chance that simply viewing someone's page might
harm your system or data. No system is absolutely
reliable and none will ever be; but Java represents
the state-of-the-art in reducing the chances of a
disaster.

What is multithreading? How does it improve the
performance of Java?
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.
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.

List at least seven major differences between C and
Java.
The following are the differences between C and
Java:
1. Java does not have a preprocessor, and as such,
does not have macros like #define. Constants
can be created by using the final modifier when
declaring class and instance variables.
2. In Java, all methods are tied to classes. Java
does not support stand-alone methods.
3. Java does not include the const keyword as
present in C or the ability to pass by const
reference explicitly.
4. In Java strings are implemented as objects and
not as an array of null-terminated characters.
5. 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.
6. The goto keyword does not exist in Java (it's a
reserved word, but currently unimplemented).
You can, however, use labeled breaks and
continues to break out of and continue
executing complex switch or loop constructs.
7. Java does not use pointers.
8. In Java, arrays are real objects because you can
allocate memory using the new operator.

How is Java strongly associated with the Internet?
Internet users can use Java to create applet
programs and run them locally using "Java-enabled
browsers" such as HotJava. They can also use a
Java-enabled browser to download an applet
located on a computer anywhere in the Internet and
run it on their local computer. Internet users can
also set up their websites containing java applets
that could be used by other remote users of the
Internet.

What is Hypertext Markup Language? Describe its
role in the implementation of Java applets.
Hypertext Markup Language or HTML is a markup
language that uses predefined tags to specify the
browser how it needs to display a Web page.
Browsers allow us to retrieve the information from
the Internet and display it using the Hypertext
Markup Language (HTML). HotJava, Netscape
Navigator and Internet Explorer are some popular
Web browsers. A Web page can embed Java
applets. To embed an applet, the <Applet> tag is
used in the HTML document. When a browser
encounters the <Applet> tag it loads the applet and
executes it with the browser Java Virtual Machine
(JVM).

List out primary goals of Java Technology.
The primary goals of Java technology are:
1. To provide an easy to use language by avoiding
pitfalls of other languages and enables users to
create clear and streamlined code.
2. To provide an interpreted environment for
improved speed of development and code
portability.
3. To provide a way for programs to run more
than one thread of activity.
4. To furnish better security.

What is an appletviewer?
An appletviewer allows you to run an applet
without the overhead of running a Web browser.

What is object-oriented programming? How is it
different from the procedure-oriented
programming?
Object- oriented programming 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
classes all members of a hierarchy of classes united
in inheritance relationships.
With procedural programming you are able to
combine returning sequences of statements into one
single place. A procedure call is used to invoke the
procedure. After the sequence is processed, flow of
control proceeds right after the position where the
call was made

How are data and methods organized in an object-
oriented program?
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 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 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.

What are unique advantages of an object-oriented
programming paradigm?
OOP offers several advantages to both the program
designer and the user. The important advantages
are:
1. Reusability: Elimination of redundant code
and use of existing classes through inheritance.
Thus provides economy of expression.
2. Modularity: Programs can be the built from
standard working modules.
3. Security: Principle of information hiding helps
programmer to build secure programs.
4. Easy mapping: Object in the problem domain
can be directly mapped to the objects in the
program.
5. 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.
6. Easy management: Easy management of
software complexity.

Describe inheritance as applied to OOP.
Inheritance in object oriented programming means
that a class of objects can inherit properties from
another class of objects. When inheritance occurs,
one class is then referred to 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.

State whether the following statements are TRUE
or FALSE:

In conventional, procedure-oriented programming,
all data are shared by all functions. True

The main emphasis of procedure-oriented
programming is on algorithms rather than on data.
True

One of the striking features of object-oriented
programming is the division of programs into
objects that represent real-world entities. True

Wrapping up of data of different types into a single
unit is known as encapsulation. True

One problem with OOP is that once a class is
created, it can never be changed. True

Inheritance means the ability to reuse the data
values of one object by other objects. True

Polymorphism is extensively used in implementing
inheritance. False

Object-oriented programs are executed much faster
than conventional programs. True

Object-oriented systems can scale up better from
small to large. True

Object-oriented approach cannot be used to create
databases. False

List a few areas of application of OOP technology.
OOP can be used for such diverse applications as
Real-time systems, simulation and modeling, AI
and Expert systems parallel programming and
Neural networks, Decision support systems, Office
automation systems and others.


Distinguish between the following terms:
Objects and classes: Object is a physical entity
which represents a person, vehicle or a conceptual
entity (thing in existence) like bank account,
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 mold 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
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 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
data structures and the methods (procedures) which
act on them together is known as encapsulation.
The easiest way to think of encapsulation is to
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, 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 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, morph
means change (or 'form').
Polymorphism is simply a name given to an action
that is performed by similar objects. Polymorphism
allows a common data-gathering message to be
sent to each class and allows each subclass object
to respond to a message format in an appropriate
manner to its own properties. Polymorphism
encourages something we call 'extendibility'. In
other words, an object or a class can have its uses
extended.
Dynamic binding and message passing: Dynamic
binding in java is the mechanism by which
compiler cannot determine which method
implementation to use in advance. Based on the
class of the object, the runtime system selects the
appropriate method at runtime. Dynamic binding is
also needed when the compiler determines that
there is more than one possible method that can be
executed by a particular call.
Java's program units, classes, are loaded
dynamically (when needed) by the Java run-time
system. Loaded classes are then dynamically linked
with existing classes to form an integrated unit.
The lengthy link-and-load step required by third-
generation programming languages is eliminated.
Message Passing: In an object based world the only
way for anything to happen is by objects
communicating with each other and acting on the
results. This communication is called message
passing and involves one object sending a message
to another and (possibly) receiving a result.

What is the task of the main method in a Java
program?
After you specify the keywords for declaring the
main() method, you specify a String array as
parameter of the main() method. The String array
represents command line arguments. It is
compulsory for a user to specify the parameter to
the main() method in all Java programs unlike in C
and C++.
For example,
class class1
{ public static void main (String args[])
{ System.out.println("Hello")
}
}

Why can't we use a keyword as a variable name?
Keywords are an essential part of a language
definition. They implement specific features of the
language. Java language has reserved 60 words as
keywords. These keywords have specific meaning
in Java, so you cannot use them as names for
variables.

Describe the structure of a typical Java program.
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.
A Java program may contain one or more sections
as shown in the following figure:
Documentation Section Suggested
Package Statement Optional
Import Statements Optional
Interface Statements Optional
Class Definitions Essential
Main Method class
{
Main Method Definition
}
Essential
General Structure Of a Java program
Documentation Section: - The documentation
section comprises a set of comment lines giving the
name of the program, the author and other details.
Java also uses the comment /**...*/ known as
documentation comment.
Package Statement: - The first statement allowed
in a Java file is a package statement. This statement
declares a package name and informs the compiler
that the classes defined here belong to this package.
Example: package student;
Import Statement: - The next thing after a
package statement (but before any class
definitions) may be a number of import statements.
This is similar to the #include statement in C++.
Example:
import student.test;
This statement instructs the interpreter to load the
test class contained in the package student.
Interface Statements: - An interface is like a class
but includes a group of method declarations. This
is also an optional section and is used only when
we wish to implement the multiple inheritance
feature in the program.
Class Definitions: - A Java program may contain
multiple class definitions. Classes are the primary
and essential elements of a Java program.
Main Method Class: - Since every Java stand-
alone program requires a main method as its
starting point, this class is the essential part of a
Java program. A simple Java program may contain
only this part. The main method creates objects of
various classes and establishes communications
between them.

Enumerate the rules for creating identifiers in Java.
Java identifiers follow the following rules:
1. They can have alphabets, digits, and the
underscore and dollar sign characters.
2. They must not begin with a digit
3. Uppercase and lowercase letters are distinct.
4. They can be of any length.

What are the conventions followed in Java for
naming identifiers? Give examples.
Conventions for naming Java identifiers are:
1. Identifier name has to be meaningful.
2. There should be no embedded space in an
identifier name.
For example: studentName, employeeID.

Explain the println statement in Java with an
example?
Consider the following statement:
System.out.println ("string to be printed");
The statement begins with System.out. This is a
constant that represents the default output mode,
which in this case is the screen. The constant helps
to read and display the data in a Java program.
The output is generated using the built-in println()
method. The string that is assigned to the println()
method is displayed when the statement is
executed.
For example,
class Class2
{
public static void main (String args[])
{
System.out.println("Here is your string"); } }
The above program will show the following output:
Here is your string

Why is the main() method in Java declared static?
The keyword static helps to specify that the main()
method can be called without instantiating an
object of a class. This is necessary because the
main() method is called by the Java interpreter
before any objects are created.
public static void main (String args[])
{//code}
After specifying the keyword static, you specify the
void keyword. This keyword indicates to the
compiler that, the main() method does not return a
value.

Can null be called an object?
No. A method is not called on a null. For example,
y.p() will give an error if y is null and p is a non-
static method.

What is a token? List the various types of tokens
supported by Java.
All characters are grouped into symbols
called tokens. Java Language includes four types of
tokens. They are:
1. Reserved Keywords
2. Identifiers
3. Literals
4. Operators

Keywords are an essential part of a language
definition. They implement specific features of the
language. Java language has reserved 60 words as
keywords. The following table lists some of the
Java keywords. These keywords have specific
meaning in Java and we cannot use them as names
for variables, classes, methods. All keywords are to
be written in lower case letters. Since Java is case-
sensitive.
synchronization volatile inner* class char
threadsafe* boolean native final else
implements default null** float long
instanceof extends outer* goto* this
Interface false** public rest* var*
operator* finally return short void
protected future* static super for
transient package switch throw int
abstract private throws while new
byvalue* const* true** byte Try
continue double break case do
generic* import catch cast if
* Reserved for future use

Identifiers are used for naming classes, methods,
variables, objects, labels, package and interfaces in
a program.
Examples:
Average
Sum
Batch_strength
Literals in Java are a sequence of characters
(digits, letters, and other characters) that represent
constant values to be stored in variables. Java
language specifies five major types of literals. They
are:
Integer literals
Floating point literals
Character literals
String literals
Boolean literals
Operators: - An operator is a symbol that takes
one or more operands and operates on them to
produce a result.

List the eight basic data types used in Java. Give
examples.
The eight basic data types used in java are:
1. byte: - It is the smallest integer type. This is a
signed 8-bit type and has a range from -128 to
127. For example, the following declaration
declares two variables B and C of type byte.
byte b,c;
b =2;
c = -114;
2. short: - It is a signed 16-bit type and has a
range from -32,768 to 32,767. For example, the
following declaration declares variable K of
type short.
short k;
k = 2;
3. int: - It is a signed 32-bit type and has a range
from -2,147,483,648 to 2,147,483,647.
For example,
int x = 10;
int j = 98;
4. long: - This is signed 64-bit type and has a
range from -263 to 263 -1.
For example,
long ds = 1000;
long se;
se =ds * 24 * 60 * 60;
5. double: - It uses 64 bits to store a value.
For example,
double P, R;
P = 10.8;
R =3.14215;
6. float: - It uses 32 bits to store a value.
For example,
float x;
x = -1111;
7. int: - It uses 32 bits to store a value.
For example,
Int score;
Score=90;
8. char: - This data type is used to store
characters. It is 16-bit type and has a range
from 0 to 65,536.
For example,
char c1,c2;
c1 =84;
c2 ='g';
9. boolean: - It can have only one of two possible
values, true or false.
For example,
boolean flag;
flag= false;

What are the primary object-oriented
methodologies used currently?
The primary object-oriented methodologies are:
BON, FUSION, HOOD, IBM, and UML.
What is scope of a variable?
The area of the program where the variable is
accessible (i.e., usable) is called its scope.
Java variables are actually classified into three
kinds:
1. Instance Variables
2. Class variables
3. Local variables
Instance and class variables are declared inside a
class. Instance variables are created when the
objects are instantiated and therefore they are
associated with the objects. They take different
values for each object. On the other hand, class
variables are global to a class and belong to the
entire set of objects that the class creates.
Variables declared and used inside methods are
called local variables. They are called so because
they are not available for use outside the method
definition. Local variables can also be declared
inside program blocks that are defined between an
opening brace '{' and a closing brace '}'. These
variables are visible to the program only from the
beginning of its program block to the end of the
program block. When the program control leaves a
block, all the variables in the block will cease to
exist.

What is an applet?
Applets are small Java programs developed for
Internet applications. An applet located on a distant
computer (Server) can be downloaded via Internet
and executed on a local computer (Client) using a
Java-capable browser.

Explain with a simple example how to create,
compile and run a program in Java.
Java program involves two steps:
Compiling source code into bytecode using javac
compiler
Executing the bytecode program using java
interpreter
For example, consider the following program
class ProgramDemo
{
public static void main (String args[])
{ System.out.println("Here is your string");
}
}
First, save the program as ProgramDemo.java.
Then, to compile this program type the following
command at command prompt:
C:\Dir1> javac ProgramDemo.java.
Once the program compiles successfully run this
program by typing the following command at
command prompt:
C:\Dir1> java ProgramDemo

What is a constant?
Constants are fixed values that do not change
during the execution of a program. In Java, you can
use the final keyword to specify that the value of a
variable cannot change.
For example,
public static final int x =10;
Here, x is a final variable with value 10.

What is a variable?
A variable is an identifier that denotes a storage
location used to store a data value. Unlike
constants that remain unchanged during the
execution of a program, a variable may take
different values at different times during the
execution of the program.

What is type casting? Why is it required in
programming?
The process of converting one data type to another
is called casting.
Type variable1 = (type) variable2;
Examples:
int m = 50;
byte n = (byte)m;
long distance = (long)m;
Type casting is required in programming when you
want to assign the value of one variable to another
variable of different data type.

Which of the following are invalid constants and
why?
The following are invalid constants:
RS 75.50: It should be written as "RS 75.50"
-1.4e(+4): It should be written as -1.4e+4

Which of the following are invalid variable names
and why?
The following are invalid variable names:
1. first.Name: Variable name should not have a
period in between
2. n1+ n2: Variable name should not have a '+' in
between
3. 3rd -row: Variable name should not begin with
a digit
4. float: Variable name should not be a keyword
5. Sum Total: Variable name should not have an
embedded space
6. Total-Marks: Variable name should not have a
'-' in between. It can only have the underscore
sign.
Find errors, if any, in the following declaration
statements:
int x;
float length, height;
double = p,q;
character c1;
final int total;
final pi = 3.142;
long int m;
The statements that contain errors are:
double = p,q;
character c1;
final pi = 3.142;
long int m;

Write a program to determine the sum of the
following harmonic series for a given value of n:
1+1/2 + 1/3+ ..............+1/n
The value of n should be given interactively
through the keyboard.
public class Series
{
double total;
public void calculate(int n)
{
for(double ctr=1;ctr<=n;ctr++)
{
total=total+1/ctr;
}
System.out.println("Sum of harmonic series:
"+total);
}
public static void main(String a[])
{
Series object=new Series();
int num=Integer.parseInt(a[0]);
object.calculate(num);
}
}

Write a program to convert the given temperature
in Fahrenheit to Celsius using the following
conversion formula
F-32
C = 1.8 and display the values in a tabular form.
public class Celsius
{
double celsius;
double fahrenheit;
public Celsius()
{
fahrenheit=98.4;
}
public void convert()
{
celsius=(fahrenheit-32)/1.8;
System.out.println("Temperature in celsius:
"+celsius);
}
public static void main(String a[])
{
Celsius object=new Celsius();
object.convert();
}
}

Which of the following arithmetic expressions are
valid?
a) 25/3 % 2 e) -14 % 3
b) +9/4 + 5 f) 15.25 + -5.0
c) 7.5 % 3 g) (5/3) * 3 + 5 % 3
d) 14 % 3 + 7 % 2 h) 21 % (int) 4.5
All of the above arithmetic expressions are valid.

Identify unnecessary parenthesis in the following
arithmetic expressions.
(a) (x-(y/5)+z) % 8) + 25
(b) ((x-y) * p) + q
(c) (m*n) + (-x/y)
(d) x/(3*y)
a) (x-(y/5)+z) % 8) + 25: - The parenthesis after 8
in this expression has no opening parenthesis.
b) ((x-y) * p) + q: - It can also be written (x-y)*p
+q
c) (m*n) + (-x/y): - It can also be written m*n +-
x/y
d) x/(3*y).: - No unnecessary parenthesis is there
in it.

Find errors, if any, in the following assignment
statements and rectify them.
(a) x = y = z = 0.5, 2.0 5.75
(b) m = ++a * 5;
(c) y = sqrt(100);
(d) p * x/y;
(e) s = /5;
(f) a = b++ - c * 2
(a) x = 0.5, y = 2.0, z = 5.75;
(b) m = ++a * 5;
(c) y = sqrt(100);
(d) p* = x/y;
(e) s/ = 5;
(f) a = b++ - c * 2;

Determine the value of each of the following
logical expressions if a=5, b=10 and c=-6
1. a>b && a<c False

2. a<b && a>c True

3. a==c || b>a True

4. b>15 && c<0 || a>0 True

5. (a/2.0 == 0.0 && b/2.0 != 0.0) || c< 0.0 True
The straight-line method of computing the early
depreciation of the value of an item is given by
Depreciation = Purchase price Salvage value /
Years of service the purchase price, years of
service, and the annual depreciation are given.
class Depreciation
{
double PurchasePrice;
double SalvageValue;
double DepricatValue;
int Years;
public double Salvage(double PurchasePrice,
double DepricatValue, int Years)
{
return PurchasePrice - (DepricatValue * Years);
}
public static void main(String args[])
{
Depreciation dep = new Depreciation ();
System.out.println("The salvage value is: " +
dep.Salvage(2000.00, 250.00, 5));
}
}

The total distance traveled by a vehicle in t seconds
is given by
Distance = ut + (at2)/2
Where u is the initial velocity (metres per second),
a is the acceleration (metres per second). Write a
program to evaluate the distance traveled at regular
intervals of time, given the values of u and a. The
program should provide the flexibility to the user to
select his own time intervals and repeat the
calculations for different values of u and a.
import java.io.*;
class Distance
{
int a;
int t;
int u;
int dist;
public Distance()
{
a = 10;
u = 10;
}
public void calculate(){
try
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter time (sec): ");
t = Integer.parseInt(br.readLine());
dist = (u*t) + (a*t*t)/2;
System.out.println("The distance is : " + dist + "
meters");
}
catch(Exception e)
{
System.out.println("error");
} }
public static void main(String arg[])
{
Distance d = new Distance();
d.calculate();
} }

In inventory management, the Economic Order
Quality for a single item is given by
2*demand rate*setup costs
EOQ
Holding cost per item per unit time


and the optimal Time Between Orders
2*setup costs
TBO
demand rate*holding cost per unit time


Write a program to compute EOQ and TBO, given
demand rate (items per unit time), setup costs (per
order), and the holding cost (per item per unit
time).
class InvenManagement
{
int DemandRate;
double SetupCost;
double HoldCost;
public double EOQ(double SetupCost, double
HoldCost, int DemandRate)
{
double value =
(2*DemandRate*SetupCost)/HoldCost;
return Math.sqrt(value);
}
public double TBO(double SetupCost, double
HoldCost, int DemandRate)
{
double value =
(2*SetupCost)/(DemandRate*HoldCost);
return Math.sqrt(value);
}
public static void main(String args[])
{
InvenManagement IM = new InvenManagement();
System.out.println("The value of EOQ is: " +
IM.EOQ(10000.00, 3000.00, 5));
System.out.println("The value of TBO is: " +
IM.TBO(10000.00, 3000.00, 5));
}
}

In what ways does a switch statement differ from
an if statement?
An if statement can be used to make decisions
based on range of values or conditions, whereas a
switch statement can make decisions based only on
a single integer value. Also, the value provided to
each case statement must be unique.
0.001 5*1.5 RS 75.50
+100 75.42E-2 "15.75"
-45.6 -1.4e(+4) 0.000001234
Minimum first.Name n1+ n2
Doubles 3rd row N$
Float Sum Total Total-Marks
Determine whether the following are true or false.
When if statements are nested, the last else gets
associated with the nearest if without an else. True

One if can have more than one else clause. False

A switch statement can always be replaced by a
series of if....else statements. True

A switch expression can be of any type. False

A program stops its execution when a break
statement is encountered. False

Find errors, if any, in each of the following
segments;
1. if (x+y = z && y > 0)
This is not a valid expression. x+y =z and y>0 must
be enclosed in parenthesis.

2. if (code>1);
a = b+c
else
a = 0
It will give an error because of the semicolon
present after the if statement.

3. if (p < 0) || (q < 0)
This statement needs to be written as:
if ( (p < 0) || (q < 0))

Rewrite each of the following without using
compound relations:
1. if (grade < = 59 && grade >=50)
second = second + 1
If (grade < = 59)
{ if (grade> =50)
second = second + 1;
}

2. if (number > 100 && number < 0)
System.out.print("Out of range");
else
Sum = sum + number;
if (number > 100 )
{ if (number < 0 )
System.out.print("Out of range");
}
else
Sum = sum + number;
}

3. if ((M1>60 && M2>60 || T >200)
y=1;
else
y=0;
if(T>200)
{ y =1;
}
else if(M1>60)
{
if(M2>60)
{ y =1;
}
else y =0;
}

Write a program to find the number of and sum of
all integers greater than 100 and less than 200 that
are divisible by 7.
public class Divisible
{
int num;
int sum;
public void calculate()
{
sum=0;
System.out.println("Numbers divisible by 7:");
for(num=100;num<200;num++)
{
if(num%7==0)
{
System.out.println(num);
sum=sum+num;
} }
System.out.println("Sum: "+sum);
}
public static void main(String a[])
{
Divisible obj=new Divisible();
obj.calculate();
} }

Write a program to compute the sum of the digits
of a given integer number
public class Sum
{
int arr[];
int r=0,i=0,sum=0;
public void calculate(int num)
{arr=new int[5];
while(num%10>0)
{r=num%10;
arr[i]=r;
i++;
num=num/10;
sum=sum+r;
}
System.out.println("Sum: "+sum);
}
public static void main(String a[])
{ int number=Integer.parseInt(a[0]);
Sum obj=new Sum();
obj.calculate(number);
} }
Given a list of marks ranging from 0 to 100, write a
program to compute and print the number of
students who have obtained marks
(a) in the range 81 to 100,
(b) in the range 61 to 80,
(c) in the range 41 to 60, and
(d) in the range 0 to 40.
The program should use a minimum number of if
statements.
import java.io.*;
public class StudentMarks
{
int r1=0;
int r2=0;
int r3=0;
int r4=0;
int rn=1;
static BufferedReader br;
public StudentMarks(int num)
{
int arr[]=new int[num];
try
{
for(int i=0;i<arr.length;i++)
{
System.out.println("enter the marks for Roll
number"+ rn);
arr[i]=Integer.parseInt(br.readLine());
rn++;
}
for(int j=0;j<arr.length;j++)
{
if(arr[j]>=0 && arr[j]<=40)
{
r1++;
}
else if(arr[j]>40 && arr[j]<=60)
{
r2++;
}
else if(arr[j]>60 && arr[j]<=80)
{
r3++;
}
else if(arr[j]>80 && arr[j]<=100)
{
r4++;
}
}
System.out.println("Students securing marks in the
range of 0-40 are\t"+r1);
System.out.println("Sudents securing marks in the
range of 40-60 are\t"+r2);
System.out.println("Sudents securing marks in the
range of 60-80 are\t"+r3);
System.out.println("Sudents securing marks in the
range of 80-100 are\t"+r4);
}//end of try
catch(Exception exp)
{
System.out.println(exp);
}//end of catch
}//end of constructor
public static void main(String args[])
{
try
{
br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the total number of
students in the class");
int total_students=Integer.parseInt(br.readLine());
StudentMarks sm=new
StudentMarks(total_students);
}//end of try
catch(Exception exp)
{
System.out.println(exp.getMessage());
}//end of catch
}//end of main
}//end of class

Compare in terms of their functions, the following
pairs of statements:
(a) while and do........while.
(b) while and for.
(c) break and continue.
a) The difference between the do-while statement
and the while statement is that in the while
statement, the loop body is executed only when
the condition stated in the statement is true. In
the do-while loop, the loop body is executed at
least once, regardless of the condition
evaluating to true or false. The while loop is
also called the top tested loop whereas the do-
while loop is also called the bottom tested loop.
b) In the for loop, three sections, initialization, test
condition and increment/decrement are placed
in the same line whereas in the while loop, all
three sections are placed in three different
places in a program. In the for loop, more than
one variable can be initialized, tested and
incremented at a time.
c) 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. The break statement immediately
terminates the loop, bypassing the conditional
expression and any remaining code in the body
of the loop. When a break statement is
encountered inside the loop, the loop is
terminated and program control resumes the
next statement following the loop.
A cloth showroom has announced the following
seasonal discounts on purchase of items:
import java.io.*;
class purchase
{
double bill;
String str;
String str_discount="";
public purchase()
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the amount of Bill: ");
bill=Double.parseDouble(br.readLine());
System.out.println("Enter the types of clothe: ");
str = br.readLine();
if (str.equalsIgnoreCase("handloom"))
{
if(bill >=0 && bill <=100)
{
bill = bill- (bill*5)/100;
str_discount="5 %";
}
if( bill >100 && bill <=200)
{
bill = bill - (bill*7.5)/100;
str_discount="7.5 %";
}
if(bill >200 && bill<=300)
{
bill = bill - (bill*10)/100;
str_discount="10 %";
}
if (bill > 300)
{
bill = bill - (bill*15)/100;
str_discount="15 %";
}}
if(str.equalsIgnoreCase("mill"))
{
System.out.println("enter");
if(bill >=0 && bill <=100)
{
bill = bill;
str_discount="0 %";
}
if( bill >100 && bill <=200)
{
bill = bill - (bill*5)/100;
str_discount="5 %";
}
if(bill >200 && bill<=300)
{
bill = bill - (bill*7.5)/100;
str_discount="7.5 %";
}
if (bill > 300)
{
bill = bill - (bill*10)/100;
str_discount="10 %";
} }
System.out.println("The Discount is: " +
str_discount);
System.out.println("The final bill after discount is:
" + bill);
}
catch(Exception e)
{
System.out.println("Exception is :"+e);
}}
public static void main(String args[])
{
purchase pur = new purchase();
}}

Given a number, write a program using while loop
to reverse the digits of the number.
For examples, the number 12345 should produce
an output 54321.
public class Reverse
{
int num;
int arr[],arr1[];
int r=0,i=0;
int len=0;
public void calculate(int num)
{ int num1=num;
arr=new int[5];
arr1=new int[5];
while(num1%10>0)
{ r=num1%10;
arr[i]=r;
i++;
num1=num1/10;
}
len=i;
int j,b,k=i;
System.out.print("Reverse Number:");
for (int a=0;k>0;a++,k--)
{ arr1[a]=arr[k-1];
System.out.print(arr[a]);
} }
public static void main(String arg[])
{ int number=Integer.parseInt(arg[0]);
Reverse obj=new Reverse();
obj.calculate(number);
} }
Analyze each of the program segments that follow
and determine how many times the body of each
loop will be executed.
1. x = 5;
y = 50;
while(x <= y) {
x = y / x;
.
.
}
Infinite

2. m = 1;
do {

.
m = m + 2;
}while (m < 10)
Five

3. int i;
for (i=0; i<=5; i= i+2/3)
{
.
.
}
Infinite

4. int m = 10
int n= 7;
while ( m % n >= 0)
{
..
m = m + 1;
n = n + 2;
.
}
Infinite

What is class? How does it accomplish data
hiding? Differentiate between instance and class
variables of a Java class.
Class is a template that defines a particular type of
object. Classes contain all the features of a
particular set of objects. We can use the class
definition to create objects of that of class type, that
is, to create objects that incorporate all the features
belonging to that class.
Data hiding is one of the important aspects of a
class. Data hiding means to hide the members of
the class and providing the access to only some of
them. We can make the members of the class
private or public. In private, the outside world
cannot access those members which have been
made private and rest we can make public only the
public members are accessed by the outside world
and all the private members can be accessed using
only the public members.in this way a class
provides security to its data members.
Each object of the class will have its own copy of
each of the instance variables that appear in the
class definition. Each object will have its own
values for each instance variable. The name
'instance variable' originates from the fact that an
object is an 'instance' or an occurrence of a class
and the values stored in the instance variables for
the object differentiate the object from others of the
same class type. An instance variable is declared
within the class definition in the usual way, with a
type name and a variable name, and can have an
initial value specified.
A given class will only have one copy of each of its
class variables, and these will be shared between
all the objects of the class. The class variables exist
even if no objects of the class have been created.
They belong to the class, and they can be
referenced by any object or class, and not just
instances of that class.

Write a program in java to calculate the area and
circumference of a circle
import java.swing.*;
import java.util.Scanner;
public class CircleAreaWithInput
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter radius:");
double radius = sc.nextDouble();
double area = Math.PI * radius * radius;
double circ = Math.PI * radius * 2; //circumference
System.out.println("Here's the result!");
System.out.println("Radius: " + radius);
System.out.println("Area: " + area);
System.out.println("Circumference: " + circ);
}
}

Write a program in java to calculate the perimeter
of a rectangle
public class PerimiterCalculator
{
public static void main(String[] args)
{
if (args.length != 2)
{
System.out.println("Need 2 args: <length side one>
<width side two>");
System.exit(0); }
int sideOne = Integer.parseInt(args[0]);
int sideTwo = Integer.parseInt(args[1]);
System.out.println((sideOne*2)+(sideTwo*2));
System.out.println(sideOne*sideTwo); //area
} }
Purchase
Amount
Discount
Mill Cloth Handloom Items
0-100 - 5.0%
101-200 5.0% 7.5%
201-300 7.5% 10.0%
Above 300 10.0% 15.0%
Write a program to read the price of an item in
decimal form (like 75.95) and print the output in
paise (7595 paise).
import java.io.*;
import java.util.*;
public class rsTOpaise
{
public static void main(String args[])
{
int paise,mantisa;
float rs,exponent;
String s;
try{
BufferedReader ob1 = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter no. of Rupees : ");
System.out.flush();
s=ob1.readLine();
rs=Float.parseFloat(s);
mantisa=(int)rs;
exponent=rs-(float)mantisa;
paise=(int)((mantisa*100) + (exponent*100));
System.out.println(rs+" Rupees equals to "+paise+"
Paise");
}
catch (Exception e)
{} } }
How do classes help us to organize our programs?
In essence a class definition is very simple. There
are just two kinds of things that you can include in
a class definition:
Variables
Variables are the data types that store data items
that typically differentiate one object of the class
from another. They are also referred to as data
members of a class. Every class you write in Java
is generally made up of two components: attributes
and behavior. Let's consider an object to define a
motorcycle. Attributes are the individual things that
differentiate one object from another and determine
the state, appearance, or other qualities of that
object. The attributes of our motorcycle might
include:
color: red, green, silver, brown.
make: Honda, BMW, Bultaco.
engineOn: true, false.
Attributes are defined by variables, in fact, you can
consider them because each instance of a class can
have different values for its variables, each variable
is called an instance variable.
Methods
These define the operations you can perform for
the class--so they determine what you can do to, or
with, objects of the class. Methods typically
operate on the fields--the variables of the class. A
class's behavior determines what instances of that
class do when asked to by another class or object.
Behavior is the only way that objects can have
anything done to them. Our motorcycle class might
well have the following behavior:
Start the engine
Stop the engine
Speed up
Change gear
To define an object's behavior you create methods.

How is a method defined?
A method is a group of programming language
statements that are given a name. A method is
associated with a particular class. The syntax of a
method is:
modifier(s) return-type method-name (parameter-
list)
{
statement-list
}

When do we declare a member of a class static?
A member of a class can be created that can be
used without referencing to a specific instance.
Such a member is created by preceding its
declaration with the keyword static. A member
declared as static can be accessed without
referencing to any other objects of class and before
creating any objects of its class. Methods and
variables both can be declared as static. The most
common example of static member, main() is
declared static as it is called before any objects
exist. All instance variables that are declared as
static are global variables.

What is a constructor? What are its special
properties?
The central player in object initialization is the
constructor. In Java, constructors are similar to
methods, but they are not methods. Like a method,
a constructor has a set of parameters and a body of
code. Unlike methods, however, constructors have
no return type. Like methods, you can give access
specifiers to constructors, but unlike methods,
constructors with public, protected, or package
access are not inherited by subclasses. (Also,
instead of determining the ability to invoke a
method, the access level of a constructor
determines the ability to instantiate an object.)
The special properties of a constructor are:
1. Constructor- names are the same as the name of
the class.
2. Constructor does not specify a return type.

Is it necessary for an if statement to have an else
statement?
No. However, an else statement must be preceded
by an if statement.
What are objects? How are they created from a
class?
An object in java is a block of memory that
contains a space to store all the instance variables.
As with real-world objects, software objects have
state and behavior. In programming terms the state
of an object is determined by its data (variables);
the behavior by its methods. Thus a software object
combines data and methods into one unit.
Creating an object is referred to as instantiating an
object. The creating object to a class is two-step
process:
1. Declare a variable of class type. This variable
does not define an object instead it is a simply a
variable that can refer to an object.
2. Physical copy of the object is created and
assigned to that variable.

How do we invoke a constructor?
The name of the constructor needs to be same as
the name of class in which the constructor is
declared.
For example, to define a zero-parameter
constructor for the Box class, you would write the
following:
No return type specified
Constructor name is the same as
class name

public Box ( )
{
... }
You can invoke the constructor box() by writing
Box b = new Box();
To create a box instance, you deploy the new
keyword with the class name and a pair of
parentheses, as shown in the following expression:
*-- Keyword
*--Class name

new box( )

What is inheritance and how does it help us create
new classes quickly?
Inheritance refers to the properties of a class being
available to other classes as well. The original class
is called Base Class and Derived classes are classes
created from the existing class (Base Class). It will
have all the features of the Base class. The concept
of inheritance is very important in object-oriented
programming languages. It 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;
Methods declaration;
}
The keyword extends signifies that the properties
of the superclass are extended to the 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.

What is an array?
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 array is called index. So
the third item in an array would be at index 2 (0,
1,2).

Why are arrays easier to use compared to a bunch
of related 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.
Arrays have following advantages over bunch of
related variables:
Arrays of any type can be created. They can have
one or more dimensions.
Any specific element can be indexed in an array by
its index.
All like type variables in an array can be referred
by a common name.

Find errors, if any, in the following code segments:
int m;
int x[ ] =int [10];
int [ ] y =int [11];
for (m=1;m<=10; ++m)
x[m]=y[m]=m;
x=y=new int[20];
for (m=0; m<10; ++m)
System.out.println(x[m])
The errors in the above statements are mentioned
as comments as follows:
int m;
int x[ ] =int [10]; //array created without using new
keyword
int [ ] y =int [11]; // array created without using
new keyword
for (m=1;m<=10; ++m)
x[m]=y[m]=m; //array can not be assigned values
before they are created.
x=y=new int[20];
for (m=0; m<10; ++m)
System.out.println(x[m])
Write a statement to declare and instantiate an
array to hold marks obtained by students in
different subjects in a class. Assume that there are
up to 60 students in a class and there are 8 subjects.
int marks[][]=new int[60][8]

Design a class to represent a bank account. Include
the following member:
Data members
Name of the depositor
Account Number
Type of account
Balance amount in the account
Methods
To assign initial values
To deposit an amount
To withdraw an amount after checking balance
To display the name and balance
import java.io.*;
public class Bank
{
String name;
String accNo;
String accType;
double balance=0;
String amount;
public void input()
{
try{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the Name of a Account
Holder");
name=br.readLine();
System.out.println("Enter the Account Number of a
Account Holder");
accNo=br.readLine();
System.out.println("Enter the Account Type of a
Account Holder");
accType=br.readLine();
System.out.println("Enter the Amount to be
deposited");
amount=br.readLine();
double balance=Double.parseDouble(amount);
}
catch(IOException g){}
}
public void deposit()
{
try{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the Amount to be
deposited");
amount=br.readLine();
double amt=Double.parseDouble(amount);
balance=balance+amt;
System.out.println("Balance: "+balance);
}
catch(IOException e){}
}
public void withdraw()
{ try{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the Amount to be
withdrawl");
amount=br.readLine();
double amt=Double.parseDouble(amount);
balance=balance-amt;
System.out.println("Balance: "+balance);
}
catch(IOException e){}
}
public void display()
{
System.out.println("Account Holder Details");
System.out.println("----------------------");
System.out.println("Name: "+name);
System.out.println("Balance: "+balance);
}
public static void main(String a[])
{
Bank object=new Bank();
while(true)
{ System.out.println("Menu");
System.out.println("1. Enter Details");
System.out.println("2. Deposit Amount");
System.out.println("3. Withdraw Amount");
System.out.println("4. Exit");
try{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the Amount to be
withdrawl");
char ch=(char)br.read();
switch(ch)
{
case '1':
object.input();
break;
case '2':
object.deposit();
break;
case '3':
object.withdraw();
break;
case '4':
System.exit(0);
} }
catch(IOException e){}
}
}
}

Describe different forms of inheritance with
examples.
The two forms of inheritance are:
1. Single- level inheritance
2. Multiple- level inheritance
Single-Level Inheritance: -
In this form of inheritance, there is only one
subclass as an extended subclass of the superclass.
A subclass is defined as follows
class subclass extends superclass
{
Variables declaration;
Methods declaration;
}
The keyword extends signifies that the properties
of superclass are extended to the 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.
import java.io.*;
//super class declaration
class book
{
String name;
int id;
void showsuper( )
{ System.out.println("the id and name of the book
is :" +id+ " " + name);
} }
class book1 extends book
{ String author;
void showderived( )
{ System.out.println("the author name is:"
+author);
} }
class simpleinhertence {
public static void main(String args[ ])
{ book superob=new book( );
book1 subobj = new book1( );
superob.id=10;
superob.name="java";
System.out.println("the contents of super object
is");
superob.showsuper( );
System.out.println( );
subobj.id=20;
subobj.name="c programming";
subobj.author="Balaguruswamy";
System.out.println("the contents of the subobj:");
subobj.showsuper( );
subobj.showderived( );
} }
Result:
The contents of super object is
The id and name of the book is: 10 java
The contents of the subobj:
The id and name of the book is : 20 c programming
The autor name is: Swamy

Multiple-Level Inheritance: -
In this form of inheritance, subclass is further
extended. This means, that there are subclasses of a
subclass.
The general form of class declaration that further
inherits the subclass is shown here:
class subclass-name extends superclass-name
{ body of the class
}
class subclass-name1 extends subclass-name
{ body of the class
}
For example, the following program shows the
multiple inheritance.
import java.io.*;
//super class declaration
class book
{ String name;
int id;
void showsuper( )
{ System.out.println("the id and name of the book
is :" +id+ " "+name);
} }
class book1 extends book
{
String author;
void showderived( )
{ System.out.println("the author name is:"
+author);
} }
class book2 extends book1
{ void showderived1( )
{ System.out.println("This is multilevel
inheritance"); } }
class simpleinhertence
{ public static void main(String args[ ])
{book superob=new book( );
book1 subobj = new book1( );
book2 subobj1 = new book2( );
superob.id=10;
superob.name="java";
System.out.println("the contents of super object
is");
superob.showsuper( );
System.out.println( );
subobj.id=20;
subobj.name="c programming";
subobj.author="Balaguruswamy";
System.out.println("the contents of the subobj:");
subobj.showsuper( );
subobj.showderived( );
subobj1.showdeived1();
}}

An election is contested by 5 candidates. The candidates are
numbered 1 to 5 and the voting is done by marking the
candidate number on the ballot paper. Write a program to
read the ballots and count the votes cast for each
candidate using an array variable count. In case, a
number read is outside the range 1 to 5, the ballot should be
considered as a 'spoilt ballot' and the program should also
count the number of spoilt ballots.
import java.io.*;
public class Election
{ int count, i, candidate1, candidate2, candidate3,
candidate4, candidate5, spoilt;
public Election(){
count = 0;
i = 0;
candidate1 = 0;
candidate2 = 0;
candidate3 = 0;
candidate4 = 0;
candidate5 = 0;
spoilt = 0; }
public void electionCount(){
while(true){
try{
System.out.println("Enter integer between 1 to 5 to
vote a candidate");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
i = Integer.parseInt(br.readLine());
if ((i>5)||(i<1)){
System.out.println("Enter a valid vote id between 1
to 5");
spoilt++;
count++; }
else if(i==1){
candidate1++;
count++; }
else if(i==2){
candidate2++;
count++; }
else if(i==3){
candidate3++;
count++; }
else if(i==4){
candidate4++;
count++; }
else if(i==5){
candidate5++;
count++;}
System.out.println("Spoilt = "+spoilt);
System.out.println("Candidate1 = "+candidate1);
System.out.println("Candidate2 = "+candidate2);
System.out.println("Candidate3 = "+candidate3);
System.out.println("Candidate4 = "+candidate4);
System.out.println("Candidate5 = "+candidate5);
System.out.println("Total : "+count);
System.out.println("Do you want to continue(y/n):
");
char ch = (char)br.read();
if(ch == 'n'||ch == 'N') break;
}catch(Exception e){System.out.println("Error");
} } }
public static void main(String arg[]){
Election e = new Election();
e.electionCount(); } }

Distinguish between Multiprocessing and
Multithreading.
Multiprocessing: - Refers to a computer system's
ability to support more than one process (program)
at the same time. Multiprocessing operating
systems enable several programs to run
concurrently Multiprocessing systems are much
more complicated than single-process systems
because the operating system must allocate
resources to competing processes in a reasonable
manner.
Multithreading: - The ability of an operating
system to execute different parts of a program,
called threads, simultaneously. The programmer
must carefully design the program in such a way
that all the threads can run at the same time without
interfering with each other.

Describe the life cycle of a Thread?
Thread exists in several states. A thread that has
been just created is in the born state. The thread
remains in this state until the thread's start method
is called. This causes the thread to enter the
runnable (ready) state when the system assigns a
processor to the thread. A thread enters the dead
state when its run method completes or terminates
for any reason. When a sleep method is called in a
running thread, that thread becomes ready after the
designated sleep time expires. Even if a processor
is available, sleeping thread cannot use it.
A running thread can enter a blocked state. One
common way is when thread issues an input/output
request. In this case, a blocked thread becomes
ready when the I/O it is waiting for completes.
When a running thread calls wait, the thread enters
a waiting state for the particular object on which
'wait' was called. A thread in the 'waiting' state for
a particular object becomes ready on a call to
'notify' issued by another thread associated with
that object.
A thread enters the 'dead' state when its 'run'
method is either completed or throws an uncaught
exception.

Do you need to close the Reader stream explicitly
when the StreamTokenizer reaches the end of the
stream?
Yes, you need to close the Reader stream explicitly
when the StreamTokenizer reaches the end of the
stream.
Explain about:
Comparison of two strings
Concatenation of two strings
Comparison of two strings
To compare two strings for equality, use equals().
It has the general form:
boolean equals(object str);
Here, str is the string object being compared with
the invoking String object.
It returns true if the string contains the same
characters in the same order
compareTo( )
Often, it is not enough to simply know whether two
strings are identical.
For sorting applications, we need to know which is
less than, equal to, or greater than the next. The
compareTo( ) method of the String class serves this
purpose. It has the general form of
compareTo(String str).

Value Meaning
value less than
zero
the invoking string is less
than str
greater than
zero
the invoking string is greater
than str
Zero the two string are equal
Class EqualsDemo {
public static void main(String args[ ]) {
String s1="Hello";
String s2="Hello";
String s3="bye";
System.out.println("COMPARE STRINGS");
System.out.println(s1 + "equals" + s2 + "->" +
s1.eqals(s2));
System.out.println(s1 + "equals" + s3 + "->" +
s1.eqals(s3));
if (name1.compareTo(name2)==0)
System.out.println("the same");
else System.out.println("not the same");
} }

Concatenation of two strings
String manipulation is something we do quite often
in our applications. One of the simplest methods to
concatenate two Strings is by using the '+' operator.
To append String s2 to s1 we simply use:
s1 += s2
But Java provides more ways for concatenating
Strings. The String class contains a instance
method named concat(String s). To add a new
String to a existing String we would code
something like this:
s1.concat(s2);
public class Test {
public static void main(String arg[ ]) {
String s1 = new String("sachin");
String s2 = new String("tendulkar");
System.out.println("First String: " + s1);
System.out.println("Second String: " + s2);
s1 = s1.concat(s2);
System.out.println("Concatenated: " + s1); } }
Output:
First String: Sachin
Second String: Tendulkar
Concatenated: Sachin Tendulkar

Explain the methods:
trim
The trim method returns a copy of the invoking
string from which any leading and trailing white
space has been removed. It has the general form
String trim ( );
class altStr{
public static void main (String args[ ])
{String str = "Hello";
String str2 = "Java";
str = str.toUpperCase();
str2 = str2.toLowerCase();
System.out.println (str);
System.out.println (str2);
str = str.concat(str2); System.out.println (str);
str = str.trim();
System.out.println (str);
str = str.substring (5,str.length()); // str = "java"
System.out.println (str);
str = str.replace ('a', 'i'); // str = "jivi"
System.out.println (str); } }

substring
The subString method is used to create new
instances of the class String from existing
instances. The new string is specified by giving the
required index range within the existing string.
String substring(int startIndex)
This returns the sub string that starts at startIndex
and runs to the end of the invoking string.
String substring(int start Index, int endIndex)
This returns the substring that starts at startindex
and runs through endIndex-1;

length
The length of a string is the number of characters
that it contains. To obtain this value call a length
method.
int length();
class strCmp {
public static void main (String args[ ]) {
String str = "Hello";
String str2 = "Java";
System.out.println (str.equals(str2)); // false
System.out.println (str.compareTo(str2));
System.out.println (str.charAt(0));
System.out.println (str.length() + str2.length());
}
}
What is a package?
Packages are containers for classes that can be
shared by Java programs. Packages are stored in a
hierarchical manner and are explicitly imported
into new class definitions.
Packages are Java's way of grouping a variety of
classes and/or interfaces together. The grouping is
done according to functionality. By organizing the
classes into packages, we get the following
benefits:
Classes contained in packages of other programs
can be reused.
Two classes in two different packages can have the
same name.
Packages provide a way to hide classes.
Designing is separated from coding by the use of
packages.

Write a procedure to create your own package.
The procedure to create your own package is:
Declare the package at the beginning of a file using
the package keyword.
package <package_name>
Define the class that is to be put into the package
and declare it public.
Create the subdirectory under the directory where
the main source file is stored.
Store the listing as the class_name.java file in the
subdirectory.

Define interface. How can multiple inheritance be
implemented using interfaces?
Interfaces are syntactically similar to classes but
they lack instance variables, and their methods are
without any body. Once an interface is defined, any
number of classes can implement it.
An interface only defines a method's name, return
type, and arguments. It does not include executable
code. An interface is defined using the interface
keyword.
Java does not support multiple inheritance. This
means that classes in Java cannot have more than
one superclass. However, there could be a situation
where a class needs to inherit from more than one
class. In such a situation you use interfaces. One
class can implement any number of interfaces.

What is a file? Why do we require files to store
data?
File is a collection of information, such as text,
data or images saved on a storage device such as a
disk or hard drive. Output from a program may go
to screen or the printer, which will not be
permanently stored. In order to store the data
permanently we require files to store the data.

What is a stream class? How are the stream classes
classified?
The java.io package contains a large number of
stream classes that provide capabilities for
processing all types of data. These classes may be
categorized into two groups based on the data type
on which they operate.
1. Byte stream classes that provide support for
handling I/O operations on bytes.
2. Character stream classes that provide support
for managing I/O operations on characters.
These two groups may further be classified based
on their purpose. Byte stream and character stream
classes contain specialized classes to deal with
input and output operations independently on
various types of devices. We can also cross-group
the streams based on the type of source or
destination they read from or write to. The source
(or destination) may be memory, a file or pipe.

What are input and output streams? Explain them
with illustrations.
As you know, all Java programs automatically
import the java.lang package. This package defines
a class called System, which encapsulates several
aspects of the run-time environment.
System.out refers to the standard output stream. By
default, this is the console. System.in refers to
standard input, which is the keyboard by default.
System.err refers to the standard error stream,
which also is the console by default. However,
these streams may be redirected to any compatible
I/O device.
System.in is an object of type InputStream;
System.out and System.err are objects of type
PrintStream. These are byte streams, even though
they typically are used to read and write characters
from and to the console. As you will see, you can
wrap these within character-based streams, if
desired.

What is a stream? How is the concept of streams
used in Java?
In Java, streams represent the ordered sequence of
data. A stream is a path along which data flows
(like a river or a pipe along which water flows). It
has a source (of data) and a destination (for that
data). Both the source and the destination may be
physical devices or programs or other streams in
the 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 in Java presents a uniform, easy-
to-use, object-oriented interface between the
program and the input/output devices.


Write a program to implement the set name method
of a thread class.
public class CurrentThreadDemo
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " +t);
t.setName("MyThread");
System.out.println("After name change: " +t);
try
{
for(int n=5;n>0;n--)
{
System.out.println(n);
Thread.sleep(10);
}
}
catch(InterruptedException e)
{
System.out.println("Main Thread Interrupted");
}
}
}
Result:
Current thread: Thread[main,5,main]
After name change: Thread[MyThread,5,main]
5 4 3 2 1

How do we design a package.
Designing or creating a packaging is quite easy.
First declare the name of the package using the
package key word followed by a package name.
This statement defines a name space in which
classes are stored. It is followed by package
definition. Here is an example,
package world;
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World");
} }

Discuss various levels of access protection
available for packages and their implications.
Java addresses four categories of visibility for class
members.
1. Subclasses in the same package
2. Non subclasses in the same package
3. Subclasses in different packages
4. Classes that are neither in the same package nor
subclass.
The three access specifiers private, public and
protected provides a variety of ways to produce
many levels of access required. The below
mentioned table, sum up the interaction.
Default Private Public Protected
Same class Yes Yes Yes Yes
Same Package
Subclass
Yes No Yes Yes
Same Package
Non-Subclass
Yes No Yes Yes
Different Package
Subclass
No No Yes Yes
Different Package
Non-Subclass
No No Yes No
Class Member Access
The four access levels are:
1. Default: Visible to the package. The default.
No modifiers are needed.
2. Private: Visible to the class only.
3. Public: Visible to the world.
4. Protected: Visible to the package and all
subclasses.

Default Access Modifier - No keyword: Default
access modifier means we do not explicitly declare
an access modifier for a class, field, method, etc.
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.
Example: Variables and methods can be declared
without any modifiers, as in the following
examples:
String version = "1.5.1";
boolean processOrder() {
return true;
}

Private Access Modifier - private: Methods,
Variables and Constructors that are declared
private can only be accessed within the declared
class itself.
Private access modifier is the most restrictive
access level. Class and interfaces cannot be private.
Variables that are declared private can be accessed
outside the class if public getter methods are
present in the class.
Using the private modifier is the main way that an
object encapsulates itself and hides data from the
outside world.
Example: The following class uses private access
control:
public class Logger {
private String format;
public String getFormat() {
return this.format;
}
public void setFormat(String format) {
this.format = format; } }
Here, the format variable of the Logger class is
private, so there's no way for other classes to
retrieve or set its value directly.
So to make this variable available to the outside
world, we defined two public methods:
getFormat(), which returns the value of format, and
setFormat(String), which sets its value.

Public Access Modifier - public: A class, method,
constructor, interface etc declared public can be
accessed from any other class. Therefore fields,
methods, blocks declared inside a public class can
be accessed from any class belonging to the Java
Universe.
However if the public class we are trying to access
is in a different package, then the public class still
need to be imported.
Because of class inheritance, all public methods
and variables of a class are inherited by its
subclasses.
Example: The following function uses public
access control:
public static void main(String[] arguments) {
// ...
}
The main() method of an application has to be
public. Otherwise, it could not be called by a Java
interpreter (such as java) to run the class.

Protected Access Modifier - protected:
Variables, methods and constructors which are
declared protected in a superclass can be accessed
only by the subclasses in other package or any
class within the package of the protected members'
class.
The protected access modifier cannot be applied to
class and interfaces. Methods, fields can be
declared protected, however methods and fields in
a interface cannot be declared protected.
Protected access gives the subclass a chance to use
the helper method or variable, while preventing a
nonrelated class from trying to use it.
Example:
The following parent class uses protected access
control, to allow its child class override
openSpeaker() method:
class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details }}
class StreamingAudioPlayer {
boolean openSpeaker(Speaker sp) {
// implementation details }}
Here, if we define openSpeaker() method as
private, then it would not be accessible from any
other class other than AudioPlayer. If we define it
as public, then it would become accessible to the
entire outside world. But our intension is to expose
this method to its subclass only, thats why we used
protected modifier.

What is a bytecode?
Bytecode is a compiled format of a Java program.
Once a Java program is converted into bytecode it
can be transferred across the network and executed
by a Java Virtual Machine (JVM).

Why is Java considered ideal for network
communication?
Java is considered ideal for network
communication because it is a platform
independent language. Java enables an application
to be executed on any network. The built-in classes
of Java support TCP/IP and UDP protocols used
for network communication. Java supports the
Client-Server model for network communication.

Define Garbage Collection.
Garbage Collection is a process that automatically
frees the memory of objects that are no longer in
use. There is no specification of a technique for
garbage collection. The implementation has been
left to vendors.

Why is the data type of the argument that main()
method takes?
The main() method takes a String as argument.

What are the examples of the object-oriented
programming languages?
The examples of the object-oriented programming
languages are: Simula, C++, Python, Smalltalk,
CLOS, and Java.

How did object-orientation evolve?
The object-orientation evolved with the evolution
of Simula that provided features, such as objects,
classes, and inheritance. Simula was the first
object-oriented programming language. Simula 1
was a simulation language and Simula 67 was
referred to as Simula. Smalltalk was another
language having various features, such as classes,
inheritance, and graphical user environment.

Is it always necessary to recompile a program after
you make a change in the program?
Yes, it is necessary that the program must be
recompiled each time you make any change in the
program.

Class B inherits features from its base class, class
A. Class C is a sub class of class B and inherits
features from class B. How many times will the
features of class A appear in class C? Once
How can you run a Java program?
After compiling the java program, type "java
classname" at the command prompt.

Class B inherits features from its base class, class
A. Class C is a sub class of class B and inherits
features from class B. How many times will the
features of class A appear in class C?
The following figure shows the class hierarchy for
classes A, B, and C:
Class Hierarchy
Class B inherits features from its base class, Class
A. These features occur only once in Class B. Class
C inherits features from its base class, Class B. The
features inherited by Class C include the features
that Class B inherited from Class A. Therefore, the
features of Class A appear only once in Class C.

Which command can be used to compile a Java
program from the command line?
The Java compiler javac is used to compile a Java
program from the command line. The command to
compile a Java program from the command prompt
is:
C:\WORK >javac first.java
In the above statement, C:\ specifies that the
command window starts in directory C:\ and
work>first.java specifies that the first.java program
is contained in work folder.

How can you convert an applet to an application?
After compiling the java program, type "java
classname" at the command prompt. You can
convert an applet to an application by including the
main() method in the applet. The declarations
included in the init() method of the applet need to
perform in the constructor of the class. The applet
class needs to extend from a frame and size, and
visibility of the frame is set in the main() method.

How is memory allocated to arrays in Java?
In Java, memory is allocated using the new
operator. Consider the following example,
int [] marks;
marks=new int[3];

How can you convert strings to numbers?
Strings can be converted into numbers by using the
Integer, Float, Double and Long type wrapper
classes.

Can the == operator be used to determine whether
two strings have the same value as in name ==
"John"?
Yes, the == operator can be used to determine
whether two strings have the same value. In Java,
you can also compare two strings using the equals()
method.

Can the value of the expression in a switch
statement be a String or a real number?
No, the value of the expression in a switch
statement cannot be a String or a real number. It
has to be an integer or a character.

What does it mean when we call a method or field
static"?
You can instantiate static variables and methods
only once per class. They are class variables, not
instance variables. When you change the value of a
static variable in an object, the value of that
variable also changes for all instances of that class.

Does Java support pointers?
No, there are no pointers in Java as it has
references, which is an abstract identifier for an
object

What will happen if the data type of a variable and
the value assigned to a variable are different?
If the data type of a variable and the value assigned
to the variable are different then compilation error
occurs. If an integer variable is assigned a character
value, the ASCII value of the assigned character is
displayed as an output. The following code shows
assigning a character value to an integer variable.
class datatype{
public static void main(String a[])
{ int x= 'b';
System.out.print(x); } }
In the preceding code, the ASCII value of the
character b is displayed as 98.
Similarly, if you assign a float or a double value to
a character variable, an error message is displayed.
The following code shows assigning a double value
to a character variable:
class datatype{
public static void main(String a[])
{ char x= 5.5;
System.out.print(x); } }
Java is a strongly typed language and it allows the
values of the specific data types, which are
compatible with the type of variable.

Is it always necessary that a package statement
must be the first statement in a java program?
The package statement if present in a Java program
must be the first statement. All other statements in
the program must follow the package statement


Write Java assignment statements to evaluate the
following equations:
a) Area = r2+2rh
b) Torque = (2m1 m2)/( m1 m2)*g
c) Side = a2 + b2 2ab cos(x)
d) Energy = mass[acceleration * height +
(velocity
2
)/2]
import java.io.*;
public class AssignmentStatements{
int r, h, m1, m2, a, b, x, mass, acceleration, height,
velocity;
double area, torque, side, energy;
public void calculateArea(){
try{
System.out.print("Enter radius : ");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
r = Integer.parseInt(br.readLine());
System.out.print("Enter height : ");
h = Integer.parseInt(br.readLine());
area = (3.14*r*r)+(2*3.14*r*h);
System.out.println("The area is : " + area);
} catch(Exception e){
System.out.println("Error"); } }
public void calculateTorque(){
try{
System.out.print("Enter m1 : ");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
m1 = Integer.parseInt(br.readLine());
System.out.print("Enter m2 : ");
m2 = Integer.parseInt(br.readLine());
torque = ((2*m1*m2)/(m1+m2))*9.8;
System.out.println("The torque is : " + torque);
} catch(Exception e){
System.out.println("Error"); } }
public void calculateSide(){
try{
System.out.print("Enter a : ");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
a = Integer.parseInt(br.readLine());
System.out.print("Enter b : ");
b = Integer.parseInt(br.readLine());
System.out.print("Enter x : ");
x = Integer.parseInt(br.readLine());
side=Math.sqrt((a*a)+(b*b)-(2*a*b*Math.cos(x)));
System.out.println("The area is : " + side);
} catch(Exception e){
System.out.println("Errpr"); } }
public void calculateEnergy(){
try{
System.out.print("Enter mass : ");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
mass = Integer.parseInt(br.readLine());
System.out.print("Enter acceleration : ");
acceleration = Integer.parseInt(br.readLine());
System.out.print("Enter height : ");
height = Integer.parseInt(br.readLine());
System.out.print("Enter velocity : ");
velocity = Integer.parseInt(br.readLine());
energy=mass*(acceleration*height+((velocity*velo
city)/2));
System.out.println("The energy is : " + energy);
} catch(Exception e){
System.out.println("Errpr"); } }
public static void main(String arg[]){
AssignmentStatements as = new
AssignmentStatements();
as.calculateArea();
as.calculateTorque();
as.calculateSide();
as.calculateEnergy(); }}

Can there be more than one catch block per try
block for the same exception?
No. In one program, there can be only one catch
block per try block for a single exception. You
cannot use two catch blocks to catch a single
exception. For example, there cannot be two catch
blocks both catching a
java.lang.ArithmeticException thrown in the try
block.

Do you have to catch all types of exceptions that
might be thrown by Java?
Yes, you have to catch all types of exceptions that
are thrown in a Java application using the
Exception class.

Can you create your own exception classes?
Yes, you can create your own exception classes to
address application specific constraints. You can
create exception classes by extending the
Exception class. For example
Class invalidAgeException extends Exception

What are the return types of the read() methods?
There are several overloaded read methods to read
bytes and array of bytes from the input stream. The
read() method returns the value of the byte of data
it encounters in the input stream as an integer.
When the method encounters the end of the stream,
it returns -1.

Do all arguments sent to a Java application have to
be strings?
Yes, all the arguments sent to a Java application
have to be string. If you use some other data type,
such as int, you need to convert the value to string.




Which element of the for statement is evaluated
before each iteration of the for statement?
The test condition.

Can a switch statement have more than one default
statement?
No, a switch statement can have only one default
statement.

Can you add the numeric value of one string to the
value of another if the + operator is used with
strings to link up two different strings?
Yes, you can use the value of a String variable as
an integer only by using a method that converts the
value of the string variable into a numeric form.
This is known as type casting because it casts one
data type, such as a string into another data type,
such as int.

Do all the arithmetic operators have the same
precedence in java?
No, all the arithmetic operators do not lie at the
same level. The two distinct priority levels of
arithmetic operators in Java:
High priority * / %
Low priority + -

What is empty statement? Explain its usefulness.
The empty statement consists of a semicolon. The
empty statement is used when the statements
within the loop are not executed.

Can you use a switch statement inside another
switch statement?
Yes, you can use a switch statement within another
switch statement. This is called nested switch. Each
switch statement creates its own block of case
statements. Therefore, no conflict occurs between
the case labels of the inner and outer switch
statements.

How does the program stop running if a loop never
ends?
A program stops running when it enters an infinite
loop by pressing the keys Ctrl and C
simultaneously.

Why should the value of the variable used in the
condition of the while statement be changed in the
loop body?
The value of the variable used in the condition of
the while statement should be changed in the loop
body. Otherwise, the condition may always remain
true and the loop may never terminate.

What is the difference between instance creation
and class initialization?
When you call a constructor with new, an instance
is created and when a class is used actively, then
class initialization occurs.

Can a subclass access the variable that is declared
private in its superclass?
Any class member that is declared private is not
accessible outside the class where it is declared.
Even a subclass cannot access the private members
of its superclass.

In what order are the constructors called when a
class hierarchy is created?
In a class hierarchy constructors are called from
superclass to subclass, that is, in the order of
derivation of the classes that make up the
hierarchy.

Why arrays as an object are not invoked using
method sign() such as myArray.length()?
Arrays, like classes, are object references but they
do not contain methods. Instead, you can use
myArray.length. In this, the data item (not method)
called "length" which belongs to myarray.

Can a String object be changed once it has been
created?
A String object cannot be changed after creation. It
means you cannot change the characters that
comprise the String after the String object is
created.

What is the difference between equals() and ==?
The equals() method compares the characters that
are inside a String object while == operator
compares whether two object references refer to
the same instance.

How does a preemptive scheduler differ from a
non-preemptive scheduler?
When the time slice of a thread runs out
preemptive scheduler interrupts it while the non-
preemptive scheduler waits for the thread to yield
control itself.

How can one thread wait for another thread to
finish before continuing?
A thread can wait for another thread to finish
before continuing by calling its join() method

How do you ensure that your threads share the
processor of the computer properly?
To ensure that all the threads share the memory of
the processor properly, call the yield() or sleep()
method in the thread. The sleep() method is used to
keep the thread in the sleeping mode for a specified
time. The yield() method is used to allocate
processor time to a low priority thread.
The two approaches to create threads are by
implementing the Runnable interface and by
extending the Thread class. Which of these two
approaches is better and why?
The Thread class defines the various methods that
can be overridden by a derived class. It is advisable
to extend a class when it is being enhanced or
modified in some way. If you are not overriding
any of the methods of the Thread class other than
the run() method, then it is recommended to
implement the Runnable interface.
In addition, Java does not support multiple
inheritance. Applets extend from the Applet class.
You cannot inherit from both the Applet and
Thread class. The Runnable interface consists only
of the run() method, which is executed when the
thread is activated. You can extend from the Applet
class, implement the Runnable interface and code
the run() method. Therefore, when a program needs
to inherit from a class apart from the Thread class,
you need to implement the Runnable interface.

Which interface is implemented to create threads?
The Runnable interface is implemented to create a
thread. The Runnable interface contains the run()
method, which is needed to start a thread.

Why does * show in the following statement?
import java.io. *;
The * in the above statement shows that the
compiler shall import the entire java.io package.
All classes and interfaces contained in this package
will be accessible to you.

How do you add a class or an interface to a
package?
To add a class or an interface to a package, place
the package keyword at the top of the source code
of the class or the interface. The package keyword
is followed by the name of the package to which
the class or interface is to be added.

Compare package with header files.
Packages are similar to header files. One difference
is that a package contains only classes whereas a
header file can contain independent methods.

Can you have a try block without a catch block?
Yes, if there is a finally block accompanying it. A
try block needs to be followed by at least a catch or
a finally block.

How do two classes in an application communicate
with each other using the input stream and the
output stream?
Two classes in an application can communicate
with each other by using input and output stream.
You can use the following code to allow
communication between the Producer and
Consumer class:
//Producer.java
import java.io.*;
public class Producer
{Producer()
{ byte buffer[]=new byte[100];
try
{System.in.read(buffer,0,100); }
catch(IOException ioe)
{System.out.println("Exception: "+ioe.toString());}
try
{FileOutputStream fout = new
FileOutputStream("message.txt");
System.out.println("Producer class writing message
to the file message.txt ......");
System.out.println(".");
System.out.println(".");
fout.write(buffer); }
catch(FileNotFoundException fnfe)
{System.out.println("Exception:
"+fnfe.toString());}
catch(IOException ioe)
{System.out.println("Exception: "+ioe.toString());
} } }
//Consumer.java
import java.io.*;
public class Consumer
{Consumer()
{byte buffer[]=new byte[100];
try
{FileInputStream file = new
FileInputStream("message.txt");
file.read(buffer,0,50); }
catch(Exception e)
{System.out.println("Exception: "+e.toString());}
String str=new String(buffer);
System.out.println("Consumer class reading
message from the file message.txt ......");
System.out.println(str); }}
//Communicate.java
class Communicate
{public static void main(String args[])
{Producer prod = new Producer();
Consumer cons = new Consumer();} }
In the preceding code, two classes Producer and
Consumer are defined and their objects are
constructed in the Communicate application. The
Producer class uses the FileOutputStream class to
write messages to a message.txt file. The consumer
class uses the FileInputStream class to read
messages from the message.txt file. Therefore, the
two classes communicate by writing and reading
messages to a common file.



Why does the complier complain about interrupted
exception when I try to use thread.sleep method
The compiler is complaining, as it is required to do,
that your code invokes a method that might throw a
checked exception, but your code is not prepared to
handle that exception; to stop the compiler from
complaining, your method must either declare or
catch the InterruptedException that Thread's sleep
method can throw.
InterruptedException belongs to the set of checked
exceptions - a subset of exceptions that a Java
compiler is required to track through any source
code it handles. One of the compiler's restrictions is
that a method declares all the checked exceptions
that it might throw. A method can throw an
exception either by an explicit throw statement or
by invoking another method that throws the
exception.
Thread's sleep method declares that it can throw an
InterruptedException; therefore, the compiler will
examine any method that invokes sleep to check
whether the exception is being dealt with. You
have two options when writing a method that
invokes sleep:
1. Declare that your method can throw
InterruptedException
2. Catch the exception inside your run code

S-ar putea să vă placă și