Java Imp Qns and Answers
Java Imp Qns and Answers
final is the keyword and access modifier which is used to apply restrictions on a class, method or
variable
Final keyword is used with the classes, methods and variables.
Final method is executed only when we call it.
(1) Once declared, final variable becomes constant and cannot be modified.
(2) final method cannot be overridden by sub class.
(3) final class cannot be inherited.
Finally
finally is the block in Java Exception Handling to execute the important code whether the
exception occurs or not.
Finally block is always related to the try and catch block in exception handling.
1) finally block runs the important code even if exception occurs or not.
(2) finally block cleans up all the resources used in try block
Finally block is executed as soon as the try-catch block is executed.
It's execution is not dependant on the exception.
Finalize
finalize is the method in Java which is used to perform clean up processing just before object is
garbage collected.
finalize() method is used with the objects.
finalize method performs the cleaning activities with respect to the object before its destruction.
finalize method is executed just before the object is destroyed.
2. Import statement
Import statement in Java is helpful to take a class or all classes visible for a program specified
under a package, with the help of a single statement. It is pretty beneficial as the programmer
do not require to write the entire class definition. Hence, it improves the readability of the
program.
Syntax 1:
import package1[.package2].(*);
Here,
package1: Top-level package
package2: Subordinate-level package under package1
*: To import all the classes
1
Syntax 2:
import package1[.package2].(myClass);
Here,
package1: Top-level package
package2: Subordinate-level package under the top-level package
myClass: Import only myClass
throw keyword
Java throw keyword is used throw an exception explicitly in the code, inside the function or the
block of code.
The throw keyword is followed by an instance of Exception to be thrown.
We are allowed to throw only one exception at a time i.e. we cannot throw multiple exceptions.
throw is used within the method
throws
Java throws keyword is used in the method signature to declare an exception which might be
thrown by the function while the execution of the code.
The throws keyword is followed by class names of Exceptions to be thrown.
throws is used with the method signature.
We can declare multiple exceptions using throws keyword that can be thrown by the method. For
example, main() throws IOException, SQLException.
public class TestThrows
{
public static int divideNum(int m, int n) throws ArithmeticException
{
int div = m / n;
return div;
}
}
2
We can divide Graphics class methods into three categories: draw, fill, and miscellaneous. Draw
methods are used to draw lines, curves, and outer boundaries of closed curves and images. Fill
methods fill the interior area of graphics objects. There are also a few miscellaneous methods
that fall in neither categoryfor example, MeasureString and Clear.
Draw Methods
The draw methods of the Graphics class are used to draw lines, curves, and outer boundaries of
closed curves and images. Table 3.2 lists the draw methods of the Graphics class.
Method Description
DrawLine draws a line beween two points specified by a pair of coordinates. DrawLines draws a serie
of lines using an array of points.
DrawArc Draws an arc (a portion of an ellipse specified by a pair of coordinates, a width, a height, a
start and end angles).
DrawLines Draws a series of line segments that connect an array of Point structures.
DrawString Draws the specified text string at the specified location using the
specified Brush and Font objects.
The automatic conversion of primitive into an object is known as autoboxing and vice-versa
unboxing.
boolean Boolean
char Character
3
byte Byte
short Short
int Integer
long Long
float Float
double Double
Example:
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
7. What is Unicode
The Unicode Standard is the universal character representation standard for text in computer
processing. Unicode provides a consistent way of encoding multilingual plain text making it
easier to exchange text files internationally.
ASCII defines 128 characters, which map to the numbers 0–127. Unicode defines (less than)
221 characters, which, similarly, map to numbers 0–221
The Unicode Standard provides a unique number for every character, no matter what
platform, device, application or language. It has been adopted by all modern software
providers and now allows data to be transported through many different platforms, devices
and applications without corruption.
The Unicode Standard defines code points (unique numbers) for characters used in the major
languages written today. This includes punctuation marks, diacritics, mathematical symbols,
technical symbols, arrows, dingbats, and so on. In all, the Unicode Standard provides codes
for over 100,000 characters from the world’s alphabets, ideograph sets, and symbol
collections, including classical and historical texts of many written languages. The characters
can be represented in different encoding forms, such as UTF-8 and UTF-16.
8. What are API?
Java application programming interfaces (APIs) are predefined software tools that easily
enable interactivity between multiple applications.
4
APIs are important software components bundled with the JDK. APIs in Java include classes,
interfaces, and user Interfaces. They enable developers to integrate various applications and
websites and offer real-time information.
The following image depicts the fundamental components of the Java API.
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
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.
Interfaces can have abstract methods and variables. It cannot have a method body.
It cannot be instantiated just like the abstract class.
There are mainly three reasons to use interface. They are given below.
interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
5
System.out.println("Hello");
}
public static void main(String args[])
{
A6 obj = new A6();
obj.print();
}
}
10. What is an Abstract class?
A class which is declared as abstract is known as an abstract class. It can have abstract and
non-abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.
Points to Remember
Example :
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
6
}
}
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot
be accessed from outside the package. If you do not specify any access level, it will be
the default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
7
The Abstract Windowing Toolkit (AWT) has the following five layout managers:
java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.CardLayout
java.awt.GridBagLayout
Sl. LayoutManager & Description
No.
1 BorderLayout - The borderlayout arranges the components to fit in the five regions: east,
west, north, south and centre.
2 CardLayout - The CardLayout object treats each component in the container as a card.
Only one card is visible at a time.
3
FlowLayout - The FlowLayout is the default layout. It layouts the components in a
directional flow.
5 GridBagLayout - This is the most flexible layout manager class. The object of
GridBagLayout aligns the component vertically, horizontally or along their baseline without
requiring the components of same size.
Arithmetic Operators
Unary Operators
8
positive without this, however)
- Unary minus operator; negates
an expression
++ Increment operator; increments
a value by 1
-- Decrement operator; decrements
a value by 1
! Logical complement operator;
inverts the value of a boolean
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
Conditional Operators
&& Conditional-AND
|| Conditional-OR
?: Ternary (shorthand for
if-then-else statement)
Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java
provides statements that can be used to control the flow of Java code. Such statements are
called control flow statements. It is one of the fundamental features of Java, which provides a
smooth flow of program.
Java provides three types of control flow statements.
9
1. Decision Making statements
if statements
switch statement
2. Loop statements
do while loop
while loop
for loop
for-each loop
3. Jump statements
break statement
continue statement
The super keyword in Java is a reference variable which is used to refer immediate parent
class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
10
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
class Animal
{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal
{
void eat()
{System.out.println("eating bread...");
}
void bark()
{System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}
}
16. Static binding and Dynamic binding (Static polymorphism and Dynamic polymorphism)
BASIS FOR
STATIC BINDING DYNAMIC BINDING
COMPARISON
Event Occurrence Events occur at compile time Events occur at run time are
are "Static Binding". "Dynamic Binding".
11
BASIS FOR
STATIC BINDING DYNAMIC BINDING
COMPARISON
There are 8 primitive data types such as byte, short, int, long, float, double, char, and boolean.
Size of these 8 primitive data types wont change from one OS to other.
boolean 1 bit
char 2 byte
12
byte 1 byte
short 2 byte
int 4 byte
long 8 byte
float 4 byte
double 8 byte
Exception Hierarchy
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
Errors are abnormal conditions that happen in case of severe failures, these are not handled by
the Java programs. Errors are generated to indicate errors generated by the runtime environment.
Example: JVM is out of memory. Normally, programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.
13
AWT provides various components like button, label, checkbox, etc. used as objects inside
a Java Program. AWT components use the resources of the operating system, i.e., they are
platform-dependent, which means, component's view can be changed according to the view of the
operating system. The classes for AWT are provided by the Java.awt package for various AWT
components.
20 . SWING in java
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Swing in java is part of Java foundation class which is lightweight and platform independent. It is used
for creating window based applications. It includes components like button, scroll bar, text field etc.
Putting together all these components makes a graphical user interface.
14
1) AWT components are platform- Java swing components are platform-
dependent. independent.
3) AWT doesn't support pluggable look Swing supports pluggable look and feel.
and feel.
The repaint() method is used to call the update() method internally that calls the paint()
method to repaint the component. The paint() and repaint() both are used to paint a
component, but the repaint() method internally calls paint() to paint the component. We cannot
override the repaint() method.
22 What is bytecode?
An event listener in Java is designed to process some kind of event — it "listens" for an event, such as a
user's mouse click or a key press, and then it responds accordingly. An event listener must be connected
to an event object that defines the event.
Event and Listener (Java Event Handling)
15
Changing the state of an object is known as an event. For example, click on button, dragging mouse etc.
The java.awt.event package provides many event classes and Listener interfaces for event handling.
Java Event classes and Listener interfaces
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
An applet is a Java program that can be embedded into a web page. It runs inside the web
browser and works at client side. An applet is embedded in an HTML page using the APPLET or
OBJECT tag and hosted on a web server. Applets are used to make the website more dynamic
and entertaining.
16
A special type of Java program that runs in a Web browser is referred to as Applet. It has less
response time because it works on the client-side. It is much secured executed by the browser under any
of the platforms such as Windows, Linux and Mac OS etc.
two types of Applets
A web page can contain two types of applets: Local applet. Remote applet.
HTML <applet> tag was used to embed the Java applet in an HTML document.
Syntax:-
<!DOCTYPE html>
<html>
<head>
<title>Applet Tag</title>
</head>
<body>
<p>Example of Applet Tag</p>
<applet code="Shapes.class" align="right" height="200" width="300">
<b>Sorry! you need Java to see this</b>
</applet>
</body>
</html>
24. What is a constructor in Java
A constructor in Java is a special method that is used to initialize objects. The constructor is
called when an object of a class is created. At the time of calling constructor, memory for the
object is allocated in the memory. It is a special type of method which is used to initialize the
object.
17
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn't physically exist. It is a specification that provides a runtime environment in which
Java bytecode can be executed. It can also run those programs which are written in other
languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each other.
However, Java is platform independent.
A class that contains an abstract keyword on the declaration is known as an abstract class. It
is necessary for an abstract class to have at least one abstract method. It is possible in an
abstract class to contain multiple concrete methods.
What is an Interface?
An interface is a sketch that is useful to implement a class. The methods used in the interface
are all abstract methods. The interface does not have any concrete method.
18
S.No. Abstract Class Interface
1. An abstract class can contain both abstract and Interface contains only abstract
non-abstract methods. methods.
2. An abstract class can have all four; static, non- Only final and static variables are
static and final, non-final variables. used.
3. To declare abstract class abstract keywords are The interface can be declared with
used. the interface keyword.
6. It has class members like private and protected, It has class members public by
etc. default.
19
Now we create a new child class D, which extends both class B and class C. Note that we
have multiple inheritance (D extends B and C), hierarchical inheritance (B and C extend A),
and multilevel inheritance (D extends A, B, and C).
In the diamond problem, child classes B and C inherit a method from parent class A. Both B
and C override the inherited method. But the new methods in B and C conflict with each other.
Ultimate child class D inherits the two independent and conflicting methods from its multiple
parents B and C. It is unclear which method class D should use, so there is ambiguity. Other
OOP programming languages implement various methods for addressing the multiple
inheritance ambiguity.
How it is solved?
The solution to the problem is interfaces. The only way to implement multiple inheritance is
to implement multiple interfaces in a class. In java, one class can implements two or more
interfaces. This also does not cause any ambiguity because all methods declared in interfaces
are implemented in class.\
Click on Advanced System Settings.-> A dialog box will open. Click on Environment
Variables. ->
Next step - If the CLASSPATH already exists in System Variables, click on the Edit button
then put a semicolon (;) at the end. Paste the Path of MySQL-Connector Java.jar file.
If the CLASSPATH doesn't exist in System Variables, then click on the New button and type
Variable name as CLASSPATH and Variable value as C:\Program
Files\Java\jre1.8\MySQL-Connector Java.jar;.;
PATH CLASSPATH
It is used by the operating It is used by Application ClassLoader to locate the .class file.
system to find the executable
files (.exe).
You are required to include the You are required to include all the directories which contain .class and
directory which contains .exe JAR files.
20
files.
PATH environment variable The CLASSPATH environment variable can be overridden by using the
once set, cannot be overridden. command line option -cp or -CLASSPATH to both javac and java
command.
29. What is JDBC in Java?
Java database connectivity (JDBC) is the JavaSoft specification of a standard application
programming interface (API) that allows Java programs to access database management
systems. The JDBC API consists of a set of interfaces and classes written in the Java
programming language.
JDBC driver
The Stream class defines objects which accepts a sequence of characters. Streams may also have
an output in which case multiple stream objects can be cascaded to build a stream pipe where the
output of a stream is directed into the input of the next stream object "down the line".
Java IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to
make input and output operation in java. In general, a stream means continuous flow of data.
Streams are clean way to deal with input/output without having every part of your code
understand the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams. They are,
Byte Stream : It provides a convenient means for handling input and output of byte.
21
Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.
Java Byte Stream Classes
Byte stream is defined by using two abstract class at the top of hierarchy, they are
InputStream and OutputStream.
These two abstract classes have several concrete classes that handle various devices such
as disk files, network connection etc.
DataOutputStream An output stream that contain method for writing java standard data type
These classes define several key methods. Two most important are
1. read() : reads byte of data.
2. write() : Writes byte of data.
Character stream is also defined by using two abstract class at the top of hierarchy, they are
Reader and Writer.
22
These two abstract classes have several concrete classes that handle unicode character.
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies software development and maintenance by providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object
23
response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Class
A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviours of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example
phone call, we don't know the internal processing.
In Java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit are
known as encapsulation. For example, a capsule, it is wrapped with
different medicines.
24
Overloading occurs when two or more methods in one class have the same method name
but different parameters.
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
class Adder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
Overriding occurs when two methods have the same method name and parameters. One of
the methods is in the parent class, and the other is in the child 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");
}
25
public static void main(String args[])
{
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
What is an exception?
An Exception is an unwanted event that interrupts the normal flow of the program. When an
exception occurs program execution gets terminated. In such cases we get a system generated
error message. The good thing about exceptions is that they can be handled in Java. By handling
26
the exceptions we can provide a meaningful message to the user about the issue rather than a
system generated message, which may not be understandable to a user.
There can be several reasons that can cause a program to throw exception. For example: Opening a
non-existing file in your program, Network connection problem, bad input data provided by user
etc.
Exception Handling
If an exception occurs, which has not been handled by programmer then program execution gets
terminated and a system generated error message is shown to the user. For example look at the
system generated exception below:
Exception handling ensures that the flow of the program doesn’t break when an
exception occurs. For example, if a program has bunch of statements and an exception
occurs mid way after executing certain statements then the statements after the
exception will not execute and the program will terminate abruptly. By handling we
make sure that all the statements execute and the flow of program doesn’t break.
Errors indicate that something severe enough has gone wrong, the application should crash
rather than try to handle the error.
Exceptions are events that occurs in the code. A programmer can handle such conditions and
take necessary corrective actions. Few examples:
NullPointerException – When you try to use a reference that points to null.
ArithmeticException – When bad data is provided by user, for example, when you
try to divide a number by zero this exception occurs because dividing a number by
zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an
array out of its bounds, for example array size is 5 (which means it has five elements)
and you are trying to access the 10th element.
27
35. Life cycle of Thread
36. Life cycle of Applet
Single dimensional array − A single dimensional array of Java is a normal array where, the
array contains sequential elements (of same type) −
int[] myArray = {10, 20, 30, 40}
Printing Array
int myArray[]={33,3,4,5};
for(int i:myArray)
System.out.println(i);
Multi-dimensional array − A multi-dimensional array in Java is an array of arrays. A two
dimensional array is an array of one dimensional arrays and a three dimensional array is an array
of two-dimensional arrays.
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(mArray[i][j]+" ");
}
}
28
38. JDK, JRE & JVM
1. JDK (Java Development Kit) is a Kit that provides the environment to develop and
execute(run) the Java program. JDK is a kit(or package) that includes two things
Development Tools(to provide an environment to develop your java programs)
JRE (to execute your java program).
3. JVM (Java Virtual Machine) is a very important part of both JDK and JRE because it is
contained or inbuilt in both. Whatever Java program you run using JRE or JDK goes into JVM
and JVM is responsible for executing the java program line by line, hence it is also known as
an interpreter.
29