0% found this document useful (0 votes)
11 views

Java Unit1

This document provides an introduction to Java, covering its history, key features, and core concepts such as inheritance, exception handling, and multithreading. It explains the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK), emphasizing Java's platform independence, object-oriented programming principles, and security features. Additionally, it discusses various types of inheritance in Java, the use of the 'super' keyword, and the importance of exception handling for creating robust applications.

Uploaded by

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

Java Unit1

This document provides an introduction to Java, covering its history, key features, and core concepts such as inheritance, exception handling, and multithreading. It explains the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK), emphasizing Java's platform independence, object-oriented programming principles, and security features. Additionally, it discusses various types of inheritance in Java, the use of the 'super' keyword, and the importance of exception handling for creating robust applications.

Uploaded by

kaurashmeet2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

UNIT- 1

Syllabus: Introduction to Java, Inheritance, Exception Handling, Multithreading, Applet


Programming. Connecting to a Server, Implementing Servers, Making URL Connections, Socket
Programming.

Introduction To Java
Java was developed by James Gosling at Sun Microsystems Inc. in May 1995 and later acquired by
Oracle Corporation and is widely used for developing applications for desktop, web, and mobile devices.
Java is known for its simplicity, robustness, and security features, making it a popular choice for
enterprise-level applications. Java applications are compiled to byte code that can run on any Java Virtual
Machine. The journey of this powerful programming language began in 1991 when James Gosling, Mike
Sheridan, and Patrick Naughton, a team of engineers at Sun Microsystems known as the “Green Team,”
set out to create a new language initially called “Oak.” Oak was later renamed Java, inspired by Java
coffee, and was first publicly released in 1996 as Java 1.0.

JVM, JDK, JRE


JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't
physically exist. It is a specification that provides a runtime environment in which Java bytecode can be
executed.JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each other.
The JVM performs the following main tasks:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment.The Java Runtime Environment is a set of software
tools which are used for developing Java applications. It is used to provide the runtime environment. It is
the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at
runtime.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It physically exists. It
contains JRE + development tools. The JDK contains a private Java Virtual Machine (JVM) and a few
other resources such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation
generator (Javadoc), etc. to complete the development of a Java Application.

Key Features of Java


1. Platform Independent
The meaning of Java platform-independent is that the Java compiled code(byte code) can run on all
operating systems. A program is written in a language that is human-readable. So, here comes the role of a
compiler. The compiler converts the high-level language (human language) into a format understood by
the machines. Therefore, a compiler is a program that translates the source code for another program from
a programming language into executable code. This executable code may be a sequence of machine
instructions that can be executed by the CPU directly, or it may be an intermediate representation that is
interpreted by a virtual machine. This intermediate representation in Java is the Java Byte Code.
Step-by-Step Execution of Java Program
 Whenever a program is written in JAVA, the java compiles it.
 The result of the JAVA compiler is the .class file or the bytecode and not the machine’s native
code (unlike the C compiler).
 The bytecode generated is a non-executable code and needs an interpreter to execute on a
machine. This interpreter is the JVM and thus the Bytecode is executed by the JVM.
 And finally, the program runs to give the desired output.

Important Points:
 In the case of Java, it is the magic of Bytecode that makes it platform-independent.
 This adds to an important feature in the JAVA language termed portability. Every system has its
own JVM which gets installed automatically when the JDK software is installed. For every
operating system separate JVM is available which is capable to read the .class file or byte code.
 An important point to be noted is that while JAVA is a platform-independent language, the JVM is
platform-dependent. Different JVM is designed for different OS and byte code is able to run on
different OS.
2. Object-Oriented Programming
Java is an object-oriented language, promoting the use of objects and classes. Organizing the program in
the terms of a collection of objects is a way of object-oriented programming, each of which represents an
instance of the class.The four main concepts of Object-Oriented programming are: Abstraction,
Encapsulation, Inheritance, Polymorphism
3. Simplicity
Java’s syntax is simple and easy to learn. It eliminates complex features like pointers and multiple
inheritances, making it easier to write, debug, and maintain code.

4. Robustness
Java language is robust which means reliable. The main features of java that make it robust are garbage
collection, exception handling, and memory allocation.
5. Security
In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it
shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several security flaws like stack
corruption or buffer overflow are impossible to exploit in Java. Also, java programs run in an
environment that is independent of the os(operating system) environment which makes java programs
more secure.
6. Distributed
Remote Method Invocation and Enterprise Java Beans are used for creating distributed applications in
java. The java programs can be easily distributed on one or more systems that are connected to each other
through an internet connection.
7. Multithreading
Java supports multithreading, enabling the concurrent execution of multiple parts of a program. This
feature is particularly useful for applications that require high performance, such as games and real-time
simulations.
8. Portability
Java code written on one machine can be run on another machine. The platform-independent feature of
java in which its platform-independent bytecode can be taken to any platform for execution makes java
portable. WORA (Write Once Run Anywhere) makes java application to generates a ‘.class’ file that
corresponds to our applications(program) but contains code in binary format.

Inheritance
Java, Inheritance is an important pillar of OOP (Object-Oriented Programming). It is the mechanism in
Java by which one class is allowed to inherit the features (fields and methods) of another class. In Java,
Inheritance means creating new classes based on existing ones. A class that inherits from another class
can reuse the methods and fields of that class. In addition, can add new fields and methods to current class
as well.
Why Do We Need Java Inheritance?
 Code Reusability: The code written in the Superclass is common to all subclasses. Child classes
can directly use the parent class code.
 Method Overriding: Method Overriding is achievable only through Inheritance. It is one of the
ways by which Java achieves Run Time Polymorphism.
 Abstraction: The concept of abstract where we do not have to provide all details, is achieved
through inheritance. Abstraction only shows the functionality to the user.
How to Use Inheritance in Java?
The extends keyword is used for inheritance in Java. Using the extends keyword indicates you are derived
from an existing class. In other words, “extends” refers to increased functionality.Inheritance,
and polymorphism are used together in Java to achieve fast performance and readability of code.
Java Inheritance Types
1. Single Inheritance 2. Multilevel Inheritance 3. Hierarchical Inheritance 4. Multiple Inheritance
5. Hybrid Inheritance
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties and
behavior of a single-parent class. In the below figure, ‘A’ is a parent class and ‘B’ is a child class. The
class ‘B’ inherits all the properties of the class ‘A’.
import java.io.*;
import java.lang.*;
import java.util.*;
class One { // Parent class
public void printMsg()
{System.out.println("CSE 6 sem"); }
}
class Two extends One {
public void sayHi() { System.out.println("Hi"); }
}
public class Main {// Driver class
public static void main(String[] args)
{ Two childobj = new Two();
childobj.printMsg();
childobj.sayHi();
}}
Output
CSE 6 sem
Hi
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived class
also acts as the base class for other classes. In the below image, class A serves as a base class for the
derived class B, which in turn serves as a base class for the derived class C.

import java.io.*;
import java.util.*;
class One {
public void print_CSE() { System.out.println("cse"); }
}
class Two extends One { // Child class Two inherits from class One
public void print_for() { System.out.println("for"); }
}
class Three extends Two { // Child class Three inherits from class Two
public void print_lastMsg() { System.out.println("Java"); }
}
public class Main {
public static void main(String[] args) { Three g = new Three(); // Creating an object of class Three
g.print_CSE(); // Calling method from class One
g.print_for(); // Calling method from class Two
g.print_lastMsg(); // Calling method from class Three
}}
Output
CSE
for
JAVA
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the
below image, class A serves as a base class for the derived classes B, C, and D.

class A {
public void print_A() { System.out.println("Class A"); } }
class B extends A {
public void print_B() { System.out.println("Class B"); } }
class C extends A {
public void print_C() { System.out.println("Class C"); } }
class D extends A {
public void print_D() { System.out.println("Class D"); } }
public class Test { // Driver Class
public static void main(String[] args)
{ B obj_B = new B();
obj_B.print_A();
obj_B.print_B();
C obj_C = new C();
obj_C.print_A();
obj_C.print_C(); }}
Output
Class A
Class B
Class A
Class C

4. Multiple Inheritance (Through Interfaces)


In Multiple inheritances, one class can have more than one superclass and inherit features from all parent
classes. Please note that Java does not support multiple inheritances with classes. In Java, we can achieve
multiple inheritances only through Interfaces.
5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t support multiple
inheritances with classes, hybrid inheritance involving multiple inheritance is also not possible with
classes. In Java, we can achieve hybrid inheritance only through Interfaces if we want to involve multiple
inheritance to implement Hybrid inheritance.
Disadvantages of Inheritance in Java:
1. Complexity: Inheritance can make the code more complex and harder to understand. This is
especially true if the inheritance hierarchy is deep or if multiple inheritances is used.
2. Tight Coupling: Inheritance creates a tight coupling between the superclass and subclass,
making it difficult to make changes to the superclass without affecting the subclass.
Important points:
 Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested
classes) from its superclass. Constructors are not members, so they are not inherited by
subclasses, but the constructor of the superclass can be invoked from the subclass.
 Private member inheritance: A subclass does not inherit the private members of its parent class.
However, if the superclass has public or protected methods (like getters and setters) for accessing
its private fields, these can also be used by the subclass.
Super keyword
The super keyword in Java is a reference variable that is used to refer to parent class when we’re
working with objects.
 super is used to call a superclass constructor: When a subclass is created, its constructor must
call the constructor of its parent class. This is done using the super() keyword, which calls the
constructor of the parent class.
 super is used to call a superclass method: A subclass can call a method defined in its parent
class using the super keyword. This is useful when the subclass wants to invoke the parent class’s
implementation of the method in addition to its own.
 super is used to access a superclass field: A subclass can access a field defined in its parent
class using the super keyword. This is useful when the subclass wants to reference the parent
class’s version of a field.
 super must be the first statement in a constructor: When calling a superclass constructor, the
super() statement must be the first statement in the constructor of the subclass.
 super cannot be used in a static context: The super keyword cannot be used in a static context,
such as in a static method or a static variable initializer.
Use of super keyword in Java
1. Use of super with Variables
This scenario occurs when a derived class and base class have the same data members. In that case, there
is a possibility of ambiguity.
class Vehicle { int maxSpeed = 120; }
class Car extends Vehicle { int maxSpeed = 180;
void display(){
System.out.println("Max Speed: " + super.maxSpeed); //print maxSpeed of base class (vehicle) } }
class Test {
public static void main(String[] args) {
Car small = new Car();
small.display(); } }
Output
Max Speed: 120
In the above example, both the base class and subclass have a member maxSpeed. We could access the
maxSpeed of the base class in subclass using super keyword.
2. Use of super with Methods
This is used when we want to call the parent class method. So whenever a parent and child class have the
same-named methods then to resolve ambiguity we use the super keyword.
class Person { void message()
{ System.out.println("This is person class\n"); } }
class Student extends Person {
void message() { System.out.println("This is student class"); }
void display() { message(); // will invoke or call current class message() method
super.message(); } } // will invoke or call parent class message() method
class Test { public static void main(String args[])
{ Student s = new Student();
s.display(); } }
Output
This is student class
This is person class
In the above example, we have seen that if we only call method message() then, the current class
message() is invoked but with the use of the super keyword, message() of the superclass could also be
invoked.
3. Use of super with constructors
The super keyword can also be used to access the parent class constructor. One more important thing is
that ‘super’ can call both parametric as well as non-parametric constructors depending on the situation.
class Person { Person()
{ System.out.println("Person class Constructor"); }}
class Student extends Person { // subclass Student extending the Person class
Student() { super(); // invoke or call parent class constructor
System.out.println("Student class Constructor"); }}
class Test {
public static void main(String[] args)
{ Student s = new Student(); } }
Output
Person class Constructor
Student class Constructor
Exception Handling
Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms
like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc.An Exception is
an unwanted or unexpected event that occurs during the execution of a program (i.e., at runtime) and
disrupts the normal flow of the program’s instructions.
import java.io.*;
class Main { //Showing an Arithmetic Exception or you can say divide by zero exception.
public static void main(String[] args)
{ int n = 10; int m = 0; int ans = n / m;
System.out.println("Answer: " + ans);
}}
Output:

Note: When an exception occurs and is not handled, the program terminates abruptly and the code after
it, will never execute.
Exception Handling in Java
Exception handling in Java is an effective mechanism for managing runtime errors to ensure the
application’s regular flow is maintained. Some Common examples of exceptions
include ClassNotFoundException, IOException, SQLException, RemoteException, etc. By handling
these exceptions, Java enables developers to create robust and fault-tolerant applications.
Example: The below Java program modifies the previous example to handle
an ArithmeticException using try-catch, and finally blocks and keep the program running.
import java.io.*;
class Main { public static void main(String[] args)
{ int n = 10; int m = 0;
try { // Code that may throw an exception
int ans = n / m;
System.out.println("Answer: " + ans); }
catch (ArithmeticException e) { // Handling the exception
System.out.println( "Error: Division by zero is not allowed!"); }
finally { System.out.println("Program continues after handling the exception."); } }}
Output
Error: Division by zero is not allowed!
Program continues after handling the exception.
Note: With the help of exception handling we can detect and handle the exceptions gracefully so that the
normal flow of the program can be maintained.
The summary is depicted via visual aid below as follows:

Java Exception Hierarchy


All exception and error types are subclasses of the class Throwable, which is the base class of the
hierarchy.

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.
Types of Java Exceptions
Java defines several types of exceptions that relate to its various class libraries. Java also allows users to
define their own exceptions.
Exceptions can be categorized in two ways:
1. Built-in Exceptions
 Checked Exception
 Unchecked Exception
2. User-Defined Exceptions
1. Built-in Exception
Build-in Exception are pre-defined exception classes provided by Java to handle common errors during
program execution.
1.1 Checked Exceptions
Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-
time by the compiler. Examples of Checked Exception are listed below:
1. ClassNotFoundException: Throws when the program tries to load a class at runtime but the class
is not found because its not present in the correct location or it is missing from the project.
2. InterruptedException: Thrown when a thread is paused and another thread interrupts it.
3. IOException: Throws when input/output operation fails
4. InstantiationException: Thrown when the program tries to create an object of a class but fails
because the class is abstract, an interface, or has no default constructor.
5. SQLException: Throws when there’s an error with the database.
6. FileNotFoundException: Thrown when the program tries to open a file that doesn’t exist
1.2 Unchecked Exceptions
The unchecked exceptions are just opposite to the checked exceptions. The compiler will not check these
exceptions at compile time. In simple words, if a program throws an unchecked exception, and even if we
didn’t handle or declare it, the program would not give a compilation error. Examples of Unchecked
Exception are listed below:
1. ArithmeticException: It is thrown when there’s an illegal math operation.
2. ClassCastException: It is thrown when you try to cast an object to a class it does not belongs to.
3. NullPointerException: It is thrown when you try to use a null object (e.g. accessing its methods or
fields)
4. ArrayIndexOutOfBoundsException: It occurs when we try to access an array element with an
invalid index.
5. ArrayStoreException: It happens when you store an object of the wrong type in an array.
6. IllegalThreadStateException: It is thrown when a thread operation is not allowed in its current
state
2. User-Defined Exception
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, users
can also create exceptions, which are called “user-defined Exceptions“.
Try-Catch Block
A try-catch block in Java is a mechanism to handle exception. The try block contains code that might
thrown an exception and the catch block is used to handles the exceptions if it occurs.
try {// Code that may throw an exception
} catch (ExceptionType e) {// Code to handle the exception
}
finally Block
The finally Block is used to execute important code regardless of wether an exception occurs or
not.Finally block is always executes after the try-catch block. It is also used for resource cleanup.
try {// Code that may throw an exception
} catch (ExceptionType e) {// Code to handle the exception
}finally{// cleanup code
}
Handling Multiple Exception
We can handle multiple type of exceptions in Java by using multiple catch blocks, each catching a
different type of exception.
try {// Code that may throw an exception
} catch (ArithmeticException e) {// Code to handle the exception}
catch(ArrayIndexOutOfBoundsException e){//Code to handle the another exception}
throw and throws in Java
In Java, Exception Handling is one of the effective means to handle runtime errors so that the regular flow
of the application can be preserved. It handles runtime errors such
as NullPointerException, ArrayIndexOutOfBoundsException, etc.

Feature Throw Throws

It is used to declare that a method


It is used to explicitly throw an exception.
Definition might throw one or more exceptions.

It is used inside a method or a block of


It is used in the method signature.
Location code.
Feature Throw Throws

It is only used for checked exceptions.


It can throw both checked and unchecked
Unchecked exceptions do not
exceptions.
Usage require throws.

The method’s caller is responsible for


The method or block throws the exception.
Responsibility handling the exception.

Flow of Stops the current flow of execution It forces the caller to handle the
Execution immediately. declared exceptions.

public void myMethod() throws


throw new ArithmeticException(“Error”);
Example IOException {}

class Geeks { static void fun()


{try {throw new NullPointerException("demo");}
catch (NullPointerException e) { System.out.println("Caught inside fun().");
throw e; // rethrowing the exception
} }
public static void main(String args[])
{ try { fun(); }
catch (NullPointerException e) { System.out.println("Caught in main."); } }}

Output
Caught inside fun().
Caught in main.
Explanation: The above example demonstrates the use of the throw keyword to explicitly throw
a NullPointerException. The exception is caught inside the fun() method and rethrown, where it is then
caught in the main() method.
Java throws
throws is a keyword in Java that is used in the signature of a method to indicate that this method might
throw one of the listed type exceptions. The caller to these methods has to handle the exception using
a try-catch block.
Syntax of Java throws
type method_name(parameters) throws exception_list //where, exception_list is a comma separated list of
all the exceptions which a method might throw.
We can use the throws keyword to delegate the responsibility of exception handling to the caller (It may
be a method or JVM) then the caller method is responsible to handle that exception.
Example 2: Using throws to Handle Exception
class ExceptionHandle {
public static void main(String[] args) throws InterruptedException
{ Thread.sleep(10000);
System.out.println("Hello CSE");
}}
Output:
Hello CSE

MultiThreading
Threads are the backbone of multithreading.
Real-life Example of Java Multithreading -Suppose you are using two tasks at a time on the computer, be
it using Microsoft Word and listening to music. These two tasks are called processes . So you start typing
in Word and at the same time start music app, this is called multitasking . Now you committed a mistake
in a Word and spell check shows exception, this means Word is a process that is broken down into sub-
processes. Now if a machine is dual-core then one process or task is been handled by one core and music
is been handled by another core.
Multitasking is being achieved in two ways :
1. Multiprocessing : Process-based multitasking is a heavyweight process and occupies different
address spaces in memory. Hence, while switching from one process to another, it will require
some time be it very small, causing a lag because of switching. This happens as registers will be
loaded in memory maps and the list will be updated.
2. Multithreading : Thread-based multitasking is a lightweight process and occupies the same
address space. Hence, while switching cost of communication will be very less.
A thread in Java can exist in any one of the following states at any given time. A thread lies only in one of
the shown states at any instant:
1. New State
2. Runnable State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State
The diagram below represents various states of a thread at any instant.

Life Cycle of a Thread


There are multiple states of the thread in a lifecycle as mentioned below:
1. New Thread: When a new thread is created, it is in the new state. The thread has not yet started
to run when the thread is in this state. When a thread lies in the new state, its code is yet to be run
and hasn’t started to execute.
2. Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a thread
might actually be running or it might be ready to run at any instant of time. It is the responsibility
of the thread scheduler to give the thread, time to run. A multi-threaded program allocates a fixed
amount of time to each individual thread. Each and every thread get a small amount of time to
run. After running for a while, a thread pauses and gives up the CPU so that other threads can run.
3. Blocked: The thread will be in blocked state when it is trying to acquire a lock but currently the
lock is acquired by the other thread. The thread will move from the blocked state to runnable state
when it acquires the lock.
4. Waiting state: The thread will be in waiting state when it calls wait() method or join() method. It
will move to the runnable state when other thread will notify or that thread will be terminated.
5. Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-out
parameter. A thread lies in this state until the timeout is completed or until a notification is
received. For example, when a thread calls sleep or a conditional wait, it is moved to a timed
waiting state.
6. Terminated State: A thread terminates because of either of the following reasons:
 Because it exits normally. This happens when the code of the thread has been entirely
executed by the program.
 Because there occurred some unusual erroneous event, like a segmentation fault or an
unhandled exception.
Two Ways to Implement Multithreading
 Using Thread Class
 Using Runnable Interface
Method 1: Using Thread Class
Java provides Thread class to achieve programming invoking threads thereby some major methods of
thread class are shown below in the tabular format with which we deal frequently along the action
performed by them.
class MyThread1 extends Thread {
public void run() // Method inside MyThread1 run() method which is called as soon as thread is started
{ System.out.println("Thread1 is running"); }} // Print statement when the thread is called
class MyThread2 extends Thread {
public void run() { // run() method which is called as soon as thread is started
System.out.println("Thread2 is running"); }}// Print statement when the thread is called
class Main { // Main Class
public static void main(String[] args)
{ MyThread1 obj1 = new MyThread1(); // Creating a thread object of our thread class
MyThread2 obj2 = new MyThread2(); // Getting the threads to the run state This thread will
transcend from runnable to run as start()
obj1.start(); // This thread will also transcend from runnable to run as start() method will look
for run() and execute it
obj2.start(); }}
Output:
Thread1 is running
Thread2 is running
Here we have created our two thread classes for each thread. In the main method , we are simply creating
objects of these thread classes where objects are now threads. So in main , we call thread using start()
method over both the threads. Now start() method starts the thread and lookup for their run() method to
run. Here both of our thread classes were having run() methods, so both threads are put to run state from
runnable by the scheduler, and output on the console is justified.
Method 2: Using Runnable Interface
Another way to achieve multithreading in java is via the Runnable interface. Runnable interface being a
functional interface has its own run() method. Here classes are implemented to the Runnable interface.
Later on, in the main() method, Runnable reference is created for the classes that are implemented in
order to make bondage with Thread class to run our own corresponding run() methods.
Further, while creating an object of Thread class we will pass these references in Thread class as its
constructor allows only one runnable object, which is passed as a parameter while creating Thread class
object in a main() method. Now start() method is invoked over the runnable object who are now already
linked with Thread class objects, so the execution begins for our run() methods in case of Runnable
interface.
import java.io.*;
import java.util.*;
class MyThread1 implements Runnable { //// Class 1 Helper class implementing Runnable interface
public void run() // run() method inside this class
{ for (int i = 0; i < 5; i++) { // Iterating to get more execution of threads
System.out.println("Thread1");
try { Thread.sleep(1000); // Making the thread pause for a certain time using sleep() method
}
catch (Exception e) {//exception caught } } }}
class MyThread2 implements Runnable {
public void run()
{ for (int i = 0; i < 5; i++) { System.out.println("Thread2");
try { Thread.sleep(1000); }
catch (Exception e) { //Exception Caught } } }}
public class GFG {
public static void main(String[] args)
{ // Creating reference of Runnable to our classes above in main() method
Runnable obj1 = new MyThread1();
Runnable obj2 = new MyThread2();
// Creating reference of thread class by passing object of Runnable in constructor of Thread class
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
t1.start();
t2.start();
}}

Output
Thread2
Thread1
Thread2
Thread1
Thread2
Thread1
Thread2
Thread1
Thread2
Thread1
Daemon thread is basically a service provider thread that provides services to the user thread. The scope
for this thread start() or be it terminate() is completely dependent on the user’s thread as it supports in the
backend for user threads being getting run. As soon as the user thread is terminated daemon thread is also
terminated at the same time as being the service provider thread.
Hence, the characteristics of the Daemon thread are as follows:
 It is only the service provider thread not responsible for interpretation in user threads.
 So, it is a low-priority thread.
 It is a dependent thread as it has no existence on its own.
 JVM terminates the thread as soon as user threads are terminated and come back into play as the
user’s thread starts.
 Yes, you guess the most popular example is garbage collector in java. Some other examples do
include ‘finalizer’.
Java Thread Safety
When multiple threads are working on the same data, and the value of our data is changing, that scenario
is not thread-safe and we will get inconsistent results. When a thread is already working on an object and
preventing another thread on working on the same object, this process is called Thread-Safety.
How to Achieve Thread Safety in Java?
There are four ways to achieve Thread Safety in Java. These are:
1. Using Synchronization
2. Using Volatile Keyword
3. Using Atomic Variable
4. Using Final Keyword
1. Using Synchronization
Synchronization is the process of allowing only one thread at a time to complete the particular task. It
means when multiple threads executing simultaneously, and want to access the same resource at the same
time, then the problem of inconsistency will occur. so synchronization is used to resolve inconsistency
problem by allowing only one thread at a time.
Synchronization uses a synchronized keyword. Synchronized is the modifier that creates a block of code
known as a critical section.
class A
{ synchronized void sum(int n)
{ // Creating a thread instance
Thread t = Thread.currentThread();
for (int i = 1; i <= 5; i++) {
System.out.println(t.getName() + " : " + (n + i)); } }}

class B extends Thread // Class B extending thread class


{ A a = new A(); // Creating an object of class A
public void run()
{ a.sum(10);// // Calling sum() method
}}
class Geeks
{ public static void main(String[] args)
{ B b = new B(); // Creating an object of class B
Thread t1 = new Thread(b); // Initializing instance t1 of Thread class with object of class B
Thread t2 = new Thread(b); // Initializing instance t2 of Thread class with object of class B
t1.setName("Thread A"); // Initializing thread t1 with name 'Thread A'
t2.setName("Thread B"); // Initializing thread t2 with name 'Thread B'
t1.start(); t2.start(); // Starting thread instance t1 and t2
}}

Output
Thread A : 11
Thread A : 12
Thread A : 13
Thread A : 14
Thread A : 15
Thread B : 11
Thread B : 12
Thread B : 13
Thread B : 14
Thread B : 15

2. Using Volatile Keyword


A volatile keyword is a field modifier that ensures that the object can be used by multiple threads at the
same time without having any problem. volatile is one good way of ensuring that the Java program is
thread-safe. a volatile keyword can be used as an alternative way of achieving Thread Safety in Java.
public class Geeks {
// Initializing volatile variables a, b
static volatile int a = 0, b = 0;
static void method_one() {
a++; b++; }
static void method_two() { System.out.println("a=" + a + " b=" + b); }
public static void main(String[] args)
{
Thread t1 = new Thread() // Creating an instance t1 of Thread class
{ public void run() { for (int i = 0; i < 5; i++)
method_one(); }
};
Thread t2 = new Thread()
{ public void run() { for (int i = 0; i < 5; i++)
method_two(); }
};
t1.start(); t2.start();
}}

Output
a=5 b=5
a=5 b=5
a=5 b=5
a=5 b=5
a=5 b=5

3. Using Atomic Variable


Using an atomic variable is another way to achieve thread-safety in java. When variables are shared by
multiple threads, the atomic variable ensures that threads don’t crash into each other.
import java.util.concurrent.atomic.AtomicInteger;

class Counter
{ AtomicInteger count = new AtomicInteger(); // Creating a variable of class type AtomicInteger
public void increment() { count.incrementAndGet(); } } // Defining increment() method to
change value of AtomicInteger variable
public class TestCounter {
public static void main(String[] args) throws Exception
{ Counter c = new Counter(); // Creating an instance of Counter class
Thread t1 = new Thread(new Runnable() { public void run() {
for(int i = 1; i <= 2000; i++) { c.increment(); } }
});
// Creating an instance t2 of Thread class
Thread t2 = new Thread(new Runnable()
{ public void run() { for (int i = 1; i <= 2000; i++) { c.increment(); }
} });
t1.start(); t2.start(); //Calling start() method with t1 and t2
t1.join(); t2.join(); // Calling join method with t1 and t2
System.out.println(c.count); }}

Output
4000

4. Using Final Keyword


Final Variables are also thread-safe in java because once assigned some reference of an object It cannot
point to reference of another object.
public class Geeks { // Initializing a string variable of final type
final String str = new String("hello");
// Defining a method to change the value of the final variable which is not possible, hence the error
will be shown
void method() { str = "world";
}}
Output:
Compilation Error in java code :
prog.java:14: error: cannot assign a value to final variable str
str = "world";
^
1 error

Applet Programming

An applet is a Java program that can be embedded into a web page. It runs inside the web browser and
works at client side. An applet is embedded in an HTML page using the APPLET or OBJECT tag and
hosted on a web server.Applets are used to make the website more dynamic and entertaining.
Important points :
1. All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.
2. Applets are not stand-alone programs. Instead, they run within either on a web browser or an
applet viewer. JDK provides a standard applet viewer tool called applet viewer.
3. In general, execution of an applet does not begin at main() method.
4. Output of an applet window is not performed by System.out.println(). Rather it is handled with
various AWT methods, such as drawString().
Life cycle of an applet :

It is important to understand the order in which the various methods shown in the above image are called.
When an applet begins, the following methods are called, in this sequence:
1. init( ) 2. start( ) 3.paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( ) 2.destroy( )
1. init( ) : The init( ) method is the first method to be called. This is where you should initialize variables.
This method is called only once during the run time of your applet.
2. start( ) : The start( ) method is called after init( ). It is also called to restart an applet after it has been
stopped. Note that init( ) is called once i.e. when the first time an applet is loaded whereas start( ) is called
each time an applet’s HTML document is displayed onscreen. So, if a user leaves a web page and comes
back, the applet resumes execution at start( ).
3. paint( ) : The paint( ) method is called each time an AWT-based applet’s output must be redrawn. This
situation can occur for several reasons. For example, the window in which the applet is running may be
overwritten by another window and then uncovered. Or the applet window may be minimized and then
restored. paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet
must redraw its output, paint( ) is called. The paint( ) method has one parameter of type Graphics. This
parameter will contain the graphics context, which describes the graphics environment in which the applet
is running. This context is used whenever output to the applet is required. It’s prototype is : public void
paint(Graphics g) ,where g is an object reference of class Graphic.
4. stop( ) : The stop( ) method is called when a web browser leaves the HTML document containing the
applet—when it goes to another page, for example. When stop( ) is called, the applet is probably running.
5. destroy( ) : The destroy( ) method is called when the environment determines that your applet needs to
be removed completely from memory. At this point, it should free up any resources the applet may be
using. The stop( ) method is always called before destroy( ).
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet
{ public void paint(Graphics g)
{ g.drawString("Hello World", 20, 20); }
}

 This class must be declared as public because it will be accessed by code that is outside the
program. Inside HelloWorld, paint( ) is declared. This method is defined by the AWT and must be
overridden by the applet.
 Inside paint( ) is a call to drawString( ), which is a member of the Graphics class. This method
outputs a string beginning at the specified X,Y location. It has the following general form:
void drawString(String message, int x, int y)
Here, message is the string to be output beginning at x,y. In a Java window, the upper-left corner is
location 0,0. The call to drawString( ) in the applet causes the message “Hello World” to be displayed
beginning at location 20,20.
Notice that the applet does not have a main( ) method. Unlike Java programs, applets do not begin
execution at main( ). In fact, most applets don’t even have a main( ) method. Instead, an applet begins
execution when the name of its class is passed to an applet viewer or to a network browser.
There are two standard ways in which you can run an applet :
1. Executing the applet within a Java-compatible web browser.
2. Using an applet viewer, such as the standard tool, applet-viewer. An applet viewer executes your
applet in a window. This is generally the fastest and easiest way to test your applet.
Each of these methods is described next.
1. Using java enabled web browser : To execute an applet in a web browser we have to write a short
HTML text file that contains a tag that loads the applet. We can use APPLET or OBJECT tag for this
purpose. Using APPLET, here is the HTML file that executes HelloWorld :
<applet code="HelloWorld" width=200 height=60></applet>
The width and height statements specify the dimensions of the display area used by the applet. The
APPLET tag contains several other options. After you create this html file, you can use it to execute the
applet.
2. Using appletviewer : This is the easiest way to run an applet. To execute HelloWorld with an applet
viewer, you may also execute the HTML file shown earlier. For example, if the preceding HTML file is
saved with
RunHelloWorld.html, then the following command line will run HelloWorld :
appletviewer RunHelloWorld.html

Features of Applets over HTML


 Displaying dynamic web pages of a web application.
 Playing sound files.
 Displaying documents
 Playing animations
Due to security reasons, the following restrictions are imposed on Java applets:
1. An applet cannot load libraries or define native methods.
2. An applet cannot ordinarily read or write files on the execution host.
3. An applet cannot read certain system properties.
4. An applet cannot make network connections except to the host that it came from.
5. An applet cannot start any program on the host that’s executing it.

Socket programming
The InetAddress class represents an IP address, both IPv4 and IPv6. Basically you create instances of this
class to use with other classes such as Socket, ServerSocket, DatagramPacket and DatagramSocket.
The InetAddress class doesn’t have public constructors, so you create a new instance by using one of its
factory methods:
 getByName(String host): creates an InetAddress object based on the provided hostname.
 getByAddress(byte[] addr): returns an InetAddress object from a byte array of the raw IP
address.
 getAllByName(String host): returns an array of InetAddress objects from the specified
hostname, as a hostname can be associated with several IP addresses.
 getLocalHost(): returns the address of the localhost.
To get the IP address/hostname you can use a couple of methods below:
 getHostAddress(): returns the IP address in text.
 getHostname(): gets the hostname.
Note that the InetAddress class’s toString() method returns both hostname and IP address,
e.g. www.codejava.net/198.57.151.22.
Get IP address of a given domain/hostname: The following code prints the IP address of a given
hostname
InetAddress address1 = InetAddress.getByName("www.codejava.net");
System.out.println(address1.getHostAddress());
Get hostname from IP address: The following code finds out the hostname from an IP address:
InetAddress address2 = InetAddress.getByName("8.8.8.8");
System.out.println(address2.getHostName());
List all IP addresses associate with a hostname/domain:The following code prints all the IP addresses
associated with the hostname google.com:
InetAddress[] google = InetAddress.getAllByName("google.com");
for (InetAddress addr : google) {System.out.println(addr.getHostAddress());}
Get the localhost address:And the following code gets the localhost address:
InetAddress localhost = InetAddress.getLocalHost();
System.out.println(localhost);

Java Socket Programming


Java Socket programming is used for communication between the applications running on different
JRE.Java Socket programming can be connection-oriented or connection-less.Socket and ServerSocket
classes are used for connection-oriented socket programming and DatagramSocket and DatagramPacket
classes are used for connection-less socket programming.The client in socket programming must know
two information: IP Address of Server, and Port number.
Here, we are going to make one-way client and server communication. In this application, client sends a
message to the server, server reads the message and prints it. Here, two classes are being used: Socket and
ServerSocket. The Socket class is used to communicate client and server. Through this class, we can read
and write message. The ServerSocket class is used at server-side. The accept() method of ServerSocket
class blocks the console until the client is connected. After the successful connection of client, it returns
the instance of Socket at server-side.

Socket class -A socket is simply an endpoint for communications between the machines. The Socket class
can be used to create a socket.
ServerSocket class -The ServerSocket class can be used to create a server socket. This object is used to
establish communication with the clients.

Creating Server:
To create the server application, we need to create the instance of ServerSocket class. Here, we are using
6666 port number for the communication between the client and server. You may also choose any other
port number. The accept() method waits for the client. If clients connects with the given port number, it
returns an instance of Socket.
1. ServerSocket ss=new ServerSocket(6666);
2. Socket s=ss.accept();//establishes connection and waits for the client

Creating Client:
To create the client application, we need to create the instance of Socket class. Here, we need to pass the
IP address or hostname of the Server and a port number. Here, we are using "localhost" because our server
is running on same system. Socket s=new Socket("localhost",6666);
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{ ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{ Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
} }

Example of Java Socket Programming (Read-Write both side)


In this example, client will write first to the server then server will receive and print the text. Then server
will write to the client and client will receive and print the text. The step goes on.
File: MyServer.java
import java.net.*;
import java.io.*;
class MyServer{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush(); }
din.close();
s.close();
ss.close();
}}
File: MyClient.java
import java.net.*;
import java.io.*;
class MyClient{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}
dout.close();
s.close();
}}

Advantages of Java Socket Programming


 Platform Independence − One of the biggest advantages of Java Sockets is that they are
platform-independent. This means that the same Java code can be run on multiple operating
systems and devices without the need for modification. This allows for easy deployment of
network-based applications across different systems and ensures that the application can be run
on different devices without the need for platform-specific code.
 Easy to Use − Java Sockets are also relatively easy to use, even for developers who are new to
network programming. The Java API provides a simple, consistent interface for creating and
managing sockets, which makes it easy to implement network-based applications without needing
to understand the underlying network protocols.
 Scalability − Java Sockets are highly scalable, making them suitable for large-scale network-
based applications. They can easily handle thousands of simultaneous connections and can be
used to create distributed systems that can handle high levels of traffic.
 Security − Java Sockets provide built-in support for secure communication, including SSL and
TLS encryption. This makes it easy to create secure network-based applications and ensures that
sensitive data is protected while in transit.
 Multithreading − Java Sockets support multithreading, which means that multiple threads can be
used to handle multiple connections simultaneously. This improves the performance of network-
based applications and allows them to handle a large number of requests without becoming
overloaded.
Disadvantages of Java Socket Programming
 Complexity − While Java Sockets are relatively easy to use, they can still be complex to
implement, particularly for developers who are new to network programming. This complexity
can make it difficult to debug and troubleshoot network-based applications, which can be time-
consuming and frustrating.
 Latency − Java Sockets can introduce latency into network-based applications, particularly when
dealing with large amounts of data. This can be a problem for applications that require real-time
communication, such as online gaming or video conferencing.
 Resource Intensive − Java Sockets can be resource-intensive, particularly when dealing with
large numbers of connections or large amounts of data. This can be a problem for systems with
limited resources, such as mobile devices or embedded systems.
 Limited Protocol Support − Java Sockets support a limited number of network protocols, which
can be a limitation for certain types of network-based applications. This can make it difficult to
create applications that need to communicate with other systems using proprietary protocols.
 Potential for Security Vulnerabilities − Java Sockets, like any network-based application, are
vulnerable to security threats, such as hacking and man-in-the-middle attacks. Careful attention
must be paid to security when designing and implementing Java Socket-based systems to ensure
that sensitive data is protected and potential vulnerabilities are identified and addressed.
Socket Programming Applications
 Chat Applications − Java Sockets are often used to create chat applications, such as instant
messaging programs and online chat rooms. These types of applications typically use a client-
server architecture, where clients connect to a central server to send and receive messages.
 File Transfer Applications − Java Sockets can also be used to create file transfer applications,
such as peer-to-peer file sharing programs. These types of applications use a peer-to-peer
architecture, where each device acts as both a client and a server. This allows for direct
communication between devices, which can improve the speed and reliability of file transfers.
 Remote Control Applications − Java Sockets can also be used to create remote control
applications, such as remote desktop software. These types of applications use a client-server
architecture, where a client connects to a remote server to control the desktop of the server. This
allows users to access and control their desktop from any device with an internet connection.
 Multiplayer Games − Java Sockets are also commonly used to create multiplayer games, such as
online role-playing games and first-person shooters. These types of applications typically use a
client-server architecture, where clients connect to a central server to play the game. The server
acts as the intermediary between clients, handling communication and game logic.
 IoT Applications − Java Sockets can also be used in IoT (Internet of Things) applications, such
as smart home systems. These types of applications use a client-server architecture, where IoT
devices connect to a central server to send and receive data. This allows for remote monitoring
and control of the devices, as well as data collection and analysis.
Making URL Connection
URL is an acronym of Uniform resource locator. It is a pointer to locate resource in www (World Wide
Web). A resource can be anything from a simple text file to any other like images, file directory etc.
The typical URL may look like
http://www.example.com:80/index.html
The URL has the following parts:
 Protocol: In this case the protocol is HTTP, It can be HTTPS in some cases
 Hostname: Hostname represent the address of the machine on which resource is located, in this
case, www.example.com
 Port Number: It is an optional attribute. If not specified then it returns -1. In the above case, the
port number is 80.
 Resource name: It is the name of a resource located on the given server that we want to see
import java.net.URL;
import java.util.Scanner;

class GFG {public static void main(String[] args)


{ String url = "https://www.geeksforgeeks.org/variables-in-java/";
getUrlInfo(url); }// Calling method to get URL info
static void getUrlInfo(String url_string)
{try { URL url = new URL(url_string);
System.out.println("Hostname: "+ url.getHost());
System.out.println("Port Number: "+ url.getPort());
System.out.println("File name: " + url.getFile());
System.out.println("Protocol: "+ url.getProtocol()); }
catch (Exception e) { }//exception caught
} }

Output:
Hostname: www.geeksforgeeks.org
Port Number: -1
File name: /variables-in-java/
Protocol: https
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified
by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized
for serving two different yet related purposes, Firstly it provides control on interaction with a
server(especially an HTTP server) than URL class. Secondly, with a URLConnection we can check the
header sent by the server and respond accordingly, we can configure header fields used in client requests.
We can also download binary files by using URLConnection.

The URLConnection and HttpURLConnection Classes


URLConnection is the superclass of all classes that represent a connection between a Java application and
a URL. The URLConnection class provides API for generic URLs, and its
subclass HttpURLConnection provides additional support for HTTP-specific features.
Note that both of these classes are abstract - meaning that you can’t directly create new instances
of URLConnection and HttpURLConnection. Instead, an instance of URLConnection is obtained by
opening the connection from a URL object.
Typically, a client program communicates with a server via a URL follows this sequence of steps:
1. Create a URL object
2. Obtain a URLConnection object from the URL
3. Configure the URLConnection
4. Read the header fields
5. Get an input stream and read data
6. Get an output stream and write data
7. Close the connection
The steps 3 to 6 are optional, and the steps 5 and 6 are interchangeable.
1. Create a URL object
Simply create a new URL object for a given URL like this:
URL url = new URL("http://www.google.com"); // This constructor will throw
a MalformedURLException if the URL is malformed. This checked exception is a subclass
of IOException.
2. Obtain a URLConnection object from the URL
A URLConnection instance is obtained by invoking the openConnection() method on the URL object:
URLConnection urlCon = url.openConnection(); // If the protocol is http://, you can cast the
returned object to an HttpURLConnection object:
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
Note that the openConnection() method doesn’t establish an actual network connection. It just returns an
instance of URLConnection class.The network connection is made explicitly when the connect() method
is invoked, or implicitly when reading header fields or getting an input stream / output stream.The
URL’s openConnection() method throws IOException if an I/O error occurs.
3. Configure the URLConnection
Before actually establish the connection, you can configure various aspects that affect the ongoing
communication between the client and the server, such as timeout, cache, HTTP request method, etc.
The URLConnection class provides the some of the below methods for configuring the connection:
setConnectTimeout(int timeout): sets the connection timeout in milliseconds.
setReadTimeout(int timeout): sets the read timeout in milliseconds.
setDefaultUseCaches(boolean default): sets whether the URLConnection uses caches by default or
not (default is true). This method affects future instances of the URLConnection class.
setRequestProperty(String key, String value): sets a general request property specified by a
key=value pair. If a property with the key already exists, the old value is overwritten with the new value.
Note that these methods should be invoked before establishing the connection. Some methods
throw IllegalStateException if the connection is already made.
In addition, the subclass HttpURLConnection provides the following methods for configuring the
connection with HTTP-specific features:
 setRequestMethod(String method): sets the method for the URL request, which is one of HTTP
methods GET, POST, HEAD, OPTIONS, PUT, DELETE and TRACE. The default method is
GET.
 setChunkedStreamingMode(int chunkLength): enables streaming of a HTTP request body
without internal buffering, when the content length is not known in advanced.
 setFixedLengthStreamingMode(long contentLength): enables streaming of a HTTP request
body without internal buffering, when the content length is known in advanced.
 setFollowRedirects(boolean follow): this static method sets whether HTTP redirects should be
automatically followed by future objects of this class (default is true).
 setInstanceFollowRedirects(boolean follow): sets whether HTTP redirects should be
automatically followed by instance of this HttpURLConnection class (default is true).
The above methods are setters. And the URLConnection and HttpURLConnection classes also provide
corresponding getters: getConnectTimeout() ,getReadTimeout()
,getDefaultUseCaches(),getUseCaches(),getDoInput(),getDoOutput() etc

4. Read the header fields


Once the connection is made, the server processes the URL request and sends back a response that
consists of metadata and actual content. The metadata is a collection of key=value pairs which are called
header fields.The header fields reveal information about the server, status code, protocol information, etc.
The actual content can be in text, HTML, image, etc. depending on the type of the document.
The URLConnection class provides the following methods for reading the header fields:
 getHeaderFields(): returns a map that contains all header fields. The key is field name and the
value is a list of String represents the corresponding field values.
 getHeaderField(int n): reads the value of the n-th header field.
 getHeaderField(String name): reads the value of the named header field.
 getHeaderFieldKey(int n): reads the key of the n-th header field.
 getHeaderFieldDate(String name, long default): reads the value of the named field parsed
as Date. If the field is missing or value is malformed, the default value is returned instead.
 getHeaderFieldInt(String name, int default): reads the value of the named field parsed as an
integer number. If the field is missing or value is malformed, the default value is returned instead.
 getHeaderFieldLong(String name, long default): reads the value of the named field parsed as a
long number. If the field is missing or value is malformed, the default value is returned instead.
These are general methods for reading any header fields. And for some frequently-accessed header fields,
the URLConnection class provides more specific methods:
 getContentEncoding(): reads the value of the content-encoding header field, which indicates the
encoding type of the content.
 getContentLength(): reads the value of the content-length header field, which indicates the size
of the content (in bytes).
 getContentType(): reads the value of the content-type header field, which indicates the type of
the content.
 getDate(): reads the value of the date header field, which indicates the date time on the server.
 getExpiration(): reads the value of the expires header field, indicates the time after which the
response is considered stale. This is for cache control.
 getLastModified(): reads the value of the last-modified header field, which indicates the last
modified time of the content.
And the subclass HttpURLConnection provides an additional method:
 getResponseCode(): returns the HTTP status code sent by the server.
Note that when the header fields are read, the connection is implicitly established, without
calling connect().

5. Get an input stream and read data


To read the actual content, you need to obtain an InputStream instance from the connection, and then use
the InputStream’s read() methods to read the data:
InputStream inputStream = urlCon.getInputStream();
byte[] data = new byte[1024];
inputStream.read(data);
The InputStream’s read() is a low-level method that reads data to an array of bytes. So it is more
convenient to wrap the InputStream in an InputStreamReader for reading data to characters:
InputStream inputStream = urlCon.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int character = reader.read(); // reads a single character
char[] buffer = new char[4096];
reader.read(buffer); // reads to an array of characters
Or wrap the InputStream in a BufferedReader for reading data to Strings:
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line = reader.readLine(); // reads a line
Note that the getInputStream() method can throw the following exceptions:
 IOException: if an I/O error occurs while creating the input stream.
 SocketTimeoutException: if the read timeout expires before data is available for read.
 UnknownServiceExcepetion: if the protocol does not support input.
6. Get an output stream and write data
To send data to the server, you have to enable output on the connection first:
urlCon.setDoOutput(true);
Then get the OutputStream object associated with the connection, and then use
the OutputStream’s write() methods to write the data:
OutputStream outputStream = urlCon.getOutputStream();
byte[] data = new
byte[1024];
outputStream.write(data);
As you can see, the OutputStream’s write() is a low-level method that writes an array of bytes. So it is
more convenient to wrap the OutputStream in an OutputStreamWriter for writing characters:
OutputStreamWriter writer = new OutputStreamWriter(outputStream);
int character = 'a';
writer.write(character); // writes a single character
char[] buffer = new char[4096];
writer.write(buffer); // writes an array of characters
Or wrap the OutputStream in a PrintWriter for writing Strings:
PrintWriter writer = new PrintWriter(outputStream);
String line = "This is String";
writer.print(line);
Note that the getOutputStream() method can throw IOException or UnknownServiceException.

7. Close the connection


To close the connection, invoke the close() method on either the InputStream or OutputStream object.
Doing that may free the network resources associated with the URLConnection instance.
Example
import java.io.*;
import java.net.*;
public class HttpURLConnectionDemo{
public static void main(String[] args){
try{ URL url=new URL("http://www.google.com/");
HttpURLConnection huc=(HttpURLConnection)url.openConnection();
for(int i=1;i<=8;i++){
System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i)); }
huc.disconnect();
}catch(Exception e){System.out.println(e);}
} }

You might also like