Java Unit1
Java Unit1
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.
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
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:
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.
Flow of Stops the current flow of execution It forces the caller to handle the
Execution immediately. declared exceptions.
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.
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)); } }}
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
Output
a=5 b=5
a=5 b=5
a=5 b=5
a=5 b=5
a=5 b=5
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
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
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);
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);}
} }
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.