Professional Documents
Culture Documents
Know All About Socket Programming in Java
Know All About Socket Programming in Java
Socket programming in Java is used for communication between the applications that are
running on different JRE. It can be either connection-oriented or connectionless. On the
whole, a socket is a way to establish a connection between a client and a server. In this
article, I will tell you all about Socket Programming.
The server forms the listener socket while the client reaches out to the server. Socket and
Server Socket classes are used for connection-oriented socket programming.
Now let’s understand the core concept of Socket Programming i.e. a socket.
Now that you know, what is Socket in Java, let’s move further and understand how does client
communicates with the server and how the server responds back.
In order to initiate a clients request, you need to follow the below-mentioned steps:
1. Establish a Connection
Instructor-led Sessions
Real-life Case Studies
Assignments
Lifetime Access
Explore Curriculum
The very first step is to establish a socket connection. A socket connection implies that the
two machines have information about each other’s network location (IP Address) and TCP
port.
2. Communication
In order to communicate over a socket connection, streams are used for both input and output
the data. After establishing a connection and sending the requests, you need to close the
connection.
The socket connection is closed explicitly once the message to the server is sent.
Now let’s see how to write a Java program to implement socket connection at client side.
In order to code the server-side application, you need two sockets and they are as follows:
A ServerSocket which waits for the client requests (when a client makes a new
Socket())
A plain old socket for communication with the client.
After this, you need to communicate with the client with the response.
Communication
It is important to close the connection by closing the socket as well as input/output streams
once everything is done.
Now let’s see how to write a Java program to implement socket connection at server side.
1. When you run the server side script, it will start and wait for the client to get started.
2. Next, the client will get connected and inputs the request in the form of a string.
3. When the client sends the request, the server will respond back.
That’s how you need to execute a socket program in Java. You can also execute these
programs on a terminal window or a command prompt.
Java Read Files
Read a File
In the previous chapter, you learned how to create and write to a file.
In the following example, we use the Scanner class to read the contents of the text
file we created in the previous chapter:
Example
import java.io.File; // Import the File class
try {
while (myReader.hasNextLine()) {
System.out.println(data);
myReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
The output will be:
Example
import java.io.File; // Import the File class
if (myObj.exists()) {
} else {
Java Threads
Java Threads
Threads allows a program to operate more efficiently by doing multiple things at the
same time.
Creating a Thread
There are two ways to create a thread.
Extend Syntax
public class Main extends Thread {
Implement Syntax
public class Main implements Runnable {
public void run() {
Running Threads
If the class extends the Thread class, the thread can be run by creating an instance
of the class and call its start() method:
Extend Example
public class Main extends Thread {
thread.start();
Try it Yourself »
Implement Example
public class Main implements Runnable {
thread.start();
Try it Yourself »
Differences between "extending" and "implementing" Threads
The major difference is that when a class extends the Thread class, you cannot
extend any other class, but by implementing the Runnable interface, it is possible to
extend from another class as well, like: class MyClass extends OtherClass
implements Runnable.
Concurrency Problems
Because threads run at the same time as other parts of the program, there is no way
to know in which order the code will run. When the threads and main program are
reading and writing the same variables, the values are unpredictable. The problems
that result from this are called concurrency problems.
Example
A code example where the value of the variable amount is unpredictable:
thread.start();
System.out.println(amount);
amount++;
System.out.println(amount);
amount++;
Try it Yourself »
Example
Use isAlive() to prevent concurrency problems:
thread.start();
while(thread.isAlive()) {
System.out.println("Waiting...");
amount++;
amount++;
Generics in Java
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and
user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is
possible to create classes that work with different data types. An entity such as class, interface,
or method that operates on a parameterized type is a generic entity.
Why Generics?
The Object is the superclass of all other classes, and Object reference can refer to any object.
These features lack type safety. Generics add that type of safety feature. We will discuss that
type of safety feature in later examples.
Generics in Java are similar to templates in C++. For example, classes like HashSet, ArrayList,
HashMap, etc., use generics very well. There are some fundamental differences between the
two approaches to generic types.
Generic Method: Generic Java method takes a parameter and returns some value after
performing a task. It is exactly like a normal function, however, a generic method has type
parameters that are cited by actual type. This allows the generic method to be used in a more
general way. The compiler takes care of the type of safety which enables programmers to code
easily since they do not have to perform long, individual type castings.
Generic Classes: A generic class is implemented exactly like a non-generic class. The only
difference is that it contains a type parameter section. There can be more than one type of
parameter, separated by a comma. The classes, which accept one or more parameters, are
known as parameterized classes or parameterized types.
Generic Class
Like C++, we use <> to specify parameter types in generic class creation. To create objects of a
generic class, we use the following syntax.
// To create an instance of generic class
BaseType <Type> obj = new BaseType <Type>()
Note: In Parameter type we can not use primitives like ‘int’,’char’ or ‘double’.
Java
// Generic classes
class Test<T> {
T obj;
class Main {
{
System.out.println(iObj.getObject());
Test<String> sObj
= new Test<String>("GeeksForGeeks");
System.out.println(sObj.getObject());
}
Output
15
GeeksForGeeks
We can also pass multiple Type parameters in Generic classes.
Java
// constructor
{
this.obj1 = obj1;
this.obj2 = obj2;
}
// To print objects of T and U
{
System.out.println(obj1);
System.out.println(obj2);
}
}
class Main
{
obj.print();
}
Output
GfG
15
Generic Functions:
We can also write generic functions that can be called with different types of arguments based
on the type of arguments passed to the generic method. The compiler handles each method.
Java
// Generic functions
class Test {
{
System.out.println(element.getClass().getName()
}
{
genericDisplay(11);
genericDisplay("GeeksForGeeks");
}
Output
java.lang.Integer = 11
java.lang.String = GeeksForGeeks
java.lang.Double = 1.0
When we declare an instance of a generic type, the type argument passed to the type parameter
must be a reference type. We cannot use primitive data types like int, char.
Test<int> obj = new Test<int>(20);
The above line results in a compile-time error that can be resolved using type wrappers to
encapsulate a primitive type.
But primitive type arrays can be passed to the type parameter because arrays are reference
types.
ArrayList<int[]> a = new ArrayList<>();
Java
class Test<T> {
// An object of type T is declared
T obj;
class Main {
{
System.out.println(iObj.getObject());
Test<String> sObj
System.out.println(sObj.getObject());
}
Output:
error:
incompatible types:
Test cannot be converted to Test
Even though iObj and sObj are of type Test, they are the references to different types because
their type parameters differ. Generics add type safety through this and prevent errors.
The type parameters naming conventions are important to learn generics thoroughly. The
common type parameters are as follows:
T – Type
E – Element
K – Key
N – Number
V – Value
Advantages of Generics:
Programs that use Generics has got many benefits over non-generic code.
1. Code Reuse: We can write a method/class/interface once and use it for any type we want.
2. Type Safety: Generics make errors to appear compile time than at run time (It’s always
better to know problems in your code at compile time rather than making your code fail at run
time). Suppose you want to create an ArrayList that store name of students, and if by mistake
the programmer adds an integer object instead of a string, the compiler allows it. But, when we
retrieve this data from ArrayList, it causes problems at runtime.
Java
import java.util.*;
class Test
{
public static void main(String[] args)
{
al.add("Sachin");
al.add("Rahul");
String s1 = (String)al.get(0);
String s2 = (String)al.get(1);
String s3 = (String)al.get(2);
}
Output :
Exception in thread "main" java.lang.ClassCastException:
java.lang.Integer cannot be cast to java.lang.String
at Test.main(Test.java:19)
When defining ArrayList, we can specify that this list can take only String objects.
Java
// Using Java Generics converts run time exceptions into
import java.util.*;
class Test
{
al.add("Sachin");
al.add("Rahul");
al.add(10);
String s1 = (String)al.get(0);
String s2 = (String)al.get(1);
String s3 = (String)al.get(2);
}
}
Output:
15: error: no suitable method found for add(int)
al.add(10);
^
3. Individual Type Casting is not needed: If we do not use generics, then, in the above
example, every time we retrieve data from ArrayList, we have to typecast it. Typecasting at
every retrieval operation is a big headache. If we already know that our list only holds string
data, we need not typecast it every time.
Java
import java.util.*;
class Test {
{
al.add("Sachin");
al.add("Rahul");
String s1 = al.get(0);
String s2 = al.get(1);
}
4. Generics Promotes Code Reusability: With the help of generics in Java, we can write code
that will work with different types of data. For example,
public <T> void genericsMethod (T data) {...}
Here, we have created a generics method. This same method can be used to perform operations
on integer data, string data, and so on.
5. Implementing Generic Algorithms: By using generics, we can implement algorithms that
work on different types of objects, and at the same, they are type-safe too.
This article is contributed by Dharmesh Singh. If you like GeeksforGeeks and would like to
contribute, you can also write an article and mail your article to review-
team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help
other Geeks. Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
The worst situation is if your application crashes while the user is doing any important
work, especially if their data is lost. To make the user interface robust, it is important to
handle Java exceptions to prevent the application from unexpectedly crashing and losing
data. There can be many causes for a sudden crash of the system, such as incorrect or
unexpected data input. For example, if we try to add two users with duplicate IDs to the
database, we should throw an exception since the action would affect database integrity.
Developers can predict many of the Java exceptions that a piece of code is capable of
throwing.
The best course of action is to explicitly handle those exceptions to recover from them
gracefully. As we will see ahead, programming languages provide ways to handle
exceptions starting from specific ones and moving toward the more generic ones. Java
exceptions that you cannot easily predict ahead of time are called unhandled exceptions. It’s
good to capture these too in order to gracefully recover. Tracking these Java exceptions
centrally offers visibility to your development team on the quality of the code and what
causes these errors so they can fix them faster.
The standard practice is to record all events in the application log file. The log file acts as a
time machine helping the developer (or analyst) go back in time to view all the phases the
application went through and what led to the Java exception.
For small-scale applications, going through a log file is easy. However, enterprise
applications can serve thousands or even millions of requests per second. This makes
manual analysis too cumbersome because errors and their causes can be lost in the noise.
This is where error monitoring software can help by grouping duplicates and providing
summarized views of the top and most recent Java errors. They can also capture and
organize contextual data in a way that’s easier and faster than looking at logs.
This method will catch any type of Java exceptions that get thrown. This is the simplest
mechanism for handling exceptions.
try {
// block of code that can throw exceptions
} catch (Exception ex) {
// Exception handler
}
Note: You can’t use a try block alone. The try block should be immediately followed either
by a catch or finally block.
4. Types of Exception
5. Exception Example
In this tutorial, we will learn about Java exceptions, it's types, and the difference between
checked and unchecked exceptions.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that is why we
need to handle exceptions. Let's consider a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement 5;
the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed.
However, when we perform exception handling, the rest of the statements will be executed.
That is why we use exception handling in Java
.
Do You Know?
o What is the difference between checked and unchecked exceptions?
o What happens behind the code int data=50/0;?
o Why use multiple catch block?
o Is there any possibility when the finally block is not executed?
o What is exception propagation?
o What is the difference between the throw and throws keyword?
o What are the 4 rules for using exception handling with method overriding?
1. Checked Exception
2. Unchecked Exception
3. Error
The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by
either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.
finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always
used with method signature.
JavaExceptionExample.java
1. public class JavaExceptionExample{
2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }
Test it Now
Output:
1. int a=50/0;//ArithmeticException
String s=null;
1. System.out.println(s.length());//NullPointerException
variable that has characters; converting this variable into digit will cause NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be
other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException
TestExceptionChild.java
1. import java.io.*;
2. class Parent{
3.
4. // defining the method
5. void msg() {
6. System.out.println("parent method");
7. }
8. }
9.
10. public class TestExceptionChild extends Parent{
11.
12. // overriding the method in child class
13. // gives compile time error
14. void msg() throws IOException {
15. System.out.println("TestExceptionChild");
16. }
17.
18. public static void main(String args[]) {
19. Parent p = new TestExceptionChild();
20. p.msg();
21. }
22. }
Output:
Rule 2: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but can declare unchecked exception.
TestExceptionChild1.java
1. import java.io.*;
2. class Parent{
3. void msg() {
4. System.out.println("parent method");
5. }
6. }
7.
8. class TestExceptionChild1 extends Parent{
9. void msg()throws ArithmeticException {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]) {
14. Parent p = new TestExceptionChild1();
15. p.msg();
16. }
17. }
Output:
1. import java.io.*;
2. class Parent{
3. void msg()throws ArithmeticException {
4. System.out.println("parent method");
5. }
6. }
7.
8. public class TestExceptionChild2 extends Parent{
9. void msg()throws Exception {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]) {
14. Parent p = new TestExceptionChild2();
15.
16. try {
17. p.msg();
18. }
19. catch (Exception e){}
20.
21. }
22. }
Output:
Example in case subclass overridden method declares same
exception
TestExceptionChild3.java
1. import java.io.*;
2. class Parent{
3. void msg() throws Exception {
4. System.out.println("parent method");
5. }
6. }
7.
8. public class TestExceptionChild3 extends Parent {
9. void msg()throws Exception {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]){
14. Parent p = new TestExceptionChild3();
15.
16. try {
17. p.msg();
18. }
19. catch(Exception e) {}
20. }
21. }
Output:
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception {
4. System.out.println("parent method");
5. }
6. }
7.
8. class TestExceptionChild4 extends Parent{
9. void msg()throws ArithmeticException {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]){
14. Parent p = new TestExceptionChild4();
15.
16. try {
17. p.msg();
18. }
19. catch(Exception e) {}
20. }
21. }
Output:
1. import java.io.*;
2. class Parent {
3. void msg()throws Exception{
4. System.out.println("parent method");
5. }
6. }
7.
8. class TestExceptionChild5 extends Parent{
9. void msg() {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]){
14. Parent p = new TestExceptionChild5();
15.
16. try {
17. p.msg();
18. }
19. catch(Exception e) {}
20.
21. }
22. }
Output:
Custom Exception