0% found this document useful (0 votes)
3 views23 pages

Java Extheory 1

The document provides an overview of various Java concepts including command line arguments, compilers, Java Virtual Machine, and key methods like finalize() and toString(). It explains the use of keywords such as 'this', 'super', and 'final', as well as the differences between exceptions and errors, and input handling using Scanner and BufferedReader. Additionally, it covers constructors, inheritance, access specifiers, and garbage collection, along with examples and explanations of each topic.

Uploaded by

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

Java Extheory 1

The document provides an overview of various Java concepts including command line arguments, compilers, Java Virtual Machine, and key methods like finalize() and toString(). It explains the use of keywords such as 'this', 'super', and 'final', as well as the differences between exceptions and errors, and input handling using Scanner and BufferedReader. Additionally, it covers constructors, inheritance, access specifiers, and garbage collection, along with examples and explanations of each topic.

Uploaded by

bocota2791
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

What is Command line argument?

Command line arguments are parameters or arguments that are passed to a program when it is
executed from the command line. These arguments are stored in the form of an array, and they can
be used to customize the behaviour of the program, such as providing options, file names, and
configuration settings.

What is Compiler?
A compiler is a program that takes source code written in a programming language and converts it
into a machine language (also known as object code) that can be executed by the computer. A
compiler translates all of the source code into machine code in one go.

Java Virtual Machine


Java Virtual Machine (JVM) is an abstract computing machine that enables a computer to
run a Java program.

What is finalize() Method?


The Java finalize() method of Object class is a method that the Garbage Collector always calls just
before the deletion/destroying the object which is eligible for Garbage Collection to perform clean-
up activity.

What is toString()?
toString() is a method that is used to convert an object into a string. It is a method of the Object
class, which is the parent of all classes in Java. It is used to represent an object as a string, usually for
displaying or logging purposes.

What is 'this' keyword in Java?


In java programming, the 'this' keyword is a keyword that is used to refer to the current object or
instance in which the code is being executed. It can be used to access and manipulate the properties
of the current object.

What is Wrapper class?


A wrapper class is a class that encapsulates a primitive data type, allowing it to be treated as an
object. Wrapper classes are used when a primitive data type needs to be passed as an object, for
example in collections such as ArrayList. Examples of wrapper classes include Integer, Double,
Boolean, and Character.

What is AnnonymousInnerClass?
An anonymous inner class is an inner class (a nested class) that is declared without a name and is
used to create objects. Anonymous inner classes are typically used when creating a short
implementation of an interface or abstract class, where a named class would be unnecessary or
undesired.

What is extends Keyword?


The extends keyword is used in Java to indicate that a class is inheriting from a parent class. It is used
to create a subclass (child class) from a superclass (parent class). The subclass will have all the same
methods and variables of the parent class and can also add new methods and variables of its own.

What is the use of implements Keyword?


The implements keyword is used in Java to indicate that a class is implementing an interface. It is
used in classes to indicate that a class is implementing an interface. The class must provide
implementations for all of the interface’s methods.
What is use of final keyword?
The final keyword in Java is used to restrict the user from modifying a variable, method, or class. It is
used to create constants (variables that cannot be changed later) or to prevent a method from being
overridden or a class from being inherited.

differences between throw and throws.


Throw:
Throw is a keyword that is used to explicitly throw an exception. It is followed by an instance of the
Throwable class. It is used within a method or block of code to throw an exception.

Throws:
Throws is a keyword used in method declaration to declare any checked exceptions thrown by the
method. It is followed by the exception class name. It is used to propagate an exception from a
method to its caller.

What is constructor?
A constructor is a special type of subroutine called to create an object. It prepares the new object for
use, often accepting arguments that the constructor uses to set required member variables.
Constructors are also known as initialization routines.

Name the package which import the tree set class.


[Link]

Name the classes which implement the set interface.


1. HashSet
2. TreeSet
3. LinkedHashSet
4. CopyOnWriteArraySet

Name the classes which implement the list interface.


- ArrayList
- LinkedList
- Vector
- Stack

What is exception in Java?


An exception in Java is an event that disrupts the normal flow of program execution. It is an object
that is thrown at runtime to indicate that an exceptional condition has occurred. Exceptions can be
caused by user error, hardware failure, programming mistakes, and many other sources.

What is a use of super keyword?


The super keyword is used to refer to a class that contains the current class, or to refer to the parent
class of the current class. It can also be used to call methods or access fields of the parent class.
Additionally, the super keyword is used to pass arguments to the parent class in its constructor.

‘‘Import statement is not essential in Java.’’ Justify True/False.


False. Import statements are essential in Java, as they allow the compiler to locate classes and
interfaces used in the program. Without import statements, the compiler will not be able to locate
the classes and interfaces and the program will not compile.
State differences between exception and error.
Exceptions and errors are both types of runtime errors.

Exceptions:
- Exceptions are events that occur during the execution of a program that disrupts the normal flow
of the program's instructions.
- Exceptions are usually handled by the application and can be triggered by user input, hardware
errors, or logic errors.
- Exceptions are usually handled using try/catch blocks.

Errors:
- Errors are events that occur during the execution of a program that disrupts the normal flow of the
program's instructions.
- Errors are usually caused by programming mistakes and can be difficult to debug.
- Errors are usually handled by the compiler and cannot be handled by the application.

Write any two constructors of JButton, JCheckBox, JRadioButton, JDialog, class.


JButton Constructors:
1. JButton(): creates a button with no text or icon
2. JButton(String text): creates a button with text
JCheckBox Constructors:
1. JCheckBox(): creates a check box with no text
2. JCheckBox(String text): creates a check box with text
JRadioButton Constructors:
1. JRadioButton(): creates a radio button with no text
2. JRadioButton(String text): creates a radio button with text
JDialog Constructors:
1. JDialog(): creates a dialog with no title
2. JDialog(Frame owner, boolean modal): creates a dialog with the specified owner and modality

Which class is super class of all classes in Java ?


The Object class is the superclass of all classes in Java.

What is scriptlet in JSP ?


A scriptlet is a piece of Java code embedded inside a JSP page. Scriptlets are used to execute
dynamic content within a JSP page. Scriptlet code is surrounded by the delimiters <% and %>.

Write any two implicit objects in JSP?


1. request: The request object contains information about the current request, such as parameters,
headers, and attributes.
2. response: The response object contains information about the response that will be sent back to
the client, such as the status code, content type, and content length.
[Link] any three JDK tools in Java.
1. Javac: The javac command is used to compile Java programs. It reads a Java source file, compiles
it, and generates the bytecode. It also checks the syntax and generates errors and warnings if any.
2. Java: It is the primary Java interpreter that enables the execution of Java bytecode. It executes the
main() method of the class file and produces the output.
3. Jar: The jar command is used to package Java class files in a jar archive. It also creates a manifest
file for the jar archive, which contains meta-information about the contents of the jar file.

[Link] Structure Of java Program.


A Java program consists of the following components:
1. Package declaration: This is an optional section that allows the programmer to group related
classes together.
2. Import statements: This is an optional section that allows the programmer to import existing Java
classes into the program.
3. Class declaration: This section declares a class, which is the main building block of a Java program.
4. Variable declarations: This section declares variables for use in the program.
5. Method declarations: This section declares methods, which are functions that can be invoked
from other parts of the program.
6. Main method: This is the main entry point of the program. It contains the code that will be
executed when the program starts.
7. Statements and expressions: This section contains the code that will be executed when the
program runs.
8. Class closing brace: This section marks the end of the class.

[Link] Features of Java


1. Platform Independent: Java code can run on any platform including Windows, Mac OS, and the
various versions of UNIX. This means that the same program can run on different platforms without
the need for recompiling.
2. Object-Oriented: Java is an object-oriented language, which means that it supports the creation of
objects that can contain data and methods. This allows for the creation of reusable code and makes
development easier.
3. Secure: Java was designed to be secure and it includes features like runtime verification and
memory management that make it very secure.
4. Robust: Java is known for its robustness. It includes features like automatic memory management
and garbage collection that improve its robustness.
5. Portable: Java code can be ported to different platforms without any changes.
6. Multi-threaded: Java supports multi-threading, which allows for the creation of applications that
can perform multiple tasks at the same time.
7. High performance: Java is known for its high performance. It includes features like Just-In-Time
compilation and Hotspot technology that help to improve its performance.

[Link] the various ways used to accept input from console in Java with proper syntax
and example.
1. Using Scanner Class:
Syntax:
Scanner sc = new Scanner([Link]);
Example:
Scanner sc = new Scanner([Link]);
int num = [Link]();
2. Using BufferedReader Class:
Syntax:
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
Example:
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
String str = [Link]();
3. Using Console Class:
Syntax:
Console console = [Link]();
Example:
Console console = [Link]();
String str = [Link]();

[Link] a note on Scanner.


The Scanner is a Java class that allows for user input from the keyboard. It can be used to read in a
variety of data types, including strings, ints, doubles, floats, and longs. The Scanner class has several
methods, such as next(), nextLine(), and hasNext(), which allow the user to input data and process it.
The Scanner class is a powerful and convenient way to read data from the keyboard, and is an
essential tool for any Java programmer.

[Link] a note on BufferedReader.


BufferedReader is a class used for reading text from a character-based input stream. It is often used
in Java programs to read data from a file or from the keyboard. The BufferedReader class provides
additional methods for reading data from the stream, such as readLine() which reads a single line of
text. It also provides methods for skipping over data, and for checking if the end of the stream has
been reached. The BufferedReader class helps to improve performance by buffering input data and
thereby reducing the number of disk accesses.

[Link] between Scanner and BufferedReader.


Scanner:
Scanner is a class in Java which is used for taking input from the user. It is present in the [Link]
package. Scanner class is used to parse primitive types and strings using the regular expressions.
Scanner class is widely used for taking input from the user because of its simplicity and easy to use
methods.
BufferedReader:
BufferedReader is a class in Java which is used for reading the text from a character-based input
stream. It is present in the [Link] package. BufferedReader reads text from a character-based input
stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
It can also be used to read a file line by line.
[Link] Specifiers (public, protected, private, default) explain.
Public: Public access specifiers mean that the members declared with public access can be accessed
from anywhere in the program using the dot (.) operator.
Protected: Protected access specifiers mean that the members declared with protected access can
only be accessed from the class in which it is declared and from the classes that inherit from this
class.
Private: Private access specifiers mean that the members declared with private access can only be
accessed within the class in which it is declared. No other class can access that member.
Default: Default access specifiers mean that the members declared without any access specifier can
only be accessed from within the package in which it is declared. No other class from outside that
package can access that member.

[Link] and Overloading Constructors explain.


Constructors are special methods that are used to initialize objects. They are used to create an initial
state for an object. Constructors usually have the same name as the class and do not have a return
type. Automatically called when an object is created.
Overloading constructors is a concept in object-oriented programming where two or more
constructors exist in a single class with different parameters. This allows the class to be instantiated
with different combinations of parameters, depending on the situation.
Example:
class Number
{ int a, b;
Number()
{ a=10;
b=20;
}
Number(int x)
{ this.a=x;
this.b=x;
}
Number(int x, int y)
{ this.a=x;
this.b=y;
}
void display()
{ [Link]("a="+a+"b="+b);
}
}
class COverload
{public static void main(String args[])
{Number N1=new Number();
[Link]();
Number N2=new Number(1);
[Link]();
Number N3=new Number(1,2);
[Link]();
}
}
[Link] copy constructor is implemented in java? Explain with an example.
A copy constructor in Java is a special type of constructor that is used to create a copy of an existing
object. The copy constructor takes an object of the same class as its parameter and creates a new
object, which is a copy of the object passed as parameter.
Example:
public class CopyConstructorExample {

private int id;


private String name;

public CopyConstructorExample(int id, String name) {


[Link] = id;
[Link] = name;
}

public CopyConstructorExample(CopyConstructorExample copyConstructor) {


[Link] = [Link];
[Link] = [Link];
}

public int getId() {


return id;
}

public String getName() {


return name;
}

public static void main(String[] args) {


CopyConstructorExample copyConstructor1 = new
CopyConstructorExample(1, "John");

[Link] of „this‟ Keyword in java.


The keyword „this‟ in Java is a reference to the current object, or the object whose method or
constructor is being called. It is used to refer to the instance variables of the current object. It can
also be used to call constructors and methods of the current class. It is often used to pass the current
object as an argument to a method or a constructor of another class.

[Link] the uses of super keyword with proper example in java.


The super keyword is used to refer to a class that contains the current class, or to refer to the parent
class of the current class. It can also be used to call methods or access fields of the parent class.
Additionally, the super keyword is used to pass arguments to the parent class in its constructor.

The super keyword in Java is a reference variable that is used to refer to the immediate parent class
object. It can be used to access members of the parent class that have been hidden by a member of
a subclass.
Example:
public class Animal {
public void eat(){
[Link]("Animal is eating...");
}
}

public class Dog extends Animal {


public void eat(){
[Link]("Dog is eating...");
}

public void bark(){


[Link]("Dog is barking...");
}

public void show(){


[Link]();
bark();
}
}
In the above example, the show() method of the Dog class is calling the eat() method of the parent
class Animal using the super keyword.

[Link] static blocks, static variable, static method.


A static block is a block of code that is executed when a class is loaded into the JVM. It is typically
used to initialize static variables.
A static variable is a variable that is shared among all instances of a class. It is typically used to store
information that is common to all instances of a class, such as constants or configuration settings.
A static method is a method that is associated with a class, rather than an instance of a class. It can
be called without creating an instance of the class, and is typically used for utility methods that
perform operations related to the class.

[Link] a note on garbage collection and finalize().


Garbage collection is a process for reclaiming the runtime unused memory automatically. Garbage
collection is also known as Automatic Memory Management, as the JVM automatically removes the
unused objects from the memory. The garbage collection is mainly used to free the heap memory.
The finalize() method is called by the garbage collector when it determines that there are no more
references to the object. The finalize() method can be used to perform cleanup processing just
before the object is garbage collected.

[Link] Basics and Types of Inheritance in java.


Inheritance is a mechanism in Java that allows a class to inherit properties and methods from
another class. Through inheritance, a class can acquire the properties and methods of another class,
allowing for new types of objects to be created.
Types of Inheritance in java:
1. Single Inheritance: In single inheritance, one class inherits the properties and methods of another
class.
2. Multi-level Inheritance: In multi-level inheritance, one class inherits the properties and methods
of another class, which in turn inherits the properties and methods of another class.
3. Hierarchical Inheritance: In hierarchical inheritance, one class inherits the properties and methods
of multiple classes, creating a hierarchy of classes.
4. Multiple Inheritance: In multiple inheritance, one class inherits the properties and methods of
multiple classes.
5. Hybrid Inheritance: Hybrid inheritance is a combination of multiple inheritance, hierarchical
inheritance, and single inheritance.
[Link] is inheritance ? Explain hierarchical and multiple inheritance with an example
Inheritance is a concept in object-oriented programming where a class can acquire the properties
and behaviours of an existing class. This allows the class to inherit the methods and fields of the
parent class, making it easier to reuse code and make classes more modular.

Hierarchical Inheritance is a type of inheritance where one class can be inherited by multiple
subclasses. For example, a Vehicle class can be inherited by two subclasses, Car and Motorcycle. The
Car and Motorcycle classes will inherit the properties and behaviours of the Vehicle class.

Multiple Inheritance is a type of inheritance where one class can be inherited from multiple parent
classes. For example, a Person class can be inherited from both a Human class and an Animal class.
This allows the Person class to inherit the properties and behaviours of both the Human
and Animal classes.

[Link] between method overloading and method overriding.


[Link] runtime polymorphism in java.
Runtime polymorphism, also known as dynamic method dispatch, is a process in which a call to an
overridden method is resolved at runtime rather than compile-time. This is achieved by using the
concept of inheritance and overriding in Java. When an overridden method is called by a reference,
Java determines which version of the overridden method to execute based on the type of object it
refers to, which is determined at run-time.
EX: class Bank
{int getRate();
{
return 0;
}
}
class SBI extends Bank
{int getRate()
{
return 9;
}}
class HDFC extends Bank
{
Int getRate()
{
return 7;
}
}
class RuntimeDemo
{
PSVM(String args[])
{
SBI S=new SBI();
[Link]();
HDFC H=new HDFC();
[Link]();
}}

[Link] keyword related to variable, method and class.


Variable:
The final keyword can be used to make a variable, a constant. A final variable that has been assigned
a value cannot be changed.
Method:
The final keyword can be used to prevent a method from being overridden in a subclass. A final
method cannot be overridden in any subclass.
Class:
The final keyword can be used to prevent a class from being inherited. A final class cannot be
extended, and so no subclass can be created.

[Link] abstract class and abstract methods.


An abstract class is a type of class that cannot be instantiated. It is used as a base class to provide
common fields and methods to its subclasses. An abstract class contains abstract methods, which
are methods that must be implemented by its subclasses. Abstract methods are methods that have
no implementation and are declared in the abstract class. Abstract methods must be implemented
by its subclasses in order for the subclass to be instantiated.
[Link] is a package? How to create a package in java?
A package in Java is a way to organize related classes and interfaces into one place. They provide
access control and namespace management. Packages are used in Java to avoid name conflicts and
to control access of class, interface and enumeration etc.

To create a package in Java, you must use the package keyword at the top of the source file. The
package statement should be the first line in the source file. The package name should be in
lowercase letters and follow the directory structure. For example, the package name could be
[Link].

[Link] a short note on built-in package and user define package.


Built-in packages are packages that are available as part of the standard Python distribution.
Examples include the os, sys, math, and time packages. They are written in C and are therefore fast
and efficient.

User-defined packages are packages that are written by users and not included in the standard
Python distribution. They can be written in Python or any other language and are typically used to
extend the functionality of Python. They are generally slower than built-in packages but provide
more flexibility.

[Link] to create and access a package in Java ?


Creating a package in Java:
1. Create a directory with the name of the package. This directory should be kept in the same
directory as your Java source files. The directory should have the same name as the package.
2. Put your Java source files in this directory.
3. Now, add a package statement at the top of each Java source file. This statement should be the
same as the name of the directory.

Accessing a package in Java:


1. You can access the classes present in a package by using the import statement.
2. The syntax of the import statement is:
import package_name.*;
3. Here, package_name is the name of the package you want to access.
4. You also need to include the full package path in the import statement, if the package is not in the
same directory as the Java source file.
5. Once you have included the import statement, you can use the classes present in the package in
your Java source file.

[Link] any four methods of string class with proper syntax in java.
1. length(): This method returns the length of the string.
Syntax:
String str = "Welcome";
int length = [Link]();

2. charAt(): This method returns the character at the specified index.


Syntax:
String str = "Welcome";
char ch = [Link](3); // ch = 'c'

3. substring(): This method returns a part of the string.


Syntax:
String str = "Welcome";
String sub = [Link](0,4); // sub = "Welc"

4. replace(): This method replaces the specified character with another character.
Syntax:
String str = "Welcome";
String newstr = [Link]('e', 'a'); // newstr = "Walcoma"

[Link] package with an example.


A package is a collection of related components, such as classes, functions, and variables, that group
together to provide a certain functionality. For example, the Java library contains a number of
packages, such as [Link], [Link], and [Link], which contain components related to various
aspects of the programming language. These packages contain classes, interfaces, and other
components that can be used to build Java applications.

Differentiate between Abstract Class & Interface.

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods. Since Java 8, it can have default and static
methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, static and Interface has only static and final variables.
non-static variables.

4) Abstract class can provide the implementation of Interface can't provide the implementation
interface. of abstract class.

5) The abstract keyword is used to declare abstract The interface keyword is used to declare
class. interface.

6) An abstract class can extend another Java class An interface can extend another Java
and implement multiple Java interfaces. interface only.

7) An abstract class can be extended using keyword An interface can be implemented using
"extends". keyword "implements".

8) A Java abstract class can have class members like Members of a Java interface are public by
private, protected, etc. default.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
What is Collection? How it is differ from array?
Collection is an object that represents a group of objects. It is similar to an array, but it is more
flexible and powerful. Unlike an array, a collection does not have a fixed size and can grow or shrink
dynamically. Whereas an array stores objects of a single data type, a collection can store objects of
different types. Additionally, a collection can contain duplicate elements, while an array cannot.

Explain Map interface with suitable example in java.


The Map interface in Java is an interface that provides a mapping between a key and its associated
value. It is part of the [Link] package and is a collection of key-value pairs. It does not allow
duplicate keys, but can contain duplicate values. It is useful for storing data that can be quickly
accessed by key.
Example:
import [Link];
import [Link];

public class MapExample {


public static void main(String[] args) {
// Create a map that stores String keys and Integer values
Map<String, Integer> numbers = new HashMap<>();

// Add key-value pairs to the map


[Link]("one", 1);
[Link]("two", 2);
[Link]("three", 3);
[Link]("four", 4);

// Print out the value associated with the key "three"


[Link]([Link]("three")); // Output: 3
}
}

Differentiate between List and Set interface.


List Interface:
The List interface provides a way to store a collection of objects that can be accessed by their index.
It allows duplicate elements, and maintains the order in which they were added. It also provides
methods to search, sort, and manipulate the list.
Set Interface:
The Set interface provides a way to store a collection of objects that cannot contain duplicate
elements. It does not maintain the order in which the elements were added and provides methods
to search, sort, and manipulate the set.

Differentiate between Iterator and ListIterator interface.


Iterator is an interface that allows you to traverse through a collection, obtaining or removing
elements. It is an interface which belongs to [Link] package.

ListIterator is an interface that extends Iterator to allow bidirectional traversal of a list. It is an


interface which belongs to [Link] package.

The main difference between Iterator and ListIterator is that Iterator allows unidirectional traversal
of a list while ListIterator allows bidirectional traversal of a list. Iterator can only be used to traverse
the list in forward direction while ListIterator can be used to traverse the list in both forward and
backward direction.

Difference between Iterator and Enumeration.


An Iterator is an object that can be used to loop through collections of objects, such as lists. It allows
the caller to remove elements from the underlying collection during the iteration with well-defined
semantics.

An Enumeration is an object that can be used to loop through a collection of objects, such as vectors
and hashtables. It does not allow the caller to remove elements from the underlying collection
during the iteration.

Explain Hashtable with an example in java.


A hashtable is a data structure that stores key-value pairs. It uses a hashing algorithm to compute an
index into an array of buckets or slots, from which the desired value can be found.
Example:
import [Link];

public class MyHashTable {

public static void main(String[] args) {

// Create a Hashtable object called capitalCities


Hashtable<String, String> capitalCities = new Hashtable<String, String>();

// Add keys and values (Country, City)


[Link]("England", "London");
[Link]("Germany", "Berlin");
[Link]("Norway", "Oslo");
[Link]("USA", "Washington DC");

// Get values
[Link]([Link]("England"));
[Link]([Link]("Germany"));
[Link]([Link]("Norway"));
[Link](capitalCities.

Explain Enumeration In java.


Enumeration in Java is a data type that contains a fixed set of named constants. It is used to
represent a group of named constants that are known at compile time. An Enum is a class that has
constants as its members, which represent certain values. Using Enums can greatly simplify code, by
making it more readable and maintainable. Enums are especially useful for representing a set of
related data that need to be accessed in a predictable way, such as a list of days in a week, or a list of
states in a country.

Write a difference between ArrayList and LinkedList.


ArrayList is an implementation of the List interface that uses an array to store its elements, while
LinkedList is an implementation that uses a doubly-linked list to store its elements.

ArrayLists are faster for retrieving elements but slower for manipulating them, while LinkedLists are
faster for manipulating elements but slower for retrieving them.
ArrayLists are fixed in size and cannot be dynamically resized, while LinkedLists can be dynamically
resized.

ArrayLists are better for retrieving elements by index, while LinkedLists are better for inserting and
removing elements.

Write a difference between array and vector.


Array: An array is a data structure that stores items of the same type in a contiguous block of
memory. Arrays are typically used to store a collection of related items that are all of the same type.

Vector: A vector is a data structure that stores a collection of items of any type. Unlike arrays, each
item in a vector can be different from the others. Vectors are dynamic and are able to expand and
contract as needed to store extra items.

What is interface ? Explain the use map interface with suitable example.
Interface in Java is a blueprint of a class that contains static constants and abstract methods. It is
used to achieve abstraction and multiple inheritance in Java. Interfaces are used to implement
abstraction.

A Map interface is a part of the Java Collection framework. It stores key-value pairs. It is not an
extension of the Collection interface. It provides a powerful way to store data in the form of key-
value pairs. The Map interface is not a subtype of the Collection interface.
Example:
import [Link];
import [Link];

public class MapExample {


public static void main(String[] args) {
// Create a map
Map<String, Integer> numbers = new HashMap<>();

// Add key-value pairs to the map


[Link]("One", 1);
[Link]("Two", 2);
[Link]("Three", 3);

// Get the value of a given key


[Link]("Value of key 'One': " + [Link]("One"));
}
}
Output:Value
What is Exception in ? Explain try, catch, finally.
An exception is an error that occurs during the execution of a program. Exceptions are usually
caused by user input or programming logic errors.

Try, catch and finally are Java keywords used to handle exceptions. The try block contains the code
that may throw an exception. If an exception is thrown, the code in the catch block is executed.
Finally, the code in the finally block is always executed, regardless of whether an exception
was thrown or not.
Differentiate between throws and throw keyword in details.
Throws:
Throws is used to declare an exception. It gives an information to the programmer that there may
occur an exception so it is better for the programmer to provide the exception handling code so that
normal flow can be maintained.
Throw:
Throw is used to throw an exception explicitly in the program. It is used to throw either checked or
unchecked exception explicitly. It is used within the method to throw an exception.
Explain User defined exception in java.
User-defined exceptions are exceptions that you create yourself, based on your application
requirements. They are created by extending the Exception class and are used when you want to
create a custom exception that is different from existing exceptions. User-defined exceptions are
useful when you want to handle errors differently from other errors, or when you want to provide
more specific information about the error in the exception.

Explain Inner and Nested class with example in java.


Inner class is a class which is declared inside the body of another class. It has access to all of the
variables and methods of its outer class and may refer to them directly in the same way that other
non-static members of the outer class do.

Nested class is a class which is declared inside another class, or a class within a method. It can be
used to logically group classes that are only used in one place.

Example:
public class Outer {
private int x;
public void doSomething() {
// do something
}

public class Inner {


public void doSomethingElse() {
x = 10; // Outer class instance variable
doSomething(); // Outer class method
}
}
}

Explain File class with an example in java.


The File class is a Java class used to interact with the file system. It provides methods for
manipulating files, such as creating, deleting and renaming files.

Example:
// Create a File object
File file = new File("C:\\Test\\[Link]");

// Create the file


[Link]();

// Check if the file exists


if([Link]()) {
[Link]("File exists");
}

// Rename the file


File newFile = new File("C:\\Test\\[Link]");
[Link](newFile);

// Delete the file


[Link]();

What Layout Manager? Explain anyone with an example in java.


A Layout Manager is a set of instructions that Java uses to control the way components are placed
within a window. It allows you to arrange components like buttons, text fields, labels, and other
elements in the window.

For example:
FlowLayout is a layout manager which arranges components in a row. It is the default layout
manager of a JFrame in Java.

//Creating a frame
JFrame f=new JFrame("FlowLayout");
//Creating components
JButton b1=new JButton("Button 1");
JButton b2=new JButton("Button 2");
JButton b3=new JButton("Button 3");
//Creating flow layout manager
FlowLayout fl=new FlowLayout();
//Setting the layout manager
[Link](fl);
//Adding components to the frame
[Link](b1);[Link](b2);[Link](b3);
//Setting the size of the frame
[Link](300,300);
//Setting the visibility of the frame
[Link](true);

Explain Event Delegation Model with example.


Delegation Event model is defined to handle events in GUI programming languages. The GUI stands
for Graphical User Interface, where a user graphically/visually interacts with the system.

The GUI programming is inherently event-driven; whenever a user initiates an activity such as a
mouse activity, clicks, scrolling, etc., each is known as an event that is mapped to a code to respond
to functionality to the user. This is known as event handling.
import [Link].*;
import [Link].*;

public class TestApp {


public void search() {
// For searching
[Link]("Searching...");
}
public void sort() {
// for sorting
[Link]("Sorting....");
}

static public void main(String args[]) {


TestApp app = new TestApp();
GUI gui = new GUI(app);
}
}

class Command implements ActionListener {


static final int SEARCH = 0;
static final int SORT = 1;
int id;
TestApp app;

public Command(int id, TestApp app) {


[Link] = id;
[Link] = app;
}

public void actionPerformed(ActionEvent e) {


switch(id) {
case SEARCH:
[Link]();
break;
case SORT:
[Link]();
break;
}
}
}

class GUI {

public GUI(TestApp app) {


Frame f = new Frame();
[Link](new FlowLayout());

Command searchCmd = new Command([Link], app);


Command sortCmd = new Command([Link], app);

Button b;
[Link](b = new Button("Search"));
[Link](searchCmd);
[Link](b = new Button("Sort"));
[Link](sortCmd);

List l;
[Link](l = new List());
[Link]("Alphabetical");
[Link]("Chronological");
[Link](sortCmd);
[Link]();

[Link]();
}
}

What is JDBC? Explain its architecture.


JDBC (Java Database Connectivity) is an application programming interface (API) for the Java
programming language that defines how a client may access a database. It is a platform independent
and database independent system.

The architecture of JDBC consists of two layers: the JDBC API and the JDBC driver API. The JDBC API
provides the application-to-JDBC Manager connection. It also provides the facility to query and
update the database. The JDBC driver API provides the vendor-specific implementations of the JDBC
API that enable a Java application to communicate with the database.

The JDBC API includes the classes and interfaces required to interact with the database. It includes
classes like DriverManager, Connection, Statement, PreparedStatement, ResultSet, and
CallableStatement. It also includes interfaces like ResultSetMetaData and DatabaseMetaData.

The JDBC driver API provides the vendor-specific implementations of the JDBC API. It includes classes
that implement the JDBC API, such as OracleDriver, MySQLDriver, SybaseDriver, and so on. These
classes are responsible for establishing the connection to the database and performing the
necessary queries and updates.

What is JDBC ? Explain types of jdbc ?


JDBC (Java Database Connectivity) is an application programming interface (API) for connecting to
relational databases from Java applications. JDBC allows Java applications to access databases,
providing access to relational databases such as Oracle, Microsoft SQL Server, and MySQL.

Types of JDBC:
1. JDBC-ODBC Bridge: This type of JDBC driver uses ODBC driver to connect to the database.
2. Native-API/Partly Java Driver: This type of JDBC driver uses native libraries of the database to
connect to the database.
3. Network Protocol Driver (Middleware Driver): This type of JDBC driver uses middleware
(application server) to connect to the database.
4. Database Protocol Driver (Thin Driver): This type of JDBC driver uses the database protocol to
connect directly to the database.

Differentiate between Statement and PreparedStatement Interface.


Statement Interface:
The Statement interface is a basic interface used for executing static SQL statements and obtaining
the results produced by them. It is generally used for executing simple SQL statements such as
create, drop, insert, update and delete.

PreparedStatement Interface:
The PreparedStatement interface is a subinterface of Statement. It is used for executing
parameterized SQL statements. It is used for executing pre-compiled SQL queries. It provides better
performance than Statement interface as the query is pre-compiled. It also supports batch
processing which is not supported by Statement interface.

Explain ResultSet Interface in details.


The ResultSet interface provides methods for retrieving and manipulating the results of a SQL query.
It represents a two-dimensional table of data, where each row represents a single record and each
column represents a field of data within that record.

ResultSet objects can be used to retrieve data from a database, as well as to insert, update or delete
records in the database. It provides methods for navigating through the result set and retrieving
data from individual columns. It also provides methods for retrieving and updating database-specific
data types.

ResultSet objects can also be used to update database records. In this case, the ResultSet object
provides methods for setting the values of the fields in a record, as well as methods for deleting and
inserting records.

The ResultSet interface is part of the Java Database Connectivity (JDBC) API, which is used for
connecting to databases and executing SQL queries.

What is ResultSet ? Explain the types of ResultSet with proper syntax.


ResultSet is an interface in the Java programming language that provides access to a table of data
generated by executing a SQL statement.

There are four types of ResultSet:


1. Forward-Only – A forward-only ResultSet object can only be scrolled forward. This type of
ResultSet provides better performance than other types of ResultSet.
Syntax: ResultSet rs = [Link]("SELECT * FROM table");

2. Scrollable – A scrollable ResultSet object can be scrolled both forward and backward.
Syntax: Statement stmt = [Link](ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = [Link]("SELECT * FROM table");

3. Updatable – An updatable ResultSet object can be updated.


Syntax: Statement stmt = [Link](ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = [Link]("SELECT * FROM table");

4. Read-only – A read-only ResultSet object cannot be updated.


Syntax: Statement stmt = [Link](ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = [Link]("SELECT * FROM table");

Explain JDBC process in details.


JDBC stands for Java Database Connectivity. It is an API that allows Java programs to interact with
databases. JDBC is a set of classes and interfaces that provide a standard API for accessing relational
databases.
The JDBC process involves four steps:
1. Establish a connection: The first step is to establish a connection between the Java program and
the database. This can be done using the [Link]() method. This method
takes a URL, username, and password as parameters and returns a Connection object.
2. Create a statement: Once the connection has been established, a statement is created. This is
done using the [Link]() method. This method returns a Statement object.
3. Execute a query: Once the statement has been created, a query can be executed. This is done
using the [Link]() or [Link]() method. Depending on the type
of query, this method will return a ResultSet or an update count.
4. Process the results: Once the query has been executed, the results must be processed. This can be
done using the [Link]() and [Link]() methods. These methods are used to iterate
through the ResultSet and retrieve the data.
Once the data has been processed, the connection must be closed. This is done using the
[Link]() method.
The JDBC process is a standard API used to access databases in Java programs. It provides a set of
classes and interfaces that can be used to establish connections, execute queries, and
process results.

What is Servlet? Explain different types of servlet.


Servlet is a Java language class used to extend the capabilities of a server. It is used to respond to
requests from clients, typically across the web. They are used to generate dynamic content for web
pages, to process form data, and to manage sessions between requests.
There are three different types of servlets:
1. Generic Servlets: These are the basic servlets that are used to handle requests from clients and
generate dynamic content for webpages.
2. HTTP Servlets: These are specifically designed to handle requests from clients over HTTP and
HTTPS protocols.
3. Java Servlets: These are designed to process form data and manage sessions. They also provide a
programming interface for applications written in the Java language.

Explain Life cycle of Servlet.


The life cycle of a servlet can be defined as the entire process from its creation till the destruction.
The following are the paths followed by a servlet.
1. Loading: The servlet class is loaded into memory by the web container.
2. Instantiation: An instance of the servlet is created.
3. Initialization: The init() method of the servlet is called by the web container to initialize the servlet.
4. Request Processing: The servlet calls the service() method each time a request is made by a client.
5. Destroying: The servlet is removed from the server memory when it is not required.

Explain the role of .xml file in servlet application.


An XML file is a file that contains data in a structured format. It is most commonly used in web
applications to store settings, configuration data, and other information. In servlet applications, an
XML file can be used to store web application settings and configurations, such as the servlet's URL
mapping, authentication settings, and database settings. It can also be used to store application-
specific parameters and data, such as user preferences, application settings, and user-defined data.
XML files can also be used to store data for use in web applications, such as product catalog
information or user data.

Explain JSP life cycle.


The JSP life cycle is the process of execution of a JSP page from start to finish. It begins when the
client requests a JSP page and ends when the response is sent back to the client.
The JSP life cycle consists of the following steps:
1. Page compilation: The JSP page is compiled into a Servlet class. This is done when the page is first
requested by a client, or when the page has been modified and needs to be recompiled.
2. Page initialization: The Servlet class is instantiated, and the jspInit() method is called. This method
is used for any initialization code that needs to be run.
3. Request processing: The service() method is called, which handles incoming requests and
generates a response. This is the main processing step for the JSP page.
4. Page cleanup: The jspDestroy() method is called to clean up any resources that were used during
the request processing.
5. Page destruction: The Servlet class is destroyed, and the compiled JSP page is
removed from memory.

Explain different types of components in JSP.


1. Custom Tags: Custom tags are user-defined JSP language elements used to create reusable
components.
2. Expression Language (EL): EL allows us to access data stored in JavaBeans components, implicitly.
3. Directive Elements: Directive elements provide the JSP engine with information about the current
page.
4. Standard Action Elements: Standard action elements are used to perform certain tasks such as
including other files, forwarding the request to other pages, or displaying a message.
5. Comments: Comments are used to provide additional information about the code that is not
interpreted by the JSP engine.
6. Scriptlets: Scriptlets are small snippets of Java code that can manipulate the output of the page.

Why is JSP fly compilation ? Explain implicit object in JSP ?


JSP fly compilation is a process that is used to dynamically compile JSP pages and servlets. This
means that when a browser requests a JSP page, the source code of the JSP page is compiled into a
servlet before it is executed. This allows for faster response time when the page is requested again.

Implicit objects in JSP are objects that are created by the web container and are available for the use
in JSP pages without being declared. These objects provide access to information related to the
request, response, page context, session, and application. Examples of implicit objects include
request, response, pageContext, session, application, out, config, page, and exception.

Difference between jsp and servlet.

Servlet JSP

Servlet is a java code. JSP is a HTML based code.

Writing code for servlet is harder than JSP as it is


HTML in java. JSP is easy to code as it is java in HTML.

Servlet plays a controller role in the hasMVC JSP is the view in the MVC approach for
approach. showing output.

Servlet is faster than JSP. JSP is slower than Servlet because the first
step in the hasJSP lifecycle is the translation
Servlet JSP

of JSP to java code and then compile.

Servlet can accept all protocol requests. JSP only accepts HTTP requests.

In Servlet, we can override the service() method. In JSP, we cannot override its service()
method.

In Servlet by default session management is not In JSP session management is automatically


enabled, user have to enable it explicitly. enabled.

In Servlet we have to implement everything like In JSP business logic is separated from
business logic and presentation logic in just one presentation logic by using JavaBeansclient-
servlet file. side.

Modification in Servlet is a time-


consumingcompiling task because it includes
reloading, recompiling, JavaBeans and restarting JSP modification is fast, just need to click
the server. the refresh button.

It does not have inbuilt implicit objects. In JSP there are inbuilt implicit objects.

There is no method for running JavaScript on the While running the JavaScript at the client
client side in Servlet. side in JSP, the client-side validation is
used.

Packages are to be imported on the top of the Packages can be imported into the JSP
program. program(i.e bottom , middleclient-side, or
top )

You might also like