Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
15 views39 pages

Importrant Questions

The document contains important questions and answers related to Java programming, covering topics such as object-oriented programming, Java features, data types, and event handling. It includes both short answer questions and detailed explanations, making it a useful study resource for Bachelor of Computer Applications students. Key concepts discussed include inheritance, polymorphism, the Java Development Kit (JDK), and the Java Virtual Machine (JVM).

Uploaded by

abiramis38
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views39 pages

Importrant Questions

The document contains important questions and answers related to Java programming, covering topics such as object-oriented programming, Java features, data types, and event handling. It includes both short answer questions and detailed explanations, making it a useful study resource for Bachelor of Computer Applications students. Key concepts discussed include inheritance, polymorphism, the Java Development Kit (JDK), and the Java Virtual Machine (JVM).

Uploaded by

abiramis38
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

lOMoARcPSD|45714441

Java Important Questions With Answers

Bachelor of computer applications (Bangalore University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Kamini Ganesan G ([email protected])
lOMoARcPSD|45714441

OBJECT-ORIENTED PROGRAMMING USING


JAVA

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.

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

• 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.

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

11. What is an object in Java?


A. An object in Java is a basic unit of Object-Oriented Programming and represents real-
life entities. Objects are the instances of a class that are created to use the attributes and
methods of a class.
12. What is instantiation?
A. Instantiation in Java refers to the process of creating a new instance/object of a class.
Syntax: ClassName objName = new ClassName();
13. What is an abstract method?
A. An abstract method in Java is a method that is declared without a body. It does not
contain any instructions after declaring the method.
Example: public abstract class Animal
{
public abstract void makeSound();
}
14. What is the importance of ‘this’ keyword in Java?
A. In Java, the this keyword is an important part of the language that serves several
purposes-
• Differentiating Between Instance Variables and Parameters- When a method
or constructor parameter has the same name as an instance variable, the this
keyword is used to refer to the instance variable.
• Invoking Other Constructors- It can be used to call another constructor in the
same class. This is known as constructor chaining and helps in reusing constructor
code.
• Returning the Current Instance- It can be used to return the current instance of a
class from a method, which is useful for method chaining.
• Referring to the Current Object- It can be used to refer to the current instance of
the class in methods, allowing access to instance variables and methods.
15. What is the use of finalize() method in Java?
A. The finalize() method in Java is called by the garbage collector on an object when the
garbage collector determines that there are no more references to the object. The
finalize() method allows an object to perform any necessary cleanup before it is garbage
collected.

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.

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

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

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

• 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.

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

• javap (Java disassembler) - Java disassembler, which enables to convert bytecode


files into a program description.
• javah (for C header files) - Produces header files for use with native methods.
• javadoc (for creating HTML documents) - Creates HTML – format
documentation from Java source code files.
• jdb (Java debugger) - Java debugger, which helps to find errors in our programs.

2. Write short notes on JVM.


A.
• JVM stands for Java Virtual Machine. It is an abstract machine that enables a
computer to run Java programs as well as programs written in other languages that
are also compiled to Java bytecode.
• Java compiler produces an intermediate code known as bytecode for a machine
that does not exist.
• This machine is called JVM and it exists only inside the computer memory.
• JVM is a simulated computer within the computer that does all major functions of
a real computer.
• JVM allows Java code to be written once and run anywhere (WORA). This is
achieved by converting Java source code into platform-independent bytecode,
which the JVM can execute on any platform.
• The JVM manages memory through a well-organized allocation of stack and heap
memory, automatic garbage collection, and memory reclamation to prevent
memory leaks.
• The JVM employs Just-In-Time (JIT) compilation to optimize performance by
compiling bytecode into native machine code at runtime, improving execution
speed.
• The components of JVM are-
o Class Loader - Loads, links, and initializes classes and interfaces, allowing
dynamic loading of Java classes during runtime.
o Bytecode Verifier - Ensures that the bytecode adheres to Java's safety and
security rules before execution.
o Interpreter - Executes bytecode instructions line by line.
o Just-In-Time (JIT) Compiler - Converts bytecode into native machine
code for better performance during runtime.
o Garbage Collector - Automatically manages memory, deallocating
memory used by objects that are no longer needed, preventing memory
leaks and optimizing resource usage.

3. Discuss the data types in Java.


A. Data types specify the size and type of values that can be stored.
The two main types of data types in Java are –
a) Primitive data types (also called intrinsic or built – in types)
b) Non – primitive data types (also called derived or reference types)
a) Primitive data types
• byte: The byte data type is an 8-bit signed integer that is primarily used for saving
memory in large arrays, where the memory savings actually matter.
• short: The short data type is a 16-bit signed integer that is also used for saving
memory in large arrays, similar to byte, but can store larger integer values, making

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

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.

4. Briefly explain method overloading with an example.


A.
• Method overloading is used to obtain Compile-time polymorphism or early
binding or static polymorphism.
• The term method overloading allows us to have more than one method with the
same name.
• Since this process is executed during compile time, that's why it is known as
Compile-Time Polymorphism.
• Binding refers to connecting the function call to the function body.
• It is achieved by overloading methods, operator overloading, and by changing the
signature of the method.
• Overloading of methods is done by the reference variable of the class.
• Operator overloading is done by extending the functionality of an operator with
different functionalities.
• The term signature of method refers to parameters and their types along with the
return value and its type.
• Example:
public class OverloadingTest
{
void addition()
{
int a=10;
float b=6.7f;
float sum=a+b;

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

System.out.println("Sum by using default values is "+sum);


}
void addition(int a, int b)
{
int sum=a+b;
System.out.println("Sum of two integer values is "+sum);
}
void addition(float a,float b)
{
float sum=a+b;
System.out.println("Sum of two float values is "+sum);
}
public static void main(String args[])
{
OverloadingTest ovl=new OverloadingTest();
ovl.addition();
ovl.addition(5,10);
ovl.addition(1.5f,8.3f);
}
}

5. Write short notes on method overriding with an example.


A.
• It is possible to define a method in the subclass that has the same name, same
arguments and same return type as a method in the super class.
• When that method is called, the method defined in the subclass is invoked instead
of one in the super class.
• This is known as overriding method or method overriding.
• Example:
class A
{
int x;
A(int x)
{
this.x=x;
}
void display()
{
System.out.println(“A ------- x=“ + x);
}
}
class B extends A
{
int y;
B(int x,int y)
{
super(x);//passes values to super class
this.y=y;
}

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

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)

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

{
return elements[index];
}
public int size()
{
return elements.length;
}
}

2. Write short notes on type casting.


A.
• In Java, type casting is a method or process that converts a data type into another
data type in both ways manually and automatically.
• The automatic conversion is done by the compiler and manual conversion is
performed by the programmer.
• Converting a value from one data type to another data type is known as type
casting.
• There are two types of type casting:
• Widening Type Casting -
o Converting a lower data type into a higher one is called widening type
casting.
o It is also known as implicit conversion or casting down.
o It is done automatically. It is safe because there is no chance to lose data.
o byte -> short -> char -> int -> long -> float -> double
• Narrowing Type Casting -
o Converting a higher data type into a lower one is called narrowing type
casting.
o It is also known as explicit conversion or casting up.
o It is done manually by the programmer.
o If we do not perform casting up, then the compiler reports a compile-time
error.
o double -> float -> long -> int -> char -> short -> byte

3. Briefly discuss instanceof operator with an example.


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.
• If we apply the instanceof operator with any variable that has null value, it returns
false.
• Program:
class Sample
{
public static void main(String args[])
{
Sample s=new Sample();

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

System.out.println(s instanceof Sample);//true


}
}

• Output: true

4. Briefly explain the usage of abstract class with an example.


A.
• Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
• A class which is declared with the abstract keyword is known as an abstract class
in Java.
• It can have abstract and non-abstract methods (method with the body).
• An abstract class needs to be extended and its method implemented. It cannot be
instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change the body of
the method.
• If there is an abstract method in a class, that class must be abstract.
• Example:

abstract class Shape


{
public abstract void draw();
}
class Circle extends Shape
{
@Override
public void draw()
{
System.out.println("Drawing a circle");
}
}
public class Main
{
public static void main(String[] args)
{
Shape shape = new Circle();
shape.draw(); // Output: Drawing a circle
}
}

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

5. Distinguish class and interface.


A.
Class Interface
• A class in Java is a set of objects • An interface is basically a kind of
which shares common class, but with a major difference
characteristics/ behavior and i.e. interfaces define only abstract
common properties/ attributes. methods and final fields.
• Members can be constants or • Members are always declared as
variables. constant, i.e.., their values are final.
• Methods can be abstract or non – • Methods are abstract in nature, i.e..,
abstract. there is no code associated with
• Can be used for instantiation, i.e.., them.
for object creation. • Cannot be used for instantiation.
• Can use various access specifiers Can only be inherited by a class.
like public, private or protected. • Can only use the public access
specifier.

6. Write short notes on packages.


A.
• Packages are Java’s 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.
• Java packages can be classified into two types-
• Java API packages - Built-in packages like java.lang, java.util, java.io, java.awt,
java.net, java.applet, etc.
• User defined packages - Packages that are made/built by the user.

• Using system packages - The packages are organized in a hierarchical structure.


There are two ways of accessing the classes stored in a package.
o By using the package name containing the class and then appending the
class name to it using the dot operator.
o Example: java.awt.Font;
o By using the import statement.
o Example: import packagename.classname;
• Creating packages -
o Declare the package at the beginning of the file using the form package
packagename;
o Define the class that is to be put in the package and declare it public.
public class Classname
{
body of class
}
o Create a subdirectory named packagename and save the file by giving
Classname.java.
• Accessing a package -

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

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.

7. Briefly explain util package.


• The java.util package in Java is a built-in package that contains various utility
classes and interfaces.
• One of the most important Java packages is java.util package.
• The java.util package contains several pre-written classes that can act as a base to
solve commonly occurring problems in software development.
• It provides basic and essential source code snippets to the programmers that can
lead to clean and maintainable code.
• It contains various classes and methods that perform common tasks such as string
tokenization, date and time formatting, Java Collections implementation, etc.
• The statement import java.util.*; is used to load all the functionalities provided
by the java.util package.
• The statement import java.util.Scanner; imports the Scanner class available in
the java.util package. This class is widely used to take input from the user in a
Java program.
• Example:
import java.util.Calendar;public class CalDemo
{
public static void main(String[] args)
{
Calendar calendar = Calendar.getInstance();
String[] month = new String[] {"January", "February", "March", "April",
"May", "June", "July", "August","September", "October", "November",
"December"
};
System.out.println("Current Month = " +
month[calendar.get(Calendar.MONTH)]);
}
}

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

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

choice lists, allowing event listeners to respond to changes in item selection or


state.

• 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.

• Platform independent and portable -


o Java can be easily moved from one computer to another, anywhere and
anytime.
o Popular language for programming on Internet.
o 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.

• Object oriented -
o It is a true object – oriented language.
o All program code and data reside within objects and classes.

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

o It has an extensive set of classes, arranged in package, that can be used in


various programs by inheritance.

• Robust and secure -


o It is a robust language.
o It has strict compile time and run time checking for data types.
o It is designed as a garbage – collected language.
o It incorporates the concept of exception handling.
o It ensures that no viruses are communicated with an applet.
o Absence of pointers ensures that programs cannot gain access to memory
locations without proper authorization.

• 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.

• Simple, small and familiar -


o It is a small and simple language.
o It doesn’t use pointers, preprocessor header files, goto statement etc.
o It eliminates operator overloading and multiple inheritance.
o To make Java familiar, it was modeled on C and C++ languages and uses
many constructs of C and C++.
o Java is a simplified version of C++.

• Multithreaded and interactive -


o Multithreaded means handling multiple tasks simultaneously.
o Java need not wait for the application to finish one task before beginning
another.
o It improves the interactive performance of graphical applications.

• 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.

• Dynamic and extensible -


o It is a dynamic language.
o It is capable of dynamically linking in new class libraries, methods and
objects.
o It supports functions written in C and C++, which are known as native
methods.
o Native methods are linked dynamically at runtime.

• 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.

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

2. Describe the structure of the Java program with an example.


A. Structure –
Documentation section Suggested
Package statement Optional
Import statements Optional
Interface statements Optional
Class definitions Optional
Main method class
{ Essential
Main method definition
}

• 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[])

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

{
//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.

3. What are command line arguments? Explain with an example.


A.
• Command line arguments are parameters that are supplied to the application
program at the time of invoking it for execution.
• Any arguments provided in the command line are passed to the array args as its
elements.
• Ex:
o javac ComLineTest.java
o java ComLineTest we are wonderful kids
• In the following example ComLineTest is the name of the file. The above
command line contains four arguments.
o we -> args[0]
o are -> args[1]
o wonderful -> args[2]
o kids -> args[3]

• Use of command line arguments


class ComLineTest
{
public static void main(String args[])
{
int count;
count=args.length;
System.out.println(“Number of arguments= “ + count);
}
}

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

o Syntax: The main method in Java is defined to accept an array of String


objects.
o Accessing Arguments: Each command line argument is stored as a string
in the args array. The length of this array (args.length) tells us how many
arguments were passed.
o Usage: These arguments can be used to control the program's flow, provide
input data, or configure the program dynamically.

4. Explain operators and expressions in Java with examples.


A. Java supports many kinds of operators.
Operators can be applied on variables or constants.
The various types of operators are:

• 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-

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

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.

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

Syntax: num1 /= num2;


Example: a /= 10 This means, a = a / 10

• 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;

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

5. Describe the branching constructs in Java with examples.


A. Branching structures in Java include conditional control structures and switch.
1. Conditional control structure (Branching):
a) if:
Syntax:
if (condition)
{
statements
}
Explanation:
o If structure is also called as conditional statement.
o In If, statements get executed only when the condition is true.
o It omits the condition based statements when the condition is false.
o Braces are not necessary if only one statement is related to the condition.
Example:
if ( x > 0 )
System.out.println(“positive”);
b) if else:
Syntax:
if (condition)
{
Statements
}
else
{
Statements
}
Explanation:
o Statements in if block get executed only when the condition is true and
statements in else block get executed only when the condition is false.
Example:
if ( x > y )
System.out.println( “x is big”);
else
System.out.println( “y is big or equal ”);
c) if else if:
Syntax:
if (condition1)
{
Statements
}
else if (condition2)
{
Statements
}
else if (condition3)
{
Statements
}

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

.
.
.
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

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

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;
}
}
}

2. Jumping control structure:


a) break:
Explanation:
o The break quits the control from corresponding iterative loop.
o The break is valid only in iterative loops and switch.
o It is used to bring the control out of iterative loops intermediately.
Example:
for ( i=1;i<=10;i++)
{
System.out.println(“ hello”);
if (i==5)
break;
}
/* prints hello 5 times */
b) continue:
Explanation:
o continue moves the control to the first statement in the corresponding
iterative loop.
o “continue” is valid only in iterative loops.

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

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.

6. Discuss the looping constructs in Java with examples.


A. Looping structures include Iterative control structures. They are called loops because
the statements in those structures will be repeatedly executed as long as the condition is
true i.e. till the condition becomes false.
a) for loop:
Syntax:
for ( expression1; condition;expression2)
{
Statements
}
Explanation:
o Statements get executed as long as the condition is true.
o Generally expression1 includes initializing statements and expression2
includes statements that use increment, decrement, and assignment
operators.
Example:
for( i=1 ; i<=10 ; i++)
System.out.println(“hello”);
/* prints hello 10 times */
b) while loop:
syntax:
while ( condition )
{

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

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

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

7. What is an array? How to create an array in Java? Explain with examples.


A. An array is a data structure in Java that allows you to store multiple values of the
same type in a single variable. Each value in an array is called an element, and each
element is accessed by its numerical index, starting from 0.
Creating an array in Java involves three steps:
Declaration: Declaring the array variable.
Instantiation: Creating the array using the new keyword.
Initialization: Assigning values to the array elements.
Example 1: Integer Array
Declaration, Instantiation, and Initialization
public class ArrayExample
{
public static void main(String[] args)
{
// Step 1: Declaration
int[] numbers;
// Step 2: Instantiation
numbers = new int[5]; // An array to hold 5 integers
// Step 3: Initialization
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Accessing and printing the array elements
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
In this example:
The array numbers is declared to hold integers.
The array is instantiated with a size of 5.
The array is initialized with values 10, 20, 30, 40, and 50.
A loop is used to access and print each element in the array.

Example 2: String Array


Combined Declaration, Instantiation, and Initialization
public class ArrayExample
{

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

public static void main(String[] args)


{
// Step 1: Declaration
int[] numbers;
// Step 2: Instantiation
numbers = new int[5]; // An array to hold 5 integers
// Step 3: Initialization
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Accessing and printing the array elements
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
In this example:
The array fruits is declared, instantiated, and initialized in a single line with values
"Apple", "Banana", "Cherry", "Date", and "Elderberry".
A loop is used to access and print each element in the array.

Example 3: Multi-Dimensional Arrays


ava also supports multi-dimensional arrays, such as two-dimensional arrays, which are
useful for representing matrices or tables.
public class TwoDimensionalArrayExample
{
public static void main(String[] args)
{
// Declaration and instantiation
int[][] matrix = new int[3][3];
// Initialization
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[1][0] = 4;
matrix[1][1] = 5;
matrix[1][2] = 6;
matrix[2][0] = 7;
matrix[2][1] = 8;
matrix[2][2] = 9;

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

// Accessing and printing the array elements


for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[i].length; j++)
{
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
In this example:
A two-dimensional array matrix is declared and instantiated with dimensions 3x3.
The array is initialized with values representing a 3x3 matrix.
Nested loops are used to access and print each element in the two-dimensional array.

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.

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

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.

d] Multiple Inheritance (Through Interfaces)


In Multiple inheritances, one class can have more than one superclass and inherit features
from all parent classes. Java does not support multiple inheritances with classes, we can
achieve multiple inheritances only through Interfaces. Here class C is derived from
interfaces A and B.

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.

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

2. Explain polymorphism in Java with examples.


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:
a) Compile-time polymorphism
b) Runtime polymorphism
a) Compile time polymorphism
• Compile-time polymorphism or early binding or static polymorphism is obtained
through method overloading.
• The term method overloading allows us to have more than one method with the
same name.
• Since this process is executed during compile time, that's why it is known as
Compile-Time Polymorphism.
• Binding refers to connecting the function call to the function body.
• It is achieved by overloading methods, operator overloading, and by changing the
signature of the method.
• Overloading of methods is done by the reference variable of the class.
• Operator overloading is done by extending the functionality of an operator with
different functionalities.
• The term signature of method refers to parameters and their types along with the
return value and its type.
• Example:
public class OverloadingTest
{
void addition()
{
int a=10;
float b=6.7f;
float sum=a+b;
System.out.println("Sum by using default values is "+sum);
}
void addition(int a, int b)
{
int sum=a+b;
System.out.println("Sum of two integer values is "+sum);
}
void addition(float a,float b)
{
float sum=a+b;
System.out.println("Sum of two float values is "+sum);
}
public static void main(String args[])
{
OverloadingTest ovl=new OverloadingTest();
ovl.addition();
ovl.addition(5,10);
ovl.addition(1.5f,8.3f);
}
}

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

b) Run time polymorphism


• It is also called dynamic binding.
• It is a process in which a call to an overridden method is resolved at runtime
• In this process, an overridden method is called through the reference variable of a
superclass.
• If the reference variable of Parent class refers to the object of Child class, it is
known as upcasting.
• Ex:
• class A{}
• class B extends A{}
• A a=new B(); //upcasting
• In run time polymorphism, method invocation is determined by JVM and not by
the compiler.
• In dynamic binding, the sub class method overrides the super class method.
• Example:
class A
{
int x;
A(int x)
{
this.x=x;
}
void display()
{
System.out.println(“A ------- x=“ + x);
}
}
class B extends A
{
int y;
B(int x,int y)
{
super(x);//passes values to super class
this.y=y;
}
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();
}
}

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

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.

4. Explain the concept of interface in Java with an example.


A.
• A large number of real – time applications require the use of multiple inheritance
(inheriting methods and properties from distinct classes).
• An interface is basically a kind of class, but with a major difference i.e. the
difference is that interfaces define only abstract methods and final fields (do not

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

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);
}

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

}
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));
}
}

5. Explain the steps to create a user-defined package in Java with an example.


A. Creating packages:
• Declare the package at the beginning of the file using the form package
packagename;
• Define the class that is to be put in the package and declare it public.
public class Classname
{
body of class
}
• Create a subdirectory named packagename under the directory. The
subdirectoryname must match the packagename.
• Save the file by giving Classname.java as the file name in the subdirectory
created.
• Compile the file to create the .class file in the subdirectory.
Accessing a package:
• There are two ways of accessing a package, either by using a fully qualified
classname or by using a shortcut approach through import statement.
• The same approach is used to access user – defined packages also.
• Syntax:
import packagename1.packagename2.Classname;
Or
import packagename.*; // here packagename may denote a single package or a
hierarchy of packages
Adding a class to an existing package:
Step1: Creating a package with one class A and saving.
package p1;
public class A
{
//body of A
}
Step2: Adding one more class B to the package p1
To do this, define the class B, make it public and place the package statement. i.e.,
package p1;

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

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()
{

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

//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();
}
}

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

HTML Code
<html>
<body>
<applet
code="MouseEvents.class"
height=100
width=700>
</applet>
</body>
</html>

2. Explain keyboard events in Java with an example.


A. A keyboard event is generated when a key is pressed, released, or typed. The relevant
method in the listener object is then invoked, and the KeyEvent is passed to it.
Some of the fields for java.awt.event.KeyEvent class:
• static int KEY_PRESSED --The "key pressed" event.
• static int KEY_RELEASED --The "key released" event.
• static int KEY_TYPED --The "key typed" event.
• char getKeyChar(): Returns the character associated with the key in this event.
• static String getKeyText(int keyCode): Returns a String describing the keyCode,
such as "HOME", "F1" or "A".
• int getKeyLocation(): Returns the location of the key that originated this key
event.
Methods of KeyListener interface:
• public abstract void keyPressed (KeyEvent e); - It is invoked when a key has been
pressed.
• public abstract void keyReleased (KeyEvente); - It is invoked when a key has been
released.
• public abstract void keyTyped (KeyEvent e); - It is invoked when a key has been
typed.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class KeyBoardEvents extends Applet implements KeyListener
{
String str="";
public void init()
{
//The listener object created from that class is then registered with a component using
the
//component's addKeyListener method.
addKeyListener(this);
//requestFocus() makes a request that the given Component gets set to a focused state.

Downloaded by Kamini Ganesan G ([email protected])


lOMoARcPSD|45714441

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>

Downloaded by Kamini Ganesan G ([email protected])

You might also like