0% found this document useful (0 votes)
832 views28 pages

Java 5marks Imp Questions

Jaava 5 marks important question

Uploaded by

Nader Macz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
832 views28 pages

Java 5marks Imp Questions

Jaava 5 marks important question

Uploaded by

Nader Macz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 28

JAVA PROGRAMMING

5 marks important questions

1. Explain the features of Java.


Features of Java are:
❖ Simple
❖ Object-oriented
❖ Portable
❖ Platform independent
❖ secured
❖ Robust
❖ Architecture neutral
❖ High Performance
❖ Multithreaded
❖ Distributed
❖ Dynamic
i. Simple
->Java is designed to be easy to learn and its syntax is simple, clean and easy to understand.
->Java syntax is based on the C++
ii. Object Oriented
->In Java, everything is an Object. Java can be easily extended since it is based on the Object
model
iii. Platform Independent
->when Java is compiled, it is not compiled into platform specific machine, rather into
platform independent byte code.
->This byte code is distributed over the web and interpreted by the Virtual Machine (JVM)
on whichever platform it is being run on. (write Once Run Anywhere)
iv. Robust
->It uses strong memory management.
->There is no pointers that avoids the security problems
->There is automatic garbage collection.
->Exception handling.
v. Architecture-neutral
->Java compiler generates an architecture-neutral because there are no implementation
dependent features. For example the size of primitive types is fixed.
vi. Portable
->Java is portable because it facilitates us to carry java byte code to any platform. It does not
require any implementation.
->High Performance.

1
vii. Distributed
->java is distributed because it facilitates users to create distributed applications in java.
->RMI and EJB are used for creating distributed applications
->This features of java makes us able to access files by calling the methods from any machine
on the internet.
viii. Multithreaded
->Multithreading in Java is a process of executing multiple threads simultaneously.
->The main advantage of multi-threading is that it does not occupy memory for each thread.
It shares a common memory area for each thread .
ix. Dynamic
->Java is dynamic language.it is capable of dynamically linking the class libraries, methods
and objects. Java program supports functions like written in C and C++.
x. Interpreted
->java can be interpreted in any platforms.it is platform independent
xi. Secure
->the java class libraries have several API that relates to security. The API is involved in
secure communication.

2. Explain Java program structure.

Java program structure

2
(i) Documentation section
> The documentation section comprises a set of comment lines giving the name of the author
and the details.
> Comments must explain why and what of classes and how of the algorithms.
> There are three types of comments that Java supports
❖ Single line Comment
❖ Multi-line Comment
// Single line comment is declared like this
/* Multi line comment is declared like this and can have multiple lines as a comment */
(ii) Package Statement
The first statement allowed in java file is a package statement. statement declares a
package name and informs the compiler th classes defined here belong to this package
Example
package student; This package statement is optional
(iii) Import statement
The import statement should be the next statement after the statement. This is similar to
#include statement in c program
Example Import java.awt.*; Import java. Lang.*; Import java.io.*; Import java.net.*; Import
java. Applet.*;
(iv) Interface statement
An interface is like a class but includes a group of method declarations. This is an optional
This is used only when we wish to implement the multiple inheritance.
(v) Class definition
Classes are primary and essential elements of a java program.
The classes are used to map the objects of real world problems.
A java program may contain multiple class definitions
(vi) Main method definition
Java stand-alone program requires a main method as its starting point, this class is a essential
part of a java program.The main method creates objects of various classes and establishes
communication between them.
Example program:-
Class addition
public static void main(String args[])
int a=10,b=20,c;
c=a+b;
System.out.println(“Addition of two numbers = “+c);

3
3.What is a vector? Mention its advantages over an array.
Vector is like the dynamic array which can grow or shrink its size. This class can be used to
create a generic dynamic array known as vector than can hold objects of any type and any
number. It is found in the java.util package.

Vectors are created like arrays as follows

Vector v = new Vector();


Example
Vector list = new Vector();
v.addElement (4); v.addElement(6) v.addElement(©)

Advantages of vector
❖ It is convenient to use vectors to store objects
❖ A vector can be used to store a list of objects that may vary in size.
❖ We can add and delete objects from the list as and when required.

4.What are static variables and static methods.

Static variables
➢ Static variables are special type of variables that are accessed without using a particular
object.
• The static variables are common to all the objects
➢ The static variables are also called as class variables
Syntax
static datatype variablename;
Example
class demo
{
static int a;
int b;
}
Static methods
➢ The method can also be declared as static
➢ The static methods are also called as class members.
❖ It is associated with a class rather than the objects of that class.
❖ Static method access only the static variables.
Example for static method
Class demo
{
Int x;
Static int j;
void static method1()

4
{
System.out.println(j);
}
}

5. Explain the following with an example:

i) Method overloading.
ii) Method overriding.
iii) Abstract method.
iv) Abstract class.

❖ Methods overloading
➢ If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
➢ Method overloading is used when objects are required to perform similar tasks but using
different input parameters
❖ Method Overriding
➢ Declaring a method in sub class which is already present in parent class is known as
method overriding.
➢ When a method in a subclass has the same name, same parameters and same return type as
a method in its super-class, then the method in the subclass is said to override the method in
the super-class.
❖ Abstract class: It is a restricted class that cannot be used to create objects (to access it, it
must be inherited from another class).
❖ Abstract method: It can only be used in an abstract class, and it does not have a body.
The body is provided by the subclass (inherited from)
Example : Refer the examples in PPT

6.Define inheritance. Explain the types of inheritance supported by Java.

Inheritance
❖ Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of another object.
❖ It is an important part of OOPs (Object Oriented programming system). For example, a
child inherits the traits of his/her parents
❖ Single level Inheritance: In Single Inheritance one class extends another class (one class
only)

Example for Single inheritance


class Employee
{

5
int salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
}
❖ Multi level inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the
derived class also act as the base class to other class.
Class A
{
public void methodA()
{
System.out.println("Class A method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("class B method");
}
}
Class C extends B
{
public void methodC()
{
System.out.println("class C method");
}}
Class expinheri
{
public static void main(String args[])
{
C obj = new C();
obj.methodA(); //calling grand parent class method
obj.methodB(); //calling parent class method
obj.methodC(); //calling local method
}
}
❖ Hierarchical Inheritance
In this inheritance one class is inherited by many sub classes. A is parent class (or base class)
of B,C & D.
class Animal

6
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class Cat extends Animal{
void meow()
{
System.out.println("meowing...");}
}}
class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
Dog d = new Dog();
d.bark();
d.eat();
}
}
❖ HYBRID INHERITANCE
Hybrid inheritance is a combination of one or more inheritance.

7. Explain any five string methods with examples.


concat()

Appends a string to the end of another string . (return type -String)


Example :
String str1 = “Hello”;
String str2 = “world”;
String str3 = str1.concat(str2);
System.out.println(str3);
Result : Hello world

7
charAt()

Returns the character at the specified index (position)


(return type -char)

Example

String str = “Computer”;


System.out.println(“The Character available in first position is :”+str.charAt(0));
Result
C

substring()

Extracts the characters from a string, beginning at a specified start position, and through
the specified number of character String

Example
String s = “Watermelon”;
System.out.println(“The substring is :”+s.substring(5,9));
Result
Melon

toLowerCase()

This method is used to convert all characters in uppercase into a lowercase.

Example
String str = “HOUSE”;
System.out.println(“The converted string is :”+str.toLowerCase());
Result
house

toUpperCase()

This method is used to convert all characters in lowercase into a uppercase.

Example
String str = “house”;
System.out.println(“The converted string is :”+str.toUpperCase());
Result
HOUSE

8
8. Explain visibility control in Java.
Access Control is used to control the access to the class members. In which parts of the
program a class member is accessible, is determined by the “access specifier”/”access
modifier”.
Types of Access Specifiers
In Java there are four types of access specifiers.
They are:
1) public
2) protected
3) default / no-modifier / package-private
4) private

Public Access
Public class members are accessible within the class, outside the class and from everywhere
else.
Friendly Access
When no access modifier is specified, then the member defaults to a limit version of public
accessibility known as “friendly” level of access. The difference between the “public” access
and “friendly” access is that the public modifier makes fields visible in all classes, regardless
of their package while the friendly access makes fields visible only in the same package, but
not in other packages.
Protected Access
The visibility level of a “protected access” field lies between the public access and Friendly
access Protected class members are accessible within the class, in subclasses in other
packages.
Private Access
Private class members are accessible within the class only. therefore not accessible in
subclasses.

9. What is an interface? Explain with an example how a class implement an interface.

• An interface in Java is a blueprint of a class. It has abstract methods and variables.


• The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body.
• It is used to achieve abstraction and multiple inheritance in Java

Syntax for declaring the interfaces


interface <interface_name>
{
// public static variables
// public abstract methods
}

9
Program to implement interfaces in java

interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
public class TestInterface2{
public static void main(String[] args){
SBI a=new SBI();
System.out.println("ROI OF SBI: "+a.rateOfInterest());
PNB b=new PNB();
System.out.println("ROI OF PNB: "+b.rateOfInterest());
}
}

10.Explain the cycle of a thread with a neat diagram


Life cycle of the thread – Thread states
A thread in Java at any point of time exists in any one of the following states. A thread lies
only in one of the shown states at any instant:
1.Newborn state
2.Runnable state
3.Running state
4.Blocked state
5.Dead state

10
New born state:
• When we create the thread object, the thread is born and is said to be in new born state.
• At this stage, Either any one of the following are possible
(i) Schedule it for running using start() method
(ii) Kill it using stop() method.
Runnable state:
• Runnable state means that the thread is ready for execution and is waiting for the
availability of the CPU.
• A multi-threaded program allocates a fixed amount of time to each individual thread. Each
and every thread runs for a short while and then pauses and relinquishes the CPU to another
thread,
• When we call start() function on Thread object, it’s state is changed to Runnable. The
control is given to Thread scheduler to finish it’s execution.
Running state:
• Running means that the processor has given its time to the thread for its execution.
• The methods used in this stage are
suspend()
resume()
sleep()
wait()
Notify()
Blocked state:
• When a thread is temporarily inactive, then it’s in one of the following
states:
• Blocked

11
• Waiting
• For example, when a thread is waiting for I/O to complete, it lies in the blocked state. A
thread in this state cannot continue its execution any further until it is moved to runnable
state.
Dead state:
Once the thread finished executing, it’s state is changed to Dead and it’s considered to be not
alive.
A thread terminates because of either of the following reasons:
• Because it exists normally. This happens when the code of thread has entirely executed by
the program.
• Because there occurred some unusual erroneous event, like segmentation fault or an
unhandled exception.

11. Explain the line “public static void main(String args[])


public : it is a access specifier that means it will be accessed by publically.
static : it is access modifier that means when the java program is loaded then it will create the
space in memory automatically.
void : it is a return type i.e it does not return any value.
main() : it is a method or a function name.
String args[] : its a command line argument it is a collection of variables in the
string format.

12.Explain the History and Evolution of Java


James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991. The small team of sun engineers called Green Team.
• Initially designed for small, embedded systems in electronic appliances like set top boxes,
television.
• But it was too advanced technology for the digital cable television industry at the time
• Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
• After that, it was called Oak and was developed as a part of the Green project.
• Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A.,
France, Germany, Romania, etc.
• Java is an island of Indonesia where the first coffee was produced (called java coffee)
In 1990 James gosling,bill joy and others at microsystems began developing a language
called "OAK"
In 1991, green team initiated the Java project
In1994, sun's hot Java browser appeared In 1995, Java 1.0 was implemented.it follows
WORS (write once run anywhere) The latest version of Java is Java 14 on march 17 th 2020

13.Differentiate constructors and methods


• Constructor is used to initialize an object whereas method is used to exhibits
functionality of an object.
• Constructors are invoked implicitly whereas methods are invoked explicitly.
12
• Constructor does not return any value where the method may/may not return a value.
• In case constructor is not present, a default constructor is provided by java compiler,
in the case of a method, no default method is provided.
• Constructor should be of the same name as that of class. Method name should not be
of the same name as that of class.

14. What is the difference between overloading and overriding?

s.no METHOD OVERLOADING METHOD OVERRIDING


1. Method overloading is a compile Method overriding is a run time polymorphism.
time polymorphism.
2. It helps readability of the program. While it is used to grant the specific
implementation of the method which is already
provided by its parent class or super class.
3. It occurs within the class. It is performed in two classes with inheritance
relationship.
4. May or may not require Method overriding always needs inheritance.
inheritance. In this methods must
have same name and different
parameter.
5. Method overloading, return type In method overriding return type must be the
may or may not be the same, but same.
we have to change the parameter.

15. What is constructor overloading? Write a program to demonstrate the same.


Ans. Constructor overloading is a concept of having more than one constructor with different
parameters list, in such a way so that each constructor performs a different task.
class Box
{
double width, height,depth;
// constructor used when all dimensions
// specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume()
{
Return width * height * depth;
}
}

13
16. What is package? How do you create and access a package?
A package in Java is used to group related classes. Group of several class definitions are
called a Package. Packages are divided into two categories:
• Built-in Packages (packages from the Java API)
• User-defined Packages (create our own packages)
* Java API package contain built-in classes provided by Java
* The user defined packages are the packages which the programmer develops.
Built-in packages
Java Provides so many built-in packages. The packages are used inside the java program by
using import statement.
Example
Import java.io.*;
Import java.util.*;

Some of the Java API packages are


java.lang It includes Language support classes.
java.util Language utility classes such as vectors, hash tables, random numbers, data, etc.
java.io Input/output support classes. They provide facilities for the input and output of data.
java.applet Classes for creating and implementing applets.
java.net Classes for networking. They include classes for communicating with local
computers as well as with internet servers.
java.awt Set of classes for implementing graphical user interface. They include classes for
windows, buttons, lists, menus and so on.
User – defined Packages
The users of the Java language can also create their own packages. They are called user-
defined packages. User defined packages can also be imported into other classes and used
exactly in the same way as the Built-in packages.
The general form of creating packages is
Package packagename;
Example
Package pkg1;
Example program for package
package pack1;
public class Simple
{
void msg1()
{
System.out.println("Welcome to package");
}
}
public class simple1
{
void msg2()
{

14
System.out.println(“hello world”);
}
}
/* Import the user defined package pack1 in another program */
import pack1.Simple;
Import pack1.simple1;
class sample
{
public static void main(String args[])
{
Simple obj = new Simple();
obj.msg1();
Simple1 obj1 = new Simple1();
obj1.msg2();

}
}

17 What is method overriding? Write a program to demonstrate method overriding


Declaring a method in sub class which is already present in parent class is known as method
overriding. When a method in a subclass has the same name, same parameters and
same return type as a method in its super-class, then the method in the subclass is said to
override the method in the super-class.

//Java Program to demonstrateing the use of Java Method Overriding


//Creating a parent class.
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}

15
18. Explain the difference between JDK and JRE?

JDK
• Java development kit.
• It is a software development kit to develop applications in java.
• When you download JDK, JRE is also downloaded, and don’t need to download it
separately.
• It contains JRE and tools such as compilers and debuggers for developing java applications.
JRE
• Java Realtime Environment.
• It is a software package that provides java class libraries, along with java virtual
machine(JVM)and other components to run applications written in java programming.
• JRE is the support of JVM.
• JRE=JVM + class libraries.
• It contains JVM, supporting libraries, and other components to run a java program.
• It does not contain any compiler and debugger.

19. What is Method overloading ? Explain with example.


• If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
• Method overloading is used when objects are required to perform similar tasks but
using different input parameters.
class MethodOverloading
{
void display(int a)
{
System.out.println("Arguments: " + a);
}
void display(int a, int b)
{
System.out.println("Arguments: " + a + " and " + b);
}
}
class mainclass
{
public static void main(String[] args)
{
MethodOverloading m = new MethodOverloading();
m.display(1);
m.display(1, 4);
}
}

16
20 . Explain final keyword with example.
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
Variable
method
class
final variable
In Java, when final keyword is used with a variable of primitive data types, value
of the variable cannot be changed.
Example
public class finalexample
{
public static void main(String args[])
{
final int i= 30;
---------
}
}

final Methods
We can declare a method as final, once we declare a method as final it cannot be overridden.
We cannot modify a final method from a sub class.
Example for final method
class Bike
{
final void run()
{System.out.println("running");}
}

class Honda extends Bike


{
void run() // error – final method cannot be used in subclass
{
System.out.println("running safely with 100kmph");
}
}
Final class
When a class is declared with final keyword, it is called a final class. A final class
cannot be extended(inherited).
final class A
{
final void m1()
{
System.out.println("This is a final method.");

17
}
}
class B extends A // error - The final class A cannot be extended
{
void m1()
{
System.out.println(“this is not final class”);
}
}

21. How the Exception handling is implemented in Java Programming?


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc
.Java exception handling is managed via five keywords: try, catch, throw,
throws and finally.
Try and catch block
• To handle a run-time error, simply enclose the code that requires to be
monitored inside a try block.
• Immediately following the try block, a catch clause that specifies the
exception type that has to be caught is included.

Finally block
When a finally block is defined, this is guaranteed to execute, regardless of whether or not
an exception is thrown.

The syntax for try and catch block is


try
{
Statement that causes an exception
}
catch( )
{
Statement that handles the exception
}
Example
class Exc2
{
public static void main(String args[])
{
int d,a;
try
{
d = 0;
a = 42/d;

18
}
catch (ArithmeticException e)
{
System.out.println ("Division by zero");
}
finally
{
System.out.println(“final block”);
}}

Throw clause
➢ The throw clause is used when the programmer want to throw an exception explicitly and
wants to handle it using catch block.
➢ The general form of throw is throw throwableobject;
Example
throw e;

throws clause
The throws clause is used when the programmer does not want to handle
the exception in the method and throw it out of method.
Example
Class demo
{
public static void main(String args[]) throws IOException
{
-------------
}

22. Explain the concept of Multi threading in java with example .


• Multi threading is a conceptual programming paradigm where a program is
divided into two or more subprograms which can be implemented at the same
time in parallel.
• Multithreading refers to two or more threads executing concurrently in a single
program.
Creation of thread by extending Thread class
• For creating a thread ,first create a new class that extends Thread.
• Then include the run() method and then to create an instance of that class.
Example for Multithreading
class mythread extends Thread
{
public void run()
{

19
System.out.println(“Myclass is running”);
}
}
class mainclass
{
public static void main(String args[])
{
mythread t1 = new mythread();
t1.start();
}}

Creation of thread by implementing Runnable


class A implements Runnable
{
public void run()
{
System.out.println(“Myclass is running”);
}
}
class mainclass
{
public static void main(String args[])
{
A a = new A();
Thread t1 = new Thread(a);
t1.start();
}}

23 . Explain the thread priorities.


Java permits us to set the priority of a thread using the setpriority() method .
The syntax is
Threadname.setPriority(int number);
Minimum priority = 1
Normal priority = 5
Max priority = 10
Example
t1.setPriority(1);
t2.setPriority(5);
t3.setPriority(10);

20
24 . Explain the life cycle of Applet

The Applet state includes


1. Born on initialization state
2. Running state
3. Idle state
4. Dead or destroyed state

Initialization state
Applet enters the initialization state when it is first loaded.This is achieved by calling the
init() method of Applet class.
public void init()
{
}
Running state
Applet enters in to running state when the system calls start() method of Applet class.This
occurs automatically after the applet is initialized.
public void start()
{
}
Idle State
An applet becomes idle when it is stopped from running . Applet enters into idle state when
the system calls start() method.
public void stop()
{
}
Dead state

21
An applet becomes idle when it is stopped from running . Applet enters into idle state when
the system calls start() method.
public void stop()
{
}

25. Explain any five methods in Graphics class or AWT Package.

Java’s Graphics class includes methods for drawing many different types of shapes from
simple lines to polygon . Graphics class is available in AWT package.

Paint() method
paint(): The paint() method is used to redraw the output on the applet display area. The
paint() method executes after the execution of start() method.

public void paint(Graphics g)


{
g.drawString(“Hello”,10,100);
}

drawOval() method
This method is used to draw the oval method.
Example
Public void paint(Graphics g)
{
g.drawOval(20,20,200,120);
g.setColor(Color.green);
g.fillOval(20,20,200,120);
}

drawLine()
This method is used to draw the lines on the Appletviewer screen.
Example
public void paint(Graphics g)
{
g.drawLine(10,20,170,40);
g.drawLine(10,20,170,40);
g.drawLine(10,20,170,40);
}
drawArc()
This method is used to draw the arcsymbol on the Appletviewer screen.

setColor()

22
This method is used to set the colour of the shape.
Example
public void paint(Graphics g)
{
g.drawArc(20,20,200,120);
g.setColor(Color.red);
g.fillArc(20,20,200,120);
}

26.Explain the concepts and steps of Applets with example.

• Applets are small programs that are primarily used in internet computing.
• They can be transported over the internet from one computer to another computer.
• Applets run using Appletviewer or any web browser that supports java.
Applet code uses the services of two classes
• Applet
• Graphics
The Applet class which is contained in the java.applet package.
The Graphics class which is contained in the java.awt package.
The paint() method of the Applet class , when it is called, actually displays the results of the
applet code on the screen.
Example :
import java.awt.*;
import java.applet.*;
public class hellojava extends Applet
{
public void paint(Graphics g)
{
g.drawString(“Hello Java”,10,100);
}}

<applet code = “hellojava.class” width=200 height=200>


</applet>

Execution
Appletviewer hellojava.class

27. Explain the use of FileInputStream class and FileOutputStream class.

FileInputStream
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.

23
Following constructor takes a file name as a string to create an input stream object to
read the file −
InputStream f = new FileInputStream("C:/java/hello");

FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would
create a file, if it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to
write the file −
OutputStream f = new FileOutputStream("C:/java/hello")

28. Explain the use of Data Input Stream and Data Output Stream with an example.

DataOutputStream
DataOutputStream implements the DataOutput interface.This interface defines methods that
write all of java’s primitive types to a file. The constructor for DataOutputStream is
DataOutputStream(OutputStream os);

The OutputStream is the stream to which data is written. The most commonly used output
methods are
Void writeBoolean(Boolean val)
Void writeInt(int val)
Void writeFloat(float val)

DataInputStream
DataInputStream implements the DataInput interface.This interface provides the methods for
reading all of java’s primitive data types.. The constructor for DataInputStream is
DataInputStream(InputStream ins);

The InputStream is the stream used to read input from a file. The most commonly used input
methods are
Void readBoolean(Boolean val)
Void readInt(int val)
Void readFloat(float val)

29. Give the classification on “java.io.IoException”.


Exceptions in java are the way of indicating the occurrence of abnormal condition in the
program.The most occurred I/O exceptions are
1. EOFException - Signals that an end of the file reached.

24
2. FileNotFoundException – If we are trying to access the file and the file does not
exists, we will get this exception.
3. InterruptedIOException – It warns that an I/O operation has been interrupted.
4. IOException – It is very generic exception of I/O

30. Explain bitwise and logical operators in java.

Bitwise Operators
Bitwise operators are used to performing manipulation of individual bits of a
number. They can be used with any of the integral types (char, short, int, etc).
They are used when performing update and query operations of Binary
indexed tree.
• BitwiseOR(|)
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 gives
0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise OR Operation of 5 and 7
0101
| 0111
________
0111 = 7 (In decimal)
• BitwiseAND(&)
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 gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise AND Operation of 5 and 7
0101
& 0111
________
0101 = 5 (In decimal)
• BitwiseXOR(^)
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

25
1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise XOR Operation of 5 and 7
0101
^ 0111
_______
0010 = 2 (In decimal)
• BitwiseComplement (~)
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, means it makes every 0 to 1, and every 1 to 0.
For example,
a = 5 = 0101 (In Binary)
Bitwise Compliment Operation of 5
~ 0101
________
1010 = 10 (In decimal)

LOGICAL OPERATORS
Logical operators are used to check whether an expression is true or false . They
are used in decision making.

Operator Example Meaning

&& (Logical expression1 && true only if both expression1 and


AND) expression2 expression2 are true

|| (Logical expression1 || true if either expression1 or


OR) expression2 expression2 is true

! (Logical true if expression is false and vice


!expression
NOT) versa

example
26
• (5 > 3) && (8 > 5) returns true because both (5 > 3) and (8 >

5) are true .
• (5 > 3) || (8 > 5) returns true because the expression (8 > 5) is true .
• !(5 == 3) returns true because 5 == 3 is false .

31. Explain the methods or events in MouseListener interface and


keyboardListener interface.

Java MouseListener Interface


The Java MouseListener is notified whenever you change the state of mouse. It is
notified against MouseEvent. The MouseListener interface is found in
java.awt.event package. It has five methods.

Methods of MouseListener interface


The signature of 5 methods found in MouseListener interface are given below:

1. public abstract void mouseClicked(MouseEvent e);


2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);

Java KeyListener Interface


The Java KeyListener is notified whenever you change the state of key. It is notified
against KeyEvent. The KeyListener interface is found in java.awt.event package. It
has three methods.

Methods of KeyListener interface


The signature of 3 methods found in KeyListener interface are given below:

27
1. public abstract void keyPressed(KeyEvent e);
2. public abstract void keyReleased(KeyEvent e);
3. public abstract void keyTyped(KeyEvent e);

************************************************************

28

You might also like