Importrant Questions
Importrant Questions
Important Questions
PART – A
Each question carries 2 marks
Unit I
1. List out the features of Java.
A.
• Compiled and interpreted
• Platform independent and portable
• Object oriented
• Robust and secure
• Distributed
• Simple, small and familiar
• Multithreaded and interactive
• High performance
• Dynamic and extensible
• Ease of development
2. Why is Java called a compiled and interpreted language?
A. Java is called a compiled and interpreted language as it follows a two stage system-
• In the first stage, Java compiler translates the source code into bytecode
instructions (Bytecodes are not machine instructions).
• In the second stage, Java interpreter generates machine code that can be directly
executed by the machine.
3. Why is Java platform independent and portable?
A. Java is platform independent and portable as it is easily moved from one computer to
another, anywhere and anytime. It is also a popular language for programming on the
Internet. It Ensures portability in two ways – first, Java compiler generates bytecode
instructions that can be implemented on any machine, secondly, the size of the primitive
data types are machine – independent.
4. List out any four differences between Java and C.
A. Java differs from C in the following ways-
• Java doesn’t include keywords sizeof and typedef.
• Java doesn’t contain the data types struct and union.
• Java doesn’t have type modifiers keywords auto, extern, register, signed and
unsigned.
• Java doesn’t support an explicit pointer type.
• Java doesn’t have a preprocessor and therefore we cannot use #define, #include
and #ifdef statements.
• Java is object-oriented while C is procedural.
• Java is an interpreted language while C is a compiled language.
5. List out any four differences between Java and C++.
A. Java differs from C++ in the following ways-
• Java doesn’t support operator overloading (exceptional case – string
concatenation).
• Java doesn’t have template classes as in C++.
• Java doesn’t support multiple inheritance of classes. This is accomplished using
“interface”.
• Java doesn’t support global variables.
• Java doesn’t use pointers.
• Java has replaced the destructor function with a finalize() function.
• There are no header files in Java.
6. Discuss the statement public static void main(String args[]).
A. The main line public static void main(String args[]) defines the method named main,
which is the starting point for the interpreter to begin the execution of the program. (Java
applets will not use the main method).
• public- An access specifier that declares the main method as unprotected.
• static- Declares the method as one that belongs to the entire class and not a part of
any objects of the class.
• void- Type modifier which states that the main method does not return any value.
• String args[]- Declares a parameter named args, which contain an array of objects
of the class type String.
7. What are Java tokens? Give an example.
A. The smallest individual units in a program are known as tokens. Tokens are the ones
which are used to prepare a program.
Java language includes five types of tokens- Reserved Keywords, Identifiers, Literals,
Operators, Separators.
Examples: const, try, break, import etc.
8. What is the significance of readLine() method?
A. The readLine() method which is invoked using an object of the class DataInputStream
reads the input from the keyboard as a string, which is then converted to the
corresponding data type wrapper class.
9. Write the syntax of conditional or ternary operator. Give an example.
A. Syntax- variable = (condition) ? Statement1 : Statement2;
Example: int x=30, y=40, big;
big = (x > y) ? x : y;
System.out.println(big); // prints 40
10. What is a class in Java?
A. Classes are the primary and essential elements of a Java program. A class in Java is a
set of objects which shares common characteristics/ behavior and common properties/
attributes.
Unit II
1. What is the use of Object class?
A. The Object class is the parent class of all the classes in java by default, it is the
topmost class of java. It is useful if we want to refer to any object the type of which we
don't know. It provides some common behaviors to all the objects.
Example: Object obj=getObject();
2. What is inheritance?
A. The process of deriving a new class from an already existing class is called
inheritance. It allows subclasses to inherit all the variables and method of their parent
class.
3. What is polymorphism?
A. Polymorphism in Java is a concept by which we can perform a single action in
different ways. We can perform polymorphism in java by method overloading and
method overriding.
There are two types of polymorphism in Java: Compile-time polymorphism and Runtime
polymorphism.
4. What is the use of an instanceof operator?
A. The instanceof in Java is used to check if the specified object is an instance of a class,
subclass, or interface. It is also referred to as the comparison operator because of its
feature of comparing the type with the instance. It returns either true or false.
5. What is an abstract class?
A. A class which is declared with the abstract keyword is known as an abstract class in
Java. An abstract class in Java is a class that is declared abstract—it may or may not
include abstract methods. Abstract classes cannot be instantiated, but they can be
subclassed.
6. What is an interface?
A. An interface is basically a kind of class, but with a major difference i.e. interfaces
define only abstract methods and final fields (do not specify any code to implement these
methods and data fields contain only constants).
Syntax: interface Interfacename
{
variables declaration;
methods declaration;
}
7. What is a package? List out the various packages in Java.
A. Packages are a way of grouping a variety of classes and/or interfaces together
according to the functionality. Using packages is a way to achieve the reusability in Java.
The two types of packages are- Java API packages and User defined packages.
The different packages in Java are-
• java.lang
• java.util
• java.io
• java.awt
• java.net
• java.applet
Unit III
1. What is an event in Java?
A. An event can be defined as changing the state of an object or behavior by performing
actions. It is a signal that is sent by an object to another object when something happens.
It is used to notify other objects of changes in state or to request that they perform some
action.
Different types of events in java are-
• Action event
• Item event
• Text event
• Window event
• Key event
2. What is event handling in Java?
A. Event handling is a mechanism used to handle events generated by applets. This
mechanism then decides what should happen if an event occurs.
3. List out the major events in Java.
A. Different types of major events in java are-
• Action event
• Item event
• Text event
• Window event
• Key event
4. What is an event source?
A. An event source is an object responsible for generating an event. When an event
occurs, the event source creates an event object and passes it to all of its registered
listeners.
5. What is an event listener?
A. An event listener is an object referred by event source at the time of occurrence. It is
the primary method for handling events. Listeners can process the event object in any
way that they want.
PART – B
Each question carries 5 marks
Unit I
1. Briefly explain JDK.
A. Java environment includes a large number of development tools and hundreds of
classes and methods.
The development tools are part of the system known as Java Development Kit (JDK)
The classes and methods are part of the Java Standard Library (JSL), also known as the
Application Programming Interface (API).
The Java Development Kit comes with a collection of tools that are used for developing
and running Java programs. They include:
• appletviewer (for viewing Java applets) - Enables to run Java applets without
actually using a Java–compatible browser.
• javac (Java compiler) - Java compiler, which translates Java sourcecode to
bytecode files that the interpreter can understand.
• java (Java interpreter) - Java interpreter, which runs applets and applications by
reading and interpreting bytecode files.
it suitable for applications where memory savings are crucial, and the range of
byte is insufficient.
• int: The int data type is a 32-bit signed integer that is the default data type for
integer values, used extensively in programming for counting, indexing, and
general-purpose arithmetic operations, offering a balance between range and
memory usage.
• long: The long data type is a 64-bit signed integer used when a wider range than
int is needed, such as for large-scale computations, handling large data sets, etc.
• float: The float data type is a single-precision 32-bit decimal point, used mainly to
save memory in large arrays of floating point numbers.
• double: The double data type is a double-precision 64-bit decimal point, which is
the default choice for decimal values in Java, providing a higher precision for
floating point arithmetic.
• char: The char data type is a single 16-bit Unicode character set used to represent
characters which includes letters, digits, and special symbols.
• boolean: The boolean data type has only two possible values, true and false, and is
used for simple flags that track true/false conditions.
b) Non – primitive data types
• Classes: Classes are user-defined data types that act as a blueprint for creating
objects, containing fields (variables) and methods to define the object's behavior.
• Interfaces: Interfaces are abstract types used to specify methods that a class must
implement, enabling multiple inheritance of method signatures.
• Arrays: Arrays are containers that hold a fixed number of values of a single type,
allowing for efficient storage and retrieval of elements.
void display()
{
System.out.println(“A------- x : “ + x);
System.out.println(“B------- y: “ + y);
}
}
class OverrideTest
{
public static void main(String args[])
{
B obj=new B(100,200);
obj.display();
}
}
• Output:
A------- x :
100
B------- y: 200
Unit II
1. Briefly explain generics programming.
A.
• Java generics programming allows us to create a single class, interface, and
method that can be used with different types of data (objects).
• This helps us to reuse our code.
• Generics programming does not work with primitive types (int, float, char etc).
• Java Generics Class
o We can create a class that can be used with any type of data.
o Such a class is known as Generics Class.
• Java Generics Method
o Similar to the generics class, we can also create a method that can be used
with any type of data.
o Such a method is known as Generics Method.
• Example:
public class List<T>
{
private T[] elements;
public List(int size)
{
elements = new T[size];
}
public void add(T element)
{
elements[elements.length - 1] = element;
}
public T get(int index)
{
return elements[index];
}
public int size()
{
return elements.length;
}
}
• Output: true
o There are two ways of accessing a package, either by using a fully qualified
classname or by using a shortcut approach through import statement.
o The same approach is used to access user – defined packages also.
Unit III
1. Briefly explain the event types in Java.
A.
• Action Event: Action events represent user actions such as button clicks or menu
selections. They are typically generated by components like buttons and menu
items when the user interacts with them, triggering the associated event listener to
execute a specific action or behavior.
• Item Event: Item events occur when the state of an item changes, such as when a
checkbox is checked or unchecked, or when an item is selected from a choice list.
These events are generated by components like checkboxes, radio buttons, and
• Text Event: Text events represent changes to text components such as text fields
or text areas, such as when the user types, deletes, or modifies text. These events
provide information about the text change, allowing event listeners to react
accordingly, for example, by validating input or updating related components.
• Window Event: Window events occur when the state of a window changes, such
as when it is opened, closed, activated, or deactivated. These events are generated
by window components like JFrame or JDialog, enabling event listeners to handle
window-related actions such as saving data before closing or updating the UI
when the window gains focus.
• Key Event: Key events represent keyboard input, including key presses, key
releases, and key typed (i.e., key presses resulting in character input). These events
are generated by components that have keyboard focus, allowing event listeners to
respond to user keystrokes, for example, by implementing keyboard shortcuts or
validating input in text fields.
PART – C
Each question carries 8 marks
Unit I
1. Explain the features of Java.
A. The different features of java are -
• Compiled and interpreted -
o It is a two stage system
o In the first stage, Java compiler translates the source code into bytecode
instructions.
o Bytecodes are not machine instructions.
o In the second stage, Java interpreter generates machine code that can be
directly executed by the machine.
• Object oriented -
o It is a true object – oriented language.
o All program code and data reside within objects and classes.
• Distributed -
o It is a distributed language for creating applications on networks.
o It has the ability to share both data and programs.
o It can open and access remote objects on Internet easily.
o It enables multiple programmers at multiple remote locations to work
together on a single project.
• High performance -
o Java performance is impressive, mainly due to the use of intermediate
bytecode.
o It reduces the overheads during runtime.
o Multithreading enhances the overall execution speed of Java programs.
• Ease of development -
o Java 2 Standard Edition (J2SE) 5.0 supports many features which help to
reduce the work of the programmer by shifting the responsibility of
creating the reusable code to the compiler.
o Java programs can be developed in an easy way.
• Documentation section:
o It comprises of a set of comment lines giving details of the program
o // single line comment
o /*…………..*/ multi line comment
o /**………..*/ documentation comment
o Ex://Welcome program
• Package statement:
o It declares a package name and informs the compiler that the classes
defined here belongs to this package.
o Ex: package student;
• Import statements:
o These are similar to #include statement, which are used to instruct the
interpreter to load the respective class contained in the specific package.
o Ex: import student.Test;
• Interface statements:
o An interface is like a class, but includes a group of method declarations. It
is used to implement multiple inheritance.
o Syntax: interface Interfacename
{
variables declaration;
methods declaration;
}
• Class definitions:
o Classes are the primary and essential elements of a Java program.
o Syntax: public class classname
{
// body
}
• Main method class:
o Since every Java stand – alone program requires main method as its starting
point, this class is the essential part of a Java program.
o The main method creates objects of various classes and establishes
communications between them.
o Syntax:
class Hello
{
public static void main(String args[])
{
//body
}
}
• Example:
class SampleOne
{
public static void main(String args[])
{
System.out.println(“Java is better than C++”);
}
}
o Class Sampleone declares a class.
o The main line public static void main(String args[]) defines the method
named main, which is the starting point for the interpreter to begin the
execution of the program.
o String args[] declares a parameter named args, which contain an array of
objects of the class type String.
o System.out.println is used for displaying the output on the screen.
o Every Java statement must end with a semicolon.
• Arithmetic Operators:
These operators involve the mathematical operators that can be used to perform
various simple or advanced arithmetic operations on the primitive data types
referred to as the operands.
o Addition(+): This operator is a binary operator and is used to add two
operands.
Syntax: num1 + num2
Example: 2+3=5
o Subtraction(-): This operator is a binary operator and is used to subtract two
operands.
Syntax: num1 - num2
Example: 5-2=3
o Multiplication(*): This operator is a binary operator and is used to multiply
two operands.
Syntax: num1 * num2
Example: 5*4=20
o Division(/): This is a binary operator that is used to divide the first
operand(dividend) by the second operand(divisor) and give the quotient as a
result.
Syntax: num1 / num2
Example: 8/4=1
o Modulus(%): This is a binary operator that is used to return the remainder
when the first operand(dividend) is divided by the second operand(divisor).
Syntax: num1 % num2
Example: 5%2=1
• Relational Operators:
Relational Operators are a bunch of binary operators used to check for relations
between two operands, including equality, greater than, less than, etc. They return
a boolean result after the comparison.
o ‘Equal to’ operator (==): This operator is used to check whether the two
given operands are equal or not.
Syntax: var1 == var2
Example: 5==4 gives false
o ‘Not equal to’ Operator(!=): This operator is used to check whether the two
given operands are equal or not. It functions opposite to that of the equal-to-
operator. It returns true if the operand at the left-hand side is not equal to the
right-hand side, else false.
Syntax: var1 != var2
Example:5!=4 gives true
o ‘Greater than’ operator(>): This checks whether the first operand is greater
than the second operand or not.
Syntax: var1 > var2
Example: 10>3 gives true
o ‘Less than’ Operator(<): This checks whether the first operand is less than
the second operand or not.
Syntax: var1 < var2
Example: 4<3 gives false
• Logical Operators:
Logical operators are used to perform logical “AND”, “OR” and “NOT”
operations. They are used to combine two or more conditions/constraints or to
complement the evaluation of the original condition under particular
consideration.
o AND Operator ( && ) – if( a && b ) [if true execute else don’t]
Example: (2>1)&&(4<2) gives true
o OR Operator ( || ) – if( a || b) [if one of them is true to execute else don’t]
Example: (2>1)||(2<1) gives true
o NOT Operator ( ! ) – !(a<b) [returns false if a is smaller than b]
Example: !true gives false
• Assignment Operators:
These operators are used to assign values to a variable. The left side operand of the
assignment operator is a variable, and the right side operand of the assignment
operator is a value.
o (=) operator: This is the most straightforward assignment operator, which is
used to assign the value on the right to the variable on the left.
Syntax: num1 = num2;
Example: a = 10;
o (+=) operator: This operator is a compound of ‘+’ and ‘=’ operators. It
operates by adding the current value of the variable on the left to the value on
the right and then assigning the result to the operand on the left.
Syntax: num1 += num2;
Example: a += 10 This means, a = a + 10
o (-=) operator: This operator is a compound of ‘-‘ and ‘=’ operators. It operates
by subtracting the variable’s value on the right from the current value of the
variable on the left and then assigning the result to the operand on the left.
Syntax: num1 -= num2;
Example: a -= 10 This means, a = a - 10
o (*=) operator:This operator is a compound of ‘*’ and ‘=’ operators. It operates
by multiplying the current value of the variable on the left to the value on the
right and then assigning the result to the operand on the left.
Syntax: num1 *= num2;
Example: a *= 10 This means, a = a * 10
o (/=) operator: This operator is a compound of ‘/’ and ‘=’ operators. It operates
by dividing the current value of the variable on the left by the value on the
right and then assigning the quotient to the operand on the left.
• Bitwise Operators:
Bitwise operators are used to performing the manipulation of individual bits of a
number. They can be used with any integral type (char, short, int, etc.). They are
used when performing update and query operations of the Binary indexed trees.
o Bitwise OR (|): This operator is a binary operator, denoted by ‘|’. It returns bit
by bit OR of input values, i.e., if either of the bits is 1, it gives 1, else it shows
0.
Example: 13 | 14 gives 15
o Bitwise AND (&):This operator is a binary operator, denoted by ‘&.’ It returns
bit by bit AND of input values, i.e., if both bits are 1, it gives 1, else it shows 0.
Example: 13 & 14 gives 12
o Bitwise XOR (^):This operator is a binary operator, denoted by ‘^.’ It returns
bit by bit XOR of input values, i.e., if corresponding bits are different, it gives
1, else it shows 0.
Example: 13 ^ 14 gives 3
o Bitwise Complement (~):This operator is a unary operator, denoted by ‘~.’ It
returns the one’s complement representation of the input value, i.e., with all
bits inverted, which means it makes every 0 to 1, and every 1 to 0.
Example: ~5 gives -6
• Other Operators:
o Unary minus(-):This operator can be used to convert a positive value to a
negative one.
Syntax: -(operand)
Example: a = -10
o Increment Operator (++): Increment Operator increases the value by “1”.
Example: x=3, x++ which gives x=4
o Decrement Operator (--): Decrement Operator decreases the value by “1”.
Example: x=3, x-- which gives x=2
o Conditional/ternary operator: Conditional operator is an equivalent form of
if-else structure. It is called as ternary operator because it is used on three
operands.
Example: k=10>5?1:2 which gives k=1.
o instance of operator: The instanceof is an object reference operator and
returns true if the object on the left – hand side is an instance of the class given
on the right – hand side.
Example: Box b1=new Box() b1 instanceof Box which gives True
Evaluation of expressions:
Expressions are evaluated using an assignment statement
The general form is variable=expression;
where variable is a valid Java variable name.
Examples:
x=a+b;
y=a*b/c;
.
.
.
else
{
statements
}
Explanation:
o Statements get executed in loops only when the corresponding conditions
are true.
o Statements in the final else block get executed when all other conditions are
false.
o The control checks a condition only when all the above mentioned
conditions are false.
Example:
if ( x > 0 )
System.out.println( “positive”);
else if ( x < 0)
System.out.println(“negative ”);
else
System.out.println( “zero”);
d) nested if:
Syntax:
if (condition1)
{
if ( condition2)
{
Statements
}
}
Explanation:
o Writing if in another if is nested if.
o Inner if is processed only when outer if’s condition is true.
o Hence, statements in inner-if get executed only when condition1 and
condition2 are true.
Example:
if ( a > b )
{
if (a>c)
System.out.println( “ a is the biggest”);
}
e) switch:
Syntax:
switch(variable)
{
case constant1: statement1
break;
case constant2: statement2
break;
.
.
default: statements
break;
}
Explanation:
o switch is similar to if else if.
o Statement 1 gets executed when the variable is equal to constant1 and so
on.
o Control comes to “default” portion when all the cases (constants), which
have been mentioned do not match with the value of the variable.
o Here break and default are optional. When there is no break for a case it
continues till it encounters break or the end of the switch loop.
Example:
class SampleSwitch
{
public static void main(String args[])
{
for(i=0;i<5;i++)
switch(i)
{
case 0: System.out.println( “ i is zero”);
break;
case 1: System.out.println(“i is 1”);
break;
case 2: System.out.println(“i is 2”);
break;
case 3: System.out.println(“i is 3”);
break;
default: System.out.println( “ i is greater than 3”);
break;
}
}
}
o It omits the statements written after “continue” and restarts the iterative
loop.
Example:
for(i=1;i<10;i++)
{
System.out.println(“ hello”);
if (i<5)
continue;
else
break;
}
/* prints hello 5 times */
c) return:
Explanation:
o return is used in functions.
o It moves the control to calling function from the called module.
o "return” is also used to return values to the point where it is called.
o But it is possible to return only one value at a time.
Example:
int sum(int x, int y)
{
return (x+y);
}
int k= sum(30,40);
Here “sum” function returns 70 into the variable k with the above call.
Statements
}
Explanation:
o Statements get executed as long as the condition is true.
o It checks the condition first and executes the statements later.
o It is also called entry control loop.
o Minimum number of execution in this case is “zero”
Example:
i=0;
while( i<10 )
{
System.out.println(“hello”);
i=i+1;
}
/* prints hello 10 times */
c) do while loop:
Syntax:
do
{
Statements
}while(condition);
Explanation:
o This is called exit control loop.
o Do-While loop gets executed as long as the condition is true
o Statements get executed first and then Condition.
o Minimum number of execution in this case is “one”
Example:
i=0;
do
{
System.out.println(“hello”);
i=i+1;
} while( i<10 );
/* prints hello 10 times */
c) for each (enhanced for) loop
Syntax:
for (variable : expression)
{
Statements
}
Explanation:
o The enhanced for loop is called as for each loop.
o It is introduced in J2SE 5.0.
o This is more used with arrays and enumerations.
o Generally to access the array elements, we use indexes. But, using for-each,
we can directly have access to each element of the array without indexes.
Example:
int x[]= {10,20,30};
for (int k : x)
System.out.print(k+” “);
//The above code prints: 10 20 30
Unit II
1. Explain the types of inheritance in Java.
A. Java Inheritance is an important pillar of OOP(Object-Oriented Programming).
Inheritance means creating new classes based on existing ones. A class that inherits from
another class can reuse the methods and fields of that class.
Syntax:
class DerivedClass extends BaseClass
{
//methods and fields
}
The different types of inheritance are-
a] Single Inheritance
In single inheritance, subclasses inherit the features of one superclass. Here class A serves
as a base class for the derived class B.
b] Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the
derived class also acts as the base class for other classes. Here class A serves as a base
class for the derived class B, which in turn serves as a base class for the derived class C.
c] Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than
one subclass. Here class A serves as a base class for the derived classes B, C, and D.
e] Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t support
multiple inheritances with classes, we can achieve hybrid inheritance only through
Interfaces.
3. What is a static variable? Write a program to show the use of a static variable.
A.
• A static variable is a variable that is declared with the static keyword.
• Static variable in Java declares the method as one that belongs to the entire class
and not a part of any objects of the class.
• The static variable can be used to refer to the common property of all objects
(which is not unique for each object).
Program:
class StatVariableDemo
{
static int count=0;
public void increment()
{
count++;
}
public static void main(String args[])
{
StatVariableDemo obj1=new StatVariableDemo();
StatVariableDemo obj2=new StatVariableDemo();
obj1.increment();
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}
Output with static keyword:
Obj1: count is=2
Obj2: count is=2
With static keyword, there's only one copy of the count variable shared among all
instances of the class.
Both obj1 and obj2 are incrementing the same count variable, so the count increases to 2
when both objects call the increment() method.
Output without static keyword:
Obj1: count is=1
Obj2: count is=1
Without static keyword, each instance of the class (obj1 and obj2) has its own copy of the
count variable.
Each object's increment() method call operates on its own copy of count, so the count
increases independently for each object.
specify any code to implement these methods and data fields contain only
constants.)
• The class that implements the interface will define the implementation of methods
in the interface.
• Syntax:
interface Interfacename
{
variables declaration;
methods declaration;
}
Extending interface:
• The interface can be extended.
• The subinterface will inherit all the members of superinterface.
Syntax:
interface InterfaceName2 extends Interfacename1
{
body of InterfaceName2
}
Implementing interfaces:
• Once an interface has been defined, one or more classes can implement that
interface.
• To do this, include the implements clause in a class definition and then define the
methods of the interface.
Syntax:
class Classname implements Interfacename
{
body of the class
}
Program:
interface Area
{
final static float PI=3.14F;
float compute(float x,float y);
}
class Rectangle implements Area
{
public float compute(float x,float y)
{
return(x*y);
}
}
class Circle implements Area
{
public float compute(float x,float y)
{
return(PI*x*x);
}
}
class InterfaceTest
{
public static void main(String args[])
{
Rectangle rect=new Rectangle();
Circle cir=new Circle();
Area z; // interface object
z=rect; // z refers to rect object
System.out.println(“Area of Rectangle=“ + z.compute(10,20));
z=cir; // z refers to cir object
System.out.println(“Area of Circle=“ + z.compute(10,0));
}
}
public class B
{
//body of B
}
Step3: Store this as B.java under the directory p1.
Step4: Compile B. java file
Unit III
1. Explain mouse events in Java with an example.
A. An event which indicates that a mouse action occurred in a component is called as a
mouse event.
Hence a mouse event is something that happens due to the specific action of the mouse
such as click, double click, mouseover, mousedown, mouseup, etc.
Some of the fields for java.awt.event.MouseEvent class:
• static int MOUSE_CLICKED --The "mouse clicked" event
• static int MOUSE_DRAGGED --The "mouse dragged" event
• static int MOUSE_ENTERED --The "mouse entered" event
• static int MOUSE_EXITED --The "mouse exited" event
• static int MOUSE_MOVED --The "mouse moved" event
• static int MOUSE_PRESSED -- The "mouse pressed" event
• static int MOUSE_RELEASED --The "mouse released" event
Some of the methods for java.awt.event.MouseEvent class:
• int getButton(): Returns which, if any, of the mouse buttons has changed state.
• int getClickCount(): Returns the number of mouse clicks associated with this
event.
• int getXOnScreen(): Returns the absolute horizontal x position of the event.
Methods of MouseListener interface:
• public abstract void mouseClicked(MouseEvent e);
• public abstract void mouseEntered(MouseEvent e);
• public abstract void mouseExited(MouseEvent e);
• public abstract void mousePressed(MouseEvent e);
• public abstract void mouseReleased(MouseEvent e);
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseEvents extends Applet implements
MouseListener,MouseMotionListener
{
String msg=" ";
public void init()
{
//The listener object created from the class is registered with a component using the
component's
//addMouseListener method.
addMouseListener(this);
////The listener object created from the class is registered with a component using the
component's
//addMouseMotionListener method.
addMouseMotionListener(this);
}
public void paint(Graphics g)
{
g.drawString(msg,20,20);
}
public void mousePressed(MouseEvent me) //method of MouseListener interface
{
msg=" mouse pressed";
repaint();
}
public void mouseClicked(MouseEvent me) //method of MouseListener interface
{
msg=" mouse clicked";
repaint();
}
public void mouseEntered(MouseEvent me) //method of MouseListener interface
{
msg=" mouse entered";
repaint();
}
public void mouseExited(MouseEvent me) //method of MouseListener interface
{
msg=" mouse exited";
repaint();
}
public void mouseReleased(MouseEvent me) //method of MouseListener interface
{
msg=" mouse released";
repaint();
}
public void mouseMoved(MouseEvent me) //method of MouseMotionListener interface
{
msg=" mouse moved";
repaint();
}
public void mouseDragged(MouseEvent me) //method of MouseMotionListener
interface
{
msg=" mouse dragged";
repaint();
}
}
HTML Code
<html>
<body>
<applet
code="MouseEvents.class"
height=100
width=700>
</applet>
</body>
</html>
requestFocus();
}
public void keyTyped(KeyEvent e)
{
str+=e.getKeyChar();
repaint(0);
}
public void keyPressed(KeyEvent e)
{
showStatus("Key Pressed");
}
public void keyReleased(KeyEvent e)
{
showStatus("Key released");
}
public void paint(Graphics g)
{
g.drawString(str,15,15);
}
}
HTML Code
<html>
<body>
<applet
code="KeyBoardEvents.class"
height=100
width=700>
</applet>
</body>
</html>