Java 5marks Imp Questions
Java 5marks Imp Questions
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
(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.
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.
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);
}
}
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
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)
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
charAt()
Example
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()
Example
String str = “HOUSE”;
System.out.println(“The converted string is :”+str.toLowerCase());
Result
house
toUpperCase()
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
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
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.
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.*;
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();
}
}
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.
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");}
}
17
}
}
class B extends A // error - The final class A cannot be extended
{
void m1()
{
System.out.println(“this is not final class”);
}
}
Finally block
When a finally block is defined, this is guaranteed to execute, regardless of whether or not
an exception is thrown.
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
{
-------------
}
19
System.out.println(“Myclass is running”);
}
}
class mainclass
{
public static void main(String args[])
{
mythread t1 = new mythread();
t1.start();
}}
20
24 . Explain the life cycle of Applet
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()
{
}
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.
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);
}
• 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);
}}
Execution
Appletviewer hellojava.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)
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
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.
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 .
27
1. public abstract void keyPressed(KeyEvent e);
2. public abstract void keyReleased(KeyEvent e);
3. public abstract void keyTyped(KeyEvent e);
************************************************************
28