Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
52 views

Java Programming456 QB

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

Java Programming456 QB

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

MAHENDRA ENGINEERING COLLEGE(AUTONOMOUS)

QUESTION BANK
19CS14403 JAVA PROGRAMMING
PART-A (ONE MARK QUESTIONS)
I.Choose the correct answer
1) Which package contains the Random class?
a) java.util package
b) java.lang package
c) java.awt package
d) java.io package
2) What do you mean by nameless objects?
a) An object created by using the new keyword.
b) An object of a superclass created in the subclass.
c) An object without having any name but having a reference.
d) An object that has no reference.
3) Which of the following exception is thrown when divided by zero statement is executed?
a) Null Pointer Exception
b) Number Format Exception
c) Arithmetic Expression
4) What do you mean by chained exceptions in Java?
a) Exceptions occurred by the Virtual Machine Error
b) An exception caused by other exceptions
c) Exceptions occur in chains with discarding the debugging information
d) None of the above
5) Which of the following option leads to the portability and security of Java?
a) Byte code is executed by JVM
b) The applet makes the Java code secure and portable
c) Use of exception handling
d) Dynamic binding between objects
6) Which of the following is not a Java features?
a) Dynamic
b) Architecture Neutral
c) Use of pointers
d) Object-oriented
7) _____ is used to find and fix bugs in the Java programs.
a) JVM
b) JRE
c) JDK
d) JDB
8) What does the expression float a = 35 / 0 return?
a) 0
b) Not a Number
c) Infinity
d) Run time exception
9) Evaluate the following Java expression, if x=3, y=5, and z=10:
++z + y - y + z + x++
a) 24
b) 23
c) 20
d) 25
10) Which of the following for loop declaration is not valid?
a) for ( int i = 99; i >= 0; i / 9 )
b) for ( int i = 7; i <= 77; i += 7 )
c) for ( int i = 20; i >= 2; - -i )
d) for ( int i = 2; i <= 20; i = 2* i )
11) Which option is false about the final keyword?
a) A final method cannot be overridden in its subclasses.
b) A final class cannot be extended.
c) A final class cannot extend other classes.
d) A final method can be inherited.
12) Which of the following is a mutable class in java?
a) java.lang.String
b) java.lang.Byte
c) java.lang.Short
d) java.lang.StringBuilder
13) Number of primitive data types in Java are?
a) 6
b) 8
c) 9
d) 10
14)What is the size of float and double in java?
a) 32 and 64
b) 32 and 32
c) 64 and 64
d) 64 and 32

15) Find the output of the following code.


int Integer = 24;
char String = ‘I’;
System.out.print(Integer);
System.out.print(String);
a) Compile error
b) Throws exception
c) I
d) 24 I
16) Select the valid statement.
a) char[] ch = new char(5)
b) char[] ch = new char[5]
c) char[] ch = new char()
d) char[] ch = new char[]
17) Select the valid statement to declare and initialize an array.
a) int[] A = {}
b) int[] A = {1, 2, 3}
c) int[] A = (1, 2, 3)
d) int[][] A = {1,2,3}
18) When is the object created with new keyword?
a) At Runtime
b) At compile time
c) Depends on the code
d) None
19) Identify the corrected definition of a package.
a) A package is a collection of editing tools
b) A package is a collection of classes
c) A package is a collection of classes and interfaces
d) A package is a collection of interfaces
20) In which of the following is toString() method defined?
a) Java.lang.object
b) java.lang.String
c) java.lang.util
d) None
21) CompareTo() returns
a) True
b) False
c) An int value
d) None
22) Identify the output of the following program.
Public class Test{
Public static void main(String argos[]){
String str1 = “one”;
String str2 = “two”;
System.out.println(str1.concat(str2));
}}
a) one
b) two
c) one two
d) two one
23) Identify the return type of a method that does not return any value.
a) int
b) void
c) double
d) None
24)Identify the modifier which cannot be used for constructor.
a) public
b) protected
c) private
d) static
25) What is the variables declared in a class for the use of all methods of the class called?
a) Object
b) Instance Variable
c) Reference variable
d) None
26) Identify the correct way of declaring constructor.Public class Solution {}
a) Solution()
b) public Solution()
c) Solution(void){}
d) Both (A) and (B)
27) How many times will “Interviewbit” be printed.
Int count = 0;
do{
System.out.println(“Interviewbit”);
count++;
} while(count < 10);
a) 8
b) 9
c) 10
d) 11
28) Which statement is true about Java?
a) Java is a sequence-dependent programming language
b) Java is a code dependent programming language
c) Java is a platform-dependent programming language
d) Java is a platform-independent programming language
29) Which of these cannot be used for a variable name in Java?
a) identifier & keyword
b) identifier
c) keyword
d) none of the mentioned
30) What is the extension of java code files?
a) .js
b) .txt
c) .class
d) .java
II.Filling the blanks
1. ________________________keyword used to implements inheritance
2. Mention the keyword using while interface
3. One base one derived class is known as_______________
4. String in Java is ______________
5. A constructor in java is a special method that is used to __________ objects
6. ___________method of String class can be used to test to strings for equality
7. Arrays are used to store ___________values in a ________ variable
8. The ---------- statement is used to include another Java package in a Java source file.
9. The output of the Java compiler is executed by the ----------
10. A ----------------- is a collection of classes and interfaces
11. The output of the Java compiler is known as -----------------.
12. Father of Java Programming Language is________________
13. ----------------- is the java compiler.
14. URL stands for -------------------.
15. ----------------- command is used as the Java interpreter.
16. Java supports -------------------_ programming.
17. ----------------- declares a class variable that is to be shared among all instances.
18. Methods defined in an interface must be -------------------.
19. Java is a ----------- generation language.
20. Many objects and their code form a user defined data type called ----------.
21. ------------ means data hiding.
22. ----------------- symbol of String class can be used to test the string comparison.
23. Java supports -------------------programming.
24. It is possible to throw an exception explicitly using the ---------- statement.
25. Java compiler produces an object file that contains ----------
26. Java byte code output from the JDK compiler will be placed into a file with ----------
extension.
27. An ----------------- is an object that is generated when a run time error occurs.
28. ------------------is not supported by java.
III. (True /False)

1. The compiler converts source code files into byte code file.

2. Methods defined in an interface must be private.

3. Instance variables are declared outside a class.

4. It is not possible to define, a method in the subclass that has the same name, same

arguments and the same return type.

5. A constructor must have the same name as the class it is declared within.

6. Java is a platform independent language.

7. Java is case sensitive language

8. Multiple Inheritance not supported by java.

9. Syntax of a Java Package is package;

10.A package is a collection of classes and interfaces.

11.An exception is an object that is generated when a run time error occurs.

12.A class declaration can include both abstract and final modifiers.

13.Java supports operator overloading.

14.If a class contains an abstract method, that class itself must also be declared abstract.

15.If a class implements an interface, it must implement all the methods declared by that

interface.

16.If a class definition does not explicitly put a class into a package, the class belongs to the

default package.

17.Java supports multithreaded programming.

18.Java has a keyword called finally.

19.Catch keyword is not a part of exception handling.

20.The object created by the string class can be modified.

21.Java has a keyword called super


I. Choose the correct answer (Answer)

1 A 7 D 13 B 19 C 25 A
2 D 8 C 14 A 20 A 26 D
3 C 9 D 15 D 21 D 27 C
4 B 10 A 16 B 22 D 28 D
5 A 11 C 17 D 23 B 29 C
6 C 12 D 18 A 24 D 30 D

II.Filling the blanks (Answer)

1. Extends

2. Keyword

3. Single inheritance

4. Object

5. Initialize objects

6. Equals ()

7. Multiple, single

8. Import keyword

9. Java Virtual Machine

10. Package

11. Code

12. James Gosling

13. platform-independent Java file

14. Uniform Resource Locator

15. javac command

16. Coding web applications

17. Static variables


18. Abstract

19. third-generation languages

20. A structured type

21. object-oriented programming

22. ==

23. Multi-platform

24. Visual Basic Throw

25. Java byte code

26. Class

27. Exception object

28. Multiple inheritances

III- True/False (Answer)

1 T 5 T 9 F 13 T 17 T
2 T 6 T 10 T 14 F 18 T
3 F 7 T 11 F 15 T 19 F
4 T 8 T 12 F 16 T 20 F
21 T
2 marks (ALL UNITS)
(UNIT 1 TO 4)

1)What is an array?
• In Java, an array is a data structure that allows you to store multiple values
of the same data type in a contiguous memory block.
• Arrays in Java are widely used for storing and manipulating collections of
data.

2)Write the advantages and disadvantages of an array?

Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the
data efficiently.
o Random access: We can get any data located at an index position.

Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection framework
is used in Java which grows automatically.
3)What is strings?

• Strings are used for storing text.

• A String variable contains a collection of characters surrounded by double


quotes:

• Example:String greeting = "Hello";

4) Explain String pool in Java.

• String Pool, also known as SCP (String Constant Pool), is a special storage
space in Java heap memory that is used to store unique string objects.
• Whenever a string object is created, it first checks whether the String object
with the same string value is already present in the String pool or not, and
if it is available, then the reference to the string object from the string pool
is returned.
• Otherwise, the new string object is added to the string pool, and the
respective reference will be returned.
5) Is String immutable in Java? If so, then what are the benefits of Strings being
Immutable?

• Yes, Strings are immutable in Java. Immutable objects mean they can't be
changed or altered once they've been created.
• However, we can only modify the reference to the string object.

6) State the difference between String and StringBuffer.

• String objects in Java are immutable and final, so we can't change their
value after they are created.
• Each time we manipulate a string, a new String object is created, and all
previous objects will be garbage, placing a strain on the garbage collector.
• This is why The Java team developed StringBuffer.
• A StringBuffer is a mutable object, meaning it can be changed, but the
string is an immutable object, so it cannot be changed once it has been
created.

7)Write the program for reversing a string.


package strings;
import java.util.Scanner;

public class Reverse {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);


String s=sc.nextLine();
String strn="";
for(int i=0;i<s.length();i++)
{
strn=s.charAt(i)+strn;
}
System.out.println(strn);

}
8)How to reverse an array?
package arrays;
import java.util.Scanner;

public class Reverse {


public static void main(String[]args)
{
int arr[]={5,2,1,7,5};
int start=0;
int temp;
int end=arr.length-1;

while(start<end)
{
temp=arr[start];
arr[start]=arr[end];
arr[end]=temp;
start++;
end--;
}
for(int i:arr)
{
System.out.println(i);
}
}
}

9)Draw the lifecycle of Thread.

In Java, a thread always exists in any one of the following states. These states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
10) What is multithreading?

• Multithreading is a process of executing multiple threads simultaneously.


Multithreading is used to obtain the multitasking. It consumes less memory
and gives the fast and efficient performance.

Its main advantages are:


• Threads share the same address space.
• The thread is lightweight.
• The cost of communication between the processes is low.

11) What do you understand by inter-thread communication?


• The process of communication between synchronized threads is termed
as inter-thread communication.
• Inter-thread communication is used to avoid thread polling in Java.
• The thread is paused running in its critical section, and another thread is
allowed to enter (or lock) in the same critical section to be executed.
• It can be obtained by wait(), notify(), and notifyAll() methods.
12) What are the advantages of multithreading?

Multithreading programming has the following advantages:


• Multithreading allows an application/program to be always reactive for
input, even already running with some background tasks
• Multithreading allows the faster execution of tasks, as threads execute
independently.
• Multithreading provides better utilization of cache memory as threads
share the common memory resources.
• Multithreading reduces the number of the required server as one server
can execute multiple threads at a time.

13) Can we call the run() method instead of start()?

• Yes, calling run() method directly is valid, but it will not work as a thread
instead it will work as a normal object.
• There will not be context-switching between the threads.
• When we call the start() method, it internally calls the run() method, which
creates a new stack for a thread while directly calling the run() will not
create a new stack.

14)What is Synchronization?

• Synchronization in Java is the capability to control the access of multiple


threads to any shared resource.
• Java Synchronization is better option where we want to allow only one
thread to access the shared resource.

14) What is Thread Scheduler in java?

• In Java, when we create the threads, they are supervised with the help of a
Thread Scheduler, which is the part of JVM.
• Thread scheduler is only responsible for deciding which thread should be
executed.
Java thread scheduler also works for deciding the following for a thread:
• It selects the priority of the thread.
• It determines the waiting time for a thread
• It checks the Nature of thread
15) What is race-condition?

• A Race condition is a problem which occurs in the multithreaded


programming when various threads execute simultaneously accessing a
shared resource at the same time.
• The proper use of synchronization can avoid the Race condition.

16)What is ThreadPriority?
Priorities in threads is a concept where each thread is having a priority which in
layman’s language one can say every object is having priority here which is
represented by numbers ranging from 1 to 10.
• The default priority is set to 5 as excepted.
• Minimum priority is set to 1.
• Maximum priority is set to 10.
Here 3 constants are defined in it namely as follows:
1. public static int NORM_PRIORITY
2. public static int MIN_PRIORITY
3. public static int MAX_PRIORITY

17)What is deadlock?

Deadlock in java is a programming situation where two or more threads are


blocked forever. Java deadlock situation arises with at least two threads and two or
more resources.

18)What is meant by java files?


• A Java file is a text-based file that contains source code written in the Java
programming language.
• It typically has a ".java" file extension.
• This file contains instructions that a Java compiler can understand and
translate into bytecode, which can then be executed by the Java Virtual
Machine (JVM).
• Java files contain classes, methods, variables, and other programming
constructs that define the behavior and structure of a Java program.
19)What is Stream Filtering and Piping?
1. Stream Filtering: Stream filtering is about selecting specific items from a
collection or sequence that meet a certain condition. It's like sifting through
a list and keeping only the items that match a particular rule.
2. Piping (Pipelining): Piping involves passing the output of one operation as
the input to the next. It's like creating a chain of actions where each action
processes the data further. This is often used to streamline complex tasks by
breaking them into smaller, interconnected steps.

20)What is Swing?

• Swing is a Java library used to create graphical user interfaces (GUIs) for
desktop applications.
• It provides a set of components like buttons, text fields, and windows that
developers can use to build interactive and visually appealing software
interfaces.

21)What is AWT?

• AWT stands for "Abstract Window Toolkit."


• It is a graphical user interface (GUI) toolkit that was introduced in the early
versions of the Java programming language.
• AWT provides a set of classes and components that allow developers to
create graphical interfaces for their Java applications.
• It includes basic GUI elements such as buttons, text fields, checkboxes, and
windows.

22)What is JDBC?

• JDBC stands for Java Database Connectivity.


• It's a Java technology that lets Java programs interact with relational
databases.
• It provides classes to connect, query, and update databases.

23)What is JDBC driver?

• A JDBC driver is a software component that enables Java applications to


connect and interact with specific types of databases using the Java Database
Connectivity (JDBC) API.
• It acts as an interface between the Java application and the database,
translating Java calls into database-specific calls and vice versa.

24) What are the steps to connect to the database in java?

To connect to a database in Java:


1. Import: Begin by importing the necessary JDBC packages, such as java.sql.
2. Load Driver: Use Class.forName() to load the JDBC driver specific to the
database being used.
3. Connection URL: Create a connection URL with details like the database
location, port, and name.
4. Establish Connection: Use DriverManager.getConnection() to establish a
connection, providing the URL, username, and password.

25) Differentiate between Statement and PreparedStatement in JDBC.


• Statement:
• Executes SQL queries directly.
• Vulnerable to SQL injection attacks.
• Re-compiles query each time, affecting performance.
• Suitable for simple, one-time queries.
• Used for executing dynamic or changing queries.
• PreparedStatement:
• Pre-compiles SQL queries for reusability.
• Mitigates SQL injection risks.
• Improves performance as query is compiled only once.
• Suitable for frequently executed or repetitive queries.
• Used when query structure remains constant, but parameters change.
UNIT-5 TO 8

26)What is Socket?

• Socket programming in Java allows you to establish communication


between different devices over a network using sockets.
• A socket is a combination of an IP address and a port number, which
together enable two-way communication between a client and a server.

27)What is secure sockets?


• Secure Socket Layer (SSL) provides security to the data that is transferred
between web browser and server.
• SSL encrypts the link between a web server and a browser which ensures
that all data passed between them remain private and free from attack.
28)Write the protocols of secure sockets.
Secure Socket Layer Protocols:
• SSL record protocol
• Handshake protocol
• Change-cipher spec protocol
• Alert protocol
29)What is record protocol?
• The SSL (Secure Sockets Layer) record protocol is a key component of the
SSL/TLS (Transport Layer Security) protocol suite, which is used to secure
data transmission over the internet. ]
• The SSL record protocol is responsible for fragmenting, compressing
(optional), encrypting, and authenticating data to ensure the confidentiality,
integrity, and authenticity of information exchanged between a client and a
server.

30)What is TCP?
• TCP, or Transmission Control Protocol, is one of the core protocols of the
Internet Protocol (IP) suite.
• It operates at the transport layer of the OSI model and plays a crucial role in
providing reliable and connection-oriented communication between devices
on a network.
31)What is encryption?

• Encryption is the process of converting information or data into a code or


cipher to make it unreadable to anyone who doesn't have the decryption key
or the necessary knowledge to decipher it.
• It is used to protect sensitive information, such as personal messages,
financial data, or confidential documents, from unauthorized access or
interception.
32)What is decryption?

• Decryption is the process of converting encrypted data or information back


into its original, readable form.
• It involves using a decryption key or algorithm to reverse the encryption
process and make the data accessible to authorized users.
• Decryption is essential for retrieving and understanding encrypted
information, and it ensures that only those with the appropriate keys or
credentials can access the protected data.
33)What is client server computing?
• Client-server computing is a network architecture and model that defines
how applications and services are structured and distributed in a networked
environment. In a client-server model, there are two primary components:
the client and the server.
• These components work together to facilitate communication and data
processing in a networked system.
34)What is RMI?

• RMI, which stands for Remote Method Invocation, is a technology used in


Java for making one program call functions or methods in another program,
even if they are on different computers.

• It allows Java programs to communicate and work together across a


network.
35)What is Java API?

Java API, which stands for "Application Programming Interface," refers to a set of
pre-defined classes, methods, and interfaces provided by the Java programming
language for developers to use when building Java applications.

36)What is meant by Java Servlets?

• Java Servlets are Java-based server-side components used to extend the


capabilities of a web server. They provide a way to dynamically generate
and process web content, typically in response to user requests.

• Servlets are a key part of the Java Platform, Enterprise Edition (Java EE),
and they are commonly used to create web applications.

37)Difference between Servlet and CGI.

Servlet CGI(Common Gateway Interface)

Servlets are portable and efficient. CGI is not portable

In Servlets, sharing data is possible. In CGI, sharing data is not possible.

Servlets can directly communicate CGI cannot directly communicate with


with the webserver. the webserver.

Servlets are less expensive than CGI. CGI is more expensive than Servlets.

Servlets can handle the cookies. CGI cannot handle the cookies.

38)What is meant by scripting?


Scripting in the context of web development refers to the use of scripting
languages, which are lightweight, interpreted programming languages, to enhance
the functionality and interactivity of web pages.

39)Tell about Custom Tag Libraries.

Custom tag libraries, often referred to simply as tag libraries, are a feature in web
development that allows developers to define and use their own custom tags in JSP
(JavaServer Pages) and other Java-based web frameworks.

40)Tell about implicit objects.

Implicit objects in web development are predefined objects that are automatically
available to server-side scripts (e.g., in JavaServer Pages or JSP, Active Server
Pages or ASP, and other similar technologies) without the need for explicit
declaration.
10 marks(UNIT-1 TO 4)

1)Write the program to find the frequency of characters in a string.


2)Write the program to find the frequency of array.
3)Sort the elements of an array using bubble sort.
4) Check if two strings are Anagram or not.
5) Find Second Smallest Element in an Array without sorting.
6)Explain in detail of life cycle of thread.

In Java, a thread always exists in any one of the following states. These states are:

1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated

Explanation of Different Thread States


New: Whenever a new thread is created, it is always in the new state. For a thread
in the new state, the code has not been run yet and thus has not begun its execution.

Active: When a thread invokes the start() method, it moves from the new state to the
active state. The active state contains two states within it: one is runnable, and the
other is running.

History of Java
o Runnable: A thread, that is ready to run is then moved to the runnable state.
In the runnable state, the thread may be running or may be ready to run at any
given instant of time. It is the duty of the thread scheduler to provide the thread
time to run, i.e., moving the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each
individual thread. Each and every thread runs for a short span of time and
when that allocated time slice is over, the thread voluntarily gives up the CPU
to the other thread, so that the other threads can also run for their slice of time.
Whenever such a scenario occurs, all those threads that are willing to run,
waiting for their turn to run, lie in the runnable state. In the runnable state,
there is a queue where the threads lie.
o Running: When the thread gets the CPU, it moves from the runnable to the
running state. Generally, the most common change in the state of a thread is
from runnable to running and again back to runnable.

Blocked or Waiting: Whenever a thread is inactive for a span of time (not


permanently) then, either the thread is in the blocked state or is in the waiting state.

For example, a thread (let's say its name is A) may want to print some data from the
printer. However, at the same time, the other thread (let's say its name is B) is using
the printer to print some data. Therefore, thread A has to wait for thread B to use the
printer. Thus, thread A is in the blocked state. A thread in the blocked state is unable
to perform any execution and thus never consume any cycle of the Central
Processing Unit (CPU). Hence, we can say that thread A remains idle until the thread
scheduler reactivates thread A, which is in the waiting or blocked state.

When the main thread invokes the join() method then, it is said that the main thread
is in the waiting state. The main thread then waits for the child threads to complete
their tasks. When the child threads complete their job, a notification is sent to the
main thread, which again moves the thread from waiting to the active state.

If there are a lot of threads in the waiting or blocked state, then it is the duty of the
thread scheduler to determine which thread to choose and which one to reject, and
the chosen thread is then given the opportunity to run.

Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread
(its name is A) has entered the critical section of a code and is not willing to leave
that critical section. In such a scenario, another thread (its name is B) has to wait
forever, which leads to starvation. To avoid such scenario, a timed waiting state is
given to thread B. Thus, thread lies in the waiting state for a specific span of time,
and not forever. A real example of timed waiting is when we invoke the sleep()
method on a specific thread. The sleep() method puts the thread in the timed wait
state. After the time runs out, the thread wakes up and start its execution from when
it has left earlier.

Terminated: A thread reaches the termination state because of the following reasons:

o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an
unhandled exception or segmentation fault.

A terminated thread means the thread is no more in the system. In other words, the
thread is dead, and there is no way one can respawn (active after kill) the dead thread.

7)Explain about the ThreadPriorities and Synchronization.

In Java, thread priorities are used to indicate the relative importance of one thread
compared to another within the same program. Thread priorities can influence how
the operating system schedules threads for execution, but they do not guarantee
strict ordering or deterministic behavior.

Java provides thread priorities as a way to influence the scheduling of threads by


the underlying operating system. However, it's important to note that the actual
behavior might vary between different operating systems and JVM
implementations.
Thread priorities are represented by integer values defined within the Thread class:

• Thread.MIN_PRIORITY (1): The minimum priority value.


• Thread.NORM_PRIORITY (5): The default priority value.
• Thread.MAX_PRIORITY (10): The maximum priority value.
Here's how you can set the priority of a thread in Java:
Thread thread = new Thread(runnable);
thread.setPriority(Thread.NORM_PRIORITY); // Set the thread's priority

Synchronization
Synchronization in the context of multithreaded programming refers to the
coordination and control of multiple threads to ensure proper and safe execution in
shared resources and critical sections. Without synchronization, when multiple
threads access and manipulate shared data concurrently, it can lead to race
conditions, data corruption, and unexpected behavior. Synchronization
mechanisms prevent these issues by ensuring that only one thread can access a
critical section of code or a shared resource at a time.

synchronized Methods: You can declare a method as synchronized to ensure


that only one thread can execute it at a time on a particular instance of the
class. When a thread enters a synchronized method, it obtains the intrinsic
lock (also known as a monitor) associated with the instance. Other threads
attempting to execute synchronized methods on the same instance will be
blocked until the lock is released.
public synchronized void synchronizedMethod() {
// Only one thread can execute this method at a time
}

8)Explain the multithreading in detail.


Multithreading is a Java feature that allows concurrent execution of two or more
parts of a program for maximum utilization of CPU. Each part of such program is
called a thread. So, threads are light-weight processes within a process.
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread class. This class overrides the
run() method available in the Thread class. A thread begins its life inside run()
method. We create an object of our new class and call start() method to start the
execution of a thread. Start() invokes the run() method on the Thread object.

// Java code for thread creation by extending


// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}

Thread creation by implementing the Runnable Interface


We create a new class which implements java.lang.Runnable interface and
override run() method. Then we instantiate a Thread object and call start()
method on this object.
// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new MultithreadingDemo());
object.start();
}
}
}
Output
Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running
9)Explain the difference between Thread class and Runnable interface.
In Java, both the Thread class and the Runnable interface are used to create and
manage threads for concurrent execution. However, they have distinct purposes
and usage patterns. Let's delve into the differences between the two:

Thread Class:
1. Inheritance: The Thread class is a concrete class in Java's java.lang package.
When you want to create a new thread, you can directly subclass the Thread
class and override its run() method, which contains the code that the thread
will execute.
2. Limitation: Java only supports single inheritance, so if you extend the
Thread class, you cannot extend another class, limiting your flexibility in
terms of code reuse.
3. Thread Control: Since the Thread class encapsulates both the thread's
behavior and its management, it provides methods to directly control the
thread, such as start() to begin execution and join() to wait for the thread to
complete.
4. Thread Instance: Each thread corresponds to an instance of the Thread class.
This means that if you want to create multiple threads, you need to create
multiple instances of the Thread class.
5. Less Flexible Resource Sharing: Sharing resources between threads created
using the Thread class can be more challenging, as the thread instances
themselves encapsulate both behavior and execution.

Example of using Thread class:

class MyThread extends Thread {


public void run() {
// Thread's execution code
}
}

MyThread thread = new MyThread();


thread.start(); // Start the thread
Runnable Interface:
1. Interface Implementation: The Runnable interface is designed to be
implemented by classes that represent the task that a thread will execute. It
focuses solely on the thread's behavior without dealing with the thread's
management.
2. Better Code Reusability: Since Java supports multiple interfaces,
implementing Runnable allows you to extend another class and still define
the thread's behavior. This promotes better code organization and
reusability.
3. Thread Management Separation: To actually execute a Runnable task in a
separate thread, you need to create an instance of the Thread class and pass
the Runnable implementation to it. This separation of thread management
and behavior allows for more flexible resource sharing.
4. Thread Instance: You can create multiple threads using a single instance of
the Runnable implementation. This is often more memory-efficient than
creating multiple instances of the Thread class.
5. Encourages Composition over Inheritance: Java's design philosophy favors
composition over inheritance. Implementing Runnable promotes this
philosophy, allowing you to encapsulate the behavior of the thread without
being locked into a specific inheritance hierarchy.

Example of using Runnable interface:

class MyRunnable implements Runnable {


public void run() {
// Thread's execution code
}
}

MyRunnable runnable = new MyRunnable();


Thread thread = new Thread(runnable);
thread.start(); // Start the thread
In summary, the choice between using the Thread class or implementing the
Runnable interface depends on your design goals. Using the Runnable interface
promotes better code structure and reusability, while using the Thread class
directly can be simpler for very basic scenarios. However, in most cases,
implementing Runnable is recommended due to its flexibility and separation of
concerns.
10)Explain in detail about stream filtering and piping.
In computer programming, "stream filtering" and "piping" are concepts commonly
associated with data processing, especially in the context of input/output
operations. They are often used to process and transform data in a sequential
manner. Let's explore these concepts in detail:

Stream Filtering:
Stream filtering refers to the process of extracting, modifying, or manipulating
specific elements from a data stream based on certain criteria. Data streams can be
sequences of characters, bytes, or any other type of data that can be processed
sequentially. Stream filtering is a common technique used to process large datasets
efficiently without loading the entire dataset into memory at once.

In Java, stream filtering is typically associated with the Java Streams API
introduced in Java 8. Java Streams provide a powerful and functional way to
process collections and other data sources. Streams allow you to apply various
operations such as filtering, mapping, sorting, and reducing on data in a concise
and expressive manner.

Here's a simple example of stream filtering in Java:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamFilterExample {


public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());

System.out.println(evenNumbers); // Output: [2, 4, 6, 8, 10]


}
}

In this example, the filter operation is used to select only the even numbers from
the list of integers.

Piping:
Piping refers to the practice of connecting the output of one process or function as
the input to another, forming a chain of processing steps. Each step in the pipeline
performs a specific operation on the data and passes the modified data to the next
step. Piping is a powerful way to combine multiple operations into a single
sequence, making complex data transformations more manageable and readable.

Piping is commonly used in Unix-like operating systems through the shell's


command-line interface, where the output of one command can be directly fed as
input to another command using the pipe (|) operator.

In programming, piping can be achieved using various constructs, such as function


chaining or method chaining. Many modern programming languages and libraries
provide built-in support for method chaining, allowing you to perform a series of
operations on a data source seamlessly.

Let's create an example using method chaining to process a list of strings:


import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;
public class PipingExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry", "date",
"elderberry");

// Example of method chaining (piping)


List<String> filteredAndTransformed = words.stream()
.filter(word -> word.length() > 5) // Filter words with length > 5
.map(String::toUpperCase) // Convert words to uppercase
.sorted() // Sort the words alphabetically
.collect(Collectors.toList());

System.out.println(filteredAndTransformed); // Output: [BANANA,


CHERRY, ELDERBERRY]
}
}

In this example:

1. We have a list of strings (words), and we want to perform a series of


operations on it.
2. We use the stream() method to create a stream of elements from the list.
3. The filter operation selects only the words with a length greater than 5
characters.
4. The map operation transforms each word to uppercase.
5. The sorted operation sorts the words alphabetically.
6. Finally, the collect operation gathers the processed elements into a new list.

The result is a new list containing the filtered, transformed, and sorted words.
While this isn't exactly the same as piping in Unix shells, it offers a similar concept
of chaining operations to process data. Java's Stream API provides a powerful and
expressive way to achieve such data transformations in a functional and efficient
manner.

11) What is the difference between swing and awt.


Swing and AWT (Abstract Window Toolkit) are both Java libraries used for
creating graphical user interfaces (GUIs) in Java applications. However, they have
some key differences in terms of features, components, and architecture:

AWT (Abstract Window Toolkit):


1. Native Components: AWT components are lightweight wrappers around the
native GUI components provided by the underlying operating system. This
means AWT components are directly mapped to native components, which
can give an appearance consistent with the host operating system's look and
feel.
2. Limited Widgets: AWT offers a basic set of GUI components, including
buttons, labels, text fields, and panels. The component set is relatively
limited and lacks more advanced UI elements like tables, trees, and tabbed
panes.
3. Platform Dependence: AWT components directly utilize native widgets,
which can lead to differences in appearance and behavior across different
operating systems.
4. Thread Safety: AWT components are not inherently thread-safe, which can
lead to synchronization issues in multithreaded applications.
5. Event Handling: AWT uses a simple event handling model, where event
listeners are directly registered on components.
Swing:
1. Lightweight Components: Swing components are implemented in Java and
are therefore known as lightweight components. They are not tied to native
components, resulting in a more consistent appearance across different
platforms.
2. Rich Component Set: Swing offers a much wider range of GUI components
compared to AWT. It includes advanced components like tables, trees, text
areas, and more. Swing also provides customizable components that allow
for a higher degree of control over appearance and behavior.
3. Look and Feel: Swing components can be styled independently of the
underlying operating system. Swing offers pluggable look and feel (PLAF)
mechanisms, allowing developers to choose between different visual themes,
such as the default "Metal" look, the native look, or third-party themes.
4. Thread Safety: Swing components are designed to be thread-safe. However,
Swing follows the single-threaded model, where all UI-related tasks should
be performed on the event dispatch thread (EDT).
5. Event Handling: Swing uses a more sophisticated event handling model that
allows events to be captured and processed more flexibly. Event listeners
can be registered for specific events and components.

In summary, Swing builds upon AWT and provides a more extensive and flexible
set of GUI components, a pluggable look and feel mechanism, and a more
advanced event handling model. Swing components are lightweight and platform-
independent, offering greater consistency across different operating systems.
Despite the emergence of newer UI frameworks like JavaFX, Swing is still widely
used and supported in Java applications.

12) Explain in detail about swing with example.


Swing is a powerful and flexible Java library for creating graphical user interfaces
(GUIs) in Java applications. It provides a comprehensive set of components and
tools for building interactive and visually appealing applications. Swing is a part of
the Java Foundation Classes (JFC) and is built on top of the Abstract Window
Toolkit (AWT), enhancing its capabilities while addressing some of its limitations.
Swing offers lightweight components, platform-independent look and feel, and a
more sophisticated event handling model.
Creating a Swing Application:
Creating a Swing application typically involves these steps:

1. Importing Packages: Import relevant Swing packages like javax.swing for


components, javax.swing.event for events, and others.
2. Creating Components: Instantiate Swing components such as JFrame,
JPanel, and various widgets like buttons, labels, and text fields.
3. Setting Layout: Use layout managers (FlowLayout, BorderLayout,
GridLayout, etc.) to position and organize components within containers.
4. Adding Listeners: Register event listeners to handle user interactions such as
button clicks, mouse events, and keyboard input.
5. Configuring Look and Feel: Optionally set the desired look and feel using
the UIManager class to control the appearance of your application.
6. Launching the Application: Display the GUI by setting up the main frame
(JFrame) and making it visible.

Here's a simple example of a Swing application:

import javax.swing.*;

public class SwingExample {


public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Swing Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel label = new JLabel("Hello, Swing!");


frame.getContentPane().add(label);

frame.pack();
frame.setVisible(true);
});
}
}

In this example, a basic Swing application creates a JFrame window with a JLabel
component.

Swing has been a fundamental part of Java GUI development for many years.
While newer UI frameworks like JavaFX have gained popularity, Swing remains
relevant and continues to be used in various applications and projects.
13)Write about the key features of JavaSwing.
Java Swing is a GUI (Graphical User Interface) toolkit for Java applications. It
provides a rich set of components and tools to create interactive and visually
appealing graphical user interfaces. Swing is built on top of the Abstract Window
Toolkit (AWT) but offers several enhancements and improvements over AWT.
Here are the key features of Java Swing:

1. Lightweight Components:
Swing components are lightweight and platform-independent. Unlike AWT, which
relies on native components, Swing components are implemented purely in Java.
This ensures consistent behavior and appearance across different platforms.

2. Rich Component Set:


Swing offers a wide range of GUI components, from basic widgets like buttons,
labels, and text fields to more advanced components like tables, trees, and tabbed
panes. These components make it easier to create complex and feature-rich user
interfaces.

3. Look and Feel Customization:


Swing supports pluggable look and feel (PLAF), which means you can change the
appearance of your application easily. You can choose between different look and
feel themes, including the default "Metal" look, the native look of the operating
system, or third-party look and feel libraries.

4. Layout Managers:
Swing provides layout managers that help you arrange components within
containers. Layout managers handle tasks like component positioning, sizing, and
alignment. Common layout managers include FlowLayout, BorderLayout,
GridLayout, and BoxLayout.

5. Customizability:
Swing components are highly customizable. You can modify their appearance by
setting properties, changing colors, fonts, and other visual attributes. Additionally,
you can create custom components by extending existing ones or implementing
Swing interfaces.

6. Event Handling:
Swing offers a flexible event handling model. You can attach event listeners to
components to respond to user interactions such as button clicks, mouse events,
and keyboard input. This model enables more precise control over how events are
processed.

7. Double Buffering:
Swing components use double buffering by default, which reduces flickering and
enhances the rendering of complex UIs. Double buffering involves rendering
components off-screen before displaying them, resulting in smoother animations
and improved performance.

8. Thread Safety:
Swing follows a single-threaded model, where all UI-related operations must be
performed on the event dispatch thread (EDT). Swing provides mechanisms to
ensure thread safety and synchronization of UI updates, helping to prevent
concurrent access issues.

9. Internationalization (I18N) and Localization (L10N):


Swing supports internationalization and localization, allowing you to create
applications that can be easily adapted to different languages and regions.
Components like labels and buttons can display text based on the user's preferred
language and locale.

10. Drag-and-Drop Support:


Swing provides built-in support for drag-and-drop operations, making it easier to
implement interactions like dragging items between components or windows.

11. Accessibility:
Swing components include built-in accessibility features, allowing visually
impaired users to interact with applications using screen readers and other assistive
technologies.

12. Integration with AWT and Other APIs:


Although Swing is designed to be lightweight and platform-independent, it can be
integrated with AWT components if needed. Additionally, Swing components can
be used alongside other Java APIs, such as Java2D for advanced graphics
rendering.

In summary, Java Swing is a comprehensive GUI toolkit that provides a wealth of


features for creating sophisticated and interactive graphical user interfaces in Java
applications. Its lightweight components, customizability, and rich set of tools have
made it a popular choice for developers over the years.
14)How to create user form using swing?
Creating a user form using Java Swing involves creating a graphical interface with
various components like labels, text fields, buttons, and more. In this example, I'll
guide you through creating a simple user registration form using Swing
components. This form will include labels, text fields, a password field, a radio
button, and a submit button.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class UserFormExample {

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
createAndShowGUI();
});
}

private static void createAndShowGUI() {


JFrame frame = new JFrame("User Registration Form");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLayout(new GridLayout(6, 2));

JLabel nameLabel = new JLabel("Name:");


JTextField nameField = new JTextField();

JLabel emailLabel = new JLabel("Email:");


JTextField emailField = new JTextField();

JLabel passwordLabel = new JLabel("Password:");


JPasswordField passwordField = new JPasswordField();

JLabel genderLabel = new JLabel("Gender:");


JRadioButton maleRadioButton = new JRadioButton("Male");
JRadioButton femaleRadioButton = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
genderGroup.add(maleRadioButton);
genderGroup.add(femaleRadioButton);

JButton submitButton = new JButton("Submit");


submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String email = emailField.getText();
char[] password = passwordField.getPassword();
String gender = maleRadioButton.isSelected() ? "Male" : "Female";

// You can process and store the form data here


System.out.println("Name: " + name);
System.out.println("Email: " + email);
System.out.println("Password: " + new String(password));
System.out.println("Gender: " + gender);
}
});

// Add components to the frame


frame.add(nameLabel);
frame.add(nameField);
frame.add(emailLabel);
frame.add(emailField);
frame.add(passwordLabel);
frame.add(passwordField);
frame.add(genderLabel);
frame.add(maleRadioButton);
frame.add(new JLabel()); // Empty label for spacing
frame.add(femaleRadioButton);
frame.add(submitButton);

frame.setVisible(true);
}
}
1. The main method initializes the Swing components on the Event Dispatch
Thread (EDT) using SwingUtilities.invokeLater() to ensure proper GUI
initialization.
2. The createAndShowGUI method sets up the main frame for the user
registration form with a 6x2 grid layout.
3. Labels, text fields, radio buttons, and a button are created to gather user
input.
4. Event listeners are added to the submit button to process form data when
clicked.
5. Form data (name, email, password, gender) is collected from the
components.
6. The form data is printed to the console for demonstration purpose.

15)Explain in detail about JDBC.


Java Database Connectivity (JDBC) is a Java-based API that provides a standard
way for Java applications to interact with databases. It allows you to connect to
various relational databases, perform SQL queries, and manipulate data using Java
code. JDBC provides a bridge between Java applications and database
management systems (DBMS), enabling you to work with data in a consistent and
efficient manner. Here's a detailed overview of JDBC:

Key Concepts and Components:


1. Driver: A JDBC driver is a platform-specific implementation that allows
Java applications to communicate with a particular database system. Drivers
are provided by database vendors and need to be loaded and registered in
your application.
2. Connection: The Connection interface represents a connection to a specific
database. It's used to establish a connection between your Java application
and the database.
3. Statement: The Statement interface is used to execute SQL queries on the
database. There are three main types of statements: Statement (basic),
PreparedStatement (precompiled), and CallableStatement (for stored
procedures).
4. ResultSet: The ResultSet interface represents the result of a query and
allows you to retrieve data from the database. It provides methods to
navigate through the result set and retrieve values based on column indexes
or column names.
5. SQLException: The SQLException class is used to handle database-related
exceptions. It provides information about errors that occur during database
operations.
Basic Workflow of JDBC:
1. Load the Driver: Load the appropriate JDBC driver for the database you're
using. This is done using the Class.forName() method, which loads the
driver class dynamically.
2. Establish Connection: Use the DriverManager.getConnection() method to
establish a connection to the database. This method returns a Connection
object.
3. Create Statements: Create instances of Statement, PreparedStatement, or
CallableStatement to execute SQL queries on the database.
4. Execute Queries: Use the executeQuery() method to execute SELECT
queries and retrieve a ResultSet containing the query result.
5. Retrieve Data: Use methods like getString(), getInt(), etc., on the ResultSet
to retrieve data from the result set.
6. Update Data: For INSERT, UPDATE, or DELETE queries, use methods
like executeUpdate() on the Statement to modify data in the database.
7. Close Resources: Close the ResultSet, Statement, and Connection objects
when you're done using them. This helps release resources and prevent
memory leaks.
Sample Java Code:
Here's a simple example of using JDBC to connect to a database, execute a query,
and retrieve data:

import java.sql.*;

public class JDBCTutorial {


public static void main(String[] args) {
String jdbcUrl = "jdbc:mysql://localhost:3306/mydb";
String username = "username";
String password = "password";

try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish the connection


Connection connection = DriverManager.getConnection(jdbcUrl,
username, password);

// Create a statement
Statement statement = connection.createStatement();

// Execute a SELECT query


ResultSet resultSet = statement.executeQuery("SELECT * FROM users");

// Process the result set


while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}

// Close resources
resultSet.close();
statement.close();
connection.close();
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}

In this example, we use the MySQL JDBC driver to connect to a MySQL database,
execute a SELECT query, and print the retrieved data. The general workflow
applies to other database systems as well.

JDBC is a foundational technology for Java applications that need to interact with
databases. It provides a standardized way to manage connections, execute queries,
and handle data, making it an essential tool for building database-driven
applications.

16)Write the principles of jdbc.


Java Database Connectivity (JDBC) is built on a set of principles that facilitate the
interaction between Java applications and relational databases. These principles
provide a structured approach to database access and manipulation, ensuring
consistency, reliability, and security. Let's delve into the key principles that
underlie JDBC:

1. Driver Manager:
The DriverManager class acts as a central hub for managing database drivers. It's
responsible for loading and registering appropriate database drivers dynamically.
The driver manager allows applications to work with different database systems
without needing to modify code extensively. You use the DriverManager to obtain
a Connection to the database using the URL, username, and password.

2. Connection Pooling:
JDBC encourages the use of connection pooling to manage database connections
efficiently. Connection pooling involves creating and maintaining a pool of
database connections that can be reused. This minimizes the overhead of
establishing and closing connections for every database operation, improving
performance and resource management.

3. Resource Management:
JDBC emphasizes proper resource management to avoid resource leaks and
potential performance degradation. Resources like Connection, Statement, and
ResultSet must be explicitly closed when they are no longer needed. Failing to
close these resources can lead to memory leaks and increased resource
consumption.

4. SQL Statements:
JDBC supports three types of SQL statements: Statement, PreparedStatement, and
CallableStatement. Each type has its own purpose and usage:

• Statement: Used for executing basic SQL queries without parameters.


• PreparedStatement: Used for executing parameterized SQL queries, offering
better performance and security.
• CallableStatement: Used for calling stored procedures in the database.
5. ResultSet Navigation:
The ResultSet interface provides methods to navigate through the results of a
query. You can move the cursor forward, backward, and access the data in the
current row using methods like next(), previous(), and column-specific methods
(getString(), getInt(), etc.).

6. Error Handling:
JDBC uses the SQLException class to handle database-related errors. Handling
exceptions is crucial for diagnosing and resolving issues that may occur during
database operations. Proper error handling helps ensure robustness and stability in
your applications.

7. Data Types Mapping:


JDBC provides mappings between Java data types and SQL data types, allowing
seamless communication between the application and the database. This mapping
ensures that data conversions are handled correctly and transparently.

8. Batch Processing:
JDBC supports batch processing, where multiple SQL statements are grouped
together and executed in a batch. This can significantly improve performance when
you need to perform repetitive tasks, such as inserting multiple rows into a table.

9. SQL Injection Prevention:


By using parameterized queries with PreparedStatement, JDBC helps prevent SQL
injection attacks. Parameterized queries separate data from the query, making it
harder for attackers to manipulate SQL statements.
10. Transaction Management:
JDBC provides mechanisms for managing transactions, ensuring the consistency
and integrity of data. You can explicitly commit or roll back transactions using the
commit() and rollback() methods on the Connection object.

11. Thread Safety:


JDBC is not inherently thread-safe. If you plan to use JDBC in a multi-threaded
environment, you need to ensure proper synchronization or use connection pooling
libraries that handle concurrency issues.

12. Connection Isolation Levels:


JDBC supports different transaction isolation levels (e.g.,
READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ,
SERIALIZABLE) that define how transactions interact with each other and what
data they can see.

In summary, JDBC principles provide a comprehensive framework for interacting


with relational databases in Java applications. By following these principles,
developers can create robust, secure, and efficient database-driven applications that
adhere to industry best practices.

17)Explain about the database connectivity.


Database connectivity in the context of software development refers to the ability
of a program or application to establish a connection to a database management
system (DBMS) and interact with the data stored within that database. In the
context of Java, database connectivity typically involves using the Java Database
Connectivity (JDBC) API to connect to and interact with relational databases.
Here's a detailed explanation of database connectivity:

Importance of Database Connectivity:


Database connectivity is a critical aspect of software development, especially in
applications that need to store, retrieve, and manipulate data. Some common
scenarios where database connectivity is essential include:

1. Data Storage and Retrieval: Applications often need to store and retrieve
data from databases to maintain information about users, products,
transactions, etc.
2. Reporting and Analysis: Database connectivity enables applications to
retrieve and analyze data for generating reports, statistics, and insights.
3. Authentication and Authorization: User authentication and authorization
information is often stored in databases, requiring connectivity for user
management.
4. E-commerce and Transactions: Online stores and financial applications rely
on database connectivity to manage orders, payments, and inventory.
5. Content Management: Content management systems use databases to store
articles, images, videos, and other media files.
Steps in Database Connectivity:
1. Loading the Driver: To establish a connection to a database, you need to
load the appropriate JDBC driver class. The driver class is provided by the
database vendor and implements the JDBC standard.
2. Establishing Connection: Once the driver is loaded, you use the
DriverManager.getConnection() method to establish a connection to the
database. You provide the connection URL, username, and password as
arguments.
3. Creating Statements: After obtaining a connection, you create a Statement or
PreparedStatement object. These objects allow you to execute SQL queries
and commands against the database.
4. Executing Queries: You execute SQL queries using the executeQuery()
method for SELECT statements and executeUpdate() for INSERT,
UPDATE, and DELETE statements. The results of a SELECT query are
returned as a ResultSet object.
5. Processing Results: When you execute a SELECT query, the result set
contains the retrieved data. You can iterate through the result set and extract
values using methods like getString(), getInt(), etc.
6. Closing Resources: After using the database resources, it's crucial to close
them properly to release database connections and resources. Failing to close
resources can lead to resource leaks.
7. Handling Exceptions: Database operations can result in exceptions due to
various reasons such as connection issues, query errors, or database
constraints. Proper error handling using try-catch blocks ensures graceful
error reporting and recovery.
JDBC and Database Connectivity:
JDBC is a Java API that provides a standard way to connect to relational databases
and perform database operations using Java code. It simplifies database
connectivity by offering a consistent interface for different databases. Developers
use JDBC to execute SQL queries, retrieve data, update records, and manage
transactions.

Overall, database connectivity is a fundamental aspect of modern software


development that enables applications to interact with and manage data efficiently.
It's crucial to understand how to establish connections, execute queries, and handle
data to build robust and functional applications.

UNIT-4 TO 8

18) Create simple client-server chat application.

CLIENT SIDE:
import java.io.*;
import java.net.*;

public class Client {


public static void main(String[] args) {
try {
// Define the server's IP address and port
String serverIP = "127.0.0.1"; // Server's IP address (localhost in this case)
int serverPort = 12345; // Port on which the server is listening

// Create a socket to connect to the server


Socket socket = new Socket(serverIP, serverPort);
// Set up input and output streams for communication
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

// Read messages from the user and send them to the server
BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));
String message;
while (true) {
System.out.print("You: ");
message = userInput.readLine(); // Read user input
out.println(message); // Send message to the server

if (message.equalsIgnoreCase("bye")) {
break; // Exit the loop if the user types "bye"
}

String response = in.readLine(); // Receive server's response


System.out.println("Server: " + response); // Print server's response
}

// Close resources
userInput.close();
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

SERVER SIDDE:

import java.io.*;
import java.net.*;

public class Server {


public static void main(String[] args) {
try {
// Create a ServerSocket that listens on a specific port
int port = 12345;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server listening on port " + port);

// Accept incoming client connections


Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " +
clientSocket.getInetAddress().getHostAddress());

// Set up input and output streams


BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

// Read and display messages from the client


String message;
while ((message = in.readLine()) != null) {
System.out.println("Client: " + message);
out.println("Server received: " + message); // Send response to client
}

// Close resources
in.close();
out.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
19)Explain Secure sockets.
Secure Socket Layer (SSL) provides security to the data that is transferred
between web browser and server. SSL encrypts the link between a web server and
a browser which ensures that all data passed between them remain private and
free from attack.
Secure Socket Layer Protocols:
• SSL record protocol
• Handshake protocol
• Change-cipher spec protocol
• Alert protocol
SSL Protocol Stack:

SSL record protocol

The SSL (Secure Sockets Layer) record protocol is a key component of the
SSL/TLS (Transport Layer Security) protocol suite, which is used to secure data
transmission over the internet. The SSL record protocol is responsible for
fragmenting, compressing (optional), encrypting, and authenticating data to ensure
the confidentiality, integrity, and authenticity of information exchanged between a
client and a server. It operates at the transport layer of the OSI model and is used to
establish secure communication channels between web browsers and web servers,
among other applications.

HANDSHAKE PROTOCOL:
The handshake protocol is an essential part of the SSL/TLS (Secure Sockets
Layer/Transport Layer Security) protocol suite, which is used to establish secure
communication channels over the internet. The handshake protocol's primary
purpose is to enable the client and server to authenticate each other, negotiate
encryption algorithms, and establish session keys for secure data exchange.

CHANGE CIPHER SPEC PROTOCOL:


The Change Cipher Spec protocol is a fundamental part of the SSL/TLS (Secure
Sockets Layer/Transport Layer Security) protocol suite, which is used to secure
data transmission over the internet. The primary purpose of the Change Cipher
Spec protocol is to signal a transition from non-secure communication to secure
communication, indicating that subsequent data exchanged will be encrypted using
the agreed-upon encryption algorithms and keys. Here's how the Change Cipher
Spec protocol works:

ALERT PROTOCOL:
The Alert Protocol is a crucial component of the SSL/TLS (Secure Sockets
Layer/Transport Layer Security) protocol suite, used to establish secure
communication channels over the internet. The primary purpose of the Alert
Protocol is to provide a means for communicating various alert and error messages
between the client and server during the SSL/TLS handshake and data exchange
phases. These alert messages can inform both parties about issues that may arise
during the secure communication.

20)Explain TCP.
TCP, or Transmission Control Protocol, is one of the core protocols of the Internet
Protocol (IP) suite. It operates at the transport layer of the OSI model and plays a
crucial role in providing reliable and connection-oriented communication between
devices on a network. Here's a detailed explanation of TCP:
1. Connection-Oriented Communication: TCP is a connection-oriented
protocol. This means that before data transfer begins, a connection is
established between the two devices (sender and receiver). This connection
setup is known as the "TCP handshake."
• Three-Way Handshake: To establish a connection, a three-way
handshake takes place:
• SYN (Synchronize): The sender (client) initiates the
connection by sending a SYN packet to the receiver (server).
• SYN-ACK (Synchronize-Acknowledge): The receiver
acknowledges the request and sends its own SYN packet back
to the sender.
• ACK (Acknowledge): The sender acknowledges the
acknowledgment, and the connection is established. Data
transfer can now begin.
2. Reliable Data Transfer: TCP ensures reliable data transfer. It achieves this
by implementing various mechanisms:
• Sequence Numbers: TCP assigns a sequence number to each byte of
data being sent. This enables the receiver to reconstruct the data in the
correct order.
• Acknowledgments (ACKs): After receiving data, the receiver sends
an acknowledgment to the sender to confirm the receipt of data up to a
certain sequence number.
• Retransmission: If the sender doesn't receive an acknowledgment
within a specific timeout period, it assumes the data was lost in transit
and retransmits it.
• Flow Control: TCP implements flow control to prevent
overwhelming the receiver with data. The receiver can inform the
sender of its current buffer space, allowing for efficient data
transmission.
3. Error Checking: TCP uses a checksum mechanism to verify the integrity of
data during transmission. If the checksum doesn't match at the receiver's
end, the data is considered corrupt, and a request is made to retransmit it.
4. Orderly Data Transmission: TCP guarantees that data sent by the sender
will be received by the receiver in the same order it was sent. This is crucial
for applications where data integrity and order matter, such as web
browsing, email, and file transfers.
5. Full Duplex Communication: TCP enables full-duplex communication,
meaning both the client and server can send and receive data simultaneously.
This allows for efficient bidirectional communication.
6. Port Numbers: TCP uses port numbers to specify which application or
service should receive the data on the receiving end. This enables multiple
applications to run simultaneously on a device and receive data on their
respective ports.
7. Connection Termination: When data exchange is complete, a connection
termination process takes place, allowing both sides to release the resources
used for the connection.
8. Flow Control: TCP includes flow control mechanisms to ensure that data is
transmitted at a rate that the receiver can handle. This prevents congestion
and buffer overflows.

TCP is commonly used for applications that require reliable and error-checked
communication, such as web browsing, email, file transfers, and most online
services. While TCP provides a high level of reliability, it may introduce some
additional overhead due to its connection-oriented nature and the various
mechanisms in place to ensure data integrity and order.

21)Explain about distributed application.

1. Distributed Applications: These are computer programs or software


applications that are designed to work on multiple computers or devices, which can
be located in different places. Instead of running on just one computer, they spread
their work across a network of connected machines.

2. Network Communication: Distributed applications rely on these computers


talking to each other over the internet or a local network. They send data back and
forth to collaborate and get things done.

3. Scalability: These applications are built in a way that allows them to handle
more work by adding more computers to the network. This is like having more
workers to do a job when it gets busier.

4. Reliability and Fault Tolerance: Even if one of the computers in the network
fails, the application keeps working. It's like having backup plans so that the whole
system doesn't break if something goes wrong.

5. Load Balancing: Think of it like distributing tasks evenly among a group of


workers so that no one gets overwhelmed, and the work gets done efficiently.
6. Data Consistency: When multiple computers are working on the same
information, they need to make sure that the data remains accurate and up-to-date.
It's like several chefs working together in a kitchen and making sure they all have
the same recipe.

7. Security: Since the computers are connected over a network, security is crucial.
It's like making sure that only authorized people can access your files and
information.

8. Location Independence: These applications can work no matter where the


computers are located. You can access the same application from your home, your
office, or even from the other side of the world.

Examples of distributed applications include websites, cloud services, and software


that lets you share files directly with other people. These applications are quite
complex to build and require knowledge of various technologies, like how
computers communicate over networks and how data is stored and managed across
different machines.

22)Explain in detail about client and server side computing.


Client-server computing is a network architecture and model that defines how
applications and services are structured and distributed in a networked
environment. In a client-server model, there are two primary components: the
client and the server. These components work together to facilitate communication
and data processing in a networked system. Here's an overview of each component
and their roles:

1. Client:
• The client is a device or software application that requests services,
resources, or data from a server.
• It can be a personal computer, smartphone, tablet, or any other device
capable of connecting to a network.
• Clients are typically responsible for presenting information to the
user, such as user interfaces, and processing user input.
• They send requests to servers and receive responses.
2. Server:
• The server is a powerful computer or software application that
provides services, resources, or data to clients over a network.
• Servers are designed to handle multiple client requests
simultaneously, making them capable of serving multiple clients
concurrently.
• They store and manage data, perform calculations, and execute tasks
on behalf of clients.
• Servers are often dedicated to specific tasks, such as web servers,
database servers, email servers, file servers, and more.

The client-server model works based on a request-response mechanism. Clients


send requests to servers, and servers process these requests and send back
responses. This model has several advantages:

• Scalability: Servers can handle multiple clients, making it easy to scale the
system as the number of clients increases.
• Centralized Data Management: Servers centralize data storage, making it
easier to maintain and secure data.
• Resource Sharing: Clients can access and share resources hosted on servers,
such as files, databases, and services.
• Client Diversity: Clients can be diverse, ranging from different platforms
and devices, as long as they can communicate with the server using standard
protocols.

The client-server model is widely used in various applications, including web


services, email systems, online gaming, and enterprise-level systems, as it allows
for efficient, organized, and reliable networked computing.

23)Write a note about Java Servlets.


Java Servlets are Java-based server-side components used to extend the capabilities
of a web server. They provide a way to dynamically generate and process web
content, typically in response to user requests. Servlets are a key part of the Java
Platform, Enterprise Edition (Java EE), and they are commonly used to create web
applications.

Here are some key points about Java Servlets:

1. Server-side technology: Java Servlets run on the server side of a web


application and handle incoming HTTP requests and generate responses.
They can be used to process form data, interact with databases, and perform
various other server-side tasks.
2. Platform-independent: Servlets are platform-independent, which means you
can develop them on one platform (e.g., Windows) and deploy them on
another (e.g., Linux) without modification, as long as you have a compatible
Java servlet container, such as Apache Tomcat.
3. Java API: Servlets are part of the Java EE standard and are based on the Java
Servlet API. Developers write servlets by creating Java classes that extend
specific servlet classes or implement servlet interfaces.
4. Lifecycle: Servlets have a well-defined lifecycle with methods like init(),
service(), and destroy(). The init() method is called when a servlet is first
loaded, the service() method handles incoming requests, and the destroy()
method is called when the servlet is being unloaded.
5. HTTP support: Servlets are primarily used to process HTTP requests and
generate HTTP responses. They can be used to handle various HTTP
methods like GET, POST, PUT, DELETE, and others.
6. Extensibility: Servlets can be extended and customized to suit the needs of a
particular web application. They can be used in conjunction with JavaServer
Pages (JSP) to separate business logic from presentation.
7. Security and session management: Servlets can incorporate security features,
such as user authentication, and manage user sessions to maintain stateful
interactions with clients.
8. Integration: Servlets can interact with databases, connect to other services,
and perform various server-side tasks, making them suitable for building
complex web applications.

To use Java Servlets, you need a Java servlet container, such as Apache Tomcat,
Jetty, or WildFly, which provides the runtime environment for servlet execution.
Servlets are a fundamental building block for developing Java-based web
applications, and they are commonly used in conjunction with other Java EE
technologies like JSP, EJB, and JDBC to create robust, scalable, and feature-rich
web applications.

24)Write about multitier application.


A multitier application, also known as a multi-tier architecture or n-tier
architecture, is a software architecture that divides the components of an
application into multiple interconnected layers or tiers. Each tier serves a specific
role and has well-defined responsibilities. This architectural approach helps in
organizing and managing complex applications, improving scalability,
maintainability, and flexibility. Multitier applications are commonly used in web
and enterprise software development.
The number of tiers in a multitier architecture can vary, but it typically consists of
the following three main tiers:

1. Presentation Tier (also known as the User Interface or Client Tier):


• This is the topmost tier and is responsible for interacting with users.
• It handles the user interface, such as web pages, mobile apps, or
desktop applications.
• Its primary role is to present information to the user and capture user
input.
• It may not perform extensive processing but instead communicates
with the other tiers to request and display data.
2. Application Tier (also known as the Business Logic Tier or Middle Tier):
• The application tier is the core of the business logic and processing in
the system.
• It contains the application's logic, rules, and algorithms.
• It processes requests from the presentation tier and communicates
with the data tier to retrieve or store data.
• This tier often encapsulates the application's functionality, ensuring
that the business rules are maintained consistently.
3. Data Tier (also known as the Data Storage Tier or Backend Tier):
• The data tier is responsible for managing and storing the application's
data.
• It typically includes databases, file storage systems, and other data
repositories.
• This tier handles data retrieval, storage, and management, providing a
structured way to access and store information.
• It ensures data integrity, security, and scalability.

In some architectures, you may find additional tiers, such as caching layers,
security layers, or messaging layers, depending on the specific requirements of the
application.

Key benefits of a multitier architecture include:

1. Scalability: Each tier can be scaled independently to accommodate increased


load or demand. This can be essential for applications with varying
workloads.
2. Maintainability: The separation of concerns in different tiers makes it easier
to maintain and update specific components of the application without
affecting the entire system.
3. Reusability: Components in each tier can be reused across different parts of
the application or in entirely different applications, promoting code
reusability and reducing development effort.
4. Security: By isolating data storage and business logic, it's easier to
implement security measures and access controls at various levels of the
application.
5. Flexibility: Different tiers can use different technologies or platforms,
enabling flexibility in the choice of tools and technologies for each layer.

In summary, a multitier application architecture divides the software into distinct


layers, each with its own responsibilities and functions, allowing for better
organization, scalability, and maintenance of complex applications. It is a
fundamental design approach in modern software development, commonly seen in
web applications, enterprise systems, and other complex software projects.
MAHENDRA ENGINEERING COLLEGE (AUTONOMOUS)
QUESTION BANK
19CS14403 -JAVA PROGRAMMING

Unit-1 1

2 Mark

1. What is introduction to OOPs?

Object-oriented programming (OOP) is a computer programming model that organizes software


design around data, or objects, rather than functions and logic. An object can be defined as a data field
that has unique attributes and behavior.

2. What are the principles of OOPs?

Abstraction, encapsulation, polymorphism, and inheritance are the four main theoretical
principles of object-oriented programming

3. What is the difference between procedure oriented and object-oriented programming?

The Procedural Programming follows a Top-Down approach. The Object Oriented Programming
follows a Bottom-Up approach. This programming model does not give importance to data. It prioritizes
the functions along with the sequence of actions that needs to follow.

4. What are the applications of Java?

By using Java, we can develop a variety of applications such as enterprise applications, network
applications, desktop applications, web applications, games, android app, and many more.

5. What is Java programming structure?

We have discussed about 8 Elements of the Structure of the Java Program below. These are
Section Documentation, Package Disclosure, Import Declarations, Connector Section, Category
Definition, Class constants and variables, Method Class Main and Techniques and conduct.

6. What is the need of object in Java?

Objects are instances or references of a class. So we can call the methods and variables present
in this class with the help of their objects.

7. What is the history of Java?

Java was originally developed by James Gosling at Sun Microsystems. It was released in May
1995 as a core component of Sun Microsystems' Java platform. The original and reference
implementation Java compilers, virtual machines, and class libraries were originally released by Sun
under proprietary licenses.

8. What are the advantages of JVM?

The two most important benefits of the JVM are the possibility to write a code once and run
everywhere, and automatic memory management.

9. What is the purpose of JDK?

The JDK is a development environment for building applications, applets, and components using
the Java programming language.

10. What are features of Java?

The major features in Java are:

• Simple.
• Object-Oriented.
• Portable.
• Platform Independent.
• Secured.
• Robust.

Unit-2 1

2 Mark

1. What are constructs in Java?

Constructor in java is used to create the instance of the class. Constructors are almost similar to
methods except for two things - its name is the same as the class name and it has no return type.

2. What are primitive data types in Java?

Primitive Data Types. The eight primitives defined in Java are int, byte, short, long, float, double,
Boolean and char. These aren't considered objects and represent raw values.

3. What is identifier in Java programming?

Identifiers in Java are a sequence of characters to identify something in a program. They are
names given to a class, variable, package, method, or interface and allow the programmer to refer to
the specific item from any place in the program.
4. What is the naming convention of a Java program?

For variables, the Java naming convention is to always start with a lowercase letter and then
capitalize the first letter of every subsequent word.

5. What are operators in programming?

In mathematics and computer programming, an operator is a character that represents a


specific mathematical or logical action or process.

6. How many expressions are there in Java?

In Java, there are four kinds of expression statements: assignment expressions, such as a += 5 , b
*= 7 , or c = 3. Prefix and postfix increment and decrement, such as ++a , --b , c++ , d--

7. What is the difference between unary and ternary operator in Java?

An operator is called a unary, binary, or ternary operator based on the number of operands. If
an operator takes one operand, it is called a unary operator; if it takes two operands, it is called a binary
operator; if it takes three operands, it is called a ternary operator.

8. What is conversion of primitive data types in Java?

Specific conversions on primitive types are called the widening primitive conversions:

• byte to short , int , long , float , or double.


• short to int , long , float , or double.
• char to int , long , float , or double.
• int to long , float , or double.
• long to float or double.
• float to double.

9. What is flow of control in Java?

Control flow statements let you control the flow of the execution of the code in your program.
In Java programming language, you can control the flow of execution of the code by placing the decision
making, branching, looping, and adding conditional blocks.

10. Which construct is used to define an array?

An array constructor can be used to define only an ordinary array with elements that are not a
row type. An array constructor cannot be used to define an associative array or an ordinary array with
elements that are a row type.
Unit-3 1

2 Mark

1. What is the difference between exception and error in Java?

Both exceptions and errors are the subclasses of a throw able class. The error implies a problem
that mostly arises due to the shortage of system resources. On the other hand, the exceptions occur
during runtime and compile time.

2. What is a abstract class in Java and interface?

The Abstract class and Interface both are used to have abstraction. An abstract class contains an
abstract keyword on the declaration whereas an Interface is a sketch that is used to implement a class.

3. Which package is used for exception in Java?

Java.lang package

The top three classes in this hierarchy (the Throw able, Error, and Exception classes) are all defined in
the java. Lang package (which is automatically imported into every class file)

4. What is the access specifies in Java for interface?

The access specifies used with classes are private, protected and public. While in Interface only
one specified is used- Public.

5. What is exception and exception handling in Java?

Exception handling is the process of responding to unwanted or unexpected events when a


computer program runs. Exception handling deals with these events to avoid the program or system
crashing, and without this process, exceptions would disrupt the normal operation of a program.

6. What are the user-defined exceptions in Java?

User-defined exceptions are also referred to as custom exceptions. The exceptions created per
our use case and thrown using the throw keyword are user-defined exceptions, and such exceptions are
derived classes of the Exception class from the java.

7. What are the different types of encapsulation in Java?

There are three types of encapsulation, namely Member variable encapsulation, Function
encapsulation and Class encapsulation.
8. What is enrichment in Java?

The process of replacing objects to refs and refs to objects is called "Enrichment" and can be
done in two different ways.

9. When should you use an assertion over an exception?

Meanwhile, exceptions indicate exceptional conditions - problems for which the developer may
not have accounted. You can use assertions for internal logic checks within your code, unchecked
exceptions for error conditions outside your immediate code's control, and checked exceptions for
business and recoverable errors.

10. How to create an exception interface in Java?

In order to create a custom exception, we need to extend the Exception class that belongs to
java. Lang package. Example: We pass the string to the constructor of the super class- Exception which is
obtained using the “get Message ()” function on the object created.

Unit-4 1

2 Mark

1. What is multitasking in Java?

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to


utilize the CPU. Multitasking can be achieved in two ways: Process-based Multitasking (Multiprocessing)
Thread-based Multitasking (Multithreading)

2. What is called thread in Java?

A thread in Java is the direction or path that is taken while a program is being executed.
Generally, all the programs have at least one thread, known as the main thread,

3. How to create a new thread in Java?

Java Thread Example by extending Thread class

class Multi extends Thread{

public void run(){

System.out.println("thread is running...");

}
public static void main(String args[]){

Multi t1=new Multi();

t1.start();

4. What are the priority levels of threads?

Threads are scheduled to run based on their scheduling priority. Each thread is assigned a
scheduling priority. The priority levels range from zero (lowest priority) to 31 (highest priority). Only the
zero-page thread can have a priority of zero.

5. What is the difference between join () and alive ()?

isAlive () just returns a Boolean that indicates whether the thread is alive, the status of the
thread - it returns true or false, indicating whether the thread is "done". . join() makes the current
thread you are in wait until the thread that you're calling . join() on has completed.

6. What is the use of alive () method in Java?

This method is used to find out if a thread has actually been started and has yet not terminated.
Note: While returning this function returns true if the thread upon which it is called is still running. It
returns false otherwise

7. What is the process synchronization in thread?

Process Synchronization means sharing system resources by processes in a such a way that,
Concurrent access to shared data is handled thereby minimizing the chance of inconsistent data.

8. What are three methods of synchronization?

Different Techniques for Synchronization

• Three Dark Lamps Method.


• Two Bright, One Dark Method.
• Synchroscope Method.

9. How to read and write multiple files in Java?

Create a file object by passing the required file path as a parameter. Read the contents of each
file using Scanner or any other reader. Append the read contents into a StringBuffer. Write the
StringBuffer contents into the required output file.
10. What is a real example of multithreading in Java?

A very good example of thread-based multithreading is a word processing program that checks
the spelling of words in a document while writing the document. This is possible only if each action is
performed by a separate thread.

Unit-5 1

2 Mark

1. What is network programming in Java?

Network programming is the procedure of writing programs that run on multiple devices
(computers) that are linked together via a network. To allow for low-level communication details, Java
encapsulates classes and interfaces.

2. What is concurrent program in Java?

Concurrency is the ability to run several or multi programs or applications in parallel. The
backbone of Java concurrency is threads (a lightweight process, which has its own files and stacks and
can access the shared data from other threads in the same process)

3. What are threads in concurrent programming?

A thread is a unit of control within a process: when a thread runs, it executes a function in the
program - the “main thread” executes the “main” function and other threads execute other functions.

4. What are interrupting threads in Java?

An interrupt is an indication to a thread that it should stop what it is doing and do something
else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very
common for the thread to terminate.

5. What is thread communication in Java?

Overview. Inter Thread Communication, as the name implies, is a method that allows many
synchronized threads to communicate or interact with one another. In Java, there are two ways to
implement inter-thread communication: using wait () and notify() methods and using the higher-level
constructs of the java.
6. What is communication between threads?

Inter-thread Communication

All the threads in the same program share the same memory space. If an object is accessible to
various threads then these threads share access to that object's data member and thus communicate
each other. The second way for threads to communicate is by using thread control methods.

7. What is the use of Java net package in Java?

Provides the classes necessary to create an applet and the classes an applet uses to
communicate with its applet context. Contains all of the classes for creating user interfaces and for
painting graphics and images.

8. Which class is used to create TCP server?

To create a TCP server, it is necessary to understand a new class, ServerSocket. ServerSocket


allows you to bind a port and wait for clients to connect, setting up a complete Socket object at that
time

9. What is TCP in Java networking?

TCP − TCP stands for Transmission Control Protocol, which allows for reliable communication
between two applications. TCP is typically used over the Internet Protocol, which is referred to as
TCP/IP.

10. What are client and server in java?

A more reliable distinction is that a client initiates a conversation, while a server waits for clients
to start conversations with it. In some cases, the same program may be both a client and a server.

Part –B

10 Mark

Unit -1

1. Explain the JVM (Java Virtual Machine) Architecture.

• Java Virtual Machine


• Internal Architecture of JVM

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

What is JVM?

It is:

1. A specification where working of Java Virtual Machine is specified. But implementation provider
is independent to choose the algorithm. Its implementation has been provided by Oracle and
other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the java
class, an instance of JVM is created.

What it does

The JVM performs following operation:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.

JVM Architecture

Let's understand the internal architecture of JVM. It contains classloader, memory area, execution
engine etc.
1) Classloader

Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it
is loaded first by the classloader. There are three built-in classloaders in Java.

1. Bootstrap ClassLoader: This is the first classloader which is the super class of Extension
classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like
java.lang package classes, java.net package classes, java.util package classes, java.io package
classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of
System classloader. It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension classloader. It loads
the classfiles from classpath. By default, classpath is set to current directory. You can change the
classpath using "-cp" or "-classpath" switch. It is also known as Application classloader.

1. //Let's see an example to print the classloader name


2. public class ClassLoaderExample
3. {
4. public static void main(String[] args)
5. {
6. // Let's print the classloader name of current class.
7. //Application/System classloader will load this class
8. Class c=ClassLoaderExample.class;
9. System.out.println(c.getClassLoader());
10. //If we print the classloader name of String, it will print null because it is an
11. //in-built class which is found in rt.jar, so it is loaded by Bootstrap classloader
12. System.out.println(String.class.getClassLoader());
13. }
14. }
Test it Now

Output:

sun.misc.Launcher$AppClassLoader@4e0e2f2a
null

These are the internal classloaders provided by Java. If you want to create your own classloader, you
need to extend the ClassLoader class.

2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and method
data, the code for methods.

3) Heap

It is the runtime data area in which objects are allocated.

4) Stack

Java Stack stores frames. It holds local variables and partial results, and plays a part in method
invocation and return.

Each thread has a private JVM stack, created at the same time as thread.

A new frame is created each time a method is invoked. A frame is destroyed when its method invocation
completes.

5) Program Counter Register

PC (program counter) register contains the address of the Java virtual machine instruction currently
being executed.

6) Native Method Stack

It contains all the native methods used in the application.

7) Execution Engine

It contains:

1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte
code that have similar functionality at the same time, and hence reduces the amount of time
needed for compilation. Here, the term "compiler" refers to a translator from the instruction set
of a Java virtual machine (JVM) to the instruction set of a specific CPU.

8) Java Native Interface

Java Native Interface (JNI) is a framework which provides an interface to communicate with another
application written in another language like C, C++, Assembly etc. Java uses JNI framework to send
output to the Console or interact with OS libraries.
12. Explain the Installation of the JDK on Microsoft Windows Platforms?

System Requirements for Installing the JDK on 64-Bit Windows Platform


For supported processors and browsers, see Oracle JDK Certified Systems Configurations.

JDK Installation Instruction Notation for Windows

JDK installers now support only one version of any Java feature release. You can't install multiple
versions of the same feature release.

For example, you can't install jdk-20 and jdk-20.0.1 simultaneously. If you attempt to install jdk-
20.0.1 after jdk-20 is installed, the installer uninstalls jdk-20 and installs jdk-20.0.1.

JDK Installation Instructions for Windows

You run a self-installing executable file to unpack and install the JDK on Windows computers.
Install JDK on Windows computers by performing the actions described in the following topics:

• Downloading the JDK Installer


• Installing the JDK from the JDK .exe Installer
• Installing the JDK from the MSI Enterprise Installer
• Installing the JDK Silently

Downloading the JDK Installer


Access the Java SE Downloads page and click Accept License Agreement. Under
the Download menu, click the Download link that corresponds to the .exe for your version of Windows.
Download the file jdk-20.interim.update.patch_windows-x64_bin.exe.

Installing the JDK from the JDK .exe Installer

You must have administrator privileges to install the JDK on Microsoft Windows.

To run the JDK installer:

1. Start the JDK 20 installer by double-clicking the installer's icon or file name in the download
location.
2. Follow the instructions provided by the installer.
3. After the installation is complete, delete the downloaded file to recover disk space.
Unit -2

11. Explain the Arrays in Java.

Array in Java is a group of like-typed variables referred to by a common name. Arrays in Java work differently
than they do in C/C++. Following are some important points about Java arrays.

• In Java, all arrays are dynamically allocated. (discussed below)


• Arrays may be stored in contiguous memory [consecutive memory locations].
• Since arrays are objects in Java, we can find their length using the object property length. This is different
from C/C++, where we find length using sizeof.
• A Java array variable can also be declared like other variables with [] after the data type.
• The variables in the array are ordered, and each has an index beginning with 0.
• Java array can also be used as a static field, a local variable, or a method parameter.
• The size of an array must be specified by int or short value and not long.
• The direct superclass of an array type is Object.
• Every array type implements the interfaces Cloneable and java.io.Serializable.
• This storage of arrays helps us randomly access the elements of an array [Support Random Access].
• The size of the array cannot be altered(once initialized). However, an array reference can be made to point
to another array.

An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a class depending on
the definition of the array. In the case of primitive data types, the actual values might be stored in contiguous
memory locations(JVM

12. Explain Java Expressions with Examples

Java Expression
Variables, operators, literals, and method calls make up a Java expression. Operands and operators are
used to build expressions. An expression’s operators specify which operations should be applied to the operands.
The precedence and associativity of the operators govern the order in which they are evaluated in an expression.

Take an example:

int marks;

marks =95;

Here, marks=90 is an expression that returns an int value.

double a = 3.2, b = 3.4, result;

result = a + b - 3.4;

Here, a+b-3.4 is an expression

if (num1 == num2)

System.out.println("num 1 is larger than num 2");


Here, num1 == num2 is an expression that returns a Boolean value. Similarly, “num 1 is larger than num 2” is a
string expression.

How to Evaluate Java Expressions?


Even though Java has its method for evaluating expressions behind the scenes, a Java expression’s
outcome and its corresponding arithmetic expression are identical. As a result, you can use the arithmetic rule to
evaluate a Java expression confidently.

Types of Expressions
While an expression typically yields a result, this is not always the case. In Java, there are a few types of
expressions:

Those that generate a value, i.e.


(1 + 1) result
Those who, for example, assign a variable
(i= 10)
Because an expression can comprise a wide range of elements such as method invocations or increment operators
that affect the state (i.e., memory), those that have no result but may have a “side effect.”

Unit -3

11. Explain the Java Exceptions.

Exception Handling in Java is one of the effective means to handle runtime errors so that the regular
flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such
as ClassNotFoundException, IOException, SQLException, RemoteException, etc.

What are Java Exceptions?


In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a
program, i.e. at run time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught
and handled by the program. When an exception occurs within a method, it creates an object. This object is
called the exception object. It contains information about the exception, such as the name and description of
the exception and the state of the program when the exception occurred.

Major reasons why an exception Occurs


• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Opening an unavailable file

Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory, memory
leaks, stack overflow errors, library incompatibility, infinite recursion, etc. Errors are usually beyond the control
of the programmer, and we should not try to handle errors.

Difference between Error and Exception


Let us discuss the most important part which is the differences between Error and Exception that is as follows:
• Error: An Error indicates a serious problem that a reasonable application should not try to catch.
• Exception: Exception indicates conditions that a reasonable application might try to catch.
Exception Hierarchy

All exception and error types are subclasses of the class Throwable, which is the base class of the hierarchy.
One branch is headed by Exception. This class is used for exceptional conditions that user programs should
catch. NullPointerException is an example of such an exception. Another branch, Error is used by the Java run-
time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError
is an example of such an error.

12. Explain the Exception Handling in Java.

Exception handling in java is one of the powerful mechanisms to handle runtime errors caused by
exceptions. Exception handling plays an important role in software development. This article helps you understand
java exception, exception in java, java exception handling, java exception hierarchy, types of exception in java, and
many more.

What is Exception Handling in Java?

Exception handling in java helps in minimizing exceptions and helps in recovering from exceptions. It is
one of the powerful mechanisms to handle runtime exceptions and makes it bug-free. Exception handling helps in
maintaining the flow of the program. An exception handling is defined as an abnormal condition that may happen
at runtime and disturb the normal flow of the program.

Also Read: Java Tutorial for beginners

What is an Exception?

An expectation is an unexpected event that occurs while executing the program, that disturbs the normal flow of
the code.

Exception handling in java with an example:

Let’s say,

statement

statement

statement

exception ………… an exception occurred, then JVM will handle it and will exit the prog.
statement

statement

statement

For handling exceptions, there are 2 possible approaches

1. JVM

If an exception is not handled explicitly, then JVM takes the responsibility of handling the exception.

Once the exception is handled, JVM will halt the program and no more execution of code will take place

• Example:

import java.util.*;

class Main {

public static void main (String[] args) {

System.out.println(5/0);

System.out.println("End of program!");

Runtime Error:

Exception in thread "main" java.lang.ArithmeticException: / by zero

at Main.main(File.java:5)
Unit -4

11. Explain the Multithreading in Java.

Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are
used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared memory area. They don't
allocate separate memory area so saves memory, and context-switching between the threads takes less time than
process.

Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple operations at the
same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU.
Multitasking can be achieved in two ways:

o Process-based Multitasking (Multiprocessing)


o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


o Each process has an address in memory. In other words, each process allocates a separate memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and loading registers, memory
maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)


o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.
12. Explain the Synchronization in Java.

Synchronization in Java is the capability to control the access of multiple threads to any shared
resource.

Java Synchronization is better option where we want to allow only one thread to access the
shared resource.

Why use Synchronization?

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data. It can be
achieved by using the following three ways:

1. By Using Synchronized Method


2. By Using Synchronized Block
3. By Using Static Synchronization
Concept of Lock in Java

Synchronization is built around an internal entity known as the lock or monitor. Every object has a lock
associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the
object's lock before accessing them, and then release the lock when it's done with them.

From Java 5 the package java.util.concurrent.locks contains several lock implementations.

Unit-5

11. Explain Socket Programming in Java.

This article describes a very basic one-way Client and Server setup where a Client connects, sends
messages to the server and the server shows them using a socket connection. There’s a lot of low-level stuff
that needs to happen for these things to work but the Java API networking package (java.net) takes care of all of
that, making network programming very easy for programmers.
Client-Side Programming
Establish a Socket Connection

To connect to another machine we need a socket connection. A socket connection means the two
machines have information about each other’s network location (IP Address) and TCP port. The java.net.Socket
class represents a Socket. To open a socket:
Socket socket = new Socket(“127.0.0.1”, 5000)
• The first argument – IP address of Server. ( 127.0.0.1 is the IP address of localhost, where code will run on
the single stand-alone machine).
• The second argument – TCP Port. (Just a number representing which application to run on a server. For
example, HTTP runs on port 80. Port number can be from 0 to 65535)

Communication

To communicate over a socket connection, streams are used to both input and output the data.

Closing the connection

The socket connection is closed explicitly once the message to the server is sent.
In the program, the Client keeps reading input from a user and sends it to the server until “Over” is typed

Java Implementation
• Java

// A Java program for a Client


import java.io.*;

import java.net.*;

public class Client {

// initialize socket and input output streams

private Socket socket = null;

private DataInputStream input = null;

private DataOutputStream out = null;

// constructor to put ip address and port

public Client(String address, int port)

// establish a connection

try {

socket = new Socket(address, port);

System.out.println("Connected");

// takes input from terminal

input = new DataInputStream(System.in);

// sends output to the socket

out = new DataOutputStream(

socket.getOutputStream());

catch (UnknownHostException u) {

System.out.println(u);
return;

catch (IOException i) {

System.out.println(i);

return;

// string to read message from input

String line = "";

// keep reading until "Over" is input

while (!line.equals("Over")) {

try {

line = input.readLine();

out.writeUTF(line);

catch (IOException i) {

System.out.println(i);

// close the connection

try {

input.close();

out.close();
socket.close();

catch (IOException i) {

System.out.println(i);

public static void main(String args[])

Client client = new Client("127.0.0.1", 5000);

Server Programming

Establish a Socket Connection

To write a server application two sockets are needed.


• A ServerSocket which waits for the client requests (when a client makes a new Socket())
• A plain old Socket to use for communication with the client.

Communication

getOutputStream() method is used to send the output through the socket.

Close the Connection

After finishing, it is important to close the connection by closing the socket as well as input/output streams

12. Explain the TCP/IP with example.

In this Java network programming tutorial, you will learn how to develop a socket server program to implement fully
functional network client/server application. You will also learn how to create a multi-threaded server.

First, let’s understand about the workflow and the API.


1. ServerSocket API

The ServerSocketclass is used to implement a server program. Here are the typical steps involve in developing a
server program:

1. Create a server socket and bind it to a specific port number


2. Listen for a connection from the client and accept it. This results in a client socket is created for the
connection.
3. Read data from the client via an InputStream obtained from the client socket.
4. Send data to the client via the client socket’s OutputStream.
5. Close the connection with the client.
The steps 3 and 4 can be repeated many times depending on the protocol agreed between the server and the
client.

The steps 1 to 5 can be repeated for each new client. And each new connection should be handled by a separate
thread.

Let’s dive into each step in details.

Create a Server Socket:


Create a new object of the ServerSocket class by using one of the following constructors:

- ServerSocket(int port): creates a server socket that is bound to the specified port number. The maximum
number of queued incoming connections is set to 50 (when the queue is full, new connections are
refused).
- ServerSocket(int port, int backlog): creates a server socket that is bound to the specified port number
and with the maximum number of queued connections is specified by the backlog parameter.
- ServerSocket(int port, int backlog, InetAddress bindAddr): creates a server socket and binds it to the
specified port number and a local IP address.

So when to use which?

Use the first constructor for a small number of queued connections (less than 50) and any local IP address
available.

Use the second constructor if you want to explicitly specify the maximum number of queued requests.

And use the third constructor if you want to explicitly specify a local IP address to be bound (in case the computer
has multiple IP addresses).

And of course, the first constructor is preferred for simple usage. For example, the following line of code creates a
server socket and binds it to the port number 6868:

1 ServerSocket serverSocket = new ServerSocket(6868);


Note that these constructors can throw IOException if an I/O error occurs when opening the socket, so you have to
catch or re-throw it.

Listen for a connection:

Once a ServerSocket instance is created, call accept() to start listening for incoming client requests:

1 Socket socket = serverSocket.accept();

Note that the accept() method blocks the current thread until a connection is made. And the connection is
represented by the returned Socket object.

You might also like