object oriented programming through javadevelopment kit (jdk) and the classes and methods are part...

133
Object Oriented Programming through Java PART A QUESTIONS (2 Marks) 1. Define Java. Java is a general purpose, object oriented programming language. We can develop two types of programs: Stand-alone applications Web applets 2. What is the functions of Java Virtual Machine? Ans: It is a program that interprets the intermediate java byte code and generates the desired output. It is because of byte code and JVM concepts that programs written in Java are highly portable. 3. How Java Differ from C++? Ans: (i) Java does not use pointers. (ii) Java has replaced the destructor function with a finalize() function. 4. What is System.Out.Println”? Ans: A print "statement" is actually a call to the print or println method of the System.out object. The print method takes exactly one argument; the println method takes one argument or no arguments. However, the one argument may be a String which you create using the string concatenation operator +. If you ask to print an object, the print and println methods call that object's toString() method to get a printable string. Example int x = 3; int y = 5; System.out.println(x + " and " + y + " is " + (x + y)); Result 3 and 5 is 8

Upload: others

Post on 02-Oct-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Object Oriented Programming through Java

PART – A QUESTIONS

(2 Marks)

1. Define Java.

Java is a general purpose, object oriented programming language. We can develop

two types of programs:

Stand-alone applications

Web applets

2. What is the functions of Java Virtual Machine?

Ans: It is a program that interprets the intermediate java byte code and generates the

desired output. It is because of byte code and JVM concepts that programs written in Java

are highly portable.

3. How Java Differ from C++?

Ans: (i) Java does not use pointers.

(ii) Java has replaced the destructor function with a finalize() function.

4. What is “System.Out.Println”?

Ans: A print "statement" is actually a call to the print or println method of the System.out

object. The print method takes exactly one argument; the println method takes one

argument or no arguments. However, the one argument may be a String which you create

using the string concatenation operator +. If you ask to print an object, the print and

println methods call that object's toString() method to get a printable string.

Example int x = 3;

int y = 5;

System.out.println(x + " and " + y + " is " + (x + y));

Result

3 and 5 is 8

Page 2: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

int x = 3;

int y = 5;

System.out.println(x + " and " + y + " is " + x + y);

Result

3 and 5 is 35

Anything concatenated ("added") to a string is first converted to a string itself. In the

second example above, the x is concatenated with the string, then the y is concatenated.

5. How OOPs differs from procedural programming?

(i) Java does not include the C unique statement keywords sizeof, and typedef.

(ii) Java does not contain the data types struct and union.

Procedural Object Oriented

i) procedure method

ii) record object

iii) module class

iv) procedural call message

6. What are java Objects?

Ans: Objects are the basic run time entities in an object oriented system. They may

represent a person, a place, a bank account, a table of data or any item that the program

may handle. They may also represent user-defined data types such as vectors and lists.

Any programming problem may be analyzed in terms of objects and the nature of

communication between them. Program objects should be chosen such that they match

closely with the real world objects.

7. List any four features of Java.

Ans: The features of Java are as follows:

(i) Compiled and Interpreted

(ii) Platform-Independent and Portable

(iii) Object Oriented

(iv) Robust and Secure

Page 3: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

8. What is meant by control statement?

Ans: Java Control statements control the order of execution in a java program, based on

data values and conditional logic. There are three main categories of control flow

statements;

Selection statements: if, if-else and switch.

Loop statements: while, do-while and for.

Transfer statements: break, continue, return, try-catch-finally and assert.

We use control statements when we want to change the default sequential order of

execution. Depending upon the position of the control statement in the loop, a control

structure may be classified either as entry-controlled loop or as exit-controlled loop.

9. What is Java Bytecode?

Ans: All language compilers translate source code into machine code for a specific

computer. Java compiler also does the same thing. The Java Compiler produces an

intermediate code known as bytecode for a machine that does not exist. This machine is

called the Java Virtual Machine.

10. What is an Arrary?

Ans: Java provides a data structure, the array, which stores a fixed-size sequential

collection of elements of the same type. An array is used to store a collection of data, but it is

often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and

number99, you declare one array variable such as numbers and use numbers[0], numbers[1],

and....numbers[99] to represent individual variables.

The different types of arrays are as follows:

Single Dimensional Array

Two Dimensional Array

Multi-dimensional Array

11. List content of a Java Devlopment Kit.

Ans: Java environment includes a large number of development tools and hundreds

of classes and methods. The development tools are the part of the system known as Java

Page 4: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Development Kit (JDK) and the classes and methods are part of the Java Standard

Library (JSL), also known the Application Programming Interface.

12. Define the term Variable with example.

Ans: A variable provides us with named storage that our programs can manipulate.

Each variable in Java has a specific type, which determines the size and layout of the

variable's memory; the range of values that can be stored within that memory; and the set of

operations that can be applied to the variable.

int a, b, c; // Declares three ints, a, b, and c.

int a = 10, b = 10; // Example of initialization

byte B = 22; // initializes a byte type variable B.

double pi = 3.14159; // declares and assigns a value of PI.

char a = 'a'; // the char variable a iis initialized with value 'a'

13. Write about evolution of Java

Ans: Java is a general purpose; object oriented programming language

developed by Sun Microsystems of USA in 1991. Originally called Oak by James

Gosling, one of the inventors of the language, Java was designed for the development for

software for consumer electronic devices like TVs, VCRs, toasters and such other

electronic devices. The goal had a strong impact on the development team to make the

language simple, portable and highly reliable.

14. What is meant by Operator?

Ans: An operator is a symbol that takes one or more arguments and operators on them

to produce a result. Operators are of many types. They are as follows:

Arithmetic Operators

Relational Operators

Logical Operators

Assignment Operators

Conditional Operators

Increment / Decrement Operators

Bitwise Operators

Special Operators

15. What is Scanner Class?

Ans: The java.util.Scanner class is a simple text scanner which can parse primitive

types and strings using regular expressions.Following are the important points about Scanner:

Page 5: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

A Scanner breaks its input into tokens using a delimiter pattern, which by default

matches whitespace.

A scanning operation may block waiting for input.

A Scanner is not safe for multithreaded use without external synchronization.

16. What is Encapsulation?

Ans: The wrapping up of data and methods into a single unit (called class) is known

as encapsulation. Data encapsulation is the most striking feature of the class. The data is

not accessible to the outside world and only those methods, which are wrapped in the

class, can access it.

17. Mention any four data types in Java.

In java, there are two types of data types

primitive data types

int

short

boolean

byte

float

non-primitive data types

18. List out the special Operator in Java.

?:

[]

.

(type)

New

instanceof

19. Mention any two applications of OOPS.

Ans: The application of OOP includes:

Page 6: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

abstract

assert

boolean

break

byte case

catch

char

class

const*

continue default

double

do

else

enum

extends false

final

finally

float

for

goto* if

implements

import

instanceof

int

interface long

native

new

null

package

private protected

public

return

short

static

strictfp super

switch

synchronized

this

throw

throws transient

true

try

void

volatile

while

Real-time systems

Simulation and modeling

Object-Oriented Databases

20. What is Servlet?

A servlet is a small Java program that runs within a Web server.Servlets receive and respond

to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.

PART – B QUESTIONS

1. What is Reserved word? Give example.

Java reserved words are keywords that are reserved by Java for particular uses and

cannot be used as identifiers (e.g., variable names, function names, classnames). The list of

reserved words in Java is provided below.

The table below lists all the words that are reserved:

2. Why String is an Object. How?

String is one of the widely used java classes. It is special in java as it has some special

characteristics than a usual java class. Let’s explore java String in this article and this page

aims to serve you as a single point reference for all your queries on Java String.

Page 7: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Though you might know most of the things, this will help you to recall them and I am sure

you will find one or two new things. I recommend you to take your time and read through

this completely as java String is a basic building block of your java programs.

Immutable Java String:

Java String is a immutable object. For an immutable object you cannot modify any of its

attribute’s values. Once you have created a java String object it cannot be modified to some

other object or a different String. References to a java String instance are mutable. There are

multiple ways to make an object immutable. Simple and straight forward way is to make all

the attributes of that class as final. Java String has all attributes marked as final except hash

field.

Java String is final. I am not able to nail down the exact reason behind it. But my guess is,

implementers of String didn’t wany anybody else to mess with String type and they wanted

de-facto definition for all the behaviours of String.

We all know java String is immutable but do we know why java String is immutable? Main

reason behind it is for better performance. Creating a copy of existing java String is easier as

there is no need to create a new instance but can be easily created by pointing to already

existing String. This saves valuable primary memory. Using String as a key for Hashtable

guarantees that there will be no need for re hashing because of object change. Using java

String in multithreaded environment is safe by itself and we need not take any precautionary

measures.

Java String Instantiation:

In continuation with above discussion of immutability of java String we shall see how that

property is used for instantiating a Sting instance. JVM maintains a memory pool for String.

When you create a String, first this memory pool is scanned. If the instance already exists

then this new instance is mapped to the already existing instance. If not, a new java String

instance is created in the memory pool.

This approach of creating a java String instance is in sync with the immutable property.

When you use ‘new’ to instantiate a String, you will force JVM to store this new instance is

fresh memory location thus bypassing the memory map scan. Inside a String class what you

have got is a char array which holds the characters in the String you create.

Following are some of the ways to instantiate a java String

String str1 = "javapapers";

String str2 = new String("Apple");

String str3 = new String(char []);

String str4 = new String(byte []);

Page 8: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

String str5 = new String(StringBuffer);

String str6 = new String(StringBuilder);

We have an empty constructor for String. It is odd, java String is immutable and you have an

empty constructur which does nothing but create a empty String. I don’t see any use for this

constructor, because after you create a String you cannot modify it.

3. Why Java is more popular?

Java is object-oriented and class-based. Developers adopt and use Java because

code can be run securely on nearly any other platform, regardless of the operating system

or architecture of the device, as long as the device has aJava Runtime Environment

(JRE) installed.

Exceptions

Garbage collection and memory management Interfaces

Object oriented

Threads

GUI

Built-in networking support

Strong typing and specified widening/casting

extensively specified operator precedence/evaluation order

Extensive libraries included as part of the language

cross-platform portability primitive type sizes are specified and platform-independent

primitive type conversions in expressions are specified by the language

4. How to create and compile simple java program? (April/May 2015)

Writing a Simple Java Program (hello world)

Open a simple text editor program such as Notepad and type the following content:

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello world!");

}

}

Page 9: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Save the file as HelloWorld.java (note that the extension is .java) under a directory, let’s

say, C:\Java.

Every Java program starts from the main() method. This program simply prints “Hello world” to

screen.

Compiling it

Now let’s compile our first program in the HelloWorld.java file using javac tool. Type the

following command to change the current directory to the one where the source file is stored:

cd C:\Java

And type the following command:

javac HelloWorld.java

That invokes the Java compiler to compile code in the HelloWorld.java file into bytecode. Note

that the file name ends with .java extension. You would see the following output:

If everything is fine (e.g. no error), the Java compiler quits silently, no fuss. After compiling, it

generates the HelloWorld.class file which is bytecode form of the HelloWorld.java file. Now try

to type dir in the command line, we’ll see the .class file:

So remember a Java program will be compiled into bytecode form (.class file).

Running it

It’s now ready to run our first Java program. Type the following command:

java HelloWorld

Page 10: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

That invokes the Java Virtual Machine to run the program called HelloWorld (note that there is

no .java or .class extension). You would see the following output:

It just prints out “Hello world!” to the screen and quits.

5. Discuss about java Operator. (April 2012)

Ans: An operator is a symbol that takes one or more arguments and operators on them to

produce a result. Operators are of many types. They are as follows:

Arithmetic Operators

Relational Operators

Logical Operators

Assignment Operators

Conditional Operators

Increment / Decrement Operators

Bitwise Operators

Special Operators

1. Arithmetic Operator

Ans: Arithmetic operators are used in mathematical expressions in the same way that they

are used in algebra. The following table lists the arithmetic operators:

Assume integer variable A holds 10 and variable B holds 20, then:

Operator Description Example

+ Addition Adds values on either side of the operator

A + B will give 30

- Subtraction Subtracts right hand operand from left hand operand

A - B will give -10

* Multiplication Multiplies values on either side of the operator

A * B will give 200

/ Division Divides left hand operand by right hand operand

B / A will give 2

% Modulus Divides left hand operand by right hand operand and returns

remainder

B % A will give 0

The different types of arithmetic operators are as follows:

Integer Arithmetic

Real Arithmetic

Mixed Mode Arithmetic

2 Assignment Operator

Page 11: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Ans: The most commonly used operator is the assignment operator. It is denoted by

the "=" character and simply assigns the value on the right to the operand on the left.

It is also called shorthand assignment operators.

3 .Conditional Opertor Ans: Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to

decide which value should be assigned to the variable. The operator is written as:

variable x = (expression) ? value if true : value if false

Following is the example:

Page 12: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

public class Test {

public static void main(String args[]){

int a , b;

a = 10;

b = (a == 1) ? 20: 30;

System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;

System.out.println( "Value of b is : " + b );

}

}

This would produce the following result:

Value of b is : 30

Value of b is : 20

2. Briefly explain about the Nested if…else statement with example.

Ans: It is always legal to nest if-else statements which means you can use one if or else if

statement inside another if or else if statement.

Syntax: The syntax for a nested if...else is as follows:

if(Boolean_expression 1){

//Executes when the Boolean expression 1 is true

if(Boolean_expression 2){

//Executes when the Boolean expression 2 is true

}

}

You can nest else if...else in the similar way as we have nested if statement.

Example: public class Test {

public static void main(String args[]){

int x = 30;

int y = 10;

if( x == 30 ){

if( y == 10 ){

Page 13: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

System.out.print("X = 30 and Y = 10");

}

}

}

}

This would produce the following result:

X = 30 and Y = 10

6. Discuss the various java data types with example. (April/May 2013)

Ans: Data type specifies the size and type of values that can be stored in an identifier. The

Java language is rich in its data types. Different data types allow you to select the type

appropriate to the needs of the application.

Data types in Java are classified into two types:

Primitive—which include Integer, Character, Boolean, and Floating Point.

Non-primitive—which include Classes, Interfaces, and Arrays.

Primitive Data Types

1. Integer:

Integer types can hold whole numbers such as 123 and −96. The size of the values that can be

stored depends on the integer type that we choose.

Type Size Range of values that can be stored

byte short

int

long

1 byte 2 bytes

4 bytes

8 bytes

−128 to 127 −32768 to 32767

−2,147,483,648 to 2,147,483,647

9,223,372,036,854,775,808 to 9,223,372,036,854,755,807

The range of values is calculated as − (2n−1) to (2n−1) −1; where n is the number of bits

required. For example, the byte data type requires 1 byte = 8 bits. Therefore, the range of

values that can be stored in the byte data type is − (28−1) to (28−1) −1

= −27 to (27) -1

= −128 to 127

Page 14: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

2. Floating Point:

Floating point data types are used to represent numbers with a fractional part. Single

precision floating point numbers occupy 4 bytes and Double precision floating point numbers

occupy 8 bytes. There are two subtypes:

Type Size Range of values that can be stored

float double

4 bytes 8 bytes

3.4e−038 to 3.4e+038 1.7e−308 to 1.7e+038

3. Character:

It stores character constants in the memory. It assumes a size of 2 bytes, but basically it can

hold only a single character because char stores unicode character sets. It has a minimum

value of ‘u0000′ (or 0) and a maximum value of ‘uffff’ (or 65,535, inclusive).

4. Boolean:

Boolean data types are used to store values with two states: true or false.

7. Explain Object Oriented Concepts.

Ans: The object-oriented is a programming paradigm where the program logic and data are

weaved. As stated by Phil Ballard, it is a way of conceptualizing a program's data into

discrete "things" referred to as objects, each having its own properties and methods.

Let's see an example. Suppose your friend is a bank manager and he wants you to help

improving their system. The first object you might design is the general-purpose Account.

The Account object has properties and methods. For each client your friend's bank have, you

would have to create an Account object.

Characteristics

As follows the most important features of object-oriented programming:

Encapsulation. Capability to hide data and instructions inside an object.

Inheritance. Ability to create one object from another.

Polymorphism. The design of new classes is based on a single class.

Message Passing. It is the way objects communicate with each other.

Garbage Collection. Automatic memory management that destroys objects that are no

longer in use by the program.

Page 15: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Benefits

As follows some benefits of using object-oriented programming:

Re-usability. You can write a program using a previous developed code.

Code Sharing. You are able to standardize the way you are programming with your

colleagues.

Rapid Modeling. You can prototype the classes and their interaction through a diagram.

Drawbacks

As follows the disadvantages of using object-oriented programming:

Size. Are larger than other programs, consuming more memory and disk space.

Effort. Require a lot of work to create, including the diagramming on the planning phase

and the coding on the execution phase.

Basic Concepts:

Class: Basic template that specifies the properties and behaviours of something (real life or

abstract).

Object: Particular instance of a class that responds consequently to events.

Attribute: Characteristics of the class. Often called instance variables.

Method: Algorithm associate to a class that represent a thing that the object does.

Subclass: Class based on another class.

Inheritance: Process where the subclass gets the attributes and methods from its parent

class.

Interface: Specific template that enforces certain attributes and methods of a class.

Package: Namespace that organizes a set of related classes and interfaces.

Event: Alert the application when there is a state change of the object.

Page 16: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

8. Explain Logical Operator with example.

Ans: A logical operator (sometimes called a “Boolean operator”) in Java programming is

an operator that returns a Boolean result that’s based on the Boolean result of one or two

other expressions.

Sometimes, expressions that use logical operators are called “compound expressions”

because the effect of the logical operators is to let you combine two or more condition

tests into a single expression.

PART – C QUESTIONS

1. What are arrays? How to define and access elements? Explain. (April/May 2014).

Ans: Normally, array is a collection of similar type of elements that have contiguous

memory location. Java array is an object that contains elements of similar data type. It is a

data structure where we store similar elements. We can store only fixed set of elements in a

java array. Array in java is index based; first element of the array is stored at 0 index.

Advantages of Java Array:

Code Optimization: It makes the code optimized; we can retrieve or sort the data easily.

Random access: We can get any data located at any index position.

Disadvantage of Java Array:

Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at

runtime. To solve this problem, collection framework is used in java.

Page 17: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Types of Array in java

There are two types of array.

Single Dimensional Array

Multidimensional Array

Single Dimensional Array:

Syntax to Declare an Array:

dataType[] arr; (or)

dataType []arr; (or)

dataType arr[];

Instantiation of an Array in java

arrayRefVar=new datatype[size];

Example of single dimensional java array

Let's see the simple example of java array, where we are going to declare, instantiate,

initialize and traverse an array.

class Testarray{

public static void main(String args[]){

int a[]=new int[5];//declaration and instantiation

a[0]=10;//initialization

a[1]=20;

a[2]=70;

a[3]=40;

a[4]=50;

//printing array

for(int i=0;i<a.length;i++)//length is the property of array

System.out.println(a[i]);

}}

Output: 10

20

70

40

50

Page 18: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization

Let's see the simple example to print this array.

class Testarray1{

public static void main(String args[]){

int a[]={33,3,4,5};//declaration, instantiation and initialization

//printing array

for(int i=0;i<a.length;i++)//length is the property of array

System.out.println(a[i]);

}}

Output: 33

3

4

5

Multidimensional array in java:

In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in java:

dataType[][] arrayRefVar; (or)

dataType [][]arrayRefVar; (or)

dataType arrayRefVar[][]; (or)

dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in java

int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in java

arr[0][0]=1;

arr[0][1]=2;

arr[0][2]=3;

arr[1][0]=4;

Page 19: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

arr[1][1]=5;

arr[1][2]=6;

arr[2][0]=7;

arr[2][1]=8;

arr[2][2]=9;

Example of Multidimensional java array:

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional

array.

class Testarray3{

public static void main(String args[]){

//declaring and initializing 2D array

int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array

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

for(int j=0;j<3;j++){

System.out.print(arr[i][j]+" ");

}

System.out.println();

}

}}

Output: 1 2 3

2 4 5

4 4 5

2. Explain the characterstics of object oriented programming. (April/May 2014)

Class definitions – Basic building blocks OOP and a single entity which has data and

operations on data together

Objects – The instances of a class which are used in real functionality – its variables and

operations

Abstraction – Specifying what to do but not how to do ; a flexible feature for having a overall

view of an object’s functionality.

Page 20: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Encapsulation – Binding data and operations of data together in a single unit – A class adhere

this feature

Encapsulation-is capaturing data and kepping if safly and securely from outside interfaces

Inheritance-this is the process by which a class can be derived from a base class with all the

features of base class and some of its own.thiincesr code reusability.

Polymorphisam-this is the ability to exist invarias forms the best examble of polymorphsm is

the operater overloading.

Abstraction-the ability to repracent data at a vary conceptual leval without any details..

Jerald jacob 11-13-2015

3. What are the various Loop Constructs available in Java? Explain with

example(April 2013)

Ans: There may be a situation when we need to execute a block of code several number of

times, and is often referred to as a loop.

Java has very flexible three looping mechanisms. You can use one of the following three

loops:

while Loop

do...while Loop

for Loop

The while Loop:

A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:

The syntax of a while loop is:

while(Boolean_expression)

{

//Statements

}

When executing, if the boolean_expression result is true, then the actions inside the loop will

be executed. This will continue as long as the expression result is true.

Page 21: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Here, key point of the while loop is that the loop might not ever run. When the expression is

tested and the result is false, the loop body will be skipped and the first statement after the

while loop will be executed.

Example: public class Test {

public static void main(String args[]) {

int x = 10;

while( x < 20 ) {

System.out.print("value of x : " + x );

x++;

System.out.print("\n");

}

}

}

This would produce the following result:

value of x : 10

value of x : 11

value of x : 12

value of x : 13

value of x : 14

value of x : 15

value of x : 16

value of x : 17

value of x : 18

value of x : 19

The do...while Loop:

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to

execute at least one time.

Syntax:

The syntax of a do...while loop is:

do

{

//Statements

}while(Boolean_expression);

Page 22: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Notice that the Boolean expression appears at the end of the loop, so the statements in the

loop execute once before the Boolean is tested.

If the Boolean expression is true, the flow of control jumps back up to do, and the statements

in the loop execute again. This process repeats until the Boolean expression is false.

Example:

public class Test {

public static void main(String args[]){

int x = 10;

do{

System.out.print("value of x : " + x );

x++;

System.out.print("\n");

}while( x < 20 );

}

}

This would produce the following result:

value of x : 10

value of x : 11

value of x : 12

value of x : 13

value of x : 14

value of x : 15

value of x : 16

value of x : 17

value of x : 18

value of x : 19

The for Loop:

A for loop is a repetition control structure that allows you to efficiently write a loop that

needs to execute a specific number of times.

A for loop is useful when you know how many times a task is to be repeated.

Syntax:

The syntax of a for loop is:

Page 23: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

for(initialization; Boolean_expression; update)

{

//Statements

}

Here is the flow of control in a for loop:

The initialization step is executed first, and only once. This step allows you to declare and

initialize any loop control variables. You are not required to put a statement here, as long as a

semicolon appears.

Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it

is false, the body of the loop does not execute and flow of control jumps to the next statement

past the for loop.

After the body of the for loop executes, the flow of control jumps back up to the update

statement. This statement allows you to update any loop control variables. This statement can

be left blank, as long as a semicolon appears after the Boolean expression.

The Boolean expression is now evaluated again. If it is true, the loop executes and the

process repeats itself (body of loop, then update step, then Boolean expression). After the

Boolean expression is false, the for loop terminates.

Example:

public class Test {

public static void main(String args[]) {

for(int x = 10; x < 20; x = x+1) {

System.out.print("value of x : " + x );

System.out.print("\n");

}

}

}

This would produce the following result:

value of x : 10

value of x : 11

value of x : 12

value of x : 13

value of x : 14

value of x : 15

value of x : 16

Page 24: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

value of x : 17

value of x : 18

value of x : 19

Enhanced for loop in Java:

Syntax:

The syntax of enhanced for loop is:

for(declaration : expression)

{

//Statements

}

Declaration: The newly declared block variable, which is of a type compatible with the

elements of the array you are accessing. The variable will be available within the for block

and its value would be the same as the current array element.

Expression: This evaluates to the array you need to loop through. The expression can be an

array variable or method call that returns an array.

Example:

public class Test {

public static void main(String args[]){

int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){

System.out.print( x );

System.out.print(",");

}

System.out.print("\n");

String [] names ={"James", "Larry", "Tom", "Lacy"};

for( String name : names ) {

System.out.print( name );

System.out.print(",");

}

}

}

This would produce the following result:

10,20,30,40,50,

James,Larry,Tom,Lacy,

Page 25: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

The break Keyword:

The break keyword is used to stop the entire loop. The break keyword must be used inside

any loop or a switch statement.

The break keyword will stop the execution of the innermost loop and start executing the next

line of code after the block.

Syntax:

The syntax of a break is a single statement inside any loop:

break;

Example:

public class Test {

public static void main(String args[]) {

int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {

if( x == 30 ) {

break;

}

System.out.print( x );

System.out.print("\n");

}

}

}

This would produce the following result:

10

20

The continue Keyword:

The continue keyword can be used in any of the loop control structures. It causes the loop to

immediately jump to the next iteration of the loop.

In a for loop, the continue keyword causes flow of control to immediately jump to the update

statement.

Page 26: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

In a while loop or do/while loop, flow of control immediately jumps to the Boolean

expression.

Syntax:

The syntax of a continue is a single statement inside any loop:

continue;

Example:

public class Test {

public static void main(String args[]) {

int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {

if( x == 30 ) {

continue;

}

System.out.print( x );

System.out.print("\n");

}

}

}

This would produce the following result:

10

20

40

50

4. Explain the features of Java. (April/May 2013)

Ans: There is given many features of java. They are also known as java buzzwords. The Java

Features given below are simple and easy to understand.

Simple

Object-Oriented

Platform independent

Secured

Robust

Architecture neutral

Portable

Page 27: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Dynamic

Interpreted

High Performance

Multithreaded

Distributed

1) Compiled and Interpreted:- has both Compiled and Interpreter Feature Program of java

is First Compiled and Then it is must to Interpret it .First of all The Program of java is

Compiled then after Compilation it creates Bytes Codes rather than Machine Language.

Then After Bytes Codes are Converted into the Machine Language is Converted into the

Machine Language with the help of the Interpreter So For Executing the java Program First

of all it is necessary to Compile it then it must be Interpreter

2) Platform Independent:- Java Language is Platform Independent means program of java

is Easily transferable because after Compilation of java program bytes code will be created

then we have to just transfer the Code of Byte Code to another Computer.

This is not necessary for computers having same Operating System in which the code of the

java is Created and Executed After Compilation of the Java Program We easily Convert the

Program of the java top the another Computer for Execution.

3) Object-Oriented:- We Know that is purely OOP Language that is all the Code of the

java Language is Written into the classes and Objects So For This feature java is Most

Popular Language because it also Supports Code Reusability, Maintainability etc.

4) Robust and Secure:- The Code of java is Robust and Means of first checks the reliability

of the code before Execution When We trying to Convert the Higher data type into the Lower

Then it Checks the Demotion of the Code the It Will Warns a User to Not to do this So it is

called as Robust

Secure: When we convert the Code from One Machine to Another the First Check the Code

either it is Effected by the Virus or not or it Checks the Safety of the Code if code contains

the Virus then it will never Executed that code on to the Machine.

5) Distributed:- Java is Distributed Language Means because the program of java is

compiled onto one machine can be easily transferred to machine and Executes them on

another machine because facility of Bytes Codes So java is Specially designed For Internet

Users which uses the Remote Computers For Executing their Programs on local machine

after transferring the Programs from Remote Computers or either from the internet.

Page 28: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

6) Simple Small and Familiar:- is a simple Language Because it contains many features of

other Languages like c and C++ and Java Removes Complexity because it doesn’t use

pointers, Storage Classes and Go to Statements and java Doesn’t support Multiple

Inheritance

7) Multithreaded and Interactive:- Java uses Multithreaded Techniques For Execution

Means Like in other in Structure Languages Code is Divided into the Small Parts Like These

Code of java is divided into the Smaller parts those are Executed by java in Sequence and

Timing Manner this is Called as Multithreaded In this Program of java is divided into the

Small parts those are Executed by Compiler of java itself Java is Called as Interactive

because Code of java Supports Also CUI and Also GUI Programs

8) Dynamic and Extensible Code:- Java has Dynamic and Extensible Code Means With

the Help of OOPS java Provides Inheritance and With the Help of Inheritance we Reuse the

Code that is Pre-defined and Also uses all the built in Functions of java and Classes

9) Distributed:- Java is a distributed language which means that the program can be design

to run on computer networks. Java provides an extensive library of classes for

communicating, using TCP/IP protocols such as HTTP and FTP. This makes creating

network connections much easier than in C/C++. You can read and write objects on the

remote sites via URL with the same ease that programmers are used to when read and write

data from and to a file. This helps the programmers at remote locations to work together on

the same project.

10) Secure: Java was designed with security in mind. As Java is intended to be used in

networked/distributor environments so it implements several security mechanisms to protect

you against malicious code that might try to invade your file system.

For example: The absence of pointers in Java makes it impossible for applications to gain

access to memory locations without proper authorization as memory allocation and

referencing model is completely opaque to the programmer and controlled entirely by the

underlying run-time platform .

11) Architectural Neutral: One of the key features of Java that makes it different from

other programming languages is architectural neutral (or platform independent). This means

that the programs written on one platform can run on any other platform without having to

rewrite or recompile them. In other words, it follows 'Write-once-run-anywhere' approach.

Java programs are compiled into byte-code format which does not depend on any machine

architecture but can be easily translated into a specific machine by a Java Virtual Machine

(JVM) for that machine. This is a significant advantage when developing applets or

applications that are downloaded from the Internet and are needed to run on different

systems.

Page 29: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

12) Portable: The portability actually comes from architecture-neutrality. In C/C++, source

code may run slightly differently on different hardware platforms because of how these

platforms implement arithmetic operations. In Java, it has been simplified.

Unlike C/C++, in Java the size of the primitive data types are machine independent. For

example, an int in Java is always a 32-bit integer, and float is always a 32-bit IEEE 754

floating point number. These consistencies make Java programs portable among different

platforms such as Windows, UNIX and Mac.

13) Interpreted: Unlike most of the programming languages which are either complied or

interpreted, Java is both complied and interpreted The Java compiler translates a java source

file to bytecodes and the Java interpreter executes the translated byte codes directly on the

system that implements the Java Virtual Machine. These two steps of compilation and

interpretation allow extensive code checking and improved security.

14) High performance: Java programs are complied to portable intermediate form know as

bytecodes, rather than to native machine level instructions and JVM executes Java bytecode

on any machine on which it is installed. This architecture means that Java programs are faster

than program or scripts written in purely interpreted languages but slower than C and C++

programs that compiled to native machine languages.

Although in the early releases of Java, the interpretation of by bytecode resulted in slow

performance but the advance version of JVM uses the adaptive and Just in time (JIT)

compilation technique that improves performance by converting Java bytecodes to native

machine instructions on the fly.

Page 30: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Classes, Objects and Methods

Question & Answers

PART – A QUESTIONS

(2 Marks)

1. What is Class? Give the general format.(April 2012)

Ans: A class, in the context of Java, are templates that are used to create objects, and to

define object data types and methods. Core properties include the data types and methods

that may be used by the object. All class objects should have the basic class properties.

Classes are categories, and objects are items within each category.

2. What is a recursion function?(April/May 2015)

Java supports recursion. Recursion is the process of defining something in terms of itself.

As it relates to java programming, recursion is the attribute that allows a method to call itself.

A method that calls itself is said to be recursive.

3. What are Java Objects? (April/May 2015)

An object is a software bundle of variables and related methods. These real-world objects

share two characteristics: they all have state and they all have behavior. For example, dogs

have state (name, color, breed, hungry) and dogs have behavior (barking, fetching, and

slobbering on your newly cleaned slacks).

Page 31: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

4. Define the term constructor. (April 2012,April/May 2016)

A constructor is a bit of code that allows you to create objects from a class. You call the

constructor by using the keyword new, followed by the name of the class, followed by any

necessary parameters.

The syntax for a constructor is:

access NameOfClass(parameters) {

initialization code

}

where

access is one of public, protected, "package" (default), or private;

NameOfClass must be identical to the name of the class in which the constructor is defined;

and the initialization code is ordinary Java declarations and statements.

5. What is Static member? (Nov 2012)

The static keyword in java is used for memory management mainly. We can apply java

static keyword with variables, methods, blocks and nested class. The static keyword belongs to

the class than instance of the class.

Page 32: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

The static can be:

variable (also known as class variable)

method (also known as class method)

block

nested class

6. Define String Class. (Nov 2014)

The java.lang.String class provides a lot of methods to work on string. By the help of these

methods, we can perform operations on string such as trimming, concatenating, converting,

comparing, replacing strings etc.

Java String is a powerful concept because everything is treated as a string if you submit any

form in window based, web based or mobile application.

Example:

String s="Sachin";

System.out.println(s.toUpperCase());//SACHIN

System.out.println(s.toLowerCase());//sachin

System.out.println(s);//Sachin(no change in original)

Output:

SACHIN

sachin

Sachin

Page 33: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

7. Differentiate public and protected. (Nov 2012)

Public Members: If members are declared as public inside a class then such members are

accessible to the classes which are inside and outside of the package where this class is

visible. This is the least restrictive of all the accessibility modifiers.

Protected Members:If members are declared as protected then these are accessible to all

classes in the package and to all subclasses of its class in any package where this class is

visible.

8. Define Wrapper Class.(April/May 2014)

In Java, a wrapper class is defined as a class in which a primitive value is wrapped up.

These primitive wrapper classes are used to represent primitive data type values as objects.

The Java platform provides wrapper classes for each of the primitive data types.

For example, Integer wrapper class holds primitive ‘int’ data type value. Similarly, Float

wrapper class contain ‘float’ primitive values, Character wrapper class holds a ‘char’ type

value, and Boolean wrapper class represents ‘boolean’ value.

Page 34: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

9. What is the task of main() method in java? (April/May 2013)

A Java program needs to start its execution somewhere. It does so in a static method of a

class. This method must be named main() and take an array of String's as parameter. When you

start a Java program you usually do so via the command line (console). You call the java

command that comes with the JRE, and tells it what Java class to execute, and what arguments

to pass to the main() method. The Java application is then executed inside the JVM (or by the

JVM some would claim).

10. What is the abstract class?(April/May 2016)

A class that is declared with abstract keyword, is known as abstract class in java. It can

have abstract and non-abstract methods (method with body). A class that is declared as

abstract is known as abstract class. It needs to be extended and its method implemented. It

cannot be instantiated.

Example abstract class:

abstract class A{}

11. Define method/function Overloading.

If a class has multiple methods by same name but different parameters, it is known as

Method Overloading. If we have to perform only one operation, having same name of the

methods increases the readability of the program.

12. Define Inheritance.

Inheritance is a mechanism wherein a new class is derived from an existing class. In Java,

classes may inherit or acquire the properties and methods of other classes.

Page 35: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

A class derived from another class is called a subclass, whereas the class from which a

subclass is derived is called a superclass. A subclass can have only one superclass, whereas

a superclass may have one or more subclasses.

13. Define method of Overriding.

If subclass (child class) has the same method as declared in the parent class, it is known as

method overriding in java. In other words, if subclass provides the specific implementation

of the method that has been provided by one of its parent class, it is known as method

overriding.

Usage of Java Method Overriding:

Method overriding is used to provide specific implementation of a method that is already

provided by its super class.

Method overriding is used for runtime polymorphism

14. What is an instance?

Instance variables are declared in a class, but outside a method, constructor or any

block.. Instance variables are created when an object is created with the use of the keyword

'new' and destroyed when the object is destroyed. Instance variables hold values that must be

referenced by more than one method, constructor or block, or essential parts of an object's

state that must be present throughout the class.

15. Define autoboxing. (April 2013)

Autoboxing is the automatic conversion that the Java compiler makes between the

primitive types and their corresponding object wrapper classes. For example, converting an int to

an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called

unboxing.

Page 36: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

16. Define superclass and subclass. (Nov 2013)

A sub class has an 'is a' relationship with its superclass. This means that a sub class is a

special kind of its super class. When we talk in terms of objects, a sub class object can also

be treated as a super class object. And hence, we can assign the reference of a sub class

object to a super class variable type.

17. What is the difference between this() and super()?

The super keyword in java is a reference variable that is used to refer immediate parent

class object.

Whenever you create the instance of subclass, an instance of parent class is created

implicitly i.e. referred by super reference variable.

Usage of java super Keyword

1. super is used to refer immediate parent class instance variable.

2. super() is used to invoke immediate parent class constructor.

3. super is used to invoke immediate parent class method.

Usage of java this Keyword

1. this keyword can be used to refer current class instance variable.

2. this() can be used to invoke current class constructor.

3. this keyword can be used to invoke current class method (implicitly)

4. this can be passed as an argument in the method call.

5. this can be passed as argument in the constructor call.

6. this keyword can also be used to return the current class instance.

Page 37: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

18. What is dynamic binding?

Binding refers to the linking of a procedural call to the code to be executed in response

to the call. Dynamic binding means that the code associated with the given procedure call is

not known until the time of the call at runtime. It is associated with the polymorphism and

inheritance..

19. What is finalize method()?

finalize method in java is a special method much like main method in java. finalize() is

called before Garbage collector reclaim the Object, its last chance for any object to perform

cleanup activity i.e. releasing any system resources held, closing connection if open etc. The

intent is for finalize() to release system resources such as open files or open sockets before

getting collected.

Syntax of finalize() method:

protected void finalize()

{

//finalize code here;

}

20. What is meant by static binding?

The binding which can be resolved at compile time by compiler is known as static or

early binding. All the static, private and final methods have always been bonded at compile-

time .

21. What are the different types of access modifier used in Java? (Nov 2012)

The basic Accessibility Modifiers are of 4 types in Java. They are

Page 38: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

1. public

2. protected

3. package/default

4. private

There are other Modifiers in Java. They are

1. static

2. abstract

3. final

4. synchronized

5. transient

6. native

7. volatile

PART – B QUESTIONS

1. Define the term static method with an example. (April/May 2015,2016)

If you apply static keyword with any method, it is known as static method.

A static method belongs to the class rather than object of a class.

A static method can be invoked without the need for creating an instance of a class.

static method can access static data member and can change the value of it.

Example of static method:

//Program of changing the common property of all objects(static field).

class Student9{

int rollno;

String name;

static String college = "ITS";

Page 39: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

static void change(){

college = "BBDIT";

}

Student9(int r, String n){

rollno = r;

name = n;

}

void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){

Student9.change();

Student9 s1 = new Student9 (111,"Karan");

Student9 s2 = new Student9 (222,"Aryan");

Student9 s3 = new Student9 (333,"Sonoo");

s1.display();

s2.display();

s3.display();

}

}

Output: 111 Karan BBDIT

222 Aryan BBDIT

333 Sonoo BBDIT

Page 40: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

2. How the data could be accessed using abstract class? (April/May 2015)

Ans: A class that is declared with abstract keyword, is known as abstract class in java. It can

have abstract and non-abstract methods (method with body). A class that is declared as

abstract is known as abstract class. It needs to be extended and its method implemented. It

cannot be instantiated.

Example abstract class:

abstract class A{}

3. What are Overriding methods? Give an example. (Nov 2014)

If subclass (child class) has the same method as declared in the parent class, it is known

as method overriding in java. In other words, if subclass provides the specific

implementation of the method that has been provided by one of its parent class, it is known

as method overriding.

Usage of Java Method Overriding:

Method overriding is used to provide specific implementation of a method that is already

provided by its super class.

Method overriding is used for runtime polymorphism

Rules for Java Method Overriding:

method must have same name as in the parent class

method must have same parameter as in the parent class.

must be IS-A relationship (inheritance).

Example Refer Q:No:7

Page 41: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

4. State and similarities between interfaces and classes. (Nov 2014)

An interface in java is a blueprint of a class. It has static constants and abstract

methods only.

The interface in java is a mechanism to achieve fully abstraction. There can be only

abstract methods in the java interface not method body. It is used to achieve fully abstraction

and multiple inheritance in Java.

Java Interface also represents IS-A relationship.

It cannot be instantiated just like abstract class.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

It is used to achieve fully abstraction.

By interface, we can support the functionality of multiple inheritance.

It can be used to achieve loose coupling.

Understanding relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends another

interface but a class implements an interface.

Simple example of Java interface

In this example, Printable interface have only one method, its implementation is provided in

the A class.

interface printable{

void print();

}

Page 42: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

class A6 implements printable{

public void print(){System.out.println("Hello");}

public static void main(String args[]){

A6 obj = new A6();

obj.print();

}

}

Test it Now

Output:Hello

5. Describe briefly about Wrapper class with example. (April 2013).

A variable of primitive data type is by default passed by value and not by reference.

Quite often, there might arise the need to consider such variables of primitive data type as

reference types. The solution to this lies in the wrapper classes provided by Java.

These classes are used to wrap the data in a new object which contains the value of that

variable. This object can then be used in a way similar to how other objects are used. For

example, we wrap the number 34 in an Integer object in the following way:

Integer intObject = new Integer (34);

The Integer class is the wrapper class that has been provided for the int data type. Similarly,

there are wrapper classes for the other data types too. The following table lists the data types

and their corresponding wrapper classes.

Data Type Wrapper Class

byte Byte

short Short

Page 43: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

int Integer

long Long

float Float

double Double

char Character

boolean Boolean

Note that the wrapper classes of all the primitive data types except int and char have the same

name as that of the data type.

Creating objects of the Wrapper classes:

Integer intObject = new Integer (34);

Integer intObject = new Integer ( "34");

Similarly, we have methods for the other seven wrapper classes: byteValue(), shortValue(),

longValue(), floatValue(), doubleValue(), charValue(), booleanValue().

6. What is Autoboxing? Compare this with Auto Unboxing. (Nov 2014)

Ans: The automatic conversion of primitive data types into its equivalent Wrapper

type is known as boxing and opposite operation is known as unboxing. This is the new

feature of Java5. So java programmer doesn't need to write the conversion code.

Advantage of Autoboxing and Unboxing:

No need of conversion between primitives and Wrappers manually so less coding is required.

Simple Example of Autoboxing in java:

class BoxingExample1{

Page 44: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

public static void main(String args[]){

int a=50;

Integer a2=new Integer(a);//Boxing

Integer a3=5;//Boxing

System.out.println(a2+" "+a3);

}

}

Output: 50 5

Simple Example of Unboxing in java:

The automatic conversion of wrapper class type into corresponding primitive type, is known

as Unboxing. Let's see the example of unboxing:

class UnboxingExample1{

public static void main(String args[]){

Integer i=new Integer(50);

int a=i;

System.out.println(a);

}

}

Output: 50

Page 45: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

7. Write a program in JAVA to implement Overriding. (Nov 2014)

class Bank{

int getRateOfInterest(){return 0;}

}

class SBI extends Bank{

int getRateOfInterest(){return 8;}

}

class ICICI extends Bank{

int getRateOfInterest(){return 7;}

}

class AXIS extends Bank{

int getRateOfInterest(){return 9;}

}

class Test2{

public static void main(String args[]){

SBI s=new SBI();

ICICI i=new ICICI();

AXIS a=new AXIS();

System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());

System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());

System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());

}

Output:

SBI Rate of Interest: 8

Page 46: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

ICICI Rate of Interest: 7

AXIS Rate of Interest: 9

8. Describe Inner Class with example.

Ans: Java inner class or nested class is a class i.e. declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place so that it can be

more readable and maintainable.

Additionally, it can access all the members of outer class including private data members and

methods.

Syntax of Inner class:

class Java_Outer_class{

...

class Java_Inner_class{

...

}

...

}

Advantage of java inner classes:

There are basically three advantages of inner classes in java. They are as follows:

1) Nested classes represent a special type of relationship that is it can access all the members

(data members and methods) of outer class including private.

2) Nested classes are used to develop more readable and maintainable code because it

logically group classes and interfaces in one place only.

Page 47: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

3) Code Optimization: It requires less code to write.

Example Program:

class TestMemberOuter1{

private int data=30;

class Inner{

void msg(){System.out.println("data is "+data);}

}

void display(){

Inner in=new Inner();

in.msg();

}

public static void main(String args[]){

TestMemberOuter1 obj=new TestMemberOuter1();

obj.display();

}

}

Output: data is 30

9. Describe various String manipulation in Java.

Java String provides a lot of concepts that can be performed on a string such as compare,

concat, equals, split, length, replace, compareTo, intern, substring etc.

In java, string is basically an object that represents sequence of char values.

An array of characters works same as java string. For example:

Page 48: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

char[] ch={'j','a','v','a','t','p','o','i','n','t'};

String s=new String(ch);

is same as:

String s="javatpoint";

Generally, string is a sequence of characters. But in java, string is an object that represents a

sequence of characters. String class is used to create string object.

There are two ways to create String object:

By string literal

By new keyword

By String Literal:

Java String literal is created by using double quotes. For Example:

String s="welcome";

For example:

String s1="Welcome";

String s2="Welcome"; //will not create new instance

By new keyword:

String s=new String("Welcome"); //creates two objects and one reference variable

Example:

public class StringExample{

public static void main(String args[]){

String s1="java";//creating string by java string literal

Page 49: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

char ch[]={'s','t','r','i','n','g','s'};

String s2=new String(ch);//converting char array to string

String s3=new String("example");//creating java string by new keyword

System.out.println(s1);

System.out.println(s2);

System.out.println(s3);

}}

Output:

java

strings

example

10. Write a program in java to count the number of characters in a string.

import java.io.*;

class count

{

void main()throws IOException

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("enter the String");

String s=br.readLine();

int i,l,c1=0,c2=0,c3=0,sp=0;

char ch;

l=s.length();

for(i=0;i<l;i++)

{

Page 50: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

ch=s.charAt(i);

if(Character.isLetter(ch))

++c1;

else if(Character.isDigit(ch))

++c2;

else if(ch==' ')

++sp;

else

++c3;

}

System.out.println("no of Letter="+c1);

System.out.println("no of Digit="+c2);

System.out.println("no of Spaces="+sp);

System.out.println("no of Symbol="+c3);

}

}

11. Explain the constructor with example.

Ans: Constructor in java is a special type of method that is used to initialize the object.

Java constructor is invoked at the time of object creation. It constructs the values i.e. provides

data for the object that is why it is known as constructor.

Rules for creating java constructor:

There are basically two rules defined for the constructor.

Constructor name must be same as its class name

Constructor must have no explicit return type

Types of java constructors:

Page 51: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

There are two types of constructors:

Default constructor (no-arg constructor)

Parameterized constructor

Java Default Constructor:

A constructor that have no parameter is known as default constructor.

Syntax of default constructor:

<class_name>(){}

Example of default constructor

class Bike1{

Bike1(){System.out.println("Bike is created");}

public static void main(String args[]){

Bike1 b=new Bike1();

}

}

Output:

Bike is created

Page 52: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Rule: If there is no constructor in a class, compiler automatically creates a default

constructor.

Purpose of default constructor:

Default constructor provides the default values to the object like 0, null etc. depending on the

type.

Example of default constructor that displays the default values:

class Student3{

int id;

String name;

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){

Student3 s1=new Student3();

Student3 s2=new Student3();

s1.display();

s2.display();

}

}

Output:

0 null

0 null

Page 53: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

12. Explain the concept of recursion with suitable example.

Ans: Java supports recursion. Recursion is the process of defining something in terms

of itself. As it relates to java programming, recursion is the attribute that allows a method to

call itself. A method that calls itself is said to be recursive.

The classic example of recursion is the computation of the factorial of a number. The

factorial of a number N is the product of all the whole numbers between 1 and N. for

example, 3 factorial is 1×2×3, or 6. Here is how a factorial can be computed by use of a

recursive method.

Example:

class Factorial {

int fact(int n) {

int result;

if ( n ==1) return 1;

result = fact (n-1) * n;

return result;

}

}

class Recursion {

public static void main (String args[]) { Factorial f

=new Factorial(); System.out.println(“Factorial of

3 is “ + f.fact(3)); System.out.println(“Factorial of

3 is “ + f.fact(4));

System.out.println(“Factorial of 3 is “ + f.fact(5));

}

}

The output from this program is shown here:

Page 54: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Factorial of 3 is 6

Factorial of 4 is 24

Factorial of 5 is 120

13. Write a short note on parameterized constructor.

Java parameterized constructor:

A constructor that have parameters is known as parameterized constructor.

Parameterized constructor is used to provide different values to the distinct objects.

Example of parameterized constructor:

In this example, we have created the constructor of Student class that has two parameters.

We can have any number of parameters in the constructor.

class Student4{

int id;

String name;

Student4(int i,String n){

id = i;

name = n;

}

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){

Student4 s1 = new Student4(111,"Karan");

Student4 s2 = new Student4(222,"Aryan");

s1.display();

Page 55: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

s2.display();

}

}

Output:

111 Karan

222 Aryan

PART – C QUESTIONS

1. Explain types of Inheritance with example. (April/May 2013).

Ans: Inheritance in Java:

The idea behind inheritance in java is that you can create new classes that are built upon

existing classes. When you inherit from an existing class, you can reuse methods and fields

of parent class, and you can add new methods and fields also.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java:

For Method Overriding (so runtime polymorphism can be achieved).

For Code Reusability.

Syntax of Java Inheritance:

class Subclass-name extends Superclass-name

{

Page 56: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

//methods and fields

}

The extends keyword indicates that you are making a new class that derives from an existing

class.

In the terminology of Java, a class that is inherited is called a super class. The new class is

called a subclass.

Example

class Employee{

float salary=40000;

}

class Programmer extends Employee{

int bonus=10000;

public static void main(String args[]){ Programmer

p=new Programmer();

System.out.println("Programmer salary is:"+p.salary);

System.out.println("Bonus of Programmer is:"+p.bonus);

}

}

Programmer salary is:40000.0

Bonus of programmer is:10000

Types of inheritance in java:

On the basis of class, there can be three types of inheritance in java: single, multilevel and

hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only.

Page 57: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Types of inheritance in java:

Note: Multiple inheritance is not supported in java through class.

When a class extends multiple classes i.e. known as multiple inheritance.

Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in

java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B classes.

If A and B classes have same method and you call it from child class object, there will be

ambiguity to call method of A or B class.

Page 58: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Since compile time errors are better than runtime errors, java renders compile time error if

you inherit 2 classes. So whether you have same method or different, there will be compile

time error now.

class A{

void msg(){System.out.println("Hello");}

}

class B{

void msg(){System.out.println("Welcome");}

}

class C extends A,B{//suppose if it were

Public Static void main(String args[]){

C obj=new C();

obj.msg();//Now which msg() method would be invoked?

}

}

Output: Compile Time Error

2. Explain how the String Class differ from StringBuffer Class. (Nov 2012)

String class objects work with complete strings instead of treating them as character arrays.

Convert variables of type char to string objects by using gStr = Character.toString(c);. String

class objects are immutable (ie. read only). When changes are made to a string, a new object is

created and the old one is disused. This causes extraneous garbage collection.

Use StringBuffer or StringBuilder instead of String objects when modification is frequent.

StringBuffer class:

Page 59: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

The StringBuffer class is used to created mutable (modifiable) string. The StringBuffer

class is same as String except it is mutable i.e. it can be changed.

Note: StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously

.So it is safe and will result in an order.

Commonly used Constructors of StringBuffer class:

StringBuffer(): creates an empty string buffer with the initial capacity of 16.

StringBuffer(String str): creates a string buffer with the specified string.

StringBuffer(int capacity): creates an empty string buffer with the specified capacity as

length.

3. What is method overloading? Explain by giving a suitable example.

Ans: If a class has multiple methods by same name but different parameters, it

is known as Method Overloading. If we have to perform only one operation, having same

name of the methods increases the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of

arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int)

for three parameters then it may be difficult for you as well as other programmers to

understand the behavior of the method because its name differs.

Advantage of Method Overloading:

Method overloading increases the readability of the program.

Different ways to overload the method:

There are two ways to overload the method in java

By changing number of arguments

Page 60: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

By changing the data type

Example of Method Overloading by changing the no. of arguments:

class Calculation{

void sum(int a,int b){System.out.println(a+b);}

void sum(int a,int b,int c){System.out.println(a+b+c);}

public static void main(String args[]){

Calculation obj=new Calculation();

obj.sum(10,10,10);

obj.sum(20,20);

}

}

Output: 30

40

Example of Method Overloading by changing data type of argument:

In this example, we have created two overloaded methods that differs in data type. The first

sum method receives two integer arguments and second sum method receives two double

arguments.

class Calculation2{

void sum(int a,int b){System.out.println(a+b);}

void sum(double a,double b){System.out.println(a+b);}

public static void main(String args[]){

Calculation2 obj=new Calculation2();

Page 61: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

obj.sum(10.5,10.5);

obj.sum(20,20);

}

}

Output: 21.0

40

4. Explain the Static and Finalize methods with suitable example.

The static keyword in java is used for memory management mainly. We can apply

java static keyword with variables, methods, blocks and nested class. The static

keyword belongs to the class than instance of the class.

The static can be:

variable (also known as class variable)

method (also known as class method)

block

nested class

finalize() method

The finalize() method is invoked each time before the object is garbage collected. This

method can be used to perform cleanup processing. This method is defined in Object

class as:

protected void finalize(){}

public class TestGarbage1{

public void finalize(){System.out.println("object is garbage collected");}

Page 62: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

public static void main(String args[]){

TestGarbage1 s1=new TestGarbage1();

TestGarbage1 s2=new TestGarbage1();

s1=null;

s2=null;

System.gc();

}

}

*****

Page 63: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Unit-III Question & Answers

PART – A

1. Define Applet.

An applet is a small Internet-based program written in Java, a programming language for

the Web, which can be downloaded by any computer. The applet is also able to run in

HTML. The applet is usually embedded in an HTML page on a Web site and can be

executed from within a browser.

2. Give the meaning for JcheckBox in Java. Nov 12

A JCheckBox is a graphical component that can be in either an on (true) or off (false)

state. The class JCheckBox is an implementation of a check box - an item that can be

selected or deselected, and which displays its state to the user.

3. Define AWT? Give example. April 11

The Abstract Window Toolkit (AWT) package in Java enables the programmers to create

GUI-based applications. It contains a number of classes that help to implement common

Window-based tasks, such as manipulating windows, adding scroll bars, buttons, list items,

text boxes, etc,.

4. What is the use of JButton class? List its possible constructors. April 13

This class creates a labeled button. The class JButton is an implementation of a push

button. This component has a label and generates an event when pressed. It can have Image

also.

JButton().

JButton(Action a).

JButton(String text).

5. What are the events to be implemented to handle mouse events? April 13

Handling mouse events in Java is split between three different event listeners. The

MouseListener interface is used to track when a mouse is entering or leaving the area

occupied by a graphical component, and when a mouse button is pressed and released.

The MouseMotionListener is used to track the mouse cursor as it is pressed and dragged

or just moves around a graphical component's area. Finally, the MouseWheelListener tracks

the movement of a mouse wheel.

6. What is meant by 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.

Page 64: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

7. What is meant by Event Classes?

All the events in Java have 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.

8. What is GUI?

Graphical User Interface (GUI) offers user interaction via some graphical components.

For example our underlying Operating System also offers GUI via window, frame, Panel,

Button, Textfield, TextArea, Listbox, Combobox, Label, Checkbox etc.

9. List out some of the GUI based applications.

Some of the GUI based applications are:

Automated Teller Machine (ATM)

Airline Ticketing System

Information Kiosks at railway stations

Mobile Applications

Navigation Systems

10. List out any two advantages of GUI.

GUI provides multitasking environment.

Using GUI it is easier to control and navigate the operating system which becomes

very slow in command user interface. GUI can be easily customized.

11. What is a Frame in AWT?

A Frame is a top-level window with a title and a border. The size of the frame includes

any area designated for the border. Frame encapsulates window. It and has a title bar, menu

bar, borders, and resizing corners.

12. Define 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, ect.

13. What is JoptionPane?(April 14)

JOptionPane provides set of standard dialog boxes that prompt users for a value or informs them of something.

14. What is the use of JComboBox?(April 14)

A JComboBox component presents the user with to show up menu of choices. The class JComboBox is a component which combines a button or editable field and a drop-down list.

Page 65: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

15. How to define JavaTextArea? (April 14) A JTextArea object is a text component that allows for the editing of a multiple lines of

text.Following is the declaration for javax.swing.JTextArea class,

public class JTextArea extends JTextComponent

16. What is adapter class? Nov/Dec 2016

Page 66: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

PART – B

1. Briefly explain about the adapter classes in java. Nov 12

o Java provides a special feature, called an adapter class that can simplify the

creation of event handlers in certain situations.

o An adapter class provides an empty implementation of all methods in an event

listener interface.

o Adapter classes are useful when you want to receive and process only some of the

events that are handled by a particular event listener interface.

o You can define a new class to act as an event listener by extending one of the

adapter classes and implementing only those events in which you are interested.

o For example, the MouseMotionAdapter class has two methods, mouseDragged()

and mouseMoved().

o The signatures of these empty methods are exactly as defined in the MouseMotionListener interface.

o If you were interested in only mouse drag events, then you could simply extend

MouseMotionAdapter and implement mouseDragged(). The empty

implementation of mouseMoved ( ) would handle the mouse motion events for us.

o The following example demonstrates an adapter. It displays a message in the

status bar of an applet viewer or browser when the mouse is clicked or dragged.

o However, all other mouse events are silently ignored. The program has three

classes. AdapterDemo extends Applet. Its init( ) method creates an instance of MyMouseAdapter and registers that object to receive notifications of mouse events.

o It also creates an instance of MyMouseMotionAdapter and registers that object to

receive notifications of mouse motion events. Both of the constructors take a

reference to the applet as an argument. MyMouseAdapter implements the

mouseClicked( ) method.

o The other mouse events are silently ignoring d by code inherited from the MouseAdapter class.

S. No. Adapter Classes Listener Interface

1 2

3

4

5

6

ComponentAdapter ContainerAdapter

FocusAdapter

KeyAdapter

MouseAdapter

MouseMotionAdapter

ComponentListener ContainerListener

FocusListener

KeyListener

MouseListener

MouseMotionListener

o MyMouseMotionAdapter implements the mouseDragged( ) method. The other

mouse motion event is silently ignored by code inherited from the

MouseMotionAdapter class.

o Note that both of our event listener classes save a reference to the applet. o This information is provided as an argument to their constructors and is used later

to invoke the showStatus( ) method.

Page 67: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/* <applet code="AdapterDemo" width=300 height=100>

</applet>

*/

public class AdapterDemo extends Applet

{

public void init()

{

addMouseListener(new MyMouseAdapter(this));

addMouseMotionListener(new MyMouseMotionAdapter(this));

}

}

class MyMouseAdapter extends MouseAdapter

{

AdapterDemo adapterDemo;

public MyMouseAdapter(AdapterDemo adapterDemo)

{

this.adapterDemo = adapterDemo;

}

// Handle mouse clicked.

public void mouseClicked(MouseEvent me)

{

adapterDemo.showStatus("Mouse clicked");

}

}

class MyMouseMotionAdapter extends MouseMotionAdapter

{

AdapterDemo adapterDemo;

public MyMouseMotionAdapter(AdapterDemo adapterDemo)

{

this.adapterDemo = adapterDemo;

}

// Handle mouse dragged.

public void mouseDragged(MouseEvent me)

{

adapterDemo.showStatus("Mouse dragged");

}

}

2. Write a note on Mouse Event Handling with example. Nov 12

Java also allows us to listen for mouse events. Essentially, we'd use these events to know

where the mouse is, either with respect to a GUI component or in terms of x and y

coordinates.

Page 68: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Here's how we'll set up this mouse event handling:

1. Add implements MouseListener.

2. Mouse listening is based upon a particular component. For an applet, that's the whole

applet. Thus, we only need the call addMouseListener(this);.

3. Finally, we need to write code to handle the event. Class MouseEvent has accessors

getX() and getY() that get us the coordinates of where the event occurred. We can

store these an use them in other methods. (For example, we could store them and use

them in paint() to draw something.) This time, though, there are five different mouse

event methods we must implement:

o mousePressed(), which is triggered when the mouse is on the component. o mouseClicked(), which is triggered when the mouse is pressed and released on the

component. (mousePressed() is called first.)

o mouseReleased(), which is triggered when the mouse is released on the component.

(mousePressed() must have been called first.)

o mouseEntered(), which is triggered upon entry to the component. o mouseExited(), which is triggered upon leaving the component. o Note that when we implement the MouseListener interface, we must provide all five

methods. The full headers look like this:

public void mousePressed(MouseEvent e)

public void mouseClicked(MouseEvent e)

public void mouseReleased(MouseEvent e)

public void mouseEntered(MouseEvent e)

public void mouseExited(MouseEvent e)

3. Explain about five event classes available in java Nov 11, April 12

AWT Event

It is the root event class for all AWT events. This class and its subclasses supersede the

original java.awt.Event class. This class is defined in java.awt package. This class has a

method named getID() that can be used to determine the type of event.

Following is the declaration for java.awt.AWTEvent class:

public class AWTEvent extends EventObject Following are the fields for java.awt.AWTEvent class,

static int ACTION_FIRST -- The first number in the range of ids used for action

events.

static long ACTION_EVENT_MASK -- The event mask for selecting action events.

static long ADJUSTMENT_EVENT_MASK -- The event mask for selecting

adjustment events.

static long COMPONENT_EVENT_MASK -- The event mask for selecting

component events.

Constructors

Page 69: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

AWTEvent(Event event)

AWTEvent(java.lang.Object source, int id)

Methods int getID() Returns the event type. String toString() Return a String representation of this object.

ActionEvent

This class is defined in java.awt.event package. The ActionEvent is generated when

button is clicked or the item of a list is double clicked.

Class declaration

public class ActionEvent extends AWTEvent

Fields

Following are the fields for java.awt.event.ActionEvent class:

static int ACTION_FIRST -- The first number in the range of ids used for

action events.

static int ACTION_LAST -- The last number in the range of ids used for

action events.

static int ACTION_PERFORMED -- This event id indicates that a

meaningful action occured.

static int ALT_MASK -- The alt modifier.

static int CTRL_MASK -- The control modifier.

static int META_MASK -- The meta modifier.

static int SHIFT_MASK -- The shift modifier.

Constructors

ActionEvent(Object source, int id, String command) ActionEvent(Object source, int id, String command, int modifiers)

Methods

String getActionCommand() int getModifiers()

long getWhen()

MouseEvent Class

This event indicates a mouse action occurred in a component. This low-level event is

generated by a component object for Mouse Events and Mouse motion events.

a mouse button is pressed

a mouse button is released

a mouse button is clicked (pressed and released)

a mouse cursor enters the unobscured part of component's geometry

a mouse cursor exits the unobscured part of component's geometry

Page 70: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

a mouse is moved

the mouse is dragged

Following is the declaration for java.awt.event.MouseEvent class:

public class MouseEvent extends InputEvent

Fields Following are the fields for java.awt.event.MouseEvent class,

static int BUTTON1 --Indicates mouse button #1; used by getButton()

static int BUTTON2 --Indicates mouse button #2; used by getButton()

static int BUTTON3 --Indicates mouse button #3; used by getButton()

static int MOUSE_CLICKED --The "mouse clicked" event

static int MOUSE_DRAGGED --The "mouse dragged" event

Constructors

MouseEvent(Component source, int id, long when, int modifier, int x, int y, int clickCount, Boolean popupTrigger)

MouseEvent(Component source, int id, long when, int modifier, int x, int y,

int clickCount, Boolean popupTrigger, int button)

Methods

int getButton() point getPoint()

int getX()

int getY()

TextEvent Class

The object of this class represents the text events. The TextEvent is generated when

character is entered in the text fields or text area.

The TextEvent instance does not include the characters currently in the text component

that generated the event rather we are provided with other methods to retrieve that

information.

Following is the declaration for java.awt.event.TextEvent class,

public class TextEvent extends AWTEvent

Fields Following are the fields for java.awt.event.TextEvent class:

static int TEXT_FIRST --The first number in the range of ids used for text

events.

static int TEXT_LAST --The last number in the range of ids used for text events.

static int TEXT_VALUE_CHANGED --This event id indicates that object's text

changed.

Constructors

TextEvent(Object source, int id)

Methods

String paramString()

Page 71: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

PaintEvent

The Class PaintEvent used to ensure that paint/update method calls are serialized along

with the other events delivered from the event queue

Following is the declaration for java.awt.event.PaintEvent class,

public class PaintEvent extends ComponentEvent

Field Following are the fields for java.awt.Component class,

static int PAINT -- The paint event type.

static int PAINT_FIRST -- Marks the first integer id for the range of paint event

ids.

static int PAINT_LAST -- Marks the last integer id for the range of paint event

ids.

static int UPDATE -- The update event type.

Constructors

PaintEvent(Component source, int id, Rectangle updateRect)

Methods

void setUpdateRect(Rectangle updateRect) String paramString()

4. What is an Itemlistener interface? Explain it briefly. Nov 11, April 12, April 14

The class which processes the ItemEvent should implement this interface. The object of

that class must be registered with a component. The object can be registered using the

addItemListener() method. When the action event occurs, that object's itemStateChanged

method is invoked.

Following is the declaration for java.awt.event. ItemListener interface,

public interface ItemListener extends EventListener

Methods inherited This interface inherits methods from the following interfaces,

java.awt.EventListener

ItemListener Example

import java.awt.*; import java.awt.event.*;

public class AwtListenerDemo

{

private Frame mainFrame;

private Label headerLabel;

private Label statusLabel;

private Panel controlPanel;

public AwtListenerDemo()

{

prepareGUI();

}

Page 72: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

public static void main(String[] args)

{

AwtListenerDemo awtListenerDemo = new AwtListenerDemo();

awtListenerDemo.showItemListenerDemo();

}

private void prepareGUI()

{

mainFrame = new Frame("Java AWT Examples");

mainFrame.setSize(400,400);

mainFrame.setLayout(new GridLayout(3, 1));

mainFrame.addWindowListener(new WindowAdapter()

{

public void windowClosing(WindowEvent windowEvent)

{

}

});

System.exit(0);

headerLabel = new Label();

headerLabel.setAlignment(Label.CENTER);

statusLabel = new Label();

statusLabel.setAlignment(Label.CENTER);

statusLabel.setSize(350,100);

controlPanel = new Panel();

controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);

mainFrame.add(controlPanel);

mainFrame.add(statusLabel);

mainFrame.setVisible(true);

}

private void showItemListenerDemo()

{

headerLabel.setText("Listener in action: ItemListener");

Checkbox chkApple = new Checkbox("Apple");

Checkbox chkMango = new Checkbox("Mango");

Checkbox chkPeer = new Checkbox("Peer");

chkApple.addItemListener(new CustomItemListener());

chkMango.addItemListener(new CustomItemListener());

chkPeer.addItemListener(new CustomItemListener());

controlPanel.add(chkApple);

controlPanel.add(chkMango);

controlPanel.add(chkPeer);

mainFrame.setVisible(true);

}

class CustomItemListener implements ItemListener

{

public void itemStateChanged(ItemEvent e)

{

statusLabel.setText(e.getItem() +" Checkbox: " +

Page 73: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

(e.getStateChange()==1?"checked":"unchecked"));

}

}

}

Output

5. Describe any five GUI components with example. April 11

a) Label Class

Label is a passive control because it does not create any event when accessed by the user.

The label control is an object of Label. A label displays a single line of read-only text.

However the text can be changed by the application programmer but cannot be changed by

the end user in any way.

Following is the declaration for java.awt.Label class:

public class Label extends Component implements Accessible

Field Following are the fields for java.awt.Component class,

static int CENTER -- Indicates that the label should be centered.

static int LEFT -- Indicates that the label should be left justified.

static int RIGHT -- Indicates that the label should be right justified.

Constructors Label()

Label(String text)

Label(String text, int alignment)

Methods void addNotify() int getAlignment()

String getText()

void setText()

b) Button Class

Button is a control component that has a label and generates an event when pressed. When a button is pressed and released, AWT sends an instance of ActionEvent to the button,

by calling processEvent on the button.

Page 74: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

The button's processEvent method receives all events for the button; it passes an action

event along by calling its own processActionEvent method. The latter method passes the

action event on to any action listeners that have registered an interest in action events

generated by this button.

If an application wants to perform some action based on a button being pressed and

released, it should implement ActionListener and register the new listener to receive events

from this button, by calling the button's addActionListener method. The application can

make use of the button's action command as a messaging protocol.

Following is the declaration for java.awt.Button class:

public class Button extends Component implements Accessible Constructors Button()

Button(String text)

Methods

String getActionCommand()

void setActionCommand(String command)

String getLabel()

void setLabel(String label)

Example import java.applet.Applet; import java.awt.Button;

/*<applet code="CreateAWTButtonExample" width=200 height=200>

</applet>*/ public class CreateAWTButtonExample extends Applet

{

public void init()

{

Button button1 = new Button();

button1.setLabel("My Button 1");

Button button2 = new Button("My Button 2");

add(button1);

add(button2);

}

}

Output

c) CheckBox Class

Page 75: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Checkbox control is used to turn an option on (true) or off (false). There is label for each

checkbox representing what the checkbox does. The state of a checkbox can be changed by

clicking on it.

Following is the declaration for java.awt.Checkbox class,

public class Checkbox extends Component implements ItemSelectable,

Accessible Constructors Checkbox()

Checkbox(String label)

Checkbox(String label, boolean state)

Methods void addItemListener(ItemListener i) String getLabel()

void setState(Boolean state )

void setCheckboxGroup(CheckboxGroup c)

CheckBox Example

import java.applet.Applet;

import java.awt.Checkbox;

import java.awt.Graphics;

/*<applet code="GetCheckboxState" width=200 height=200>

</applet>*/ public class GetCheckboxState extends Applet

{

Checkbox checkBox1 = null;

Checkbox checkBox2 = null;

public void init()

{

checkBox1 = new Checkbox("My Checkbox 1");

checkBox2 = new Checkbox("My Checkbox 2", true);

add(checkBox1);

add(checkBox2);

}

public void paint(Graphics g)

{ g.drawString("Is checkbox 1 selected? " + checkBox1.getState(), 10, 80);

g.drawString("Is checkbox 2 selected? " + checkBox2.getState(), 10, 100);

}

}

Output

d) CheckBoxGroup Class

The CheckboxGroup class is used to group the set of checkbox.

Page 76: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Following is the declaration for java.awt.CheckboxGroup class:

public class CheckboxGroup extends Object implements Serializable

Constructors CheckBoxGroup()

Methods

Checkbox getCurrent() Checkbox getSelectedCheckbox()

void setSelectedCheckbox(Checkbox box)

Example import java.applet.Applet; import java.awt.Checkbox;

import java.awt.CheckboxGroup;

/*<applet code="CreateRadioButtonsExample" width=200 height=200>

</applet>*/ public class CreateRadioButtonsExample extends Applet

{

public void init()

{

CheckboxGroup lngGrp = new CheckboxGroup();

Checkbox java = new Checkbox("Java", lngGrp, true);

Checkbox cpp = new Checkbox("C++", lngGrp, true);

Checkbox vb = new Checkbox("VB", lngGrp, true);

add(java);

add(cpp);

add(vb);

}

}

Output

e) List Class The List represents a list of text items. The list can be configured to that user can choose

either one item or multiple items.

Following is the declaration for java.awt.List class:

public class List extends Component implements ItemSelectable, Accessible

Constructors List()

Page 77: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

List(int rows)

Methods void add(String item) void addActionListener(ActionListener l)

void addItem(String item)

void clear()

6. Write the Java Code to implement the use of JCheckBox. April 13

The class JCheckBox is an implementation of a check box - an item that can be selected

or deselected, and which displays its state to the user.

Following is the declaration for javax.swing.JCheckBox class,

public class JCheckBox extends JToggleButton implements Accessible

Field Following are the fields for javax.swing.JCheckBox class:

static String BORDER_PAINTED_FLAT_CHANGED_PROPERTY --

Identifies a change to the flat property.

Constructors JCheckBox()

JCheckBox(Action a)

JCheckBox(Icon icon)

JCheckBox(String text)

Methods boolean isBorderPaintedFlat() String getUIClassID()

void updateUI()

JCheckBox Example

JCheckBox checkbox = new JCheckBox("Enable logging");

// add to a container frame.add(checkbox);

// set state checkbox.setSelected(true);

// check state if (checkbox.isSelected())

{

// do something...

}

else

{

// do something else... }

Page 78: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

7. How java makes different kinds of events? April 14

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

The events can be broadly classified into two categories,

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.

Event Handling is the mechanism that controls the event and decides what should

happen if an event occurs. This mechanism has the code which is known as event handler

that is executed when an event occurs. Java Uses the Delegation Event Model to handle

the events. This model defines the standard mechanism to generate and handle the events.

Let's have a brief introduction to this model.

The Delegation Event Model has the following key participants namely

Source - The source is an object on which event occurs. Source is responsible for

providing information of the occurred event to its handler. Java provide as with

classes for source object.

Listener - It is also known as event handler. Listener is responsible for generating

response to an event. From java implementation point of view the listener is also an

object. Listener waits until it receives an event. Once the event is received, the

listener processes the event an then returns.

The benefit of this approach is that the user interface logic is completely separated

from the logic that generates the event. The user interface element is able to delegate the

processing of an event to the separate piece of code. In this model, Listener needs to be

registered with the source object so that the listener can receive the event notification.

This is an efficient way of handling the event because the event notifications are sent

only to those listeners that want to receive them.

8. Describe the function of JLabel with an example. April 14

The class JLabel can display text, an image, or both. Label's contents are aligned by

setting the vertical and horizontal alignment in its display area. By default, labels are

vertically centered in their display area. Text-only labels are leading edge aligned, by default;

image-only labels are horizontally centered, by default.

Following is the declaration for javax.swing.JLabel class:

public class JLabel extends JComponent implements SwingConstants, Accessible

Field

Page 79: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Following are the fields for javax.swing.JLabel class:

protected Component labelFor

Constructors JLabel()

JLabel(Icon image)

JLabel(String text)

Class methods Icon getDisabledIcon() int getHorizontalAlignment()

int getHorizontalTextPosition()

Icon getIcon()

String getText()

Example Program import java.awt.GridLayout; import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JFrame;

import javax.swing.ImageIcon;

public class JlabelDemo extends JPanel

{

JLabel jlbLabel1, jlbLabel2, jlbLabel3;

public JlabelDemo()

{

ImageIcon icon = new ImageIcon("java-swing-tutorial.JPG",

"My Website");

// Creating an Icon

setLayout(new GridLayout(3, 1));

// 3 rows, 1 column Panel having Grid Layout

jlbLabel1 = new JLabel("Image with Text", icon, JLabel.CENTER);

// We can position of the text, relative to the icon:

jlbLabel1.setVerticalTextPosition(JLabel.BOTTOM);

jlbLabel1.setHorizontalTextPosition(JLabel.CENTER);

jlbLabel2 = new JLabel("Text Only Label");

jlbLabel3 = new JLabel(icon); // Label of Icon Only

// Add labels to the Panel

add(jlbLabel1);

add(jlbLabel2);

add(jlbLabel3);

}

public static void main(String[] args)

{

JFrame frame = new JFrame("jLabel Usage Demo");

frame.addWindowListener(new WindowAdapter()

{

// Shows code to Add Window Listener

public void windowClosing(WindowEvent e)

Page 80: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

{

}

});

System.exit(0);

frame.setContentPane(new JlabelDemo());

frame.pack();

frame.setVisible(true);

}

}

Output

Page 81: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

PART – C

1. Discuss the various GUI components available in java. Nov 12

Graphical User Interface (GUI) offers user interaction via some graphical components.

For example our underlying Operating System also offers GUI via window, frame, Panel,

Button, Textfield, TextArea, Listbox, Combobox, Label, Checkbox etc. These all are known

as components. Using these components we can create an interactive user interface for an

application.

GUI provides result to end user in response to raised events.GUI is entirely based events.

For example clicking over a button, closing a window, opening a window, typing something

in a textarea etc. These activities are known as events.GUI makes it easier for the end user to

use an application. It also makes them interesting.

Examples of GUI based Applications Following are some of the examples for GUI based applications.

o Automated Teller Machine (ATM) o Airline Ticketing System o Information Kiosks at railway stations o Mobile Applications o Navigation Systems

Advantages of GUI over CUI

GUI provides graphical icons to interact while the CUI (Character User Interface)

offers the simple text-based interfaces.

GUI makes the application more entertaining and interesting on the other hand CUI

does not.

GUI offers click and execute environment while in CUI every time we have to enter

the command for a task.

New user can easily interact with graphical user interface by the visual indicators but

it is difficult in Character user interface.

GUI offers a lot of controls of file system and the operating system while in CUI you

have to use commands which are difficult to remember.

Windows concept in GUI allow the user to view, manipulate and control the multiple

applications at once while in CUI user can control one task at a time.

GUI provides multitasking environment so as the CUI also does but CUI does not

provide same ease as the GUI does.

Using GUI it is easier to control and navigate the operating system which becomes

very slow in command user interface. GUI can be easily customized.

Basic Terminologies

Page 82: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Every AWT controls inherits properties from Component class.

AWT UI Elements

Following is the list of commonly used controls while designed GUI using AWT.

Page 83: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

2. Discuss the different types of event handling in java. April 11, April 12

Changing the state of an object is known as an event. For example, click on button,

dragging mouse etc. The java.awt.event package provides many event classes and Listener

interfaces for event handling.

Event classes and Listener interfaces

Event Classes Listener Interfaces ActionEvent ActionListener MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform EventHandling: Following steps are required to perform event handling:

Implement the Listener interface and overrides its methods

Register the component with the Listener

For registering the component with the Listener, many classes provide the registration

methods. For example:

Button public void addActionListener(ActionListener a){}

MenuItem public void addActionListener(ActionListener a){}

TextField public void addActionListener(ActionListener a){} public void addTextListener(TextListener a){}

TextArea public void addTextListener(TextListener a){}

Checkbox public void addItemListener(ItemListener a){}

Choice public void addItemListener(ItemListener a){}

List public void addActionListener(ActionListener a){} public void addItemListener(ItemListener a){}

EventHandling Codes We can put the event handling code into one of the following places,

Same class

Other class

Annonymous class

Page 84: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Example of event handling within class import java.awt.*; import java.awt.event.*;

class AEvent extends Frame implements ActionListener

{

TextField tf;

AEvent()

{

tf=new TextField();

tf.setBounds(60,50,170,20);

Button b=new Button("click me");

b.setBounds(100,120,80,30);

b.addActionListener(this);

add(b); add(tf);

setSize(300,300);

setLayout(null);

setVisible(true);

}

public void actionPerformed(ActionEvent e)

{

tf.setText("Welcome");

}

public static void main(String args[])

{

new AEvent();

}

}

public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the

above example that sets the position of the component it may be button, textfield etc.

Output

Page 85: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

3. Explain the various Event Listener Interfaces with example. April 13 The Event listener represents the interfaces responsible to handle events. Java provides

us various Event listener classes but we will discuss those which are more frequently used.

Every method of an event listener method has a single argument as an object which is

subclass of EventObject class. For example, mouse event listener methods will accept

instance of MouseEvent, where MouseEvent derives from EventObject.

EventListner interface It is a marker interface which every listener interface has to extend. This class is defined

in java.util package.

Following is the declaration for java.util.EventListener interface:

public interface EventListener

AWT Event Listener Interfaces Following is the list of commonly used event listeners.

a) ActionListener Interface The class which processes the ActionEvent should implement this interface. The object

of that class must be registered with a component. The object can be registered using the

addActionListener() method. When the action event occurs, that object's action Performed

method is invoked.

Interface declaration Following is the declaration for java.awt.event.ActionListener interface:

public interface ActionListener extends EventListener

Interface methods

Page 86: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

ActionListener Example import java.awt.*; import java.awt.event.*;

class ButtonAction extends Frame

{

Button b1,b2,b3;

Frame thisFrame;

public ButtonAction()

{

// Set the frame properties

setTitle("Button with ActionListener Demo");

setSize(400,400);

setLayout(new FlowLayout());

setLocationRelativeTo(null);

setVisible(true);

// Assign current object

thisFrame=this;

// Create buttons

b1=new Button("Minimize");

b2=new Button("Maximize/Restore");

b3=new Button("Exit");

// Add buttons

add(b1);

add(b2);

add(b3);

// Add action listeners to buttons

b1.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae)

{

setState(Frame.ICONIFIED);

}

});

b2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae)

{

if(thisFrame.getExtendedState()==Frame.NORMAL)

setExtendedState(Frame.MAXIMIZED_BOTH);

else if(thisFrame.getExtendedState()==Frame.MAXIMIZED_BOTH)

setExtendedState(Frame.NORMAL);

}

});

b3.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae)

Page 87: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

{

System.exit(0);

} });

}

public static void main(String args[])

{

new ButtonAction();

}

}

Output

4. Develop an application on your own to exhibit the usage of JLabel, JTextfield, and

JTextarea in java. April 14 import java.awt.*; import javax.swing.*;

public class Label_TextField_TextArea

{

public static void main(String[] args)

JFrame f = new JFrame("My First GUI");

JLabel L;

L = new JLabel("Hello World !"); // Make a JLabel component

f.getContentPane().add(L); // Stick

f.setSize(400, 300);

f.setVisible(true);

JFrame h = new JFrame("My Second GUI");

JTextField x;

x = new JTextField(); // Make a JTextField

h.getContentPane().add(x); // Stick

x.setEditable(false); // Output only

x.setText("Hello World");

h.setSize(400, 300);

Page 88: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

h.setVisible(true);

JFrame g= new JFrame("My GUI");

JTextArea m;

m = new JTextArea(); // Make a JTextArea

g.getContentPane().add(m); // Stick

m.setEditable(true); // Output only

m.setText("Hello World");

m.append("\n");

m.append("Hello Again");

g.setSize(400, 300);

g.setVisible(true);

}

}

Page 89: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Unit-IV Question & Answers

PART – A

1. What is flow layout? (April 12)

This is the default layout manager for an applet. The FlowLayout class places controls

in a row that is centered in the available space. If the controls cannot fit in the current row,

another row is started.

2. What is the syntax of drawLine() method? (April 13, April 14,Nov/Dec 2016)

The general form is:

void drawLine ( int x1, int y1, int x2, int y2 )

This method takes two pairs of coordinates. (x1, y1) and (x2, y2) as arguments and

draws a line between them.

3. How to select a font? Give example. (April 13)

The class Font is used to set the fonts used in the graphical object. The Font class defines

the following constructor:

Font ( String name, int style, int size )

Example: Font f = new Font (“Arial”, Font.ITALIC, 40);

4. Describe the argument used in the method drawRect(). (Nov 12)

void drawRect ( int x, int y, int w, int h )

Here, the first two arguments x and y represent the x and y coordinates of the top left

corner of the rectangle. The last two arguments w and h represent the width and height of the

rectangle.

5. How to define menus?(April 14)

Menus allow the user to perform actions without unnecessarily cluttering a GUI.

Example:

JMenu file = JMenu(“File”); File.add(“New”);

File.add(“Open”);

File.add(“Save”);

File.add(“Save As”);

6. What are the different types of layout managers?

The various layout managers are as follows:

i. Flow Layout

ii. Border layout

iii. Grid Layout

Page 90: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

7. List FlowLayout constructors. (Apr/May 2016)

The Flow Layout class has three constructors. They are:

a) FlowLayout ( )

b) FlowLayout ( int alignment )

c) FlowLayout ( int alignment, int h, int v )

8. What is meant by Border Layout?

The Border Layout class allows geographic terms: North, South, East, West and

Center. The Border Layout class has two constructors. Namely,

BorderLayout ( ) : It is used to create default border layout.

BorderLayout ( int h, int v ) : It is used to create a Border layout with a specified

horizontal and vertical space between the components.

9. Define Layout manager.(Noc/Dec 2016)

Layout Manager are special objects that determine how the components of a container

are organized. A Layout Manager is an instance of any class that implements the Layout

Manager interface. The Layout Managers is set by the setLayout() method. The general

format is:

void setLayout ( LayoutManager obj )

10. List the different regions followed in Border Layout.

The BorderLayout defines the following regions:

BorderLayout . NORTH

BorderLayout . SOUTH

BorderLayout . EAST

BorderLayout . WEST

BorderLayout . CENTER

11. Define Grid layout.

The Grid Layout class automatically arranges components in a grid. The Grid Layout

Manager organizes the display into a rectangular grid. All components of the grid is created

of the grid is created with equal size.

12. What is Graphics Class in Java?

Class graphics is an abstract class. When Java is implemented on each platform, a

subclass of Graphics is created that implements the drawing capabilities. This

implementation is hidden from us by Class Graphics, which supplies the interface that

enables us to use graphics in a platform-independent manner.

Page 91: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

13. Define Color Control.

The Class Color is used to control the color of the graphics object. This class contains

methods and constants for manipulating colors in applet programs. The different colors are

created from the base color red, green, and blue.

14. What are the most commonly used Color methods?

The most commonly used color ( ) methods are as follows:

Methods Description

int getRed ( ) Returns the current color red value ( 0 to 255 )

int getGreen ( ) Returns the current color green value ( 0 to 255 )

int getBlue ( ) Returns the current color blue value ( 0 to 255 )

color getColor ( ) Returns the color of the current graphics objects

void setColor ( Color c ) Sets the current drawing color

15. Define Font Control.

The class Font is used to set the fonts used in the graphical object. The Font class define

the following constructor:

Font ( String name, int style, int size )

The Font class constructor has three arguments: Font name, Font Style, and Font Size. The

size of a font is measured as points. A point is 1/72 of an inch.

16. How to draw ovals in Java?

The drawOval ( ) method is used to draw an oval with the specified width and height

from (x, y). The general form is:

void drawOval ( int x, int y, int w, int h )

Here, the first two parameters x and y represent the bounding rectangle’s top left corner is

at the coordinates (x, y). The last two parameters width w and height h specifies the width

and height of the oval.

17. Define JMenuBar.

The JMenuBar class is used as a container for menus. The general form is,

JMenuBar ( )

18. What is JMenu?

The JMenu class is used to control the menus. The general form is,

Page 92: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

SCS41 /Java Programming /Unit-IV Q

JMenu ( String str )

19. What is the function of JMenuItem?

The JMenuItem class is used to control the menu items. The general form is,

JMenuItem ( String str )

20. Define JCheckBoxMenuItem.

The JCheckBoxMenuItem class is used to control menu items that we can be toggled

on or off. Using this we can select more than one option.

PART – B

1. Explain in detail about the grid layout. (Nov 12)

The Grid Layout class automatically arranges components in a grid. The Grid Layout

Manager organizes the display into a rectangular grid. All components of the grid is created

of the grid is created with equal size. The Grid Layout has three constructors they are,

GridLayout ( )

GridLayout ( int numrows, numcols )

GridLayout ( int numrows, numcols, int h, int v )

Parameters

numrows - Determine the number of rows

numcols - Determine the number of columns

h - Specifies the horizontal gap in pixels between components

v - Specifies the vertical gap in pixels between components

Example An applet program whose display is organized as two dimensional grid: import java.awt.*;

import java.applet.*;

/*<applet code="GridLayoutDemo" width = 900 height=900> </applet>*/

public class GridLayoutDemo extends Applet

{

Button b1, b2, b3, b4;

GridLayout g = new GridLayout(2,2);

public void init()

{

setLayout(g);

b1=new Button("Xavier");

b2=new Button("Catherin");

b3=new Button("Benjamin");

b4=new Button("John");

add(b1);

add(b2);

RAAK/B. Sc. (CS)/ M. Usha/II Year/IV Sem/ &A

Page 93: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

add(b3);

add(b4);

}

}

2. Write a Java program to draw a rectangle, circle and ellipse. (April 13) import java.awt.*; import java.applet.*;

import java.awt.event.*;

/*<applet code="dra1" width = 300 height=300> </applet>*/

public class dra1 extends Applet implements ActionListener

{

Button dl,dov,dr;

String s;

public void init() {

dl=new Button("Circle");

dov=new Button("Oval");

dr=new Button("Rectangle");

add(dl); add(dov);

add(dr);

dl.addActionListener(this);

dov.addActionListener(this);

dr.addActionListener(this);

}

public void actionPerformed(ActionEvent ae)

{

s=ae.getActionCommand();

repaint();

}

public void paint(Graphics g)

{

g.drawString("Usage Graphics Class",300,100);

if(s.equals("Circle"))

g.drawOval(300,250,100,100);

else if(s.equals("Oval"))

g.drawOval(300,250,150,75);

else

g.drawRect(300,200,200,100);

g.drawString("U Pressed " +s,300,400);

}}

Page 94: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Output:

3. List the necessary methods for drawing a Line and Rectangle. (April 14,Apr/May

2016)

Drawing Lines

The drawLine ( ) method is used to draw a straight line between points (x1, y1) and (x2, y2).

The general form is:

void drawLine(int x1, int y1, int x2, int y2)

This method takes two pair of coordinates (x1, y1) and (x2, y2) as arguments and draws a

line between them.

Drawing Rectangles

Using Graphics class methods we can draw three types of rectangles.

i. Sharp Corner Rectangle

ii. Round Corner Rectangle iii. 3D Rectangle

The drawRect ( ) method is used to draws a rectangle with upper-left corner at coordinates x

and y, width w, and height h. The general form is:

void drawRect ( int x, int y, int w, int h )

Here, the first two arguments x and y represent the x and y coordinates of the top left

corner of the rectangle. The last two arguments w and h represent the width and height of the

rectangle.

Page 95: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Rounded Corner Rectangle

The drawRoundRect ( ) method is used to draws a round corner rectangle with the specified

width w, and height h from (x,y). Arc width aw and Arc height ah determines the rounding

of the corners. The general form is:

void drawRoundRect ( int x, int y, int w, int h, int aw, int ah)

3D Rectangle

The draw3DRect ( ) method is used to draw a three dimensional rectangle with the specified

width w and height h from left corner at coordinates x and y. The general form is:

void draw3DRect ( int x, int y, int h, int w, Boolean b)

The first two parameters x and y represent the top-left corner of the rectangle, the third and

fourth arguments h and w represent the width and height of the rectangle and last parameter

b indicates that whether the rectangle has to be raised or not.

4. Write a Java program to define a frame. (April 14)

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class JFrameDemo {

public static void main(String s[]) {

JFrame frame = new JFrame("JFrame Source Demo");

// Add a window listner for close button frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

// This is an empty content area in the frame JLabel jlbempty

= new JLabel(""); jlbempty.setPreferredSize(new

Dimension(175, 100)); frame.getContentPane().add(jlbempty,

BorderLayout.CENTER); frame.pack();

frame.setVisible(true);

}

}

Page 96: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Output

5. How to create a frame window in applet? (Nov 12, April 13)

Creating a new frame window from within an applet is actually quite easy. The

following steps may be used to do it,

Create a subclass of Frame

Override any of the standard window methods, such as init(),start(),stop(),and

paint().

Implement the windowClosing() method of the windowlistener interface, calling

setVisible(false) when the window is closed

Once you have defined a Frame subclass, you can create an object of that class. But it

will not be initially visible

When created, the window is given a default height and width

You can set the size of the window explicitly by calling the setSize() method

The example program is shown below:

// Create a child frame window from within an applet. import java.awt.*; import java.awt.event.*;

import java.applet.*; /*

<applet code="AppletFrame" width=400 height=60>

</applet>

*/

// Create a subclass of Frame. class SampleFrame extends Frame { SampleFrame(String title) {

super(title);

// create an object to handle window events MyWindowAdapter adapter = new MyWindowAdapter(this);

// register it to receive those events addWindowListener(adapter); }

public void paint(Graphics g) {

g.drawString("This is in frame window", 10, 40);

}

}

Page 97: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

class MyWindowAdapter extends WindowAdapter {

SampleFrame sampleFrame;

public MyWindowAdapter(SampleFrame sampleFrame) { this.sampleFrame = sampleFrame;

}

public void windowClosing(WindowEvent we) {

sampleFrame.setVisible(false);

}

}

// Create frame window. public class AppletFrame extends Applet { Frame f;

public void init() {

f = new SampleFrame("A Frame Window");

f.setSize(150, 150);

f.setVisible(true);

}

public void start() {

f.setVisible(true);

}

public void stop() {

f.setVisible(false);

}

public void paint(Graphics g) {

g.drawString("This is in applet window", 15, 30);

}

}

Output:

6. State the functions/methods of Flow Layout. (April 14)

This is the default layout manager for an applet. The FlowLayout class places controls

in a row that is centered in the available space. If the controls cannot fit in the current row,

another row is started.

Page 98: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

The Flow Layout class has three constructors. They are:

a) FlowLayout ( )

b) FlowLayout ( int alignment )

c) FlowLayout ( int alignment, int h, int v )

Parameters:

Alignment – specifies how each line is aligned. The valid values are alignment. They are:

FlowLayout.LEFT

FlowLayout RIGHT

FlowLayout.CENTER

H – specifies the horizontal or gap between the controls.

V – specifies the vertical gap between controls.

Example:

import java.awt.*;

import java.applet.*;

/*<applet code="FlowLayoutDemo" width = 200 height=200> </applet>*/

public class FlowLayoutDemo extends Applet

{

public void init()

{

setLayout(new FlowLayout(FlowLayout.RIGHT, 5,5));

for(int i=1;i<12;i++)

{

add(new Button("Toys" +i));

}

}

}

Output:

Page 99: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

7. Explain in detail about the border layout. April 12

The Border Layout class allows geographic terms: North, South, East, West and

Center. The Border Layout class has two constructors. Namely,

BorderLayout ( ) : It is used to create default border layout.

BorderLayout ( int h, int v ) : It is used to create a Border layout with a specified horizontal

and vertical space between the components.

The BorderLayout defines the following regions:

BorderLayout . NORTH

BorderLayout . SOUTH

BorderLayout . EAST

BorderLayout . WEST

BorderLayout . CENTER

Example

An Applet whose display is organized as geographic terms (north, south, east, west and

center)

import java.awt.*;

import java.applet.*;

/*<applet code="BorderLayoutDemo" width = 200 height=200> </applet>*/

public class BorderLayoutDemo extends Applet

{

public void init()

{

setLayout(new BorderLayout(5,5));

Button b1=new Button("North");

Button b2=new Button("South");

Button b3=new Button("East");

Button b4=new Button("West");

Button b5=new Button("Center");

add(b1,"North");

add(b2,"South");

add(b3,"East");

add(b4,"West");

add(b5,"Center");

}}

Page 100: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

8. Write an applet program to display organized geographic terms(north, south, east and

center) using BorderLayout.

An Applet whose display is organized as geographic terms (north, south, east, west and

center)

import java.awt.*;

import java.applet.*;

/*<applet code="BorderLayoutDemo" width = 200 height=200> </applet>*/

public class BorderLayoutDemo extends Applet

{

public void init()

{

setLayout(new BorderLayout(5,5));

Button b1=new Button("North");

Button b2=new Button("South");

Button b3=new Button("East");

Button b4=new Button("West");

Button b5=new Button("Center");

add(b1,"North");

add(b2,"South");

add(b3,"East");

add(b4,"West");

add(b5,"Center");

}}

Page 101: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

PART – C

1. Develop a scientific calculator in Java with menus and frames. (April 14)

import java.awt.*; import

java.awt.event.*; import

javax.swing.*; import

javax.swing.event.*;

class Calculator extends JFrame {

private final Font BIGGER_FONT = new Font("monspaced",Font.PLAIN, 20);

private JTextField textfield;

private boolean number = true;

private String equalOp = "=";

private CalculatorOp op = new CalculatorOp();

public Calculator() {

textfield = new JTextField("", 12);

textfield.setHorizontalAlignment(JTextField.RIGHT);

textfield.setFont(BIGGER_FONT);

ActionListener numberListener = new NumberListener();

String buttonOrder = "1234567890 ";

JPanel buttonPanel = new JPanel();

buttonPanel.setLayout(new GridLayout(4, 4, 4, 4));

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

String key = buttonOrder.substring(i, i+1);

if (key.equals(" ")) {

buttonPanel.add(new JLabel(""));

} else {

JButton button = new JButton(key);

button.addActionListener(numberListener);

button.setFont(BIGGER_FONT);

buttonPanel.add(button);

}

}

ActionListener operatorListener = new OperatorListener();

JPanel panel = new JPanel();

panel.setLayout(new GridLayout(4, 4, 4, 4));

String[] opOrder = {"+", "-", "*", "/","=","C","sin","cos","log"};

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

JButton button = new JButton(opOrder[i]);

button.addActionListener(operatorListener);

button.setFont(BIGGER_FONT);

panel.add(button);

}

JPanel pan = new JPanel();

pan.setLayout(new BorderLayout(4, 4));

Page 102: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

pan.add(textfield, BorderLayout.NORTH );

pan.add(buttonPanel , BorderLayout.CENTER);

pan.add(panel , BorderLayout.EAST);

this.setContentPane(pan);

this.pack();

this.setTitle("Calculator");

this.setResizable(false);

}

private void action() {

number = true;

textfield.setText("");

equalOp = "=";

op.setTotal("");

}

class OperatorListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

String displayText = textfield.getText();

if (e.getActionCommand().equals("sin"))

{

textfield.setText("" + Math.sin(Double.valueOf(displayText).doubleValue()));

}else

if (e.getActionCommand().equals("cos"))

{

textfield.setText("" + Math.cos(Double.valueOf(displayText).doubleValue()));

}

else

if (e.getActionCommand().equals("log"))

{

textfield.setText("" + Math.log(Double.valueOf(displayText).doubleValue()));

}

else if (e.getActionCommand().equals("C"))

{

textfield.setText("");

}

else

{

if (number)

{

action();

textfield.setText("");

}

Page 103: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

else

{

number = true;

if (equalOp.equals("="))

{

op.setTotal(displayText);

}else

if (equalOp.equals("+"))

{

op.add(displayText);

}

else if (equalOp.equals("-"))

{

op.subtract(displayText);

}

else if (equalOp.equals("*"))

{

op.multiply(displayText);

}

else if (equalOp.equals("/"))

{

op.divide(displayText);

}

textfield.setText("" + op.getTotalString());

equalOp = e.getActionCommand();

}

}

}

}

class NumberListener implements ActionListener {

public void actionPerformed(ActionEvent event) {

String digit = event.getActionCommand();

if (number) {

textfield.setText(digit);

number = false;

} else {

textfield.setText(textfield.getText() + digit);

}

}

}

public class CalculatorOp {

private int total;

public CalculatorOp() {

total = 0;

}

public String getTotalString() {

Page 104: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

return ""+total;

}

public void setTotal(String n) {

total = convertToNumber(n);

}

public void add(String n) {

total += convertToNumber(n);

}

public void subtract(String n) {

total -= convertToNumber(n);

}

public void multiply(String n) {

total *= convertToNumber(n);

}

public void divide(String n) {

total /= convertToNumber(n);

}

private int convertToNumber(String n) {

return Integer.parseInt(n);

}

}

}

class SwingCalculator {

public static void main(String[] args) { JFrame frame = new

Calculator();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

} }

Output

Page 105: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

2. Write short notes on “BorderLayout” and “GridLayout” with an example. (April 14)

Border Layout

The Border Layout class allows geographic terms: North, South, East, West and Center.

The Border Layout class has two constructors. Namely,

BorderLayout ( ) : It is used to create default border layout.

BorderLayout ( int h, int v ) : It is used to create a Border layout with a specified horizontal

and vertical space between the components.

The BorderLayout defines the following regions:

BorderLayout . NORTH

BorderLayout . SOUTH

BorderLayout . EAST

BorderLayout . WEST

BorderLayout . CENTER

Example:

An Applet whose display is organized as geographic terms (north, south, east, west and

center)

import java.awt.*;

import java.applet.*;

/*<applet code="BorderLayoutDemo"

width = 200 height=200> </applet>*/

public class BorderLayoutDemo extends Applet

{

public void init()

{

setLayout(new BorderLayout(5,5));

Button b1=new Button("North");

Button b2=new Button("South");

Button b3=new Button("East");

Button b4=new Button("West");

Button b5=new Button("Center");

add(b1,"North");

add(b2,"South");

add(b3,"East");

add(b4,"West");

add(b5,"Center");

}}

Page 106: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Grid Layout:

The Grid Layout class automatically arranges components in a grid. The Grid Layout

Manager organizes the display into a rectangular grid. All components of the grid is created

of the grid is created with equal size. The Grid Layout has three constructors they are,

GridLayout ( )

GridLayout ( int numrows, numcols )

GridLayout ( int numrows, numcols, int h, int v )

Parameters:

numrows - Determine the number of rows numcols - Determine the number of columns h - Specifies the horizontal gap in pixels between components v - Specifies the vertical gap in pixels between components

Example:

An applet program whose display is organized as two dimensional grid:

import java.awt.*;

import java.applet.*;

/*<applet code="GridLayoutDemo" width = 900 height=900> </applet>*/

public class GridLayoutDemo extends Applet

{

Button b1, b2, b3, b4;

GridLayout g = new GridLayout(2,2);

public void init()

{

setLayout(g);

b1=new Button("Xavier");

b2=new Button("Catherin");

b3=new Button("Benjamin");

b4=new Button("John");

add(b1);

add(b2);

add(b3);

add(b4);

} }

3. Write a program to create a menu by using JFrame.

import java.awt.*; import java.awt.event.*;

import java.util.*;

import javax.swing.*;

Page 107: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

public class Menu1 extends JFrame

{

public static Menu1 fr;

public Menu1()

{

this(null);

}

public Menu1(String title)

{

super(title);

}

protected void frameInit()

{

super.frameInit();

JMenuBar mb=createMenu();

setJMenuBar(mb);

}

protected JMenuBar createMenu()

{

JMenuBar mb= new JMenuBar();

JMenu file= new JMenu("file");

file.add("New");

file.add("Open");

file.addSeparator();

file.add("Save");

file.add("SaveAs");

file.addSeparator();

JMenuItem item = new JMenuItem("Exit");

item.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent e)

{

System.exit(0);

}

});

file.add(item);

mb.add(file);

return(mb);

}

public static void main(String args[])

{

JFrame fr1=new Menu1("File Menu");

fr1.pack();

fr1.setVisible(true);

}

}

Page 108: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

4. Describe the different layout managers with example. (April 13)

Layout Manager are special objects that determine how the components of a container

are organized. A Layout Manager is an instance of any class that implements the Layout

Manager interface. The Layout Managers is set by the setLayout() method. The general

format is:

void setLayout ( LayoutManager obj )

The various layout managers are as follows:

i. Flow Layout

ii. Border layout

iii. Grid Layout

Flow Layout:

This is the default layout manager for an applet. The FlowLayout class places controls in a

row that is centered in the available space. If the controls cannot fit in the current row,

another row is started.

The Flow Layout class has three constructors. They are:

d) FlowLayout ( )

e) FlowLayout ( int alignment )

f) FlowLayout ( int alignment, int h, int v )

Parameters: Alignment – specifies how each line is aligned. The valid values are alignment. They are:

FlowLayout.LEFT

FlowLayout RIGHT

FlowLayout.CENTER

H – specifies the horizontal or gap between the controls.

V – specifies the vertical gap between controls.

Example: import java.awt.*; import java.applet.*;

/*<applet code="FlowLayoutDemo" width = 200 height=200> </applet>*/

public class FlowLayoutDemo extends Applet

{

public void init()

{

setLayout(new FlowLayout(FlowLayout.RIGHT, 5,5));

for(int i=1;i<12;i++)

{

add(new Button("Toys" +i));

}

} }

Page 109: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Border Layout:

The Border Layout class allows geographic terms: North, South, East, West and Center.

The Border Layout class has two constructors. Namely,

BorderLayout ( ) : It is used to create default border layout.

BorderLayout ( int h, int v ) : It is used to create a Border layout with a specified horizontal

and vertical space between the components.

The BorderLayout defines the following regions:

BorderLayout . NORTH

BorderLayout . SOUTH

BorderLayout . EAST

BorderLayout . WEST

BorderLayout . CENTER

Example: An Applet whose display is organized as geographic terms (north, south, east, west and center)

import java.awt.*;

import java.applet.*;

/*<applet code="BorderLayoutDemo" width = 200 height=200> </applet>*/

public class BorderLayoutDemo extends Applet

{

public void init()

{

setLayout(new BorderLayout(5,5));

Button b1=new Button("North");

Button b2=new Button("South");

Button b3=new Button("East");

Button b4=new Button("West");

Button b5=new Button("Center");

add(b1,"North");

add(b2,"South");

add(b3,"East");

add(b4,"West");

add(b5,"Center");

}}

Page 110: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Academic Year: 2016 – 2017 Regulation CBCS - 2012

Java Programming /Unit-IV Q&A

Question and Answer Bank Page 22 of 2

Grid Layout:

The Grid Layout class automatically arranges components in a grid. The Grid Layout

Manager organizes the display into a rectangular grid. All components of the grid is created

of the grid is created with equal size. The Grid Layout has three constructors they are,

GridLayout ( )

GridLayout ( int numrows, numcols )

GridLayout ( int numrows, numcols, int h, int v )

Parameters:

numrows - Determine the number of rows numcols - Determine the number of columns h - Specifies the horizontal gap in pixels between components v - Specifies the vertical gap in pixels between components

Example:

An applet program whose display is organized as two dimensional grid:

import java.awt.*;

import java.applet.*;

/*<applet code="GridLayoutDemo" width = 900 height=900> </applet>*/

public class GridLayoutDemo extends Applet

{

Button b1, b2, b3, b4;

GridLayout g = new GridLayout(2,2);

public void init()

{

setLayout(g);

b1=new Button("Xavier");

b2=new Button("Catherin");

b3=new Button("Benjamin");

b4=new Button("John");

add(b1);

add(b2);

add(b3);

add(b4);

}

}

Page 111: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Exception and File Handling

Question & Answers

PART – A QUESTIONS

1. Define Exception.(April 2012)

Ans:An exception is an object that is generated at runtime to describe a problem encountered

during the execution of a program.

2. What is Tomcat? (April 2012)

Ans:Apache Tomcat is an open-source web server and servlet container developed by the

Apache Software Foundation (ASF). Tomcat implements several Java EE specifications

including Java Servlet, JavaServer Pages (JSP), Java EL, and WebSocket.

3. Define Applet. (Nov 2012)

Ans:Applets are small java programs developed for internet applications. This can be run

using the web browser or applet viewer.

4. Define Multithreading.(April 2013)

Ans:Multithreading is the mechanism in which more than onethreadrunindependentofeach

otherwithintheprocess

5. What is meant by Packages in Java?(Nov/Dec 2016)

Ans:Packages are group of classes and interfaces. Two types of Packages are

1) System package

2) User defined package

6. Define Interface.(Nov/Dec 2016)

Ans:An interface is a group of constants and methods declarations that define the form of a

class.

Page 112: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

7. What is the use of finally block?

Ans:Finally block creates a statement that will be executed after a try or catch block has been

computed. The finally block will execute whether or not an exception is thrown.

8. What is thread?(Nov/Dec 2016)

Ans:Thread is a single sequential flow of control. A thread is a sequence of execution within

a program.

9. What are the ways available in java to creating thread?

Ans:There are two ways of creating a thread in java.

Extending the class thread

Implementing Runnable Interface

10. What is Stream?

Ans:A stream is a path of communication between the source and destination of data.

11. List out any three Java API packages.

Java.util package

Java.lang package

Java.io package

12. Whatis thedifferencebetweenthrowandthrows clause?

Ans:Throw is used to throw an exception manually, whereas throws is used in the case of

checked exceptions, to tell the compiler that we haven't handled the exception, so that the

exception will be handled by the calling function.

13. What are purpose waitand sleepmethods?

Ans:Sleep() method maintains control of thread execution but delays the next action until the

sleep time expires. Wait() method gives up control over thread execution in definitely so that

other threads can run.

14. Whatis synchronization?

Ans:Synchronization is the capability to control the access of multiple threads to shared

resources. Without synchronization ,it is possible for one thread to modify a shared object.

Page 113: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

PART – B QUESTIONS

1. Explain the importance of synchronization in multithreading.( April 2012

Ans:Synchronization in java is the capability of control the access of multiple threads to any

shared resource.

Java Synchronization is better option where we want to allow only one thread to access the

shared resource.

Why use Synchronization?

The synchronization is mainly used to

To prevent thread interference.

To prevent consistency problem.

Types of Synchronization:

There are two types of synchronization

Process Synchronization

Thread Synchronization

Thread Synchronization:

There are two types of thread synchronization mutual exclusive and inter-thread

communication.

Mutual Exclusive

o Synchronized method.

o Synchronized block.

o Static synchronization.

Cooperation (Inter-thread communication in java)

Java synchronized method:

If you declare any method as synchronized; it is known as synchronized

method.Synchronized method is used to lock an object for any shared resource.

Page 114: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

When a thread invokes a synchronized method, it automatically acquires the lock for that

object and releases it when the thread completes its task.

Example:

public class BankAccount

{

intaccountNumber;

doubleaccountBalance;

public synchronized boolean transfer (double amount)

{

doublenewAccountBalance;

if( amount >accountBalance)

{

}

else

{

}

}

return false;

newAccountBalance = accountBalance - amount;

accountBalance = newAccountBalance;

return true;

public synchronized boolean deposit(double amount)

{

doublenewAccountBalance;

if( amount < 0.0)

{

}

else

{

}

return false; // can not deposit a negative amount

newAccountBalance = accountBalance + amount;

accountBalance = newAccountBalance;

return true;

}}

Page 115: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

2. How do applets differ from applications?(April 2012)

Applet Application

Small Program Large Program

Used to run on client browser Can be executed on standalone computer

system Applet is portable and can be executed by any JAVA

supported browser. Need JDK, JRE, JVM installed on client

machine. Applet applications are executed in a Restricted Environment

Application can access all the resources of the computer

Applets are created by extending the java.applet.Applet

Applications are created by writing public static void main (String[] s)

method. Applet application has 5 methods which will be automatically invoked on occurrence of specific event

Application has a single start point

which is main method

importjava.awt.*; importjava.applet.*;

public class Myclass extends Applet

{ public void init() { } public void start() { }

public void stop() {}

public void destroy() {}

public void paint(Graphics g) {}

}

public class MyClass

{

public static void main(String args[]) {} }

3. With example explain Frame window creation in applet.(Nov 2012)

Ans:Creating a new frame window from within an applet is actually quite easy. The

following steps may be used to do it,

Create a subclass of Frame Override any of the standard window methods, such as

init(),start(),stop(),and paint().

Implement the windowClosing() method of the window listener interface, calling

AppletVisible(false)when the window is closed.

Once you have defined a Frame subclass,you can create an object of that class.But it

will not be initially visible.

When created, the window is given a default height and width.

You can set the size of the window explicitly by calling the setSize() method

Example:

Page 116: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

importjava.awt.*;

importjava.applet.*;

/*

<applet code="AppletFrame" width=400 height=60>

</applet>

*/

public class AppletFrame extends Applet

{

Frame f;

public void init()

{

f = new SampleFrame("A Frame Window");

f.setSize(150, 150);

f.setVisible(true);

}

public void start()

{

f.setVisible(true);

}

public void stop()

{

f.setVisible(false);

}

public void paint(Graphics g)

{

g.drawString("This is in applet window", 15, 30);

}

}

4. Explain the output stream of java in detail.(April 2013)

Ans: Java I/O (Input and Output) is used to process the input and produce the output based

on the input.

Java uses the concept of stream to make I/O operation fast. The java.io package contains all

the classes required for input and output operations.

Stream:

A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream

because it's like a stream of water that continues to flow.

In java, output streams are created as System.out: standard output stream

Page 117: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

OutputStream:

Java application uses an output stream to write data to a destination, it may be a file,an

array,peripheral device or socket.

OutputStream class:

OutputStream class is an abstract class.It is the superclass of all classes representing an

output stream of bytes. An output stream accepts output bytes and sends them to some

sink.

Commonly used methods of OutputStream class

Method Description

1) public void write(int)throws IOException:

is used to write a byte to the current output stream.

2) public void write(byte[])throws IOException:

is used to write an array of byte to the current output stream.

3) public void flush()throws IOException: flushes the current output stream.

4) public void close()throws IOException: is used to close the current output stream.

5. Explain how to handle arithmetic exception by giving a suitable example.(April

2013)

Class: Java.lang.ArithmeticException

This is a built-in-class present in java.lang package. This exception occurs when an

integer is divided by zero.

Eg:

class ExceptionDemo1

{

public static void main(String args[])

Page 118: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

{

try{

int num1=30, num2=0; int

output=num1/num2; System.out.println

("Result = " +output);

}

catch(ArithmeticException e){

System.out.println ("Arithmetic Exception: You can't divide an integer by 0");

}

}

}

Output of above program:

Arithmetic Exception: You can't divide an integer by 0

6. Describe the Applet life cycle.(Nov 2013)

Ans:Java applet inherits features from the class Applet. Thus, whenever an applet is

created, it undergoes a series of changes from initialization to destruction. Various stages

of an applet life cycle are depicted in the figure below:

Initial State:

When a new applet is born or created, it is activated by calling init() method. At this

stage, new objects to the applet are created, initial values are set, images are loaded and

the colors of the images are set. An applet is initialized only once in its lifetime. Its

general form is:

public void init( )

{

//Action to be performed

}

Page 119: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Running State:

An applet achieves the running state when the system calls the start() method. This

occurs as soon as the applet is initialized. An applet may also start when it is in idle state.

At that time, the start() method is overridden. Its general form is:

public void start( )

{

//Action to be performed

}

Idle State:

An applet comes in idle state when its execution has been stopped either implicitly or

explicitly. An applet is implicitly stopped when we leave the page containing the

currently running applet. An applet is explicitly stopped when we call stop() method to

stop its execution. Its general form is:

public void stop

{ //Action to be performed

}

Dead State

An applet is in dead state when it has been removed from the memory. This can be done

by using destroy() method. Its general form is:

public void destroy( )

{

//Action to be performed

}

7. What is Package? How packages are created in java.(Nov 2013)

Ans:Packages are container for classes. It is like a header file in C++ and it is stored in a

hierarchical manner.

Uses:

Package reduce the complexity of the software

Because a large number of classes can be grouped into limited number of

package.

We can create classes with same name in different package.

Page 120: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Using package we can hide class

Crating a package:

Java has a facility to create our own package. Create a sub directory with the same name

of the package. This gives one package. We can also create another package within this

director.

Example: c:\package1>package2>md package 3;

Defining a package:

Each package contains number of related classes. We access these class in our

application. There are two methods to access a package

a) By specifying the fully qualified class name

b) By using import statement

By specifying the fully qualified class name:

We can access a package by specifying the class path at time of declaration of our object.

Syntax: pack1.pack2.packn.classname obj;

Example: bb.aa.sample.obj;

Let a class sample belong to a package “aa”, this package is inside another package “b”.

If we want to use the class sample in our application. We have to do the declaration.

By using import statement:

By using statement we can either use all classes of a package in our application or a

specific class.

Example: import aa.sample;

This statement allows us to use the sample class of package as in our application.

8. Explain the importance of try-catch block with example. (April 2014)

Java try block:

Page 121: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Java try block is used to enclose the code that might throw an exception. It must

be used within the method.

Java try block must be followed by either catch or finally block.

Syntax of java try-catch:

Try {

//code that may throw exception

}catch(Exception_class_Name ref){}

Syntax of try-finally block:

Try {

//code that may throw exception

}finally{}

Java catch block:

Java catch block is used to handle the Exception. It must be used after the try

block only. We can use multiple catch block with a single try.

Internal working of java try-catch block:

Example:

public class Testtrycatch2

Page 122: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

{

public static void main(String args[])

{

Try {

int data=50/0;

}catch(ArithmeticException e){System.out.println(e);}

System.out.println("rest of the code...");

}

}

9. Write short notes on File streams used for I/O. (April 2014)

Ans:In Java, FileInputStream and FileOutputStream classes are used to read and write

data in file. In another words, they are used for file handling in java.

Java FileOutputStream class

Java FileOutputStream is an output stream for writing data to a file.

If we have to write primitive values then use FileOutputStream.Instead, for character-

oriented data, prefer FileWriter.

Example:

import java.io.*;

class Test

{

public static void main(String args[])

{

Try {

FileOutputstream fout=new FileOutputStream("abc.txt");

String s="Sachin Tendulkar is my favourite player";

byte b[]=s.getBytes();//converting string into byte array

fout.write(b);

fout.close();

Page 123: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

System.out.println("success...");

}catch(Exception e){system.out.println(e);}

}

}

Java FileInputStream class:

Java FileInputStreamclass obtains input bytes from a file.It is used for reading streams

of raw bytes such as image data. For reading streams of characters, consider using

FileReader.

It should be used to read byte-oriented data for example to read image, audio, video etc.

Example :

import java.io.*;

class SimpleRead

{

public static void main(String args[])

{

Try {

FileInputStream fin=new FileInputStream("abc.txt");

int i=0;

while((i=fin.read())!=-1)

{

System.out.println((char)i);

}

fin.close();

}catch(Exception e){system.out.println(e);}

}

}

Page 124: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

10. Describe the concept of Multithreading using an example.(April 2014)

Ans:Multithreading is a program control. A multithreaded program contains two or

more parts that can run concurrently. Each parts of such a program are called a Thread.

The OS is responsible for scheduling and allocating resource for thread.

Thread class:-

Thread is a class and it contains constructors and methods needed for creating threads.

This class is present in java.lang.package.

Important thread Constructors:-

a) Public thread(String threadname)

b) Public thread()

Advantages of thread:-

It increase the speed of the execution

It allow the run more task simultaneously

It reduce the complexity of large programs

It maximize cpu utilization

Thread Methods:-

The important thread class methods are

Run() – contains the statement for the particular thread

Start() – to start the execution of thread

Stop() – to block the currently executing thread

Interrupt() – to interrupt the currently running thread

IsAlive() - to check whether the thread is running or not

Yield() - to bring the stopped thread to run mode

Wait() – to stop the currently running thread

Page 125: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

PART – C QUESTIONS

1. Discuss the inter-thread communication with example.(April 2012, Nov 2012 &

April 2013)

Ans:Inter-thread communication or Co-operation is all about allowing synchronized

threads to communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused

running in its critical section and another thread is allowed to enter (or lock) in the same

critical section to be executed. It is implemented by following methods of Object class:

wait()

notify()

notifyAll()

wait() method:

Causes current thread to release the lock and wait until either another thread invokes the

notify() method or the notifyAll() method for this object, or a specified amount of time

has elapsed.

The current thread must own this object's monitor, so it must be called from the

synchronized method only otherwise it will throw exception.

Method Description

public final void wait()throws

InterruptedException

waits until object is notified.

public final void wait(long timeout)throws

InterruptedException

waits for the specified amount of

time.

notify() method:

Wakes up a single thread that is waiting on this object's monitor. If any threads are

waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and

occurs at the discretion of the implementation.

Syntax:public final void notify()

notifyAll() method:

Page 126: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

Wakes up all threads that are waiting on this object's monitor.

Syntax:public final void notifyAll()

Understanding the process of inter-thread communication

The point to point explanation of the above diagram is as follows:

Threads enter to acquire lock.

Lock is acquired by on thread.

Now thread goes to waiting state if you call wait() method on the object.

Otherwise it releases the lock and exits.

If you call notify() or notifyAll() method, thread moves to the notified state

(runnable state).

Now thread is available to acquire lock.

After completion of the task, thread releases the lock and exits the monitor state

of the object.

2. Explain the two ways of creating threads in java. (Nov 2013)

Thread Creation:

There are two ways to create thread in java;

Implement the Runnable interface (java.lang.Runnable)

By Extending the Thread class (java.lang.Thread)

Implementing the Runnable Interface:

The Runnable Interface Signature

public interface Runnable

{

void run();

}

The procedure for creating threads based on the Runnable interface is as follows:

Page 127: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

A class implements the Runnable interface, providing the run() method that will

be executed by the thread. An object of this class is a Runnable object.

An object of Thread class is created by passing a Runnable object as argument to

the Thread constructor. The Thread object now has a Runnable object that

implements the run() method.

The start() method is invoked on the Thread object created in the previous step.

The start() method returns immediately after a thread has been spawned.

The thread ends when the run() method ends, either by normal completion or by

throwing an uncaught exception.

Eg:

class Multi3 implements Runnable

{

public void run()

{

System.out.println("thread is running...");

}

public static void main(String args[])

{

Multi3 m1=new Multi3();

Thread t1 =new Thread(m1);

t1.start();

}

}

Extending Thread Class

The procedure for creating threads based on extending the Thread is as follows:

A class extending the Thread class overrides the run() method from the Thread

class to define the code executed by the thread.

This subclass may call a Thread constructor explicitly in its constructors to

initialize the thread, using the super() call.

The start() method inherited from the Thread class is invoked on the object of the

class to make the thread eligible for running.

Eg:

class Multi extends Thread

{

public void run()

{

System.out.println("thread is running...");

}

Page 128: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

public static void main(String args[])

{

Multi t1=new Multi();

t1.start();

}

}

3. Explain the method of defining and using packages. (April 2014)

Ans:A java package is a group of similar types of classes, interfaces and sub-

packages.Package in java can be categorized in two form, built-in package and user-

defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql

etc.

Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package:

1) Java package is used to categorize the classes and interfaces so that they can be

easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Simple example of java package:

The package keyword is used to create a package in java.

Page 129: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

package mypack;

public class Simple

{

public static void main(String args[])

{

System.out.println("Welcome to package");

}

}

How to compile java package:

If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename

How to run java package program:

We need to use fully qualified name e.g. mypack.Simpleetc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

How to access package from another package?

There are three ways to access the package from outside the package.

import package.*;

importpackage.classname;

4. Describe method of defining and implementing interfaces. (April 2014,Nov/Dec

2016)

Defining Interface:

An interface declaration consists of modifiers, the keyword interface, the interface name,

a comma-separated list of parent interfaces (if any), and the interface body.

For example:

public interface GroupedInterface extends Interface1, Interface2, Interface3

{

// constant declarations

// base of natural logarithms

double E = 2.718282;

// method signatures

Page 130: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

voiddoSomething (int i, double x);

intdoSomethingElse(String s);

}

The public access specifier indicates that the interface can be used by any class in any

package. If you do not specify that the interface is public, then your interface is

accessible only to classes defined in the same package as the interface.

An interface can extend other interfaces, just as a class subclass or extend another class.

However, whereas a class can extend only one other class, an interface can extend any

number of interfaces. The interface declaration includes a comma-separated list of all the

interfaces that it extends.

Implementing Interfaces:

When a class implements an interface, you can think of the class as signing a contract,

agreeing to perform the specific behaviors of the interface. If a class does not perform all

the behaviors of the interface, the class must declare itself as abstract.

A class uses the implements keyword to implement an interface. The implements

keyword appears in the class declaration following the extends portion of the declaration.

Eg:

public class MammalInt implements Animal

{

public void eat()

{

System.out.println("Mammal eats");

}

public void travel()

{

System.out.println("Mammal travels");

}

publicintnoOfLegs()

{

return 0;

}

public static void main(String args[])

{

MammalInt m = new MammalInt();

m.eat();

m.travel();

}

}

Page 131: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

5. Explain the fundamentals of Exception handling.(April 2014)

Ans:An exception is a problem that arises during the execution of a program. An

exception can occur for many different reasons, including the following:

A user has entered invalid data.

A file that needs to be opened cannot be found.

A network connection has been lost in the middle of communications or

the JVM has run out of memory.

Exception Hierarchy:

The Exception class has two main subclasses: IOException class and

RuntimeException Class.

Throwable

Error Exception

IOException Runtime

Exception

Categories of exceptions:

Checked exceptions: A checked exception is an exception that is typically

a user error or a problem that cannot be foreseen by the programmer.

Runtime exceptions: A runtime exception is an exception that occurs that

probably could have been avoided by the programmer.

Errors: These are not exceptions at all, but problems that arise beyond the

control of the user or the programmer.

Catching Exceptions (try-catch)

A method catches an exception using a combination of the try and catch keywords. A

try/catch block is placed around the code that might generate an exception.

Syntax:

try

{

Page 132: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

//Protected code

}catch(ExceptionName e1)

{

//Catch block

}

A catch statement involves declaring the type of exception you are trying to catch. If an

exception occurs in protected code, the catch block (or a block) that follows the try is

checked.

The throws/throw Keywords:

If a method does not handle a checked exception, the method must declare it using

the throws keyword. The throws keyword appears at the end of a method's signature.

The finally Keyword

The finally keyword is used to create a block of code that follows a try block. A finally

block of code always executes, whether or not an exception has occurred.

Syntax:

try

{

//Protected code

}catch(ExceptionType1 e1)

{

//Catch block

}catch(ExceptionType2 e2)

{

//Catch block

}catch(ExceptionType3 e3)

{

//Catch block

}finally

{

//The finally block always executes.

}

Declaring you own Exception:

You can create your own exceptions in Java. Keep the following points in mind when

writing your own exception classes:

All exceptions must be a child of Throwable.

Page 133: Object Oriented Programming through JavaDevelopment Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known the Application Programming Interface

If you want to write a checked exception that is automatically enforced by the

Handle or Declare Rule, you need to extend the Exception class.

If you want to write a runtime exception, you need to extend the

RuntimeException class.

Common Exceptions:

In Java, it is possible to define two categories of Exceptions and Errors.

JVM Exceptions: - These are exceptions/errors that are exclusively or logically

thrown.

Programmatic exceptions: - These exceptions are thrown explicitly by the

application or the API

--------------