Java Notes-Ii CS
Java Notes-Ii CS
SEMESTER : IV
UNIT – II
Unit – III
Class and objects: Defining a class – Methods – Creating objects – Accessing class
members – Constructors – Method overloading – Static members –Nesting of
Methods – this keyword – Command line input. Inheritance: Defining inheritance
–types of inheritance– Overriding methods – Final variables and methods – Final
classes – Final methods - Abstract methods and classes – Visibility Control-
Interfaces: Defining interface – Extending interface - Implementing Interface -
Accessing interface variables. Strings: String Array – String Methods – String
Buffer Class.
UNIT – IV
Packages: Java API Packages – System Packages – Naming Conventions –
Creating & Accessing a Package – Adding Class to a Package – Hiding Classes.
Exception Handling: Limitations of Error handling – Advantages of Exception
Handling - Types of Errors – Basics of Exception Handling – try blocks – throwing
an exception – catching an exception – finally statement. Multithreading: Creating
Threads – Life of a Thread – Defining & Running Thread – Thread Methods –
Thread Priority – Synchronization –Implementing Runnable interface – Thread
Scheduling.
UNIT – V
I/O Streams: File – Streams – Advantages - The stream classes – Byte streams –
Character streams. Applets: Introduction – Applet Life cycle – Creating &
Executing an Applet –Applet tags in HTML – Parameter tag – Aligning the display
- Graphics Class: Drawing and filling lines – Rectangles – Polygon – Circles –
Arcs – Line Graphs – Drawing Bar charts AWT Components and Even Handlers:
Abstract window tool kit – Event Handlers – Event Listeners – AWT Controls and
Event Handling: Labels – Text Component – Action Event – Buttons – Check
Boxes – Item Event – Choice– Scrollbars – Layout Managers- Input Events –
Menus.
TEXT BOOK
INTRODUCTION TO OOPS
One Characteristic that is constant in software industry today is the “change”.
Change is one of the most critical aspects of software development and management.
Most important among them are main ability, reusability, security, portability, security,
and integrity and user friendliness of software products.
The advent of languages such as “C” structured programming becomes very popular and
was the paradigm of the 1980’s.
Structured programming proved to be a powerful tool that enabled programmer to write
moderately complex program fairly easily.
Even the structured approach failed to show the desired results in terms bug-free, easy –
to maintain and reusable programs.
Object oriented programming is an approach to program organization and development,
which attempts to eliminate some of the pitfalls of conventional programming methods
by incorporating the best of structured programming features with several new concepts.
All language are suitable to implement the oops concept easily.
Language that support OOPS features include small talk, objective C,C++, Ada and
object Pascal..
C++ an extension of c language is most popular OOP language today
Java a pure Object-oriented language is one of the recent language added to this list, the
latest one being c#.
OBJECT-ORIENTED PARADIGM
The major objective of object-oriented approach is the eliminate some of the flaws
encountered in the procedure approach.
OOPS treats data as critical elements in the program development and does not allow it to
flow free around the system.
OOPs allow us to decompose a problem into number of entries called objects.
The data of an object can be accessed only by the methods associated with that object.
Emphasis is on data rather that procedure.
Programs are divided into what are know as object
Data structure are designed such that they characteristic the object.
Methods that operate on the data of an object are tried together in the data
structure.
Data is hidden and cannot be accessed by external functions.
Objects may communicate with each other through methods.
New data and methods can be easily added whenever necessary.
Follow bottom-up approach in program design.
Object-oriented programming is an approach that provides away of
modularizing programs by creating partitioned memory area for both data and
functions that can be used as templates for creating copies of such modules on
demand.
The wrapping up of data and methods in to single unit called is known as encapsulation.
Data Encapsulation is the most striking features of class.
This insulation of the data from direct access by the program is called data hiding.
Inheritance:
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
Inheritance is the process by which objects of one class acquire the properties of objects
of another class.
Inheritance supports the concepts of hierarchical classification.
Dynamic Binding:
Binding refers to the linking of a procedure call to the code to be executed in response to
the call.
Dynamic binding means that the code associated with a given procedure call is not know
until the time of the call at runtime.
Message Communication:
Message passing involves specifying the name of an object the name of the
method(message and information to be sent.
DIFFERENCES BETWEEN PROCEDURE ORIENTED PROGRAMMING
AND OBJECT ORIENTED PROGRAMMING
13. Data hiding There is not any proper way for data There is a possibility of data
hiding. hiding.
Inheritance we can eliminate redundant code and extend the use of existing classes.
We can build programs from the standard working modules.
The principle of data hiding helps the programmer to build secure programs.
It is possible to have multiple objects to coexist without any inheritance.
It is possible to map objects in the problem domain to those objects in the programs
It is easy to partition the work in a project based on objects.
Object oriented system can be easily upgraded from small to large system.
Message passing techniques for communication.
Software complexity can be easily managed.
APPLICATION OF OBJECT ORIENTED PROGRAMMING.
Real business system are often much more complex and contain many object complicated
attributes and methods.
o Real time system.
o Simulation and modeling.
o Object-oriented databases.
o Hypertext hyper media and expertext.
o AI and experts system.
o Neural Network and parallel programming
o Decision support and office automation systems.
o CM/CAD/CAD system.
JAVA EVOLUTION
Java History
Java does not include the C statement keywords sizeof and typedef.
Java does not contain data types struct and union.
Java does not define the type modifiers keywords auto,extern,register,signed and
unsigned.
Java does not support an explicit pointer type.
Java does not have a preprocessor and we cannot use # define, # include and # ifdef
statements.
Java requires that the functions with no arguments must be declared with empty
parenthesis and not with the void keyword as done in C.
Java adds new operators such as instanceof and >>>.
Java adds labeled break and continue statements.
Differences between java and C++:
Java environment includes a large number of development tools and hundreds of classes
and methods.
The development tools are part of the system known as Java Development Kit(JDK)
and the classes and methods are part of the Java Standard Library(JSL), also known as
the Application Programming Interface(API).
JAVA DEVELOPMENT KIT (JDK)
Java Development Kit comes with a collection of tools used for developing and running
java programs. They are
Applet viewer (for viewing java applets) Enables us to run Java applets.
Javac (java compiler) It translates Java source code to byte code files that the
interpreter can understand.
Java(java interpreter) Java interpreter, which runs applets and applications by reading
and interpreting bytecode files.
Javadoc(for creating HTML document) Creates HTML format documentation from
source code files.
Javap(java dissembler)Enables us to convert bytecode files into a program description.
Javah(for C header files) Produces header files for use with native codes.
Jdb(java debugger) It helps us to find errors in our programs.
class SampleOne
{
public static void main (String args[])
{
System.out.println(“ Java is better than C++”);
}
}
Class declaration
Opening Brace
Every class definition in java begins with an opening brace “{“ and ends with a
matching closing brace “}”.
Every java application program must include the main() method. This the starting point
for the interpreter to begin the execution of the program.
A java application can have any number of classes but only one of them must include a
main method to initiate the execution.
Public : The keyword public is an access specifier that declares the main method as
unprotected and therefore making it accessible to all other classes.
Static : Declares this method as one that belongs to the entire class and not a part of any
object of the class. The main methods must always be declared as static since the
interpreter uses this method before any object are created.
Void: The void states that the main method does not return any value.
Since java is a true object oriented language, every method must be part of an object.
The println method is a member of the out object, which is a static data member of
System class.
Suggested
Documentation section
Optional
Package statement
Optional
Class Definitions
The documentation section comprises a set of comment lines giving the name of the
program, the author and other details.
Comments must explain why and what of classes and how of algorithms.
Java also uses a third style of comment /** ….*/ known as documentation
comment. This form of comment is used for generating documentation
automatically.
Package Statement:
This statement declares a package name and informs the compiler that the
classes define here belong to this package. Example
Package student;
This package statement is optional.
Import Statements:
This is similar to the # include statement in C. Example
Import student. test;
Interface Statements:
An interface is like a class but includes a group of method declaration.
This is also an optional section and is used only when we wish to implement the
multiple inheritance features in the program.
Class Definitions:
A java program may contain multiple class definitions.
Classes are the primary and essential elements of a java program.
These classes are used to map the objects of real world problem.
Main method class:
Every java program requires a main method as its starting point.
The main method creates objects of various classes and establishes
communication between them.
On reaching the end of main, the program terminates and the control back
to the operating system.
JAVA TOKENS
A java program is basically a collection of classes.
A class is defined by a set of declaration statements and methods containing executable
statements.
Most statements contain expression, which describe the actions carried out on data.
Smallest individual units in a program are known as tokens.
The compiler recognizes them for building up expressions and statements.
In simple terms, a java program is a collection of tokens, comments and white spaces.
Java language includes five types of tokens.
They are
Reserved keywords
Identifiers
Literals
Operators
Separators
Reserved keywords
Java language has reserved 60 words as keywords.
These keywords combined with operators and separators according to
syntax, form definition of the java language.
Since keywords have specific meaning in java, we cannot use them as
name for variables, classes, methods and so on. All keywords are to be
written in lowercase letters. Some examples are byte, class,
do, extends, for, import etc.
Identifiers
They are used for naming classes, methods, variables, objects, labels,
packages and interfaces in a program.
Rules for naming an identifier
They can be of any length.
Uppercase and lowercase letter are distinct.
They can have alphabets, digits, underscore and dollar sign
characters.
They must not begin with digit.
Eg average, sum
Literals
Literals in java are a sequence of 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 arguments and operators
on them to produce a result.
Separators
Separators are symbols used to indicate where groups of code are divided
and arranged.
() parantheses,{} braces, [] brackets, ; semicolon, , comma, .
period .
JAVA VIRTUAL MACHINE
All language compilers translate source code into machine code.
Java compiler produces an intermediate code known as byte code for a machine that does
not exist.
This machine is called the Java Virtual Machine.
The process of compiling a java program into byte code is referred to as virtual machine
code.
Process of Compilation
The java object framework (Java API) acts as the intermediary between the user programs
and the virtual machine which in turn acts as the intermediary between the operating system
and the java object framework
Real Machine
Operating System
Compiler Interpreter
User
COMMENTS IN JAVA
The Java comments are the statements in a program that are not executed by the compiler and
interpreter.
The single-line comment is used to comment only one line of the code. It is the widely used and
easiest way of commenting the statements.
Single line comments starts with two forward slashes (//). Any text in front of // is not executed
by Java.
Syntax:
CommentExample1.java
Output:
10
The multi-line comment is used to comment multiple lines of code. It can be used to explain a
complex code snippet or to comment multiple lines of code at a time (as it will be difficult to use
single-line comments there).
Multi-line comments are placed between /* and */. Any text between /* and */ is not executed by
Java.
Syntax:
1. /*
2. This
3. is
4. multi line
5. comment
6. */
7. public class CommentExample2 {
8. public static void main(String[] args) {
9. /* Let's declare and
10. print variable in java. */
11. int i=10;
12. System.out.println(i);
13. /* float j = 5.9;
14. float k = 4.4;
15. System.out.println( j + k ); */
16. }
17. }
Documentation comments are usually used to write large programs for a project or software
application as it helps to create documentation API. These APIs are needed for reference, i.e.,
which classes, methods, arguments, etc., are used in the code.
To create documentation API, we need to use the javadoc tool. The documentation comments
are placed between /** and */.
1. /**
2. *
3. *We can use various tags to depict the parameter
4. *or heading or author name
5. *We can also use HTML tags
6. *
7. */
***************************UNITI COMPLETED*************************
UNIT II
CONSTANTS
Constants refers to fixed values that do not change during the execution of a
program.
Constants
Integer Constants
Decimal integer
Octal integer
Hexadecimal integer
Decimal integers consist of a set of digits, 0 through 9, preceded by an
optional minus sign.
Embedded spaces, commas, and non-digit characters are not permitted
between digits.
Valid Invalid
1234 70.00
-789 $234
An octal integer constant consists of any combination of digits from set 0
through 7, with a leading 0.
Examples
0345
0556
Real Constants
Numbers containing fractional parts are called real or floating point constants.
Examples are
These numbers are shown in decimal notation , having a whole number followed by
decimal point and the fractional part, which is an integer. That is
mantissa e exponent
a whole number
a decimal point
a fractional part
an exponent
Single character constants
A single character constant contains a single character enclosed within a pair of single quote
marks. Examples of character constants are:
‘5’ ‘X’ ‘:’ ‘ ‘
String constants
A string constant is sequence of characters enclosed between double quotes.
The characters may be alphabets, digits, special characters and blank spaces. Examples are:
“Hello” “1997”
Backslash character constants
Java supports some special backslash character constants that are used in output methods.
For example, the symbol ‘\n’ stands a new line character.
They consist of two characters. These characters combinations are known as escape
sequences.
Meaning
Constant
Backspace
‘\b’
Form feed
‘\f’
New line
‘\n’
Carriage return
‘\r’
Horizontal tab
‘\t’
‘\” Single quote
Double quote
‘\”’
‘\\’
Backslash
VARIABLES
A variable is an identifier that denotes a storage location used to store a data value.
Variable names may consist of alphabets, digits, the underscore( _ ) and dollar
characters, subject to the following conditions:
1. They must not begin with a digit.
2. Uppercase and lowercase are distinct.
3. It should not be a keyword.
4. White space is not allowed.
5. Variable names can be of any length.
Declaration of variables
The declaration statement defines the type of variable. The general form of declaration of a
variable is:
Variables are separated by commas. A declaration statement must end with semicolon. Some
valid declarations are:
int count;
float x, y;
Giving values to variables
A variable must be given a value after it has been declared it is used in an expression. This
can be achieved in two ways:
1. By using an assignment statement
2. By using a read statement
Assignment Statement
A simple method of giving value to a variable is through the assignment statement as follows:
variablename = value;
For example:
initialvalue = 0;
finalvalue = 123;
We can also string assignment expression as shown below:
x = y = z = 0;
It is also possible to assign a value to a variable at the time of its declaration. The general form
is as follows:
Examples:
int finalvalue = 123;
char yes = ‘x’;
Read Statement
We may also give values to variables interactively through the keyword using the readline( )
method.
The readline( ) method reads the input from the keyboard as a string which is then
converted to the corresponding data type using the data type wrapper classes.
Getting values of variables
Java supports two output methods that can be used to send the results to the screen.
print ( ) method // print and wait
println ( ) method // print a line and move the next line
The print ( ) method prints output on one line until a new line character is
encountered. For example, the statements
System.out.print (“Hello”);
System.out.print(“Java!”);
will display the words Hello Java! On one line and waits for displaying further
information on the same line.
The println ( ) method, by contrast, takes the information provided and displays it
on a line followed by a line feed. For example
System.out.println (“Hello”);
System.out.println(“Java!”);
will produce the following output:
Hello
Java!
DATA TYPES
Data types specify the size and type of values that can be stored.
Primitive(Intrinsic) Non-Primitive(Derived)
Integer Types
Integer types can hold whole numbers such as 123, -96, 5678. Java supports four types of
integers. They are byte, short, int, and long.
Character Type
Java provides a character data type called char.
The char type assumes a size of 2 bytes but, basically, it can hold only a single character.
Boolean Type
It is used to test a particular condition during the execution of the program.
There are only two values that a boolean type can take: true or false.
Boolean type is denoted by the keyword boolean and uses only one bit of storage.
SCOPE OF VARIABLES
Java variables are actually classified into three types:
Instance variables
Class variables
Local variables
Instance and class variable are declared inside a class. Instance variables are created
when the objects are instantiated and they are associated with the objects.
Class variables are global to a class and belong to the entire set of objects that class
creates. Only one memory location is created for each class variable.
Variables declared and used inside methods are called local variables. They are not
available for use outside method definition.
TYPE CASTING
We often encounter situations where there is a need to store a value on one type into a variable of
another type.
In such situation, we must cast the value to be stored by proceeding it with the type name in
parentheses. The syntax is
The process of converting one data type to another is called casting. Examples:
int m= 50;
byte n = (byte)m;
Four integer types can be cast to any other type except Boolean. Casting into a smaller type
may result in loss of data. Similarly, the float and double can be cast to any other type except
Boolean.
From To
byte short, char, int, long, float, double
short int, long, float, double
char int, long, float, double
int long, float, double
long float, double
float Double
Casts that results in no loss of information
Introduction:
Java supports a rich set of operators.
An operator is a symbol that is used for manipulate data and variables.
Operators are used in programs to manipulate data and variables.
Java operators are classified into number of categories.
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Increment and decrement operators
Conditional operators
Bitwise operators
Special operators
ARITHMETIC OPERATORS
Arithmetic operators are used to construct mathematical expressions as in algebra
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division
When one of the operands is real and the other is an integer, the expression is
called a mixed-mode expression.
If either operand is of the real type, then the other operand is converted to real and
the real arithmetic is performed.
E.g.: 15/10.0=1.5
15/10=1
RELATIONAL OPERATORS
Compares two quantities depending on their relation.
Operator Meaning
Java supports six relational operators.
< is less than
A simple relational expression
<= is less than or equal
contains only one relational operator
to
and is of the following form:
> is greater than
LOGICAL OPERATORS
Java has three logical operators.
Operator Meaning
|| Logical OR
! Logical NOT
A logical operator returns either TRUE or FALSE values.
Truth Table
Logical operator && and || are used to check compound condition (ie for combining two or
more relations)
When an expression combines two or more relational expressions then it is called logical
expression or a compound relational expression
Eg: if (age>55 && salary<1000)
if (mark1>40 && mark2 >40)
ASSIGNMENT OPERATORS
Used to assign the value of an expression to a variable.
Assignment operators are usually in the form “=”.
Shorthand form:
v op=exp;
v variable
exp expression
a=a+1 a+=1
a=a-1 a-=1
a=a*(n+1) a*=n+1
a=a/(n+1) a/=n+1
A=a % b a%=b
Advantages:
It has 3 advantages.
Easy to write.
Easy to read
Efficient code.
INCREMENT AND DECREMENT OPERATORS
Eg. a[i++]
Sample Program:
class Incrementoperator
{
public static void main(String args[ ])
{
int m=10,n=20;
System.out. println("m=" +m);
System.out. println("n="+n);
S ystem.out. println("++m="+++m);
System.out.println("n++="+n++);
Systern.out. println("m="+m);
System .out. println("n="+n);
}
}
Output
m=10
n=20
++m=11
n++=21
m=11
n=21
CONDITIONAL OPERATORS
The character pair ?: is used for conditional operator.
It is also called as ternary operator.
General Form
exp1 ? exp2: exp3
exp1, exp2, exp3 are expressions
The operator ?: works as follows
Expression1 is evaluated first, if its is true then the expression2 is evaluated.
Eg a=10;
b=15
X= (a>b) ? a : b;
The output is X=15
BITWISE OPERATORS:
Bitwise operators are used to manipulate data at values of bit level.
These operators are used for testing the bits, or shifting them to the right or left.
Bitwise operators may not to float or double.
Operator Meaning
! Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
2.Low priority + -
If the operands are of different types, the lower type is automatically converted to the
higher type before the operation proceeds.
The result is of the higher type.
If byte, short and int variables are used in expression, the result is always promoted to
int, to avoid overflow.
If a single long is used in expression, the whole expression is promoted to long.
Casting a value:
To convert an object or variable of one type to another is called casting a value.
The general form of a cast is
(type_name) expression
Example
Highest
The Precedence of ( ) [] .
the Java Operators ++ –– ~ !
* / %
+ –
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
?:
= op=
JAVA EXPRESSIONS
Lowest
A Java expression consists of variables, operators, literals, and method calls. To know more
about method calls, visit Java methods. For example,
int score;
Score=90;
Here, score = 90 is an expression that returns an int. Consider another example,
Double a=2.2,b=3.4,result;
Result=a+b-3.4;
Here, a + b - 3.4 is an expression.
If(number1==number2)
System.out.println(“Number 1 is larger than number 2”);
Arithmetic Expressions
Java does not have an operator for exponentiation. Some of the expressions are
ab-c a*b-c
(m+n)(x+y) (m+n)*(x+y)
ab/c a*b/c
3x2+2x+1 3*x*x+2*x+1
Evaluation of Expression:
Variable=expression;
Variable is any valid Java variable name . When the statement is encountered , the
expression is evaluated first and the result then replaces the previous value of the variable on the
left hand side.
Eg: x= a*b-c;
y= a-b /c+d;
When a program breaks the sequential flow and jumps to another part of the code, it is
called branching.
When the branching is based on a particular condition, it is known as conditional
branching.
If branching takes place without any decision, it is known as unconditional branching.
The following statements are known as control or decision making
statements.
if statement
switch statement
Conditional operator statement
The if statement is a powerful decision making statement and is used to control the flow
of execution of statements.
General form
if (test expression)
1. simple if statement
2. if…else statement
3. Nested if…else statement
4. else if ladder
1. Simple If Statement
If the test expression is true the statement block will be executed; otherwise the
execution will jump to the statement-x
Statement block may be single statement or a group of statement.
Example
if (degree = = “BCA”)
{
General form points = points+500;
System.out.println(“Its BCA”);
if (test expression) }
{ else
True block statements; {
} points = points+200;
else
System.out.println(“Its BSC
{
False block statements; CS”);
} }
Statement-X; ….
4. Else if ladder
Else if ladder is a chain of ifs in which the statement associated with each else is an
if.
The condition is evaluated from the top to downwards.
As soon as the condition is true, then the statements associated with it are
executed and the control is transferred to the statement -x.
When all the n condition is false, then the final else containing the default-
statement will be executed.
Block1, block2 … are statements lists may contain zero or more statements.
No need to put braces around each block
Case labels end with a colon (:)
The break statement at the end of each block signal the end of a particular
case and causes an exit from the switch statement, transferring the control to the
statement -x following the switch.
The default is an option case; it will be executed if the value of the expression
does not match with any of the case values.
If not present, no action takes place when all matches fail and the control goes
to the statement –x.
Flag = (x<0) ? 0 :
1;
Ex2:
Y = (x>2) ?
(2*x+1) : (3*x+2);
INTRODUCTION
THE DO STATEMENT
In do statement, the program proceeds to evaluate the body of the loop first.
At the end of the loop, the test condition in the while statement is evaluated.
If the condition is true, the program continues to evaluate the body of the loop once
again.
The program continues to evaluate the body of the loop as long as the condition is
true.
When the condition becomes false, the loop will be terminated and the control goes to
the statement that appears immediately after the while statement.
Example
Sum=0;
General form N=1;
Initialization; do
do {
{ sum=sum + N;
Body of the loop N=N+1;
} } while (N<=10);
while (test condition); System.out.println(“sum’”+sum);
(1) Initialization of the control variables is done first, using assignment statements such as
i=1 and count=0. The variable i and count are known as loop-control variables.
(2) The value of the control variables is tested using the test condition. The test condition
is a relational expression, such as i<10 that determines when the loop will exit.
It the condition is true, the body of the loop is executed; otherwise the loop is
terminated and the execution continues with the statement that immediately
follows the loop.
(3) When the body of the loop is executed, the control is transferred back to the for
statement after evaluating the last statement in the loop.
Now the control variable is incremented using an assignment statement such as
i=i+1 and the new value of the control variable is again tested to see whether it
satisfies the loop condition.
If the condition is satisfied, the body of the loop is again executed.
This process continues till the value of the control variable fails to satisfy the test
condition.
General form
for (initialization; test condition; increment)
{
Body of the loop
}
JUMPS IN LOOPS
Loops perform a set of operations repeatedly until the control variable fails to satisfy the
test condition.
Java permits a jump from one statement to the end or beginning of a loop as well as a
jump out of a loop.
ARRAY
An array is a group of contiguous or related data items that share a common name.
E.g. name[10]
For example, The values to the array elements 35, 40, 20, 57, 19 can be assigned as
follows:
number[0] = 35;
number[1] = 40;
number[2] = 20;
number[3] = 57;
number[4] = 19;
CREATING AN ARRAY
Arrays must be declared and created in the computer memory before they are used.
Example
Int number[];Int[] number;
Float average[];Float[] average;
Initialization of Arrays
arrayname [subscript]=value;
Eg: number[0]=90;
number[1]=100;
……….
Arrays starts with a subscript 0 and ends with a value one less than the size specified.
Trying to access an array beyond its boundaries will generate an error message.
If size is not specified means compiler allocates enough space for all the elements
specified in the list
Array length
Eg : int myarray[][];
myarray=new int[3][4];
Example program:
class MulTable
{
final static int ROWS = 0;
System.out.println(“ “);
int i,j;
product [i] [ j] = i * j;
System.out.println(“ “ + product [ i] [ j ];
System.out.println(“ “);
VECTORS
Vector class is used to create a generic dynamic array known as vector that can hold
objects of any type and any number.
Created like
Vector intvect=new vector(); // declared without size
Advantages
A vector can be used to store a list of objects that may vary in size.
We can add and delete objects from the list as and when required.
WRAPPER CLASS
Vectors cannot handle primitive data types like int, float, double and char.
This conversion is done by using the wrapper class contains in the java.lang package
Converting string objects to numeric objects using the static method ValueOf()
float num1=Float.ValueOf(in.readLine());
int val=Integer.ParseInt(in.readLine());
*******************UNIT II COMPLETED*********************
UNIT III
INTRODUCTION
CLASS: “A class is a way of binding the data and associated methods in a single
unit”
Any JAVA program if we want to develop then that should be developed with respective
class only i.e., without class there is no JAVA program.
Classes create objects and object uses methods to communicate between them.
Classes provide convenient method for packing together a group of logically related data
items and functions that work on them.
The data items are called fields and the functions are called methods.
DEFINING A CLASS
A class is a user-defined data type with a template that serves to define its properties.
Anything in square bracket is optional.
Classname and superclassname are valid java identifiers.
The keyword extends indicates that the properties of the superclassname class are
extended the classname class.
The basic form of a class definition is Example1 Example2
class classname [extends superclassname] class empty class sample
{ { {
[fields declaration;] int i,j;
[method declaration;] } void getdata();
} }
FIELDS DECLARATION
Data is encapsulated in a class by placing data fields inside the body of the class
definition.
These variables are called instance variables because they are created whenever an object
of the class is instantiated.
Instance variables are also know as member variables.
Example
class Triangle
{
int length;
int height;
}
The class triangle contains two integer type instance variable, length
and height.
METHODS DECLARATION
Eg2: Triangle tri1 = new Triangle ( ); tri1 and tri2 are the objects of
Triangle class
Syntax:
Accessing variables Accessing method
E.g.
objectname. variablename = value; Tri1.length=10; Tri1.getdata (10, 20);
objectname.methodname(parameter-list); Tri1.height=20;
class Square
{
int side;
void getdata(int s)
{
side=s;
}
int rectarea()
{
int area=side * side;
return(area);
}
}
class Squareaea
{
public static void main (String args[])
{
Square s1= new Square();
s1.getdata(5);
sqarea =s1.rectarea();
CONSTRUCTORS
Java supports a special type of method called a constructor that enables an object to
initialize itself when it is created.
Constructors have the same name as the class name.
They does not return any value and do not specify even void.
Constructors are automatically called during the creation of the objects.
EXAMPLE:
class Volume
{
int x,y,z;
Volume() // constructor
{
x=10;
Y=10;
Z=30;
}
int calvolume()
{
int vol=x*y*z;
return vol;
}
}
class Demovolume()
{
public static void main(String args[])
{
Volume volobj=new Volume; // creating object
int result=volobj.calvolume(); // calling method
System.out.println(“the volume is =”+result);
}
ADVANTAGES OF CONSTRUCTORS:
1. A constructor eliminates placing the default values.
2. A constructor eliminates calling the normal method implicitly.
RULES/PROPERTIES/CHARACTERISTICS of a constructor:
1. Constructor name must be similar to name of the class.
2. Constructor should not return any value even void also (if we write the return type for
the
constructor then that constructor will be treated as ordinary method).
3. Constructors should not be static since constructors will be called each and every time
whenever an object is creating.
4. Constructor should not be private provided an object of one class is created in another
class
(constructor can be private provided an object of one class created in the same class).
5. Constructors will not be inherited at all.
6. Constructors are called automatically whenever an object is creating.
TYPES OF CONSTRUCTORS:
Based on creating objects in JAVA we have two types of constructors.
They are
1. Default/parameter less/no argument constructor and
2. Parameterized constructor.
1. DEFAULT CONSTRUCTOR
A default constructor is one which will not take any parameters.
Syntax: class Test
class <clsname> {
{ int a, b;
clsname () //default constructor Test ()
{ {
Block of statements; System.out.println ("I AM FROM DEFAULT
………………………………; CONSTRUCTOR...");
………………………………; a=10;b=20;
} System.out.println ("VALUE OF a = "+a);
………………………; System.out.println ("VALUE OF b = "+b);
………………………; }
}; };
class TestDemo
{
public static void main (String [] args)
{
Test t1=new Test ();
}
};
2. PARAMETERIZED CONSTRUCTORS
class Volume
int x,y,z;
{ x=l;
y=m;
z=n;
int vol=x*y*z;
return vol;
}
METHOD OVERLOADING
Methods that have the same name, but different parameter lists and different definitions
are called method overloading.
Method overloading is used when objects are required to perform similar tasks but using
different input parameters.
Java matches up the method name first and then the number and type of parameters to
decide which one of the definition to execute. This process is known as polymorphism.
class Calculatearea
{
int area()
{
int val=10*20*30;
return val;
}
int area(int m, int n)
{
int val=m*n;
return val;
}
int area(int l, int m, int n)
{
int val=l*m*n;
return val;
}
float area(float m, float n)
{
float val=m*n;
return val;
}
float area(int l, float m, int n)
{
float val=l*m*n;
return val;
STATIC MEMBERS
It defines a member that is common to all the objects and accessed without using a
particular object.
That is the member belongs to the class as a whole rather than the objects created form
the class.
Static members can be defined as follows
static int count;
Static members are associated with the class itself rather than individual object.
Static variables and static methods are often referred to as class variables and class
methods.
Static variables are used when we want to have a variable common to all instances of a
class.
Eg: variable that keep a count of how many objects of a class have been created.
Static variables and static methods are called without using the objects.
Restriction of static methods
{return x*y;
{return x/y;
class Mathapplication
NESTING OF METHODS
A method can be called by using only its name by another method of the same class. This is
known as nesting of methods.
Example
class Nesting
int a, b, result;
Nesting(int x, int y)
a=x;
b=y;
void Process()
{ result = a+b;
display();
void display()
{ System.out.println(result); }
class nestingtest
{
nest.process();
}}
THIS KEYWORD
The most common use of the this keyword is to eliminate the confusion between class attributes
and parameters with the same name (because a class attribute is shadowed by a method or
constructor parameter). If you omit the keyword in the example above, the output would be "0"
instead of "5".
Example
Int x;
This.x=x;
Sysytem.out.println(
“Value of x=”+myObj.x);
The java command-line argument is an argument i.e. passed at the time of running the java
program.
The arguments passed from the console can be received in the java program and it can be used as
an input.
So, it provides a convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
1. class CommandLineExample{
2. public static void main(String args[]){
3. System.out.println("Your first argument is: "+args[0]);
4. }
5. }
1. compile by > javac CommandLineExample.java
2. run by > java CommandLineExample sonoo
3. Output: Your first argument is: sonoo
1. class A{
2. public static void main(String args[]){
3.
4. for(int i=0;i<args.length;i++)
5. System.out.println(args[i]);
6.
7. }
8. }
1. compile by > javac A.java
2. run by > java A sonoo jaiswal 1 3 abc
INHERITANCE
When one class acquires the properties of another class it is known as inheritance.
( The mechanism of deriving a new class from an old one is called inheritance.)
A class that is inherited is called a super class or base class.
The class that does the inheriting is called a subclass or derived class.
Advantage of inheritance is that it allows reusability of coding.
Inheritance may take different forms. They are
3. Hierarchical inheritance
Hierarchical inheritance is one in which there exits single base class and n number of
derived classes.
4. Multiple inheritance
Multiple inheritance is one in which there exists n number of base classes and single derived
classes.
Multiple inheritances are one supported by JAVA through classes but it is supported by
JAVA through the concept of interfaces.
Defining a subclass
variables declaration;
methods declaration;
The keyword extends signifies that the properties of the superclassname are extended to the
subclassname.
SINGLE INHERITANCE
When a single sub class extends the properties of a single super class, then it is known as
single level inheritance.
Example
class Room
int volume ()
{ {
return (Length*Breadth*Height);
int Length, Breadth;
}
Room (int x, int y) }
class inhert
{
public static void main (String args[])
{
Room1 obj=new Room1(14,12,10);
int area1=obj.area ();
{
Length=x;
Breadth=y;
}
int area ()
{
return (Length*Breadth);
}
}
class Room1 extends Room
{
int height;
Room1 (int x, int y, int z)
{
super (x, y);
Height=z;
}
}
SUBCLASS CONSTRUCTOR
A subclass constructor is used to construct the instance variables of both the subclass and
the super class.
The sub class constructor uses the keyword super to invoke the constructor method of the
super class.
The keyword super is used in following conditions.
Super may only be used within a subclass constructor method.
The call to super class constructor must appear as the first statement within
the sub class constructor.
The parameter in the super call must match the order and type of the instance
variable declared in the program.
MULTILEVEL INHERITANCE
Since java supports the concept of concept of inheritance it is extensively used in
building the class library.
Multilevel inheritance is used to build chain of classes.
Example
class Rectangle
class Circle extends Box
{ {
int L, W; circle (int i, int j, int k)
{
Rectangle (int i, int j)
super (i, j, k);
{ System.out.println(“Area=”+(3.14*i*i));
L=i; }
}
W=j; class mainclass
System.out.println(“Area =” +(L*W)); {
public static void main(String args[])
}
{
} Circle obj=new Circle (10, 20, 30);
class Box extends Rectangle }
}
{
Box (int i, int j, int k)
{
super (i, j);
Output
System.out.println(“Volume=”+(i*j*k));
Area =200
}
} Volume=6000
HIERARCHICAL INHERITANCE
When a finally of classes is created in hierarchical model then it is called as hierarchicaal
inheritance.
Example
class A
{ class mainclass
{
int a, b; public static void main(String args [])
void input() {
{ A obja=new A();
B objb=new B();
a=10;
C objc=new C();
b=20; obja.input();
System.out.println(“a=”+a+”b=”+b); objb.a=10;
objb.b=20;
objb.addtion();
objc.a=10;
objc.b=20;
objc.product();
}
}
class B extends A
{
void addition ()
{
System.out.println(“a+b=”+(a+b));
}
}
class C extends A
{ void product ()
{
System.out.println(“a*b=”+(a*b));
}}
OVERRIDING METHODS
A method defined in a super class is inherited by its sub class and is used by the objects
created by the sub class.
There may be occasions when we want an object to respond to the same method is called.
This is possible by defining a method in the sub class that has the same name, same
arguments and same return type as a method in the super class.
When the methods are called, the method defined in the sub class is invoked and executed
instead of the one in the super class. This is known as overriding.
Example
class Super
{ int x; void display ()
Super (int x) {
{ System.out.println(“Super x=”+x);
System.out.println(“Sub y=”+y);
this.x=x;
} }
} class overridetest
void display () {
public static void main (String args[])
{
{
System.out.println(“x=”+x); Sub S1=new Sub (100, 200);
S1.display ();
}
}
}
}
class Sub extends Super
{ int y;
Sub (int x, int y)
{
super (x);
this.y=y;
}}
FINAL VARIABLES AND METHODS
It prevents the subclasses form overriding the member of the superclass.
Final variables and methods are declared as final using the keyword final as a modifier.
Example: size =100
final int SIZE = 100;
final void showstatus( ){…………..}
Making a method final ensures that the functionality defined in that method will never be
altered in any way.
The value of a final variable can never be changed.
FINAL CLASSES
A class that cannot be sub-classed is called a final class.
It prevents a class being further sub-classed for security reasons.
Any attempt to inherit these classes will cause an error.
FINALIZER METHODS
Initializationà constructor method is used to initialize an object when it is declared.
This process is called initialization.
Finalizationàfinalizer method is just opposite to initialization, it automatically frees
up the memory resources used by the objects. This process is known as finalization.
It acts like a destructor.
The method can be added to any class.
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code
defined outside its class.
{ abstract class Op
}; };
ABSTRACT METHODS
When a method is defined as final than that method is not re-defined in a subclass.
Java allows a method to be re-defined in a sub class and those methods are called abstract
methods.
When a class contains one or more abstract methods, then it should be declared as abstract
class.
When a class is defined as abstract class, it must satisfy following conditions
We can’t use abstract classes to instantiate objects directly. For example
Op s = new Op( )
is illegal because Op is an abstract class.
The abstract methods of an abstract class must be defined in its sub class.
We can’t declare abstract constructors or abstract static methods.
Final allows the methods not redefine in the subclass.
Abstract method must always be redefined in a subclass, thus making overriding
compulsory.
This is done using the modifier keyword abstract in the method definition.
When a class contains one or more abstract methods, it should also be declared abstract.
Example
abstract class shape
{
………..
…………
abstract void draw();
…………
………..
}
RULES:
We cannot use abstract classes to instantiate objects directly.
The abstract methods of an abstract class must be defined in its subclass.
We cannot declare abstract constructors or abstract static method.
General form
<access specifier> <static> void method-name (object …arguments)
{
}
In the above syntax The method contains an argument called varargs in which
Object is the type of an argument
Ellipsis (…) is the key to varargs
Argument is the name of the variable.
For eg: Public void sample(String username, String password, String mail)
Can be written as Public void sample (String …var_name)
Here var_name is the variable name that specifies that we can pass any number of
String arguments to the sample method.
Example program
Class exampleprg
{
Exampleprg(String… person)
{
for (String name: person)
{
System.out.println(“hello” + name);
}
}
public static void main(String ars[])
{
exampleprg (“ram”, “siva”, “suriya”);
}
}
VISIBILITY CONTROL
The modifiers are also known as access modifiers.
Java provides three types of visibility modifiers: public, private and protected.
Public Access:
To declare the variable or method as public, it is visible to the entire class in which it is
defined.
Example:
public int number;
public void sum ( ) {……………..}
Friendly Access:
When no access modifier is specified, the number defaults to a limited version of public
accessibility known as “friendly” level of access.
The difference between the “public” and “friendly” access is that the public modifier
makes fields visible in all classes.
While friendly access makes fields visible only in the same package, but not in other
package.
Protected Access:
The protected modifier makes the fields visible not only to all classes and subclasses
in the same package but also to subclasses in other packages.
Non-subclasses in other packages cannot access the “protected” members.
Private Access:
Private fields are accessible only with their own class.
They cannot be inherited by subclasses and therefore not accessible in subclasses.
A method declared as private behaves like a method declared as final.
Private protected Access:
A field can be declared with two keywords private and protected together like:
private protected int codeNumber;
This gives a visibility level in between the “protected” access and “private” access.
Rules:
1. Use public if the field is to be visible everywhere.
2. Use protected if the field is to be visible everywhere in the current package and
also subclasses in other packages.
3. Use “default” if the field is to be visible everywhere in the current package only.
4. Use private protected if the field is to be visible only in subclasses, regardless of
packages.
5. Use private if the field is not to be visible anywhere except in its own class.
INTERFACES
INTRODUCTION
DEFINING INTERFACES
interface <InterfaceName>
Example
interface Item
{
{
static final int code = 1001;
variables declaration;
void display();
} declaration;
methods
All variables are declared as constants. Methods declaration will contain only a list of
methods without any body statements.
EXTENDING INTERFACES
For example, we can put all the constants in one interface and the methods in the other.
interface ItemConstants
{
int code = 1001;
string name = “Fan”;
}
interface Item extends ItemConstants
{
void display( );
}
The interface Item will inherit both the constants code and name into it.
IMPLEMENTING INTERFACES
class mainpgm
{
interface interfaceA public static void main(String args[])
{ {
final int m=10; ClassA objA=new classA();
} objA.show();
class ClassA implements interfaceA }
{ }
void show()
{
System.out.println(m);
}
}
STRINGS
General form
String stringname;
Stringname = new String(“string”);
Eg
String firstname;
firstname=new String(“anil”);
Or
String firstname=new String(“anil”);
String arrays
item[0]=”soap”;
item[1]=”biscuits”;
item[2]=”powder”;
String methods
s2=s1.trim(); Remove white space at the beginning and end of the String s1
s1.indexOf(‘x’) Gives the position of the first occurrence of ‘x’ in the string s1
s1.indexOf(‘x’,’n’); Gives the position ‘x’ that occurs after nth position in the string s1
StringBuffer class
StringBuffer class creates string of flexible length that can be modified in terms of both
length and content.
In stringbuffer class we can insert characters and substrings in the middle of a string, or
append another string to the end.
Methods Task
Example program
class stringmanipulation
int p=i+1;
// modifying characters
str.setcharAt(6,’-‘);
System.out.println(“string now: ” + str);
UNIT IV
PACKAGES
INTRODUCTION
BENEFITS:
The classes contained in the packages of other programs can be easily reused.
In packages, classes can be unique compared with classes in other packages.
That is two classes in two different packages can have the same name.
They may be referred by their fully qualified name, comprising the package name and the
class name.
Packages provide a way to "hide" classes thus preventing other programs or packages
from accessing classes that are meant for internal use only.
Packages also provide a way for separating "design" form "coding".
Packages Contents
java.util Language utility classes such as vectors, hash tables, random number,
date etc.
The first statement allows the specified class in the specified package to be imported. For
example, the statement
import java.awt.Color;
imports the class Color and therefore the class name can now be directly used in the
program.
The second statement imports every class contained in the specified package. For example, the
statement
import java.awt.*;
will bring all classes of java.awt package.
NAMING CONVENTIONS
This statement uses a fully qualified class name Math to invoke the method sqrt( ).
CREATING PACKAGES
First declare the name of the package using the package keyword followed by a package
name.
Example
Steps:
Define the class that is to be put in the package and declare it public.
Create a subdirectory under the directory where the main source files are stored.
Example 1
Example 2
Here the class Y which is not declared public is hidden from outside of the package p1.
This class can be seen and used only by other classed in the same package.
Consider the following code, which imports the package p1 that contains classes X and Y:
import p1. *;
X objectX; // ok; class X is available here.
Y objectY; // not ok: Y is not available.
Java compiler generate an error message because the class Y is not declared as public.
STATIC IMPORT
The static import declaration is similar to that of import.
The import statement to import classes from packages and use them without qualifying
the package.
The static import statement to import static members from classes and use them without
qualifying the class name
Syntax:
import static package-name. subpackage-name. class-name . staticmember-name;
(or)
import static package-name. subpackage-name. class-name.*;
Example:
public interface Salary_increment
{
public static final double Manager=0.5;
public static final double Clerk=0.25;
}
To access the interface, we can import the interface using the static import statement as
follows:
import static employee. employee_details. Salary_increment;
class Salary_hike
{
public static void main( String args[ ])
{
double manager_salary=Manager*Manager_current_salary;
double clerk_salary=Clerk*Clerk_current_salary;
………..
……………
}
}
We can use the static member in the code without qualifying the class name or
interface name.
Also, the static feature eliminates the redundancy of using the qualified class name with
the static member name and increases the readability of the program.
INTRODUCTION
Rarely does a program run successfully as its very first attempt. It is common to make
mistakes while developing as well as typing a program.
A mistake might lead on to an error causing to program to produce unexpected results.
Errors are the wrongs that can make a program go wrong.
An error may produce an incorrect output or may terminate the execution of the program
abruptly or even cause the system to crash.
It is therefore important to detect and manage properly all the possible error conditions in
the program so that the program will not terminate or crash during execution.
TYPES OF ERRORS
Errors are of two types. They are compile time errors and run time errors.
Compile time errors are those which are occurring because of poor
understanding of the language.
Run time errors are those which are occurring in a program when the user inputs
invalid data.
The run time errors must be always converted by the JAVA programmer into user
friendly messages by using the concept of exceptional handling.
COMPILE-TIME ERRORS
All syntax errors will be detected and displayed by the Java compiler and therefore these
errors are known as compile-time errors.
Whenever the compiler displays an error, it will not create the .class file.
It is therefore necessary that we fix all the errors before we can successfully compile ad
run the program.
Most of the compile-time errors due too typing mistakes. Typographical errors are
hard to find.
We may have to check the code word by word, or even character by character.
The most common problems are:
Missing semicolons
Missing brackets in classes and methods
Misspelling of identifiers and keywords
Missing double quotes in strings
Use of undeclared variables.
Incompatible types in assignments/initialization
Bad references to objects
Use of = in place of = = operator
RUN-TIME ERRORS
Sometimes, a program may compile successfully creating the .class file but may not
run properly.
Such programs may produce wrong results due to wrong logic or may terminate due to
errors such as stack overflow.
Most common run-time errors are:
Dividing an integer by zero
Accessing an element that is out of bounds of an array
Trying to store a value into an array of an incompatible class or
type
Trying to cast an instance of a class to one of its subclasses.
Passing a parameter that is not in a valid range or value for a method.
Trying to illegally change the state of a thread
Attempting to use a negative size for an array
Using a null object reference as a legitimate object reference to access a
method or a variable.
Converting invalid string to a number
Accessing a character that is out of bounds of a string
Example
class Example
{
public static void main(String args[])
{
int d=0;
int a = 42/d;
}
}
When the Java run-time system detects the attempt to divide by zero, it constructs a
new exception object and then throws this exception. This causes the execution of example
to stop, because once an exception has been thrown, it must be caught by an exception
handler and dealt with immediately. In this example, we haven’t supplied any exception
handlers of our own, so the exception is caught by the default handler provided by the Java
run-time system.
EXCEPTIONS
An exception is a condition that is caused by a runtime error in the program.
Exceptional handling is a mechanism of converting system error messages into user
friendly messages.
The purpose of exception handling mechanism is to provide a means to detect and report
an “exceptional circumstance” so that appropriate action can be taken.
The mechanism suggests incorporation of a separate error handling code that performs
the following tasks:
Checked exceptions: These exceptions are explicitly handled in the code itself with the
help of try-catch blocks. Checked exceptions are extended from java.lang.Exception
class.
Unchecked exceptions: These exceptions are not essentially handled in the program
code; instead the JVM handles such exceptions. Unchecked exceptions are extended
from the java.lang.RuntimeException class.
catch block
Java uses a keyword try to preface of a block of code that is likely to cause an
error condition and “throw” an exception.
A catch block defined by the keyword catch “ catches” the exception “thrown”
by thee try block and handles it appropriately.
The catch block is added immediately after the try block.
The following example illustrates the use of simple try and catch statements.
………………..
………………….
try
{
statement; // generates an exception
}
catch (Exception-type e)
{
statement; // processes the exception
}
………………….
………………………
Example
class Example
OUT PUT
{ Division by zero
public static void main(String args[])
y=1
{
int a=10;
int b= 5;
int c=5;
int x, y;
try
{
x = a / (b-c)
}
catch( ArithmeticException e)
{
System.out.println(“Division by zero”);
}
y= a / (b+c);
System.out.println(“y=”+y);
}
}
catch (Exception-Type-1 e)
catch (Exception-Type-2 e)
catch (Exception-Type-N e)
……………
When an exception in a try block is generated, the java treats the multiple catch
statements like cases in a switch statement.
The first statement whose parameter matches with the exception object will be
executed, and the remaining statements will be skipped.
Example
class Multicatch
{
public static void main(String args[])
{
int a[ ] = (5,10);
int b = 5;
try
{
int x = a[2] / b – a[1];
}
catch(ArithmeticException e)
{
System.out.println(“Division by zero”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array Index error”);
}
catch(ArrayStoreException e)
{
System.out.println(“Wrong data type”);
}
int y = a[1] / a[0];
System.out.println(“y = ” + y);
}
}
Output:
Array Index error
y =2
USING FINALLY STATEMENT
Java supports another statement known as finally statement that can be used to handle an
exception that is not caught by any of the previous statement.
finally block can be used to handle any exception generated within a try block.
It may be added immediately after the try block or after the last catch block shown as
follows.
try try
{ {
--- ---
--- ---
} }
finally catch(…. )
{ {
--- -----
} --- --
}
….
….
finally
{
---
---
}
when a finally block is defined, this is guaranteed to execute, regardless of whether or not
an exception is thrown.
As a result, we can use it to perform certain house-keeping operations such as closing
files and releasing system resources.
Example
class FinallyDemo
Output
{
inside procA
static void proA( ) procA’s
{ finally
try
{
System.out.println(“Inside ProcA”);
}
finally
{
System.out.println(“ProA’s finally”);
}
}
public static void main( String args[] )
{
procA( );
}
}
There may be when we would like to throw our own exceptions. We can do this by using the
keyword throw as follows:
throw new Throwabl’e subclass;
Example:
import java.lang.Exception;
class MyException extends Exception
{
MyException (String message)
{
super(message);
}
}
class TestMyException
{
public static void main(String args[])
{
int x=5, y= 1000;
try
{
float z = (float) x / (float) y;
if (z < 0.01)
{
throw new Myexception (“Number is too small”);
}
}
catch ( MyException e)
{
System.out.println(“Caught my exception”);
System.out.println(e.getMessage());
}
finally
{
System.out.println(“I am always here”);
}
}
}
Output:
Caught my exception
Number is too small
I am always here
MULTITHREADED PROGRAMMING
INTRODUCTION
A flow of control is known as thread.
If a program contains multiple flow of controls for achieving concurrent execution
then that program is known as multi threaded program.
A program is said to be a multi threaded program if and only if in which there exist ‘n’
number of sub-programs there exist a separate flow of control.
All such flow of controls are executing concurrently such flow of controls are known as
threads and such type of applications or programs is called multi threaded programs.
A thread is similar to a program that has a single flow of control. It has a beginning a
body, and an end, and executes commands sequentially.
Switching Switching
CREATING THREADS
{
---- ( Statements for implementing thread )
----
The run( ) method should be invoked by an object of the concerned thread. This can be
achieved by creating the thread and initiating it with the help of another thread method
called start( ).
A NEW THREAD CAN BE CREATED IN TWO WAYS.
1. By creating a thread class : Define a class that extends thread class and override its
run( ) method with the code required by the thread.
The approach to be used depends on what the class we are creating requires.
If it requires to extend another class, then we have no choice but to implement the
Runnable interface, since Java classes cannot have two superclasses.
EXTENDING THE THREAD CLASS
We can make our class Runnable as a thread by extending the class java.lang.Thread.
This gives us access to all the thread methods directly. It includes the following steps:
1. Declare the class as extending the Thread class.
2. Implement the run( ) method that is responsible for executing the sequence of code that
the thread will execute.
3. Create a thread object and call the start( ) method to initiate the thread execution.
To actually create and run on instance of the thread class, we must write the following
MyThread aThread = new MyThread( );
The second line calls the start( ) method causing the thread to move into the runnable
state.
Then the Java runtime will schedule the thread to run by invoking its run( ) method. Now,
the thread is said to be in the running state.
Output
From thread A:i=1
From thread A:i=2
From thread B:i=1
From thread B:i=2
From thread A:i=3
Exit from A
From thread B:i=3
Exit from B
The main thread dies at the end of its main method. However, before it dies, it creates and
starts all the two threads A and B. Note that the output from the threads are not specially
sequential.
STOPPING AND BLOCKING THE THREAD
Stopping a Thread
Whenever we want to stop a thread from running further, we may do so by calling its
stop( ) method, like:
aThread.stop( );
This statement causes the thread to move to the dead state. The stop( ) method may be
used when the premature death of a thread is desired.
Blocking a Thread
A thread can also be temporarily suspended or blocked from entering into the runnable
and subsequently running state by using either of the following thread methods:
sleep( ) // blocked for a specified time
The thread will return to the runnable state when the specified time is elapsed in the case
of sleep( ), the resume( ) method is invoked in the case of suspend( ) and the notify( )
method is called in the case of wait( ).
LIFE CYCLE OF A THREAD
During the life time of a thread, there are many states it can enters. They include:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state(Terminated)
Newborn
start
Active Thread
yield
stop
Killed thread
sleep,wait,suspend resume,notify
Blocked stop
Idle thread
NEWBORN STATE
When we create a thread object, the thread is born and is said to be in newborn state. The
thread is not yet scheduled for running. At this state, we can do only one of the following
things with it:
Schedule it for running using start( ) method
Kill it using stop( ) method
If scheduled, it moves to the runnable state. If we attemps to use any other method at this
stage, an exception will be thrown.
RUNNABLE STATE
The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor. That is, the thread has joined the queue of threads that are
waiting for execution.
If all threads have equal priority, then they are given time slots for execution in round
robin fashion, i.e., first-come, first-serve manner.
This process of assigning time to threads is known as time-slicing.
However, if we want a thread to relinquish control to another thread of equal priority
before its turn comes, we can do so by using the yield( ) method.
Yield
●
● ● ●
RUNNING STATE
Running means that the processor has given its time to the thread for its execution.
The thread runs until it relinquish control on its own or it is preempted by a higher
priority thread.
A running thread may relinquish its control in one of the following situations.
1 .It has been suspended using suspend( ) method. A suspended thread can be revived by using
the resume( ) method. This approach is useful when we want to suspend a thread for some time
due to certain reason, but do not want to kill it.
. suspend
● ● ●
resume
2. It has been made to sleep. We can put a thread to sleep for a specified time period
using the method sleep( time) where time is in milliseconds. This means that the
thread is out of queue during this time period. The thread re-enters the runnable state
as soon as this time period is elapsed.
Sleep ( t )
● ● After( t) ●
3.It has been told to wait until some event occurs. This is done using the wait( ) method. The
thread can be scheduled to run again using the notify( ) method.
Wait
● ● ●
notify
BLOCKED STATE
The thread is said to be blocked when it is prevented from entering into the runnable state
and subsequently the running state.
This happens when the thread is suspended, sleeping, or waiting in order to satisfy certain
requirements. A blocked thread is considered “ not runnable” but not dead and therefore
qualified to run again.
DEAD STATE
Every thread has a life cycle.
A running thread ends its life when it has completed executing its run( ) method.
It is a natural death. However, we can kill it by sending the stop message to it at any state
thus causing premature death to it.
A thread can be killed as soon as it is born, or while it is running, or even when it is in “
not runnable “ condition.
USING THREAD METHODS
Example
class A extends Thread
{
public void run( )
{
for(int i=1; i< 5;i++)
{
if (i == 1 ) yield( );
System.out.println(“\n From Thread A:i=”+i);
}
System.out.println(“Exit from A”);
}
}
class B extends Thread
{
public void run( )
{
for(int j=1 ;j<=5;j++)
{
System.out.println(“\n From Thread B:j=”+j);
if (j==3 )
stop( );
}
System.out.println(“Exit from B”);
}
}
class C extends Thread
{
public void run( )
{
for(int k=1; k<=5;k++)
{
System.out.println(“\t From Thread C:k=”+k);
if (k === 1 )
try
{
sleep(1000);
}
catch( Exception e)
{
}
}
System.out.println(“Exit from C”);
}
}
class ThreadMethods
{
public static void main(String[] args)
{
A threadA =new A( );
B threadB =new B( );
C threadC =new C( );
System.out.println(“Start thread A”);
threadA.start( );
System.out.println(“Start thread B”);
threadB.start( );
System.out.println(“Start thread C”);
threadC.start( );
System.out.println(“End of main thread”);
}
}
Output
Start thread A
Start thread B
Start thread C
From Thread B:j=1
From Thread B:j=2
From Thread A:i=1
From Thread A:i=2
End of main thread
From Thread C:k=1
From Thread B:j=3
From Thread A:i=3
From Thread A:i=4
From Thread A:i=5
Exit from A
From Thread C:k=2
From Thread C:k=3
From Thread C:k=4
From Thread C:k=5
Exit from C
THREAD EXCEPTIONS
Note that the call to sleep( ) method is enclosed in a try block and followed by a catch
block. This is necessary because the sleep( ) method throws an exception, which should
be caught.
If we fail to catch the exception, program will not compile.
Java run system will throw IllegalThreadStateException whenever we attempt to invoke a
method that a thread cannot handle in the given state.
For example, a sleeping thread cannot deal with the resume( ) method because a sleeping
thread cannot receive any instructions. The same is true with the suspend( ) method when
it is used on a blocked ( not runnable ) thread.
Whenever we call a thread method that is likely to throw an exception, we have to supply
an appropriate exception handler to catch it.
THREAD PRIORITY
In Java, each thread is assigned a priority, which affects the order in which it is scheduled
for running.
The threads of the same priority are given equal treatment by the Java scheduler and,
therefore they share the processor on a first-come,first-serve basis. Java permits us to set
the priority of a thread using the setPriority( ) method as follows:
ThreadName.setPriority( int number );
The number is an integer value to which the thread’s priority is set. The thread class
defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY=5
MAX_PRIORITY = 10
The number may assume one of these constants or any value between 1 and 10. Note that
the default setting is NORM_PRIORITY.
By assigning priorities to threads, we can ensure that they are given the attention they
deserve. Whenever multiple threads are ready for execution, the Java system chooses the
highest priority thread and execute it.
Remember that the highest priority thread always preempts any lower priority threads.
Example
class A extends Thread
{
public void run( )
{
System.out.println(“Thread` A Started”);
for(int i=1;i<=3;i++)
System.out.println(“\t From thread A:i=”+i);
System.out.println(“Exit from A”);
}
}
class B extends Thread
{
public void run( )
{
System.out.println(“Thread B Started”);
for(int i=1;i<=3;i++)
System.out.println(“\t From thread B:j=”+j);
System.out.println(“Exit from B”);
}
}
class C extends Thread
{
public void run( )
{
System.out.println(“Thread C Started”);
for(int i=1;i<=3;i++)
System.out.println(“\t From thread C:i=”+i);
System.out.println(“Exit from C”);
}
}
class ThreadPriority
{
public static void main(String args[])
{
A threadA = new A( );
B threadB = new B( );
C threadC = new C( );
threadC.setPriority( Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority( )+1);
threadA.setPriority( Thread.MIN_PRIORITY);
System.out.println(“Start thread A”);
threadA.start( );
System.out.println(“Start thread B”);
threadB.start( );
System.out.println(“Start thread C”);
threadC.start( );
System.out.println(“End of main thread”);
}
}
Output
Start thread A
Start thread B
Start thread C
Thread B Started
From thread B:j=1
From thread B:j=2
Thread C Started
From thread C:k=1
From thread C:k=2
From thread C:k=3
Exit from C
End of main thread
From thread B:j=3
Exit from B
Thread A Started
From thread A:i=1
From thread A:i=2
From thread A:i=3
Exit from A
SYNCHRONIZATION
In the above examples, we have seen threads that use their own data and methods
provided inside their run( ) method.
What happens when they try to use data and methods outside themselves. On such
occasions, they may compete for the same resources and may lead to serious problems.
For example, one thread may try to send a record from a file while another is still writing
to the same file.
Depending on the situation, we may get strange results. Java enables us to overcome this
problem using a technique known as synchronization.
In case of Java, the keyword synchronized helps to solve such problems by keeping a
watch an such locations. For example, the method that will read information from a file
and the method that will update the same file may be declared as synchronized.
Example
synchronized void update( )
{
---- // code here is synchronized
----
}
When we declare a method synchronized, Java creates a “monitor” and hands it over to
the thread that calls the method first time.
As long as the thread holds the monitor, no other thread can enter the synchronized
section of code.
A monitor is like a key and the thread that holds the key can only open the lock.
It is also possible to mark a block of code as synchronized as shown below:
synchronized ( lock-object )
{
---- // code here is synchronized
----
}
Whenever a thread has completed its work by using synchronized method, it will hand
over the monitor to the next thread that is ready to use the same resource.
An interesting situation may occur when two or more threads are waiting to gain control
of a resource.
Due to some reason, the condition on which the waiting threads rely on gain control does
not happen.
This result in what is known as deadlock. For example, assume that the thread A must
access method1 before it can release method2, but the threadB cannot release method1
until it gets hold on method2.
Because these are mutually exclusive conditions, a deadlock occurs. The code below
illustrate this:
ThreadA
synchronized method2( )
{
synchronized method1( )
{
…………………
}
}
ThreadB
synchronized method1( )
{
synchronized method2( )
{
………………………….
}
}
IMPLEMENTING THE RUNNABLE INTERFACE
To create thread using the Runnable interface, we must perform the steps listed below:
1. Declare the class as implementing the Runnable interface.
2. Implement the run( ) method.
3. Create a thread by defining an object that is instantiated from this “runnable” class as the
target of the thread.
4. Call the thread’s start( ) method to run the thread.
If the direct reference to the thread threadX is not required, then we may use a shortcut as
shown below:
new Thread( new X( ) ).start( );
Example
class X implements Runnable
{
public void run( )
{
for(int i=1;i<3;i++)
{
System.out.println(“\t ThreadX:”+ i);
}
System.out.println(“End of thread X”);
}
}
class RunnableTest
{
public static void main(String[] args)
{
X runnable = new X( );
Thread threadX = new Thread( runnable );
threadX.start( );
System.out.println(“End of main thread”);
}
}
Output
End of main Thread
ThreadX:1
ThreadX:2
End of ThreadX
INTER-THREAD COMMUNICATION
Inter-thread communication can be defined as the exchange of messages between two or
more threads.
The transfer of messages takes place before or after the change of state of a thread.
For example, an active thread may notify to another suspended thread just before
switching to the suspend state.
Java implements inter-thread communication with the help of following three methods.
notify(): Resumes the first thread that went into the sleep mode. The object class
declaration of
notify() method is shown below:
notifyall(): Resumes all the threads that are in sleep mode. The execution of these threads
happens as per priority. The object class declaration of notifyall() method is shown below:
Wait(): sends the calling thread into the sleep mode. This thread can now be activated only
by notify() or notifyall() methods. The object class declaration of wait() method is shown
below:
**************UNIT IV COMPLETED***************
UNIT V
INTRODUCTION
A file is a collection of records placed in a particular area on the disk.
A record is composed of several fields is a group of characters.
Characters in java are Unicode characters composed of two bytes, each byte
containing eight binary digits, 1 or 0.
Storing and managing data using files is known as file processing which includes
tasks such as creating files, updating files and manipulation of data.
Java supports many powerful features for managing input and output of data using
files.
The process of reading and writing objects is called object serialization.
CONCEPT OF STREAMS
In file processing, input refers to the flow of data into a program and output means the flow
of data out of a program.
Input to a program may come from the keyboard, the mouse, the memory, the disk, a
network, or another program.
Output from a program may go to the screen, the printer, the memory, the disk, or another
program.
Relationship of Java program with I/O devices
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.
Reading bytes
Closing streams
Making positions in streams
Skipping ahead in a stream
Finding the number of bytes in a stream
The OutputStream includes methods that are designed to perform the following tasks:
Writing bytes
Closing streams
Flushing streams
OuputStream Methods
Hierarchy of output stream classes
APPLET PROGRAMMING
INTRODUCTION
Applets are small java program that are primarily used in internet
computing. They can be transferred over the internet from one computer to another and run
using the applet viewer or any web browser that support the java program.
An applet can perform arithmetic operations, play sounds, display graphics,
accept user input , create animation and play interactive games.
Java applications are generally run from a command-line prompt using JDK.
Applets are run on any browser supporting Java.
For an applet to run it must be included in a web page using HTML pages.
When a browser loads a web page including an applet, the browser downloads the
applet from the web server and runs it on the web owner’s system.
Java interpreter is not required specifically for doing so it is already built-in the
browser.
Local Applet:
An applet which is developed locally and stored in the local system is known as
the local applet When the web page is trying to find the local applet.
It does' need to use the internet and therefore the local system does not require the
internet connection. It simply searches the directories in the local system and locates and load
the specified applet.
In order to locate and load the local applet we must know the applet address on
the web page.
This address is known as the URL uniform resource locator. and must be
specified in the applet HTML document as the value of the code base attribute.
Remote Applet:
URL:
java.lang.object
java.awt.component
java.awt.container
java.awt.pannel
java.applet.Applet
APPLET LIFE CYCLE
Every java applet inherit a set a default behavior from the Applet class. As the
result applet is loaded,it undergoes a series of changes in its state as shown in the above figure
the applet states will be
* Born or initialization state
* Running state
* Idle state
* Dead or destroyed state
Dead End
Destroyed
Exit of Browser
Initialization State:
It is achieved by calling init() method of the applet class. We can perform the
functions like
Create objects needed by the applet
Set up initial values
Load images or fonts
Setup colors
This method occurs only once
Syntax:
……..(Action)
Running state:
Applet enter the running state when the system calls the start() method of the
applet class. This occurs automatically after the applet is initialized.
Starting can also if the applet is already in the idle stopped state. The start()
method may be called by more than one time.
public void start()
………(Action)
…………….(Action)
}
Dead State
An applet is said to be dead when it is removed from the memory. This occurs
automatically by invoking the destroy() method.
When we quit the browser. Like the initialization destroying stage occur only
once in the applet life cycle.
public void destroy()
{
...........(Action)
}
Display State
Applet moves to the display state whenever it has to perform some output
operation on the screen. This happens immediately after the applet enters into the running
state.
The paint() method is called to accomplish this task. Almost every applet
will have a paint() method like other method in the life cycle.
public void paint(Graphics g)
{
……….(Display statements)
}
CREATING AN EXECUTABLE APPLET
Let us consider the HelloJava applet created. This applet has been stored in a file
called HelloJava.java. Here are the steps required for compiling the HelloJava applet.
1. Move to the directory containing the source code and type the following command
javac HelloJava.java
2. The compiled o/p file called HelloJava.class is placed in the same directory as the
source.
3. If any error message is received ,then we must check for errors correct them and
compile the applet again.
DESIGINING A WEB PAGE
A webpage is basically made up of text and HTML tags. It is also known as HTML
page or document.
A webpage is marked by an opening HTML tag <HTML> and a closing
tag</HTML>
It is divided into three major sections.
1. Comment section(optional)
2. Head section(optional)
3. Body section
HTML tags format:
<HTML>
<!
……………………………. Comment Section
>
<HEAD>
Title tag
Head Section
</HEAD>
<BODY>
Applet tag Body Section
</BODY>
</HTML>
1. Comment Section:
This section contains comments about the web page.
It tells what is going on the web page.
The comment line begins with <! And ends with >
2. Head Section:
This session contains the title for the web page.
Starting<HEAD> and ending with </HEAD>
<HEAD>
<TITLE> WELCOME TO JAVA APPLETS</TITLE>
</HEAD>
3.Body Section:
This section contains the entire information about the web page
<BODY>
<CENTER>
<H1> APPLETS</H1>
<BR>
</CENTER>
<APPLET
CODE= “HELLO.CLASS”
WIDTH=300
HEIGHT=200>
</APPLET>
</BODY>
APPLET TAG
The <APPLET…> tag supplies the name of the applet to be loaded and tells the
browser how much space the applet requires.
Example:
<APPLET
CODE=helloJava.class
WIDTH = 400
HEIGHT = 200>
</APPLET>
Note that <APPLET> tag discussed above specifies three things:
1. Name of the applet.
2. Width of the applet.(in pixels)
3. Height of the applet.(in pixels)
HelloJava.java
HelloJava.class
HelloJava.html
If we use a Java-enabled web browser, we will be able to see the entire web page
containing the applet.
If we use the appletviewer tool, we will only see the applet output.
Ex: appletviewer Hellojava.html
AppletViewer:Hellojava.class
Applet
Hello Java
appletloader.started
APPLET TAGS
The syntax of the <APPLET> tag in full form is shown as follows:
<APPLET
[CODEBASE = codebase_URL]
CODE = AppletFileName.class
[ALT = alternate_text]
[NAME = applet_instance_name]
WIDTH = pixels
HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels]
[HSPACE = pixels]
>
……….
</APPLET>
Attribute Meaning
CODE = Specifies the name of the applet to be laoded.
AppletFileName.class
CODEBASE = codebase_URL Specifies the URL of the directory in which the applet resides.
WIDTH = pixels These attributes specify the width and height of the space on
HEIGHT = pixels the HTML page that will be reserved for the applet.
NAME = A name for the applet may optionally be specified.
applet_instance_name
ALIGN = alignment This optional attribute specifies where on the page the applet
will appear. Possible values for alignment are:TOP, BOTTOM,
LEFT, RIGHT, MIDDLE ETC.
HSPACE = pixels This attribute specifies the amount of horizontal blank space
the browser should leave surrounding the applet.
VSPACE = pixels This attribute specifies the amount of vertical blank space the
browser should leave surrounding the applet.
ALT = alternate_text Non-java browsers will display this text where the applet
would normally go. This attribute is optional.
import java.awt.*;
import java.applet.*;
public class HelloJavaParam extends Applet
String str;
str= getParameter(“string”);
if (str == null)
str = “Java”;
<HTML>
<HEAD>
<BODY>
WIDTH = 400
VALUE = “Applet!”>
</APPLET>
</BODY>
</HTML>
Save this file as HelloJavaParam.html and then run the applet using the applet viewer
as follows:
Appletviewer HelloJavaParam.html
AppletViewer:HelloJavaParam.class
Applet
Hello Applet!
appletloader.started
APPLET TAGS
Now, remove the <PARAM> tag from the HTML file and then run the applet again.
The result will be as shown below
AppletViewer:HelloJavaParam.class
Applet
Hello Java
appletloader.started
APPLET TAGS
We can align the output of the applet using the ALIGN attribute. This attribute can have
one of the nine values:
For example ALGN = LEFT will display the output at the left margin of the page.
Example:
<HTML>
<HEAD>
</HEAD>
<BODY>
WIDTH = 400
HEIGHT = 200
</APPLET>
</BODY>
</HTML>
…………………………………
………………………………………….
……………………………………………………………………………
Hello Java
applet
Text
An applet aligned
right
MORE ABOUT HTML TAGS
Tag Function
<HTML> … Indicates starting & ending of a HTML file
</HTML>
In applets, we can display numerical values by first converting them into strings
and then using the drawstring() method of Graphics class.
We can do this easily by calling the ValueOf() method of String class.
import java.awt.*;
import java.applet.*;
public class NumValues extends Applet
{
public void paint (Graphics g)
{
int value1 = 10;
int value2= 20;
int sum = value1 + value2;
String s = “sum:” + String.valueOf(sum);
g.drawString(s, 100, 100);
}
}
<html>
<applet
Code = Numvalues.class
Width = 300
Height = 300 >
</applet>
</html>
Output:
AppletViewer:Numvalues.class
Applet
Sum: 30
appletloader.started
import java.awt.*;
import java.applet.*;
TextField text1,text2;
text1=new TextField(8);
text2=new TextField(8);
add(text1);
add(text2);
text1.settext(“0”);
text2.settext(“0”);
int x=0,y=0,z=0;
String s1,s2,s;
try
s1=text1.gettext();
x=integer,parseINT(S1);
s2=text2.getText();
y=Integer.parseint(s2);
z=x+y;
s=String.valueof(z);
g.drawstring(s, 100,75);
repaint();
return true;
<html>
<applet
code =userIn.class
width = 300
height = 200>
</applet>
</html>
appletloader.started
EVENT HANDLING
Action Event is triggered whenever a user interface element is activated, such as
selection of a menu item.
Item Event is triggered at the selection or deselection of an itemized or list element, such
as check box.
TextEvent is triggered when a text field is modified.
WindowEvent is triggered whenever a window-related operation is performed, such as
closing or activating a window.
KeyEvent is triggered whenever a key is pressed on the keyboard.
Event Sources
The registration of a listener object with an event ensures that on occurrence
of the event, the corresponding listener object is notified for taking
appropriate action.
Following is the syntax for registering a listener for an event.
Event Listeners
The event listener object contains methods for receiving and processing event
notifications sent by the source object.
These methods are implemented from the corresponding listener interface
contained in the java.awt.event package.
Event Classes
All the events in java corresponding event classes associated with them.
Each of these classes is derived from one single super class, i.e.,
EventObject.
It is contained in the java.util.package.
The EventObject class contains the following two important methods for
handling events:
getSource(): Returns the event source.
toString(): Returns a string containing information about the event
source.
GRAPHICS PROGRAMMING
INTRODUCTION
One of the most important features of Java is its ability to draw graphics.
We can write java applets that draw lines, figures of different shapes, images, and text in
different fonts and styles.
We can also incorporate different colours in display.
Every applet has its own area of the screen known as canvas, where it creates its display.
A Java applet draws graphical image inside its space using the coordinate system.
Java’s coordinate system has the origin(0,0) in the upper-left corner.
Positive x values are to the right, and positive y values are to the bottom.
The values of coordinates x and y are in pixels.
THE GRAPHICS CLASS
Java’s graphics class includes methods for drawing many different types of shapes.
To draw a shape on the screen , we may call one of the methods available in the Graphics class.
The following are the most commonly used methods in Graphics class.
Drawing methods of the graphics class
Method Description
clearRect( ) Erases a rectangular area of the canvas.
copyArea( ) Copies a rectangular area of the canvas to another area.
drawArc( ) Draws a hollow arc.
drawLine( ) Draws a straight line.
drawOval( ) Draws a hollow oval.
drawPolygon( ) Draws a hollow polygon.
drawRect( ) Draws a hollow rectangle.
drawRoundRect( ) Draws a hollow rectangle with rounded corners.
drawstring( ) Displays a text string.
fillArc( ) Draws a filled arc.
fillOval( ) Draws a filled oval.
fillPolygon( ) Draws a filled polygon
fillRect( ) Draws a filled rectangle.
frillRoundRect( ) Draws a filled rectangle with rounded corners.
getcolor( ) Retrieves the current drawing colour.
getFont( ) Retrieves the currently used font.
getFontMetrics( ) Retrieves information about the current font.
setColor( ) Sets the drawing colour.
setFont( ) Sets the font.
Example:
<html>
<body>
<applet code=graphics_methods.class width = 200 height=200>
</applet>
</body>
</html>
import java.awt.*;
import java.applet.*;
public class graphics_methods extends Applet
{
public void paint(Graphics GA)
{
GA.drawRect(160,5,60,60);
GA.drawLine(380,100,200,180);
GAdrawOval(10,120,155,95);
}
}
AppletViewer graphics_methods.class
Applet
Ex:
g.drawLine(10,10,50,50);
Ex:
g.drawRect(10,60,40,30)
g.fillRect(60,10,30,80)
Example:
import java.awt.*;
import java.Applet.*;
g.drawLine(10,10,50,50);
g.drawRect(10,60,40,30);
<Applet
Code = LineRect.class
Width = 250
Height = 200>
</Applet>
AppletViewer:Linerect.class
Applet
appletloader.started
Heigh
t
Width
Ex:
import java.awt.*;
import java.applet.*;
</Applet>*/
appletloader.started
DRAWING ARCS
An arc is a part of an oval.
The drawArc( ) designed to draw arcs takes six arguments.
The first four of are the same as arguments for drawOval( )method and the last
two represent the starting angle of the arc and the number of degrees around the
arc.
The fillArc( ) method to fill the arc.
import java.awt.*;
import java.applet.*;
}
}
DRAWING POLYGONS
import java.awt.*;
import java.applet.*;
import java.awt.*;
import java.applet.*;
int n = x.length;
g.drawPolygon( x, y, n);
}
USING CONTROL LOOPS IN APPLETS
Example:
import java.awt.*;
import java.applet.*;
public class ControlLoop extends Applet
{
public void paint(Graphics g)
{
for (int i=0;i<=4;i++)
{
if(i%2)==0
g.drawOval(120, i*60+10, 50, 50);
else
g.fillOval(120, 1*60+10, 50, 50);
}
}
} AppletViewer.controlLoop.class
Applet
appletloader.started
Applets can be designed to display bar charts, which are commonly used in
comparative analysis of data.
The table below shows the annual turnover of a company during the period 1991
– 1994.
These values may be placed in a HTML file as PARAM attributes and then used
in applet for displaying a bar chart.
Example:
import java.awt.*;
import java.applet.*;
public class BarChart extends Applet
{
int n=0;
String label [];
int value [];
public void init()
{
try
{
n=integer.parsInt (getParameter(“columns”));
label=new String[n];
value = new int [n];
label[0]=getParameter (“label1”);
label[1]=getParameter (“label2”);
label[2]=getParameter (“label3);
label[3]=getParameter (“label4”);
value [0] =Integer.parseInt (getParameter (“c1”));
value [1] =Integer.parseInt (getParameter (“c2”));
value [2] =Integer.parseInt (getParameter (“c3”));
value [3] =Integer.parseInt (getParameter (“c4”));
}
catch (NumberFormatException e)
{
}
}
public void paint (Graphics g)
{
for ( int i=0;i<n;i++)
{
g.setcolor(color.red);
g.drawstring(label [i],20,i*50+30);
g.fillRect(50,i*50+10, value [i],40);
}
}
}
<html>
<applet
Code = BarChart.class
Width = 300
Height = 250>
<PARAM NAME = “columns” VALUE = “4”>
<PARAM NAME = “c1” VALUE =”110”>
<PARAM NAME = “c2” VALUE =”150”>
<PARAM NAME = “c3” VALUE =”100”>
<PARAM NAME = “c4” VALUE =”170”>
<PARAM NAME = “label1” VALUE =”91”>
<PARAM NAME = “label2” VALUE =”92”>
<PARAM NAME = “label3” VALUE =”93”>
<PARAM NAME = “label4” VALUE =”94”>
</applet>
</html>
AppletViewer.BarChart.class
Applet
91
92
93
94
appletloader.started
EVENT HANDLING
Action Event is triggered whenever a user interface element is activated, such as
selection of a menu item.
Item Event is triggered at the selection or deselection of an itemized or list element, such
as check box.
TextEvent is triggered when a text field is modified.
WindowEvent is triggered whenever a window-related operation is performed, such as
closing or activating a window.
KeyEvent is triggered whenever a key is pressed on the keyboard.
Event Sources
The registration of a listener object with an event ensures that on occurrence
of the event, the corresponding listener object is notified for taking
appropriate action.
Following is the syntax for registering a listener for an event.
Event Listeners
The event listener object contains methods for receiving and processing event
notifications sent by the source object.
These methods are implemented from the corresponding listener interface
contained in the java.awt.event package.
Event Classes
All the events in java corresponding event classes associated with them.
Each of these classes is derived from one single super class, i.e.,
EventObject.
It is contained in the java.util.package.
The EventObject class contains the following two important methods for
handling events:
getSource(): Returns the event source.
toString(): Returns a string containing information about the event
source.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
What is an Event?
Change in the state of an object is known as event i.e. event describes the change in state of
source. Events are generated as result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character through
keyboard,selecting an item from list, scrolling the page are the activities that causes an event to
happen.
Types of Event
Foreground Events - Those events which require the direct interaction of user.They are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering
a character through keyboard,selecting an item from list, scrolling the page etc.
Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer
expires, an operation completion are the example of background events.
Registration Methods
For registering the component with the Listener, many classes provide the registration methods.
For example:
o Button
o MenuItem
o TextArea
o Checkbox
o Choice
o List
Layout Manager
The layout manager automatically positions all the components within the container. If we do not
use layout manager then also the components are positioned by the default layout manager. It is
possible to layout the controls by hand but it becomes very difficult because of the following two
reasons.
Java provide us with various layout manager to position the controls. The properties like
size,shape and arrangement varies from one layout manager to other layout manager. When the
size of the applet or the application window changes the size, shape and arrangement of the
components also changes in response i.e. the layout managers adapt to the dimensions of
appletviewer or the application window.
The layout manager is associated with every Container object. Each layout manager is an object
of the class that implements the LayoutManager interface.
1 LayoutManager
2 LayoutManager2
Following is the list of commonly used controls while designed GUI using AWT.
1 BorderLayout
The borderlayout arranges the components to fit in the five regions: east, west, north,
south and center.
2 CardLayout
The CardLayout object treats each component in the container as a card. Only one card is
visible at a time.
3 FlowLayout
The FlowLayout is the default layout.It layouts the components in a directional flow.
4 GridLayout
5 GridBagLayout
This is the most flexible layout manager class.The object of GridBagLayout aligns the
component vertically,horizontally or along their baseline without requiring the
components of same size.
MENUS
As we know that every top-level window has a menu bar associated with it. This menu bar
consist of various menu choices available to the end user. Further each choice contains list of
options which is called drop down menus. Menu and MenuItem controls are subclass of
MenuComponent class.
Menu Hiearchy
Menu Controls
1 MenuComponent
3 MenuItem
The items in the menu must belong to the MenuItem or any of its subclass.
4 Menu
The Menu object is a pull-down menu component which is displayed from the menu
bar.
5 CheckboxMenuItem
6 PopupMenu
************UNIT V COMPLETED**********
PROGRAMMING IN JAVA
ONE MARK QUESTIONS
1. Who invented Java Programming?
a) Guido van Rossum
b) James Gosling
c) Dennis Ritchie
d) Bjarne Stroustrup
Answer: b
Answer: d
3. Which component is used to compile, debug and execute the java programs?
a) JRE
b) JIT
c) JDK
d) JVM
Answer: c
Answer: b
Answer: c
Answer: d
Answer: d
Answer: c
Answer: b
Answer: b
Answer: b
Answer: c
Answer: b
Answer: d
Answer: c
17. Which of the following is a superclass of every class in Java?
a) ArrayList
b) Abstract class
c) Object class
d) String
Answer: c
Answer: c
19. Which of these packages contains the exception Stack Overflow in Java?
a) java.io
b) java.system
c) java.lang
d) java.util
Answer: c
Answer: b
21. Which of these keywords are used for the block to be examined for exceptions?
a) check
b) throw
c) catch
d) try
Answer: d
22. Which one of the following is not an access modifier?
a) Protected
b) Void
c) Public
d) Private
Answer: b
Answer: c
Answer: d
Answer: b
26. Which of the following option leads to the portability and security of Java?
a. Dynamic
b. Architecture Neutral
c. Use of pointers
d. Object-oriented
Answer: d
Answer: a
30. When does method overloading is determined?
a) At run time
b) At compile time
c) At coding time
d) At execution time
Answer: b
32.Which concept of Java is a way of converting real world objects in terms of class?
a) Polymorphism
b) Encapsulation
c) Abstraction
d) Inheritance
Answer: c
33.Which concept of Java is achieved by combining methods and attribute into a class?
a) Encapsulation
b) Inheritance
c) Polymorphism
d) Abstraction
Answer: a
34.What is it called if an object has its own lifecycle and there is no owner?
a) Aggregation
b) Composition
c) Encapsulation
d) Association
Answer: d
35. What is it called where child object gets killed if parent object is killed?
a) Aggregation
b) Composition
c) Encapsulation
d) Association
Answer: b
36. What is it called where object has its own lifecycle and child object cannot belong to another
parent object?
a) Aggregation
b) Composition
c) Encapsulation
d) Association
Answer: a
37. Method overriding is combination of inheritance and polymorphism?
a) True
b) false
Answer: a
38. What is the default encoding for an OutputStreamWriter?
a. UTF-8
b. Default encoding of the host platform
c. UTF-12
d. None of the above
39. What is the return type of the hashCode() method in the Object class?
a. Object
b. int
c. long
d. void
40. Evaluate the following Java expression, if x=3, y=5, and z=10:
++z + y - y + z + x++
a. 24
b. 23
c. 20
d. 25
Answer: (d) 25
41.Which of the following tool is used to generate API documentation in HTML format
from doc comments in source code?
a. javap tool
b. javaw command
c. Javadoc tool
d. javah command
Answer: b
43. Which of this package is used for analyzing code during run-time?
a) java.applet
b) java.awt
c) java.io
d) java.lang.reflect
Answer: d
44.Which of this package is used for handling security related issues in a program?
a) java.security
b) java.lang.security
c) java.awt.image
d) java.io.security
View Answer
Answer: a
45.Which of these class allows us to get real time data about private and protected member
of a class?
a) java.io
b) GetInformation
c) ReflectPermission
d) MembersPermission
Answer: c
46.Which of this package is used for invoking a method remotely?
a) java.rmi
b) java.awt
c) java.util
d) java.applet
Answer: a
47.Which of these functions is called to display the output of an applet?
a) display()
b) paint()
c) displayApplet()
d) PrintApplet()
View Answer
Answer: b
48.Which of these methods can be used to output a string in an applet?
a) display()
b) print()
c) drawString()
d) transient()
Answer: c
Answer: b
50.Which of these modifiers can be used for a variable so that it can be accessed from any
thread or parts of a program?
a) transient
b) volatile
c) global
d) No modifier is needed
View Answer
Answer: b
51.Which of these operators can be used to get run time information about an object?
a) getInfo
b) Info
c) instanceof
d) getinfoof
Answer: c
Answer: a
53. Which of these keywords is not a part of exception handling?
a) try
b) finally
c) thrown
d) catch
Answer: c
54. Which of these keywords must be used to monitor for exceptions?
a) try
b) finally
c) throw
d) catch
Answer: a
55. Which of these keywords must be used to handle the exception thrown by try block in
some rational manner?
a) try
b) finally
c) throw
d) catch
Answer: d
Answer: c
ONE MARK QUESTIONS
UNIT I
1. Who invented Java Programming?
a) Guido van Rossum
b) James Gosling
c) Dennis Ritchie
d) Bjarne Stroustrup
Answer: b
2. Which statement is true about Java?
a) Java is a sequence-dependent programming language
b) Java is a code dependent programming language
c) Java is a platform-dependent programming language
d) Java is a platform-independent programming language
Answer: d
3. Which component is used to compile, debug and execute the java programs?
a) JRE
b) JIT
c) JDK
d) JVM
Answer: c
4. Which one of the following is not a Java feature?
a) Object-oriented
b) Use of pointers
c) Portable
d) Dynamic and Extensible
Answer: b
5. Which of these cannot be used for a variable name in Java?
a) identifier & keyword
b) identifier
c) keyword
d) none of the mentioned
Answer: c
6. What is the extension of java code files?
a) .js
b) .txt
c) .class
d) .java
Answer: d
7. What will be the output of the following Java code?
class increment {
public static void main(String args[])
{
int g = 3;
System.out.print(++g * 8);
}
}
a) 32
b) 33
c) 24
d) 25
Answer: a
output:
$ javac increment.java
$ java increment
32
8. Which environment variable is used to set the java path?
a) MAVEN_Path
b) JavaPATH
c) JAVA
d) JAVA_HOME
Answer: d
9. What will be the output of the following Java program?
class output {
public static void main(String args[])
{
double a, b,c;
a = 3.0/0;
b = 0/4.0;
c=0/0.0;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
a)NaN
b) Infinity
c) 0.0
d) all of the mentioned
Answer: d
10. Which of the following is not an OOPS concept in Java?
a) Polymorphism
b) Inheritance
c) Compilation
d) Encapsulation
Answer: c
11. What is not the use of “this” keyword in Java?
a) Referring to the instance variable when a local variable has the same name
b) Passing itself to the method of the same class
c) Passing itself to another method
d) Calling another constructor in constructor chaining
Answer: b
byte b = 50;
b = b * 50;
a) b cannot contain value 50
b) b cannot contain value 100, limited by its range
c) No error in this code
d) * operator has converted b * 50 into int, which can not be converted to byte without
casting
Answer: d
14. Which of the following is a type of polymorphism in Java Programming?
a) Multiple polymorphism
b) Compile time polymorphism
c) Multilevel polymorphism
d) Execution time polymorphism
Answer: b
15. What will be the output of the following Java program?
class leftshift_operator
{
public static void main(String args[])
{
byte x = 64;
int i;
byte y;
i = x << 2;
y = (byte) (x << 2)
System.out.print(i + " " + y);
}
}
a) 0 256
b) 0 64
c) 256 0
d) 64 0
Answer: c
output:
$ javac leftshift_operator.java
$ java leftshift_operator
256 0
16. What will be the output of the following Java code?
class box
{
int width;
int height;
int length;
}
class main
{
public static void main(String args[])
{
box obj = new box();
obj.width = 10;
obj.height = 2;
obj.length = 10;
int y = obj.width * obj.height * obj.length;
System.out.print(y);
}
}
a) 100
b) 400
c) 200
d) 12
Answer: c
output:
$ javac main.java
$ java main200
17. What is Truncation in Java?
a) Floating-point value assigned to a Floating type
b) Floating-point value assigned to an integer type
c) Integer value assigned to floating type
d) Integer value assigned to floating type
Answer:b
18. What will be the output of the following Java program?
class Output
{
public static void main(String args[])
{
int arr[] = {1, 2, 3, 4, 5};
for ( int i = 0; i < arr.length - 2; ++i)
System.out.println(arr[i] + " ");
}
}
a) 1 2 3 4 5
b) 1 2 3 4
c) 1 2
d) 1 2 3
Answer: d
output:
$ javac Output.java
$ java Output
123
19. What will be the output of the following Java code snippet?
class abc
{
public static void main(String args[])
{
if(args.length>0)
System.out.println(args.length);
}
}
a) The snippet compiles and runs but does not print anything
b) The snippet compiles, runs and prints 0
c) The snippet compiles, runs and prints 1
d) The snippet does not compile
Answer: a
20. What is the extension of compiled java classes?
a) .txt
b) .js
c) .class
d) .java
Answer: c.
21. Which exception is thrown when java is out of memory?
a) MemoryError
b) OutOfMemoryError
c) MemoryOutOfBoundsException
d) MemoryFullException
Answer: b
22. What will be the output of the following Java code?
class String_demo
{
public static void main(String args[])
{
char chars[] = {'a', 'b', 'c'};
String s = new String(chars);
System.out.println(s);
}
}
a) abc
b) a
c) b
d) c
Answer: a
23. Which of these are selection statements in Java?
a) break
b) continue
c) for()
d) if()
Answer: d
24. What will be the output of the following Java program?
class recursion
{
int func (int n)
{
int result;
if (n == 1)
return 1;
result = func (n - 1);
return result;
}
}
class Output
{
public static void main(String args[])
{
recursion obj = new recursion() ;
System.out.print(obj.func(5));
}
}
a) 1
b) 120
c) 0
d) None of the mentioned
Answer: a
Output:
$ javac Output.javac
$ java Output 1
25. What will be the output of the following Java code?
class output
{
public static void main(String args[])
{
String c = "Hello i love java";
boolean var;
var = c.startsWith("hello");
System.out.println(var);
}
}
a) 0
b) true
c) 1
d) false
Answer: d
26. Which of these keywords is used to define interfaces in Java?
a) intf
b) Intf
c) interface
d) Interface
Answer: c.
27. What will be the output of the following Java program?
class output
{
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer("Quiz");
StringBuffer s2 = s1.reverse();
System.out.println(s2);
}
}
a) QuizziuQ
b) ziuQQuiz
c) Quiz
d) ziuQ
Answer: d
Output:
$ javac output.java
$ java output
ziuQ
28. What will be the output of the following Java code?
class Output
{
public static void main(String args[])
{
Integer i = new Integer(257);
byte x = i.byteValue();
System.out.print(x);
}
}
a) 257
b) 256
c) 1
d) 0
Answer: c
Output:
$ javac Output.java
$ java Output: 1
29. What will be the output of the following Java program?
class Output
{ public static void main(String args[])
{
double x = 2.0;
double y = 3.0;
double z = Math.pow( x, y );
System.out.print(z);
}
}
a) 9.0
b) 8.0
c) 4.0
d) 2.0
Answer: b
Output:
$ javac Output.java
$ java Output: 8.0
import java.net.*;
class networking
{
public static void main(String[] args) throws Exception
{
URL obj = new URL("https://www.sanfoundry.com/javamcq");
URLConnection obj1 = obj.openConnection();
int len = obj1.getContentLength();
System.out.print(len);
}
}
a) 127
b) 126
c) Runtime Error
d) Compilation Error
Answer: a
Output:
$ javac networking.java
$ java networking : 127
33. Which of the below is not a Java Profiler?
a) JProfiler
b) Eclipse Profiler
c) JVM
d) JConsole
Answer: c
34. What will be the output of the following Java program?
import java.net.*;
class networking
{
public static void main(String[] args) throws MalformedURLException
{
URL obj = new URL("https://www.sanfoundry.com/javamcq");
System.out.print(obj.toExternalForm());
}
}
a) www.sanfoundry.com
b) https://www.sanfoundry.com/javamcq
c) sanfoundry
d) sanfoundry.com
Answer: b
Output:
$ javac networking.java
$ java networking
https://www.sanfoundry.com/javamcq
35. What will be the output of the following Java code snippet?
import java.util.*;
class Arraylists
{
public static void main(String args[])
{
ArrayLists obj = new ArrayLists();
obj.add("A");
obj.add("B");
obj.add("C");
obj.add(1, "D");
System.out.println(obj);
}
}
a) [A, D, C]
b) [A, B, C]
c) [A, B, C, D]
d) [A, D, B, C]
Answer: d
Output:
$ javac Arraylist.java
$ java Arraylist
[A, D, B, C].
36. Which of these packages contains the exception Stack Overflow in Java?
a) java.io
b) java.system
c) java.lang
d) java.util
Answer: c
37. What will be the output of the following Java program?
import java.util.*;
class Collection_iterators
{
public static void main(String args[])
{
LinkedList list = new LinkedList();
list.add(new Integer(2));
list.add(new Integer(8));
list.add(new Integer(5));
list.add(new Integer(1));
Iterator i = list.iterator();
Collections.reverse(list);
Collections.sort(list);
while(i.hasNext())
System.out.print(i.next() + " ");
}
}
a) 1 2 5 8
b) 2 1 8 5
c) 1 5 8 2
d) 2 8 5 1
Answer: a
38. Which of these statements is incorrect about Thread?
a) start() method is used to begin execution of the thread
b) run() method is used to begin execution of a thread before start() method in special cases
c) A thread can be formed by implementing Runnable interface only
d) A thread can be formed by a class that extends Thread class
Answer: b
39. Which of these keywords are used for the block to be examined for exceptions?
a) check
b) throw
c) catch
d) try
Answer: d
40. What will be the output of the following Java code?
class newthread extends Thread
{
Thread t;
newthread()
{
t1 = new Thread(this,"Thread_1");
t2 = new Thread(this,"Thread_2");
t1.start();
t2.start();
}
public void run()
{
t2.setPriority(Thread.MAX_PRIORITY);
System.out.print(t1.equals(t2));
}
}
class multithreaded_programing
{
public static void main(String args[])
{
new newthread();
}
}
a) truetrue
b) falsefalse
c) true
d) false
Answer: b
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
falsefalse
41. Which one of the following is not an access modifier?
a) Protected
b) Void
c) Public
d) Private
Answer: b.
42. What will be the output of the following Java program?
final class A
{
int i;
}
class B extends A
{
int j;
System.out.println(j + " " + i);
}
class inheritance
{
public static void main(String args[])
{
B obj = new B();
obj.display();
}
}
a) 2 2
b) 3 3
c) Runtime Error
d) Compilation Error
Answer: d
output:
$ javac inheritance.java
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
i cannot be resolved or is not a field
43. What is the numerical range of a char data type in Java?
a) 0 to 256
b) -128 to 127
c) 0 to 65535
d) 0 to 32767
Answer: c
44. Which class provides system independent server side implementation?
a) Server
b) ServerReader
c) Socket
d) ServerSocket
Answer: d
46. Which of the following is true about servlets?
a) Servlets can use the full functionality of the Java class libraries
b) Servlets execute within the address space of web server, platform independent and uses
the functionality of java class libraries
c) Servlets execute within the address space of web server
d) Servlets are platform-independent because they are written in java
Answer: b
5 Marks
1. Explain in detail about features of java.
2. Describe about Java program structure.
3. Explain in detail about Java statements.
4. Explain Command line arguments with suitable example.
5. What are the types of constants? Explain in detail.
6. Write short notes on Data types in java.
7. Explain in detail about variables.
10 Marks
1. What is mean by OOP? Explain OOP Concepts.
class multidimention_array
{
public static void main(String args[])
{
int arr[][] = new int[3][];
arr[0] = new int[1];
arr[1] = new int[2];
arr[2] = new int[3];
int sum = 0;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < i + 1; ++j)
arr[i][j] = j + 1;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < i + 1; ++j)
sum + = arr[i][j];
System.out.print(sum);
}
}
a) 11
b) 10
c) 13
d) 14
Answer: b
output:
$ javac multidimention_array.java
$ java multidimention_array
10
8. What will be the output of the following Java code?
class evaluate
{
public static void main(String args[])
{
int arr[] = new int[] {0 , 1, 2, 3, 4, 5, 6, 7, 8, 9};
int n = 6;
n = arr[arr[n] / 2];
System.out.println(arr[n] / 2);
}
}
a) 3
b) 0
c) 6
d) 1
Answer: d
output:
$ javac evaluate.java
$ java evaluate:1
9. What will be the output of the following Java code?
class array_output
{
public static void main(String args[])
{
char array_variable [] = new char[10];
for (int i = 0; i < 10; ++i)
{
array_variable[i] = 'i';
System.out.print(array_variable[i] + "");
}
}
}
a) 1 2 3 4 5 6 7 8 9 10
b) 0 1 2 3 4 5 6 7 8 9 10
c) i j k l m n o p q r
d) i i i i i i i i i i
Answer: d
output:
$ javac array_output.java
$ java array_output
iiiiiiiiii
10. What will be the output of the following Java code?
class array_output
{
public static void main(String args[])
{
int array_variable[][] = {{ 1, 2, 3}, { 4 , 5, 6}, { 7, 8, 9}};
int sum = 0;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3 ; ++j)
sum = sum + array_variable[i][j];
System.out.print(sum / 5);
}
}
a) 8
b) 9
c) 10
d) 11
Answer: b.
output:
$ javac array_output.java
$ java array_output:9
11. What is the type of variable ‘b’ and ‘d’ in the following Java snippet?
int a[], b;
int []c, d;
a) ‘b’ and ‘d’ are int
b) ‘b’ and ‘d’ are arrays of type int
c) ‘b’ is int variable; ‘d’ is int array
d) ‘d’ is int variable; ‘b’ is int array
Answer: c
12. Which of these is an incorrect array declaration?
a) int arr[] = new int[5] ;
b) int [] arr = new int[5] ;
c)int arr[];arr = new int[5];
d) int arr[] = int [5] new;
Answer: d
13. What will be the output of the following Java code?
1. int arr[] = new int [5];
2. System.out.print(arr);
a) 0
b) value stored in arr[0].
c) 00000
d) Garbage value
Answer: d
14. What will be the output of the following Java code snippet?
1. Object[] names = new String[3];
2. names[0] = new Integer(0);
a) ArrayIndexOutOfBoundsException
b) ArrayStoreException
c) Compilation Error
d) Code runs successfully
Answer: b
15. Generics does not work with?
a) Set
b) List
c) Tree
d) Array
Answer: d
16. How to sort an array?
a) Array.sort()
b) Arrays.sort()
c) Collection.sort()
d) System.sort()
Answer: b.
17. How to copy contents of array?
a) System.arrayCopy()
b) Array.copy()
c) Arrays.copy()
d) Collection.copy()
Answer: a
18. Can you make an array volatile?
a) True
b) False
Answer: a
19. Where is an array stored in memory?
a) heap space
b) stack space
c) heap space and stack space
d) first generation memory
Answer: a
20. An array elements are always stored in ________ memory locations.
a) Sequential
b) Random
c) Sequential and Random
d) Binary search
Answer: a
21. What is the range of short data type in Java?
a) -128 to 127
b) -32768 to 32767
c) -2147483648 to 2147483647
d) None of the mentioned
Answer: b
22. What is the range of byte data type in Java?
a) -128 to 127
b) -32768 to 32767
c) -2147483648 to 2147483647
d) None of the mentioned
Answer: a
23. Which of the following are legal lines of Java code?
1. int w = (int)888.8;
2. byte x = (byte)100L;
3. long y = (byte)100;
4. byte z = (byte)100L;
a) 1 and 2
b) 2 and 3
c) 3 and 4
d) All statements are correct
Answer: d
24. An expression involving byte, int, and literal numbers is promoted to which of these?
a) int
b) long
c) byte
d) float
Answer: a
25. Which of these literals can be contained in float data type variable?
a) -1.7e+308
b) -3.4e+038
c) +1.7e+308
d) -3.4e+050
Answer: b
26. Which data type value is returned by all transcendental math functions?
a) int
b) float
c) double
d) long
Answer: c
27. What will be the output of the following Java code?
class average {
public static void main(String args[])
{
double num[] = {5.5, 10.1, 11, 12.8, 56.9, 2.5};
double result;
result = 0;
for (int i = 0; i < 6; ++i)
result = result + num[i];
System.out.print(result/6);
}
}
a) 16.34
b) 16.566666644
c) 16.46666666666667
d) 16.46666666666666
Answer: c
output:
$ javac average.java
$ java average: 16.46666666666667
28. What will be the output of the following Java statement?
class output {
public static void main(String args[])
{
double a, b,c;
a = 3.0/0;
b = 0/4.0;
c=0/0.0;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
a) Infinity
b) 0.0
c) NaN
d) all of the mentioned
Answer: d
29. What will be the output of the following Java code?
class increment {
public static void main(String args[])
{
int g = 3;
System.out.print(++g * 8);
}
}
a) 25
b) 24
c) 32
d) 33
Answer: c
output:
$ javac increment.java
$ java increment:32
30. What will be the output of the following Java code?
class area {
public static void main(String args[])
{
double r, pi, a;
r = 9.8;
pi = 3.14;
a = pi * r * r;
System.out.println(a);
}
}
a) 301.5656
b) 301
c) 301.56
d) 301.56560000
Answer: a
output:
$ javac area.java
$ java area
301.5656
31. Which component is used to compile, debug and execute java program?
a) JVM
b) JDK
c) JIT
d) JRE
Answer: b
32. Which component is responsible for converting bytecode into machine specific code?
a) JVM
b) JDK
c) JIT
d) JRE
Answer: a
33. Which component is responsible to run java program?
a) JVM
b) JDK
c) JIT
d) JRE
Answer: d
34. Which component is responsible to optimize bytecode to machine code?
a) JVM
b) JDK
c) JIT
d) JRE
Answer: c
35. Which statement is true about java?
a) Platform independent programming language
b) Platform dependent programming language
c) Code dependent programming language
d) Sequence dependent programming language
Answer: a
36. Which of the below is invalid identifier with the main method?
a) public
b) static
c) private
d) final
Answer: c
37. What is the extension of java code files?
a) .class
b) .java
c) .txt
d) .js
Answer: b.
38. What is the extension of compiled java classes?
a) .class
b) .java
c) .txt
d) .js
Answer: a.
39. How can we identify whether a compilation unit is class or interface from a .class file?
a) Java source file header
b) Extension of compilation unit
c) We cannot differentiate between class and interface
d) The class or interface name should be postfixed with unit type
Answer: a
Answer: a
Explanation: Encapsulation is implemented by combining methods and attribute into a class. The
class acts like a container of encapsulating properties.
47. What is it called if an object has its own lifecycle and there is no owner?
a) Aggregation
b) Composition
c) Encapsulation
d) Association
Answer: d
48. What is it called where child object gets killed if parent object is killed?
a) Aggregation
b) Composition
c) Encapsulation
d) Association
Answer: b
49. What is it called where object has its own lifecycle and child object cannot belong to
another parent object?
a) Aggregation
b) Composition
c) Encapsulation
d) Association
Answer: a
50. Method overriding is combination of inheritance and polymorphism?
a) True
b) false
Answer: a
5MARK
10 MARK
Answer: d
6. Which of these is supported by method overriding in Java?
a) Abstraction
b) Encapsulation
c) Polymorphism
d) None of the mentioned
Answer: c
7. What will be the output of the following Java program?
class Alligator
{
public static void main(String[] args)
{
int []x[] = {{1,2}, {3,4,5}, {6,7,8,9}};
int [][]y = x;
System.out.println(y[2][1]);
}
}
a) 2
b) 3
c) 7
d) Compilation Error
Answer: c
Explanation: Both x,and y are pointing to the same array.
8. Which of these constructors is used to create an empty String object?
a) String()
b) String(void)
c) String(0)
d) None of the mentioned
Answer: a
9. What will be the output of the following Java program?
class Abc
{
public static void main(String[]args)
{
String[] elements = { "for", "tea", "too" };
String first = (elements.length > 0) ? elements[0]: null;
}
}
a) Compilation error
b) An exception is thrown at run time
c) The variable first is set to null
d) The variable first is set to elements[0]
Answer: d
11. Which of these class is superclass of every class in Java?
a) String class
b) Object class
c) Abstract class
d) ArrayList class
Answer: b
12. Which of these method of Object class can clone an object?
a) Objectcopy()
b) copy()
c) Object clone()
d) clone()
Answer: c
13. Which of these method of Object class is used to obtain class of an object at run time?
a) get()
b) void getclass()
c) Class getclass()
d) None of the mentioned
Answer: c
14. Which of these keywords can be used to prevent inheritance of a class?
a) super
b) constant
c) class
d) final
Answer: d
15. Which of these keywords cannot be used for a class which has been declared final?
a) abstract
b) extends
c) abstract and extends
d) none of the mentioned
Answer: a
16. Which of these class relies upon its subclasses for complete implementation of its
methods?
a) Object class
b) abstract class
c) ArrayList class
d) None of the mentioned
Answer: b
17. What will be the output of the following Java program?
abstract class A
{
int i;
abstract void display();
}
class B extends A
{
int j;
void display()
{
System.out.println(j);
}
}
class Abstract_demo
{
public static void main(String args[])
{
B obj = new B();
obj.j=2;
obj.display();
}
}
a) 0
b) 2
c) Runtime Error
d) Compilation Error
Answer: b
18. What will be the output of the following Java program?
class A
{
int i;
int j;
A()
{
i = 1;
j = 2;
}
}
class Output
{
public static void main(String args[])
{
A obj1 = new A();
A obj2 = new A();
System.out.print(obj1.equals(obj2));
}
}
a) false
b) true
c) 1
d) Compilation Error
Answer: a
19. What will be the output of the following Java code?
class Output
{
public static void main(String args[])
{
Object obj = new Object();
System.out.print(obj.getclass());
}
}
a) Object
b) class Object
c) class java.lang.Object
d) Compilation Error
Answer: c
20. What will be the output of the following Java code?
class A
{
int i;
int j;
A()
{
i = 1;
j = 2;
}
}
class Output
{
public static void main(String args[])
{
A obj1 = new A();
System.out.print(obj1.toString());
}
}
a) true
b) false
c) String associated with obj1
d) Compilation Error
Answer: c
21. Which of these keywords are used to define an abstract class?
a) abst
b) abstract
c) Abstract
d) abstract class
Answer: b
22. Which of these is not abstract?
a) Thread
b) AbstractList
c) List
d) None of the Mentioned
Answer: a
23. If a class inheriting an abstract class does not define all of its function then it will be
known as?
a) Abstract
b) A simple class
c) Static class
d) None of the mentioned
Answer: a
24. Which of these is not a correct statement?
a) Every class containing abstract method must be declared abstract
b) Abstract class defines only the structure of the class not its implementation
c) Abstract class can be initiated by new operator
d) Abstract class can be inherited
Answer: c
25. Which of these packages contains abstract keyword?
a) java.lang
b) java.util
c) java.io
d) java.system
Answer: a.
26. What will be the output of the following Java code?
class A
{
public int i;
private int j;
}
class B extends A
{
void display()
{
super.j = super.i + 1;
System.out.println(super.i + " " + super.j);
}
}
class inheritance
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}
a) 2 2
b) 3 3
c) Runtime Error
d) Compilation Error
Answer: d
27. What will be the output of the following Java code?
class A
{
public int i;
public int j;
A()
{
i = 1;
j = 2;
}
}
class B extends A
{
int a;
B()
{
super();
}
}
class super_use
{
public static void main(String args[])
{
B obj = new B();
System.out.println(obj.i + " " + obj.j)
}
}
a) 1 2
b) 2 1
c) Runtime Error
d) Compilation Error
Answer: a
output:
$ javac super_use.java
$ java super_use:1 2
28. What will be the output of the following Java code?
class A
{
int i;
void display()
{
System.out.println(i);
}
}
class B extends A
{
int j;
void display()
{
System.out.println(j);
}
}
class method_overriding
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}
a) 0
b) 1
c) 2
d) Compilation Error
Answer: c
output:
$ javac method_overriding.java
$ java method_overriding: 2
29. What will be the output of the following Java code?
class A
{
public int i;
protected int j;
}
class B extends A
{
int j;
void display()
{
super.j = 3;
System.out.println(i + " " + j);
}
}
class Output
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}
a) 1 2
b) 2 1
c) 1 3
d) 3 1
Answer: a
output:
$ javac Output.java
$ java Output:1 2
31. Which of this keyword must be used to inherit a class?
a) super
b) this
c) extent
d) extends
Answer: d
32. A class member declared protected becomes a member of subclass of which type?
a) public member
b) private member
c) protected member
d) static member
Answer: b
33. Which of these is correct way of inheriting class A by class B?
a) class B + class A {}
b) class B inherits class A {}
c) class B extends A {}
d) class B extends class A {}
Answer: c
class A
{
int i;
}
class B extends A
{
int j;
void display()
{
super.i = j + 1;
System.out.println(j + " " + i);
}
}
class inheritance
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}
a) 2 2
b) 3 3
c) 2 3
d) 3 2
Answer: c
output:
$ javac inheritance.java
$ java inheritance: 2 3
37. What will be the output of the following Java program?
class A
{
public int i;
public int j;
A()
{
i = 1;
j = 2;
}
}
class B extends A
{
int a;
B()
{
super();
}
}
class super_use
{
public static void main(String args[])
{
B obj = new B();
System.out.println(obj.i + " " + obj.j)
}
}
a) 1 2
b) 2 1
c) Runtime Error
d) Compilation Error
Answer: a
output:
$ javac super_use.java
$ java super_use:1 238
38. What is not type of inheritance?
a) Single inheritance
b) Double inheritance
c) Hierarchical inheritance
d) Multiple inheritance
Answer: b
39. Using which of the following, multiple inheritance in Java can be implemented?
a) Interfaces
b) Multithreading
c) Protected methods
d) Private methods
Answer: a
1.Define Class, Method and Object? Show the syntax to define these in java
2. Compare Method Overriding and Method Overloading
3.Create a java program to display “Hello! Java” using Class, Object and Method.
4. Give the differences between Abstract class and Interface
5. Discuss in detail about Abstract Classes in Java
10 MARK
package pkg;
class display
{
int x;
void show()
{
if (x > 1)
System.out.print(x + " ");
}
}
class packages
{
public static void main(String args[])
{
display[] arr=new display[3];
for(int i=0;i<3;i++)
arr[i]=new display();
arr[0].x = 0;
arr[1].x = 1;
arr[2].x = 2;
for (int i = 0; i < 3; ++i)
arr[i].show();
}
}
a) 0
b) 1
c) 2
d) 0 1 2
Answer: c
9. What will be the output of the following Java program?
package pkg;
class output
{
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer("Hello");
s1.setCharAt(1, x);
System.out.println(s1);
}
}
a) xello
b) xxxxx
c) Hxllo
d) Hexlo
Answer: c
10. What will be the output of the following Java program?
package pkg;
class output
{
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer("Hello World");
s1.insert(6 , "Good ");
System.out.println(s1);
}
}
a) HelloGoodWorld
b) HellGoodoWorld
c) Compilation error
d) Runtime error
Answer: d
11. Which of these keywords is used to define interfaces in Java?
a) interface
b) Interface
c) intf
d) Intf
Answer: a
12. Which of these can be used to fully abstract a class from its implementation?
a) Objects
b) Packages
c) Interfaces
d) None of the Mentioned
Answer: c
13. Which of these access specifiers can be used for an interface?
a) Public
b) Protected
c) private
d) All of the mentioned
Answer: a
14. Which of these keywords is used by a class to use an interface defined previously?
a) import
b) Import
c) implements
d) Implements
Answer: c
15. Which of the following is the correct way of implementing an interface salary by class
manager?
a) class manager extends salary {}
b) class manager implements salary {}
c) class manager imports salary {}
d) none of the mentioned
Answer: b
16. Which of the following is an incorrect statement about packages?
a) Interfaces specifies what class must do but not how it does
b) Interfaces are specified public if they are to be accessed by any code in the program
c) All variables in interface are implicitly final and static
d) All variables are static and methods are public if interface is defined pubic
Answer: d
17. What will be the output of the following Java program?
interface calculate
{
void cal(int item);
}
class display implements calculate
{
int x;
public void cal(int item)
{
x = item * item;
}
}
class interfaces
{
public static void main(String args[])
{
display arr = new display;
arr.x = 0;
arr.cal(2);
System.out.print(arr.x);
}
}
a) 0
b) 2
c) 4
d) None of the mentioned
Answer: c
18. What will be the output of the following Java program?
1 interface calculate
{
void cal(int item);
}
class displayA implements calculate
{
int x;
public void cal(int item)
{
x = item * item;
}
}
class displayB implements calculate
{
int x;
public void cal(int item)
{
x = item / item;
}
}
class interfaces
{
public static void main(String args[])
{
displayA arr1 = new displayA;
displayB arr2 = new displayB;
arr1.x = 0;
arr2.x = 0;
arr1.cal(2);
arr2.cal(2);
System.out.print(arr1.x + " " + arr2.x);
}
}
a) 0 0
b) 2 2
c) 4 1
d) 1 4
Answer: c
19. What will be the output of the following Java program?
interface calculate
{
int VAR = 0;
void cal(int item);
}
class display implements calculate
{
int x;
public void cal(int item)
{
if (item<2)
x = VAR;
else
x = item * item;
}
}
class interfaces
{
for(int i=0;i<3;i++)
arr[i]=new display();
arr[0].cal(0);
arr[1].cal(1);
arr[2].cal(2);
System.out.print(arr[0].x+" " + arr[1].x + " " + arr[2].x);
}
}
a) 0 1 2
b) 0 2 4
c) 0 0 4
d) 0 1 4
Answer: c
21. Which of the following access specifiers can be used for an interface?
a) Protected
b) Private
c) Public
d) Public, protected, private
Answer: a
22. Which of the following is the correct way of implementing an interface A by class B?
a) class B extends A{}
b) class B implements A{}
c) class B imports A{}
d) None of the mentioned
Answer: b
23. All methods must be implemented of an interface.
a) True
b) False
Answer: a
24. What type of variable can be defined in an interface?
a) public static
b) private final
c) public final
d) static final
Answer: d
25. What does an interface contain?
a) Method definition
b) Method declaration
c) Method declaration and definition
d) Method name
Answer: b
26. What type of methods an interface contain by default?
a) abstract
b) static
c) final
d) private
Answer: a
27. What will happen if we provide concrete implementation of method in interface?
a) The concrete class implementing that method need not provide implementation of that method
b) Runtime exception is thrown
c) Compilation failure
d) Method not found exception is thrown
Answer: c
28. What happens when a constructor is defined for an interface?
a) Compilation failure
b) Runtime Exception
c) The interface compiles successfully
d) The implementing class will throw exception
Answer: a
29. What happens when we access the same variable defined in two interfaces implemented
by the same class?
a) Compilation failure
b) Runtime Exception
c) The JVM is not able to identify the correct variable
d) The interfaceName.variableName needs to be defined
Answer: d
30. Can “abstract” keyword be used with constructor, Initialization Block, Instance
Initialization and Static Initialization Block.
a) True
b) False
Answer: b
31. Which of these package is used for graphical user interface?
a) java.applet
b) java.awt
c) java.awt.image
d) java.io
Answer: b
32. Which of this package is used for analyzing code during run-time?
a) java.applet
b) java.awt
c) java.io
d) java.lang.reflect
Answer: d
33. Which of this package is used for handling security related issues in a program?
a) java.security
b) java.lang.security
c) java.awt.image
d) java.io.security
Answer: a
34. Which of these class allows us to get real time data about private and protected member
of a class?
a) java.io
b) GetInformation
c) ReflectPermission
d) MembersPermission
Answer: c
35. Which of this package is used for invoking a method remotely?
a) java.rmi
b) java.awt
c) java.util
d) java.applet
Answer: a
36. What will be the output of the following Java program?
import java.lang.reflect.*;
class Additional_packages
{
public static void main(String args[])
{
try
{
Class c = Class.forName("java.awt.Dimension");
Constructor constructors[] = c.getConstructors();
for (int i = 0; i < constructors.length; i++)
System.out.println(constructors[i]);
}
catch (Exception e)
{
System.out.print("Exception");
}
}
}
a) Program prints all the constructors of ‘java.awt.Dimension’ package
b) Program prints all the possible constructors of class ‘Class’
c) Program prints “Exception”
d) Runtime Error
Answer: a
37. What will be the output of the following Java program?
import java.lang.reflect.*;
class Additional_packages
{
public static void main(String args[])
{
try
{
Class c = Class.forName("java.awt.Dimension");
Field fields[] = c.getFields();
for (int i = 0; i < fields.length; i++)
System.out.println(fields[i]);
}
catch (Exception e)
{
System.out.print("Exception");
}
}
}
a) Program prints all the constructors of ‘java.awt.Dimension’ package
b) Program prints all the methods of ‘java.awt.Dimension’ package
c) Program prints all the data members of ‘java.awt.Dimension’ package
d) program prints all the methods and data member of ‘java.awt.Dimension’ package
Answer: c
38. What is the length of the application box made in the following Java program?
import java.awt.*;
import java.applet.*;
public class myapplet extends Applet
{
Graphic g;
g.drawString("A Simple Applet",20,20);
}
a) 20
b) Default value
c) Compilation Error
d) Runtime Error
Answer: c
39. What will be the output of the following Java program?
import java.lang.reflect.*;
class Additional_packages
{
public static void main(String args[])
{
try
{
Class c = Class.forName("java.awt.Dimension");
Method methods[] = c.getMethods();
for (int i = 0; i < methods.length; i++)
System.out.println(methods[i]);
}
catch (Exception e)
{
System.out.print("Exception");
}
}
}
a) Program prints all the constructors of ‘java.awt.Dimension’ package
b) Program prints all the methods of ‘java.awt.Dimension’ package
c) Program prints all the data members of ‘java.awt.Dimension’ package
d) program prints all the methods and data member of ‘java.awt.Dimension’ package
Answer: b
38. Why are generics used?
a) Generics make code more fast
b) Generics make code more optimised and readable
c) Generics add stability to your code by making more of your bugs detectable at compile
time
d) Generics add stability to your code by making more of your bugs detectable at runtime
Answer: c
39. Which of these type parameters is used for a generic class to return and accept any type
of object?
a) K
b) N
c) T
d) V
Answer: c
40. Which of these type parameters is used for a generic class to return and accept a
number?
a) K
b) N
c) T
d) V
Answer: b
41. Which of these is an correct way of defining generic class?
a) class name(T1, T2, …, Tn) { /* … */ }
b) class name<T1, T2, …, Tn> { /* … */ }
c) class name[T1, T2, …, Tn] { /* … */ }
d) class name{T1, T2, …, Tn} { /* … */ }
Answer: b
42. Which of the following is an incorrect statement regarding the use of generics and
parameterized types in Java?
a) Generics provide type safety by shifting more type checking responsibilities to the compiler
b) Generics and parameterized types eliminate the need for down casts when using Java
Collections
c) When designing your own collections class (say, a linked list), generics and
parameterized types allow you to achieve type safety with just a single class definition as
opposed to defining multiple classes
d) All of the mentioned
Answer: c
43. Which of the following reference types cannot be generic?
a) Anonymous inner class
b) Interface
c) Inner class
d) All of the mentioned
Answer: a
44. What will be the output of the following Java program?
5MARK
1. What is a Java Exception and its Types
2. Explain about try, catch, statements with examples
3.Write a java program to create own exception for Negative Value Exception if the user
enter negative value.
4.Explain Exception handling fundamentals.
5. explain in Uncaught Exception.
6.Short notes on difference between checked and unchecked exceptions?
7.detail about the use of finally statements with examples
10 MARK
package pkg;
class output
{
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer("Hello World");
s1.insert(6 , "Good ");
System.out.println(s1);
}
}
a) HelloGoodWorld
b) HellGoodoWorld
c) Compilation error
d) Runtime error
Answer: d
9. Which of these functions is called to display the output of an applet?
a) display()
b) paint()
c) displayApplet()
d) PrintApplet()
Answer: b
10. Which of these methods can be used to output a string in an applet?
a) display()
b) print()
c) drawString()
d) transient()
Answer: c
11. Which of these methods is a part of Abstract Window Toolkit (AWT) ?
a) display()
b) paint()
c) drawString()
d) transient()
Answer: b
12. Which of these modifiers can be used for a variable so that it can be accessed from any
thread or parts of a program?
a) transient
b) volatile
c) global
d) No modifier is needed
Answer: b
13. Which of these operators can be used to get run time information about an object?
a) getInfo
b) Info
c) instanceof
d) getinfoof
Answer: c
14. What is the Message is displayed in the applet made by the following Java program?
import java.awt.*;
import java.applet.*;
public class myapplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("A Simple Applet", 20, 20);
}
}
a) A Simple Applet
b) A Simple Applet 20 20
c) Compilation Error
d) Runtime Error
Answer: a
15. What is the length of the application box made by the following Java program?
import java.awt.*;
import java.applet.*;
public class myapplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("A Simple Applet", 20, 20);
}
}
a) 20
b) 50
c) 100
d) System dependent
Answer: a
16. What is the length of the application box made the following Java program?
import java.awt.*;
import java.applet.*;
public class myapplet extends Applet
{
Graphic g;
g.drawString("A Simple Applet", 20, 20);
}
a) 20
b) Default value
c) Compilation Error
d) Runtime Error
Answer: c
17. What will be the output of the following Java program?
import java.io.*;
class Chararrayinput
{
public static void main(String[] args)
{
String obj = "abcdefgh";
int length = obj.length();
char c[] = new char[length];
obj.getChars(0, length, c, 0);
CharArrayReader input1 = new CharArrayReader(c);
CharArrayReader input2 = new CharArrayReader(c, 1, 4);
int i;
int j;
try
{
while((i = input1.read()) == (j = input2.read()))
{
System.out.print((char)i);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
a) abc
b) abcd
c) abcde
d) none of the mentioned
Answer: d
18. Which of these package is used for text formatting in Java programming language?
a) java.text
b) java.awt
c) java.awt.text
d) java.io
Answer: a
19. Which of this class can be used to format dates and times?
a) Date
b) SimpleDate
c) DateFormat
d) textFormat
Answer: c
20. Which of these method returns an instance of DateFormat that can format time
information?
a) getTime()
b) getTimeInstance()
c) getTimeDateinstance()
d) getDateFormatinstance()
Answer: b
21. Which of these class allows us to define our own formatting pattern for dates and time?
a) DefinedDateFormat
b) SimpleDateFormat
c) ComplexDateFormat
d) UsersDateFormat
Answer: b
22. Which of these formatting strings of SimpleDateFormat class is used to print AM or
PM in time?
a) a
b) b
c) c
d) d
Answer: a
22. Which of these formatting strings of SimpleDateFormat class is used to print week of
the year?
a) w
b) W
c) s
d) S
Answer: a
23. What will be the output of the following Java program?
import java.text.*;
import java.util.*;
class Date_formatting
{
public static void main(String args[])
{
Date date = new Date();
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("mm:hh:ss");
System.out.print(sdf.format(date));
}
}
a) 3:55:4
b) 3.55.4
c) 55:03:04
d) 03:55:04
Answer: c
24. What will be the output of the following Java program?
import java.text.*;
import java.util.*;
class Date_formatting
{
public static void main(String args[])
{
Date date = new Date();
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("hh:mm:ss");
System.out.print(sdf.format(date));
}
}
a) 3:55:4
b) 3.55.4
c) 55:03:04
d) 03:55:04
Answer: d
25. What will be the output of the following Java program?
import java.text.*;
import java.util.*;
class Date_formatting
{
public static void main(String args[])
{
Date date = new Date();
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("E MMM dd yyyy");
System.out.print(sdf.format(date));
}
}
a) Mon Jul 15 2013
b) Jul 15 2013
c) 55:03:04 Mon Jul 15 2013
d) 03:55:04 Jul 15 2013
Answer: a
26. What will be the output of the following Java program?
import java.text.*;
import java.util.*;
class Date_formatting
{
public static void main(String args[])
{
Date date = new Date();
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("z");
System.out.print(sdf.format(date));
}
}
a) z
b) Jul
c) Mon
d) PDT
Answer: d
27. Which of the following is not a class of java.util.regex?
a) Pattern class
b) matcher class
c) PatternSyntaxException
d) Regex class
Answer: d
28.What is the significance of Matcher class for regular expression in java?
a) interpretes pattern in the string
b) Performs match in the string
c) interpreted both pattern and performs match operations in the string
d) None of the mentioned.
Answer:a
29. Object of which class is used to compile regular expression?
a) Pattern class
b) Matcher class
c) PatternSyntaxException
d) None of the mentioned
Answer: a
30. Which capturing group can represent the entire expression?
a) group *
b) group 0
c) group * or group 0
d) None of the mentioned
Answer: b
Explanation: Group 0 is a special group which represents the entire expression.
31. groupCount reports a total number of Capturing groups.
a) True
b) False
Answer: a
32. Which of the following matches nonword character using regular expression in java?
a) \w
b) \W
c) \s
d) \S
Answer: b
33. Which of the following matches end of the string using regular expression in java?
a) \z
b) \\
c) \*
d) \Z
Answer: a
34. What does public int end(int group) return?
a) offset from last character of the subsequent group
b) offset from first character of the subsequent group
c) offset from last character matched
d) offset from first character matched
Answer: a
35. what does public String replaceAll(string replace) do?
a) Replace all characters that matches pattern with a replacement string
b) Replace first subsequence that matches pattern with a replacement string
c) Replace all other than first subsequence of that matches pattern with a replacement string
d) Replace every subsequence of the input sequence that matches pattern with a
replacement string
Answer: d
36. What does public int start() return?
a) returns start index of the input string
b) returns start index of the current match
c) returns start index of the previous match
d) none of the mentioned
Answer: c
37. Which of these packages contains all the classes and methods required for even
handling in Java?
a) java.applet
b) java.awt
c) java.event
d) java.awt.event
Answer: d
38. What is an event in delegation event model used by Java programming language?
a) An event is an object that describes a state change in a source
b) An event is an object that describes a state change in processing
c) An event is an object that describes any change by the user and system
d) An event is a class used for defining object, to create events
Answer: a
39. Which of these methods are used to register a keyboard event listener?
a) KeyListener()
b) addKistener()
c) addKeyListener()
d) eventKeyboardListener()
Answer: c
40. Which of these methods are used to register a mouse motion listener?
a) addMouse()
b) addMouseListener()
c) addMouseMotionListner()
d) eventMouseMotionListener()
Answer: c
41. What is a listener in context to event handling?
a) A listener is a variable that is notified when an event occurs
b) A listener is a object that is notified when an event occurs
c) A listener is a method that is notified when an event occurs
d) None of the mentioned
Answer: b
42. Event class is defined in which of these libraries?
a) java.io
b) java.lang
c) java.net
d) java.util
Answer: d
43. Which of these methods can be used to determine the type of event?
a) getID()
b) getSource()
c) getEvent()
d) getEventObject()
Answer: a
44. Which of these class is super class of all the events?
a) EventObject
b) EventClass
c) ActionEvent
d) ItemEvent
Answer: a
45. Which of these events will be notified if scroll bar is manipulated?
a) ActionEvent
b) ComponentEvent
c) AdjustmentEvent
d) WindowEvent
Answer: c.
46. Which of these events will be generated if we close an applet’s window?
a) ActionEvent
b) ComponentEvent
c) AdjustmentEvent
d) WindowEvent
Answer: d
47. Which of these keywords is used to define packages in Java?
a) pkg
b) Pkg
c) package
d) Package
Answer: c
48. Which of these is a mechanism for naming and visibility control of a class and its
content?
a) Object
b) Packages
c) Interfaces
d) None of the Mentioned.
Answer: b
49. Which of this access specifies can be used for a class so that its members can be
accessed by a different class in the same package?
a) Public
b) Protected
c) No Modifier
d) All of the mentioned
Answer: d
50. Which of these access specifiers can be used for a class so that its members can be
accessed by a different class in the different package?
a) Public
b) Protected
c) Private
d) No Modifier
Answer: a.
51. Which of the following is the correct way of importing an entire package ‘pkg’?
a) import pkg.
b) Import pkg.
c) import pkg.*
d) Import pkg.*
Answer: c
5MARK
10 MARK