Q.
1
a) What do you mean by anonymous class? Explain with suitable example.
Ans:
An inner class with no name is called anonymous inner class.
Anonymous classes enables you to define and instantiate a class at the same time.
Generally, they are used whenever you need to override the method of a class or an
interface.
An Anonymous class has access to the members of its enclosing class.
An Anonymous class can’t have static members.
An Anonymous class can have final variables.
Anonymous classes are often used in GUI applications.
Anonymous classes are used to implements listeners on GUI.
Syntax:
AnonymousInner an_inner = new AnonymousInner() {
public void my_method()
{ ........ ........
}
};
Example:
abstract class AnonymousInner {
public abstract void mymethod();
}
public class Outer_class {
public static void main(String args[]) {
AnonymousInner inner = new AnonymousInner() {
public void mymethod() {
[Link]("This is an example of anonymous inner class");
}
};
[Link]();
}
}
b) Explain the use of “this Keyword”.
Ans:
‘this’ is a keyword in java.
‘this’ points to the current object.
‘this’ always holds address of an object which invokes the member function.
The keyword this can be used inside any method to refer to the current object.
Box(double w, double h, double d) {
[Link]=w; [Link]=h;
[Link]=d; }
Inside Box(), ‘this’ always refers to the invoking object.
“this” can also be used to:
1. Invoke current class constructor.
2. Invoke current class method.
3. Return the current class object.
4. Pass an argument in the method call.
5. Pass an argument in the constructor call.
The most common use of the “this” keyword is to eliminate the confusion between class
attributes and parameters with the same name.
public class Main {
int x;
// Constructor with a parameter
public Main(int x) {
this.x = x;
}
// Call the constructor
public static void main(String[] args) {
Main myObj = new Main(5);
[Link]("Value of x = " + myObj.x);
}
}
o/p- Value of x = 5
If you omit “this” keyword in the example above, the output would be "0" instead of "5".
E.g. [Link]
[Link]
[Link]
c) What is polymorphism? Explain the compile time polymorphism and
run time polymorphism.
Ans:
Polymorphism:
When one task is performed by different ways i.e. known as polymorphism.
For example: to convenes the customer differently, to draw something e.g. shape or
rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
There are two types of polymorphism in java: compile time polymorphism and
runtime polymorphism.
Runtime Polymorphism in java:
Runtime polymorphism or Dynamic Method Dispatch is a process in which
a call to an overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of
a superclass. The determination of the method to be called is based on the
object being referred to by the reference variable.
Example :
class Bike{
void run(){[Link]("running");}
}
class Splender extends Bike{
void run(){[Link]("running safely with 60km");}
Output:
running safely with 60km.
Compile time Polymorphism in java:
Compile-time polymorphism, sometimes referred to as static polymorphism or
early binding, is the capacity of a programming language to decide which
method or function to use based on the quantity, kind, and sequence of inputs at
compile-time. Method overloading, which enables the coexistence of many
methods with the same name but distinct parameter lists within a class, enables
Java to accomplish compile-time polymorphism.
public static void main(String args[]){
Bike b = new Splender();//upcasting
[Link]();
}
}
Example:
1. public class Calculator {
2. public int add(int a, int b) {
3. return a + b;
4. }
5. public double add(double a, double b) {
6. return a + b;
7. }
8. public static void main(String[] args) {
9. Calculator calc = new Calculator();
10. int sum1 = [Link](5, 10);
11. [Link]("Sum of 5 and 10 (integers): " + sum1
);
12. double sum2 = [Link](2.5, 3.7);
13. [Link]("Sum of 2.5 and 3.7 (doubles): " + su
m2);
14. }
15. }
Output:
Sum of 5 and 10 (integers): 15
Sum of 2.5 and 3.7 (doubles): 6.2
d) What is a naming convention for package?
Ans:
The name of the package should be in small letters.
It is suggested to start the name of the package with the top level domain level
followed by sub domains, ex: [Link].
Packages in the Java language itself begin with java. or javax.
Q.2
a) Explain un-checked exceptions with the suitable example.
Ans:
An Unchecked exception is an exception that occurs at the time of execution, these
are also called as Runtime Exceptions, these include programming bugs, such as
logical errors or improper use of an API.
Runtime exceptions are ignored at the time of compilation.
For example, if you have declared an array of size 5 in your program, and trying to
call the 6th element of the array then an ArrayIndexOutOfBoundsException
exception occurs.
public class Unchecked_Demo {
public static void main(String args []) {
int num[]={1,2,3,4};
[Link](num[5]);
}
}
If you compile and execute the above program you will
get exception as shown below.
Exception in thread "main" [Link]: 5 at
Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
b) Define array, explain two – dimensional array with suitable example.
Ans:
An array is a collection of similar type of elements which has contiguous memory
location.
Java array is an object which contains elements of a similar data type.
The elements of an array are stored in a contiguous memory location.
It is a data structure where we store similar elements.
We can store only a fixed set of elements in a Java array.
We can store primitive values or objects in an array in Java.
Like C/C++, we can also create single dimensional or multidimensional arrays in
Java.
2-Dimensional Array:
In such case, data is stored in row and column based index (also known as matrix
form).
Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example-
int[][] arr=new int[3][3];//3 row and 3 column
//Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
[Link](arr[i][j]+" ");
}
[Link]();
}
}
}
c) Explain thread priorities with proper example.
Ans:
A single sequential flow of control within a program.
A thread is a lightweight, smallest unit of processing.
A process is typically made up of multiple threads.
A thread shares the memory space with other threads of the same process.
Java allows a program to have multiple threads running concurrently.
Example
class Multi extends Thread {
public void run() {
[Link]("thread is running...");
public static void main(String args [ ] ) {
Multi t1=new Multi();
[Link]();
Output: thread is running...
d) What is mean of thread – deadlock? Elaborate it with suitable example.
Ans:
Deadlock is a situation of complete Lock when no thread can complete its execution
because lack of resources.
In the above picture, Thread 1 is holding a resource R1, and need another resource R2
to finish execution, but R2 is locked by Thread 2, which needs R3, which in turn is
locked by Thread 3.
Hence none of them can finish and are stuck in a deadlock.
Q.3)
a) Define array list. Write a program to accept search element from the
user to find it from given array list.
Ans:
Array List is resizable array implementation of the List Interface.
Represents list which is like a single dimensional array that can be resized
dynamically.
Should be considered when there is more data retrieval than add or delete.
In addition to Implementing the List interface, this class provides methods to
manipulate the size of the array that is used internally to store the list.
It is an ordered collection (by Index).
Often used methods – add(), get(), remove(), set(), size()
E.g. [Link]
[Link]
Example :
import [Link];
import [Link];
public class SearchElement {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
Scanner scanner = new Scanner([Link]);
// Add elements to the ArrayList
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](50);
[Link]("Enter the element to search: ");
int searchElement = [Link]();
// Search for the element in the ArrayList
boolean found = false;
for (int number : numbers) {
if (number == searchElement) {
found = true;
break;
}
}
if (found) {
[Link]("Element found in the ArrayList.");
} else {
[Link]("Element not found in the ArrayList.");
}
}
}
Output :
Enter the element to search: 10
Element found in the ArrayList.
b) What is the mean of hashing? Explain with suitable example for insert operation in hash
map.
Ans: Hashing :
It is the process of converting an object into an integer value. The integer value helps
in indexing and faster searches.
Hashing means using some function or algorithm to map object data to some
representative integer value.
This so-called hash code (or simply hash) can then be used as a way to narrow down
our search when looking for the item in the map.
Generally, these hash codes are used to generate an index, at which the value is stored.
Example:
import [Link];
public class HashMapExample {
public static void main(String[] args) {
// Create a new HashMap
HashMap<String, Integer> hashMap = new HashMap<>();
// Insert key-value pairs into the HashMap
[Link]("John", 25);
[Link]("Alice", 30);
[Link]("Bob", 35);
// Print the HashMap
[Link]("HashMap: " + hashMap);
}
}
Output: HashMap: {Bob=35, Alice=30, John=25}
c) Write a note on tree set and tree map
Ans: 1)Tree set :
The Java tree set class implement the set interface that uses a tree for storage. It inherits
abstract set class and implements the navigation interface the object of the tree state class are
stored in ascending order.
Contains unique elements only like hash set
Axis and retrieval time are quite fast
doesn’t allow null element.
Three said is non synchronised.
Three set maintain ascending order.
Example : // TreeSet
import [Link].*;
public class TreeSetDemo {
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//traversing elements
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Output:
Ajay
Ravi
Vijay
2)tree map
A map contains values on the basis of key, i.e. key and value pair. Each key and value
pair is known as an entry.
A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis of a key.
There are two interfaces for implementing Map in java: Map and SortedMap, and
three classes: HashMap, LinkedHashMap, and TreeMap.
A Map can't be traversed, so you need to convert it into Set
using keySet() or entrySet() method.
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key
or value.
d) Write a short note on list interface.
Ans:
It is the child interface of collection.
If we want to represent a group of individual objects as a single entity where
duplicates are allowed and insertion order must be preserved then we should go for
List.
We can differentiate duplicates by using Index.
We can preserve insertion order by using index , hence index play very important role
in list interface.
Q.4)
a) Design following GUI>using Submit AWT component.
Student Name:
City:
Gender:
Male Female
Language: Data Structure Java
Ans:
import [Link].*;
import [Link].*;
public class StudentForm {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public StudentForm(){
prepareGUI();
}
public static void main(String[] args){
StudentForm studentForm = new StudentForm();
[Link]();
}
private void prepareGUI(){
mainFrame = new Frame("Student Form");
[Link](400,400);
[Link](new GridLayout(3, 1));
[Link](new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
[Link](0);
}
});
headerLabel = new Label();
[Link]([Link]);
statusLabel = new Label();
[Link]([Link]);
[Link](350,100);
controlPanel = new Panel();
[Link](new FlowLayout());
[Link](headerLabel);
[Link](controlPanel);
[Link](statusLabel);
[Link](true);
}
private void showEventDemo(){
[Link]("Student Form");
Label nameLabel = new Label("Name: ", [Link]);
TextField nameText = new TextField(6);
Label cityLabel = new Label("City: ", [Link]);
TextField cityText = new TextField(6);
CheckboxGroup genderGroup = new CheckboxGroup();
Checkbox maleCheckbox = new Checkbox("Male", genderGroup, false);
Checkbox femaleCheckbox = new Checkbox("Female", genderGroup, false);
Checkbox languageJava = new Checkbox("Java");
Checkbox languagePython = new Checkbox("Python");
Button submitButton = new Button("Submit");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Name: " + [Link]()
+ ", City: " + [Link]()
+ ", Gender: " + ([Link]() ? "Male" : "Female")
+ ", Language: " + ([Link]() ? "Java " : "")
+ ([Link]() ? "Python" : ""));
}
});
[Link](nameLabel);
[Link](nameText);
[Link](cityLabel);
[Link](cityText);
[Link](maleCheckbox);
[Link](femaleCheckbox);
[Link](languageJava);
[Link](languagePython);
[Link](submitButton);
[Link](true);
}
}
b) Demonstrate key listener interface with suitable example.
Ans:
Java Key Listener interface
The Java KeyListener is notified whenever you change the state of key. It
is notified against KeyEvent. The KeyListener interface is found in [Link]
package, and it has three methods.
Interface Declaration:
public interface KeyListener extends EventListener
Methods of Key Listener interface
Sr. Method name Description
no.
1. public abstract void It is invoked when a
keyPressed key has been
(KeyEvent e); pressed.
2. public abstract void It is invoked when a
keyReleased key has been
(KeyEvent e); released.
3. public abstract void It is invoked when a
keyTyped key has been
(KeyEvent e); typed.
Example:
1. // importing awt libraries
2. import [Link].*;
3. import [Link].*;
4. // class which inherits Frame class and implements KeyListener inter
face
5. public class KeyListenerExample extends Frame implements Key
Listener {
6. // creating object of Label class and TextArea class
7. Label l;
8. TextArea area;
9. // class constructor
10. KeyListenerExample() {
11. // creating the label
12. l = new Label();
13. // setting the location of the label in frame
14. [Link] (20, 50, 100, 20);
15. // creating the text area
16. area = new TextArea();
17. // setting the location of text area
18. [Link] (20, 80, 300, 300);
19. // adding the KeyListener to the text area
20. [Link](this);
21. // adding the label and text area to the frame
22. add(l);
23. add(area);
24. // setting the size, layout and visibility of frame
25. setSize (400, 400);
26. setLayout (null);
27. setVisible (true);
28. }
29. // overriding the keyPressed() method of KeyListener interface
where we set the text of the label when key is pressed
30. public void keyPressed (KeyEvent e) {
31. [Link] ("Key Pressed");
32. }
33. // overriding the keyReleased() method of KeyListener interfac
e where we set the text of the label when key is released
34. public void keyReleased (KeyEvent e) {
35. [Link] ("Key Released");
36. }
37. // overriding the keyTyped() method of KeyListener interface w
here we set the text of the label when a key is typed
38. public void keyTyped (KeyEvent e) {
39. [Link] ("Key Typed");
40. }
41. // main method
42. public static void main(String[] args) {
43. new KeyListenerExample();
44. }
45. }
46. Output:
47.
Q.5)
a) Create Jdbc application for product table with fields id name and price
perform insert operation and display inserted data retrieved from table to
the user.
Ans:
1) import [Link].*;
import [Link].*;
public class StudentForm {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public StudentForm(){
prepareGUI();
}
public static void main(String[] args){
StudentForm studentForm = new StudentForm();
[Link]();
}
private void prepareGUI(){
mainFrame = new Frame("Student Form");
[Link](400,400);
[Link](new GridLayout(3, 1));
[Link](new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
[Link](0);
}
});
headerLabel = new Label();
[Link]([Link]);
statusLabel = new Label();
[Link]([Link]);
[Link](350,100);
controlPanel = new Panel();
[Link](new FlowLayout());
[Link](headerLabel);
[Link](controlPanel);
[Link](statusLabel);
[Link](true);
}
private void showEventDemo(){
[Link]("Student Form");
Label nameLabel = new Label("Name: ", [Link]);
TextField nameText = new TextField(6);
Label cityLabel = new Label("City: ", [Link]);
TextField cityText = new TextField(6);
CheckboxGroup genderGroup = new CheckboxGroup();
Checkbox maleCheckbox = new Checkbox("Male", genderGroup, false);
Checkbox femaleCheckbox = new Checkbox("Female", genderGroup, false);
Checkbox languageJava = new Checkbox("Java");
Checkbox languagePython = new Checkbox("Python");
Button submitButton = new Button("Submit");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Name: " + [Link]()
+ ", City: " + [Link]()
+ ", Gender: " + ([Link]() ? "Male" : "Female")
+ ", Language: " + ([Link]() ? "Java " : "")
+ ([Link]() ? "Python" : ""));
}
});
[Link](nameLabel);
[Link](nameText);
[Link](cityLabel);
[Link](cityText);
[Link](maleCheckbox);
[Link](femaleCheckbox);
[Link](languageJava);
[Link](languagePython);
[Link](submitButton);
[Link](true);
}
}
2)import [Link].*;
public class JdbcProductApp {
public static void main(String[] args) {
try {
// Register JDBC driver
[Link]("[Link]");
// Open a connection
Connection conn = [Link](
"jdbc:mysql://localhost/your_database_name", "your_username",
"your_password");
// Execute a query to create table
Statement stmt = [Link]();
String sql = "CREATE TABLE Product " +
"(id INTEGER not NULL, " +
" name VARCHAR(255), " +
" price FLOAT, " +
" PRIMARY KEY ( id ))";
[Link](sql);
// Execute a query to insert data
sql = "INSERT INTO Product " +
"VALUES (100, 'Product1', 1000.00)";
[Link](sql);
// Execute a query to select data
sql = "SELECT id, name, price FROM Product";
ResultSet rs = [Link](sql);
// Extract data from result set
while([Link]()){
// Retrieve by column name
int id = [Link]("id");
String name = [Link]("name");
float price = [Link]("price");
// Display values
[Link]("ID: " + id);
[Link](", Name: " + name);
[Link](", Price: " + price);
}
// Clean-up environment
[Link]();
[Link]();
[Link]();
} catch(Exception se) {
// Handle errors for JDBC
[Link]();
}
}
}
b) Create a web page by using servlet find factorial of a given number.
Ans:
First create HTML file [Link]
<!DOCTYPE html>
<html>
<body>
<form action="FactorialServlet" method="post">
Enter a number: <input type="number" name="num" required>
<input type="submit" value="Submit">
</form>
</body>
</html>
Then,creat a servlet [Link]:
import [Link].*;
import [Link].*;
import [Link].*;
public class FactorialServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
int num = [Link]([Link]("num"));
int factorial = 1;
for(int i = 1; i <= num; ++i) {
factorial *= i;
}
[Link]("<html><body>");
[Link]("<h1>Factorial of " + num + " is " + factorial + "</h1>");
[Link]("</body></html>");
}
}
Finally,you need to configure your servlet in [Link]
<web-app>
<servlet>
<servlet-name>FactorialServlet</servlet-name>
<servlet-class>FactorialServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FactorialServlet</servlet-name>
<url-pattern>/FactorialServlet</url-pattern>
</servlet-mapping>
</web-app>