0% found this document useful (0 votes)
4 views72 pages

Java Programming Essentials Guide

The document is a comprehensive guide on programming in Java, covering essential concepts such as Java's platform independence, object-oriented features, and key tools like JDK, JRE, and JVM. It includes detailed sections on the Java Collection Framework, multithreading, and data management using JDBC, along with practical examples and explanations of Java's syntax and operators. Additionally, it discusses the advantages and disadvantages of arrays, types of variables, and various collection classes like ArrayList and LinkedList.

Uploaded by

La Sad
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)
4 views72 pages

Java Programming Essentials Guide

The document is a comprehensive guide on programming in Java, covering essential concepts such as Java's platform independence, object-oriented features, and key tools like JDK, JRE, and JVM. It includes detailed sections on the Java Collection Framework, multithreading, and data management using JDBC, along with practical examples and explanations of Java's syntax and operators. Additionally, it discusses the advantages and disadvantages of arrays, types of variables, and various collection classes like ArrayList and LinkedList.

Uploaded by

La Sad
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

Programming in Java

All rights reserved. No part of this publication may be reproduced, distributed or transmitted in
any form or by any means, including photocopying, recording, or other electronic or mechanical
methods, without the prior written permission of the publisher, except in the case of brief
quotations embodied in critical reviews and certain other noncommercial uses permitted by
copyright law. Although the author/co-author and publisher have made every effort to ensure
that the information in this book was correct at press time, the author/co-author and publisher do
not assume and hereby disclaim any liability to any party for any loss, damage, or disruption
caused by errors or omissions, whether such errors or omissions result from negligence,
accident, or any other cause. The resources in this book are provided for informational purposes
only and should not be used to replace the specialized training and professional judgment of a
health care or mental health care professional. Neither the author/co-author nor the publisher
can be held responsible for the use of the information provided within this book. Please always
consult a trained professional before making any decision regarding the treatment of yourself or
others.

Publisher – C# Corner
Editorial Team – Deepak Tewatia, Baibhav Kumar
Publishing Team – Praveen Kumar
Promotional & Media – Rohit Tomar, Rohit Sharma

[Link] 2
Table of Contents:
Introduction to Java ..................................................................................................................... 4
Collection Framework ..................................................................................................................13
Multithreading ............................................................................................................................21
Swings and Layouts .....................................................................................................................34
Managing data using JDBC ...........................................................................................................50
Network Programming ................................................................................................................62

[Link] 3
1
Introduction to Java

Overview

In this chapter, we explore Java programming, covering essential


concepts and tools. We start by explaining Java's origin and its
platform independence. Key tools like JDK, JRE, and JVM are
introduced. We then explore Java's features, such as object-orientation
and robustness. Through practical examples, we illustrate the usage of
reserved Java keywords and variable types. Additionally, we discuss
data type sizes, user input handling, wrapper classes, and various
operators. This chapter provides a solid foundation for readers to begin
their journey into Java programming.

[Link] 4
What is Java?
Java is a high-level, object-oriented programming language developed by Sun Microsystems
(now owned by Oracle Corporation) in the mid-1990s. It was designed with the goal of being
platform-independent, meaning that Java programs can run on any device or operating system
that has a Java Virtual Machine (JVM) installed.

Java Programming Development Tools


• Java Development Kit (JDK): The Java Development Kit is a software development
environment that is used to develop Java applications.
• Java Runtime Environment (JRE): The Java Runtime Environment is an installation
package that provides an environment to only run (not develop) the Java program (or
application) onto your machine. JRE is only used by those who only want to run Java
programs.
• Java Virtual Machine (JVM): The Java Virtual Machine is a very important part of both
JDK and JRE because it is contained or built-in both. Whatever Java program you run
using JRE or JDK goes into JVM and JVM is responsible for executing the Java program
line by line, hence it is also known as an interpreter.

Working with JVM, JDK and JRE

Key Features of Java


Platform Independence: Java achieves platform independence through its "write once, run
anywhere" principle. Once a Java program is compiled into bytecode, it can be executed on any
platform that has a compatible JVM.

Object-Oriented: Java is a pure object-oriented programming language, which means it


revolves around objects and classes. Everything in Java is an object, and programs are
designed by creating classes and objects that interact with each other.

Robustness: Java emphasizes strong type checking and exception handling to ensure
robustness. It provides features like automatic memory management (garbage collection) to
prevent memory leaks and array bounds checking to prevent buffer overflows.

Security: Java has built-in security features that protect against various security threats, such
as viruses and malicious software. It provides a sandbox environment for executing untrusted
code and supports encryption and authentication mechanisms.

Portability: Java's platform independence and bytecode compilation make it highly portable.
Developers can write Java code once and deploy it on multiple platforms without modification,
reducing the need for platform-specific development.

[Link] 5
Multithreading: Java supports multithreading, allowing programs to perform multiple tasks
concurrently. This feature is essential for developing efficient and responsive applications,
especially in modern computing environments.

Performance: While Java was initially criticized for its performance compared to lower-level
languages like C or C++, advancements in JIT (Just-In-Time) compilation and runtime
optimizations have greatly improved Java's performance over the years.

Reserve Java Words

Byte keyword
• The Java byte keyword is a primitive data type. It is used to declare variables. It can hold
8-bit signed integers.
• The byte range lies between -128 to 127 (inclusive).
public class ByteExample1 {

public static void main(String[] args)


{

byte num1=127;
byte num2=-128;

[Link]("num1 : "+num1);
[Link]("num2 : "+num2);
}
}

Example2:
public class ByteExample2
{
public static void main(String[] args)
{

byte num1=128;

[Link] 6
byte num2=-129;

[Link]("num1 : "+num1);
[Link]("num2 : "+num2);
}
}

Use of Byte with a Method


public class ByteExample3
{
byte age=18;

public byte display()


{
return age;
}
public static void main(String[] args)
{
ByteExample2 b=new ByteExample2();
[Link]("The age must be: "+[Link]());
}
}

Types of Variables:
1) Local
2) Instance
3) Statics

To find size of datatypes

class MainClass
{
public static void main(String []args)
{
[Link]("Size of int: " + ([Link]/8) + "
bytes.");
[Link]("Size of long: " + ([Link]/8) + " bytes.");

[Link] 7
[Link]("Size of char: " + ([Link]/8) + "
bytes.");
[Link]("Size of float: " + ([Link]/8) + "
bytes.");
[Link]("Size of double: " + ([Link]/8) + "
bytes.");
}
}

User Input in Java


Java Scanner Class

• Java Scanner class allows the user to take input from the console. It belongs
to [Link] package. It is used to read the input of primitive types like int, double, long,
short, float, and byte.

Scanner sc=new Scanner([Link]);

The above statement creates a constructor of the Scanner class having [Link] as an
argument. It means it is going to read from the standard input stream of the program.

Wrapper Classes
• A Wrapper class is a class whose object wraps or contains primitive data types.
• Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.

[Link] 8
Operators in Java

• Arithmetic operators: Arithmetic operators perform basic mathematical operations.

• Assignment Operators: Assignment operators are used to assign values to variables.

• Comparison operators:

[Link] 9
• Logical operators:

• Bitwise operators: Bitwise operators perform operations on individual bits of integers.

• AND Operator: If both side bit is on result will be On

• OR Operator: If any side bit is on result will be On

[Link] 10
• XOR Operator: If both side bit is opposite result will be On

Inner and nested classes


Define a class within another class, such classes are known as nested classes.
Nested classes are divided into two categories:

• Static Nested Class: Nested classes that are declared static are called static nested
classes.
• Inner Class: An inner class is a non-static nested class.

Array
• Array is a collection of similar types of elements that have contiguous memory location.
• In java, array is an object the contains elements of similar data type.
• It is a data structure where we store similar elements. We can store only fixed elements
in an array.

[Link] 11
• Array is index based: the first element of the array is stored at 0 index.

Advantage of Array

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

Disadvantage of Array

• Size Limit: We can store only fixed size elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in java.

Types of Arrays:
One-Dimensional Array
This is a type of array that is arranged in the form of rows only i.e. all the elements are stored
and can only be visualized in a linear format/ 1D figure.

Two-Dimensional Array
This is a type of array that is arranged in the form of rows and columns i.e. all the elements
stored can be visualized as a Matrix or in a 2D figure.

Multi-Dimensional / N-Dimensional Array


This is a type of array that is arranged in the form of (N-C) rows and C columns, where N is the
dimension of the array and C is the number of columns i.e. all the elements stored can be
visualized as (N-C) x C dimensional matrix or in an N-dimensional figure.

Read More about How to use Array in Java

[Link] 12
2
Collection Framework

Overview

In this chapter, we explore Java Collection Framework, a set of


interfaces and classes for efficiently managing collections of objects.
It introduces the concept of collections as groupings of individual
objects and explores essential classes like ArrayList, which allows
dynamic array-based storage with no size limit. The chapter also
covers methods for adding, accessing, and removing elements from
ArrayLists, as well as essential interfaces like Iterator and ListIterator
for traversing collections. Additionally, it discusses other collection
classes like LinkedList, TreeSet, and PriorityQueue, highlighting their
unique features and common operations. Lastly, the chapter touches
upon Comparator, Comparable, the Properties class, and Lambda
expressions, essential components for effective collection
manipulation and configuration management in Java programming.

[Link] 13
Collection
The Collection Framework in Java is a set of interfaces and classes that provide a unified
architecture for manipulating and storing collections of objects. It offers a wide range of data
structures and algorithms to efficiently organize and manage groups of elements. The Collection
Framework was introduced in Java 2 (JDK 1.2) and has been continuously expanded and
improved in subsequent Java releases.

Group of individual objects.

Student S1=new
Student()

Collection framework
Several classes and interfaces which can be used as a group of objects.
Package: util

import [Link].*;

[Link] 14
Array List Class:
• ArrayList class uses the concept of dynamic array for storing the elements.
• It is like an array, with no size limit. We can add or remove elements anytime.
• It is found in the [Link] package.
• ArrayList class can contain duplicate elements also.

Creating instance of ArrayList


ArrayList al=new ArrayList();
//creating old non-generic arraylist
ArrayList<String> al=new ArrayList<String>();
//creating new generic arraylist

Java new generic collection allows you to have only one type of object in a collection. Now it is
type safe so typecasting is not required at runtime.

Methods in ArrayList:
• Add(): Add new elements to an ArrayList using the add() method.
Syntax:
[Link](arrayListElement)
Ex:
[Link](“java”)

• Adding an element at a particular index in an ArrayList.


Syntax:
[Link](arrayListIndex, arrayListElement)
Ex:
[Link](2, “java”)

• addAll(Collection C): adds a complete collection in an ArrayList


• size(): to find the size of an ArrayList using the size() method.
Syntax:
[Link]()
Ex:
[Link]()

• get(): access the element at a particular index in an ArrayList using the get() method.
Syntax:
[Link](0)
Ex:
[Link](0)

[Link] 15
• Set(): to modify the element at a particular index in an ArrayList using the set() method.
Syntax:
[Link](index,element)
Ex:
[Link](4, “java”)

• isEmpty(): To check if an ArrayList is empty using the isEmpty() method. It will return
true or false.
[Link]()

• contains(object): This method returns true if this list contains the specified element.
Ex:
boolean retval = [Link](10);

• remove (index or object): to remove the element at a given index in an ArrayList


Syntax:
[Link](int index) or [Link](object)

• removeAll(Collection c): to remove all the elements that are contained in the specified
collection.
• clear() : used to remove all the elements from ArrayList.
• indexOf(Object o): The indexOf() method of ArrayList returns the index of the first
occurrence of the specified element in this list, or -1 if this list does not contain the
element.
• lastIndexOf(Object o): The index of the last occurrence of a specific element is either
returned or -1 in case the element is not in the list.
• clone(): used to return a shallow copy of an ArrayList.
ArrayList newarray = (ArrayList)[Link]();

Iterator interface
• Iterator is an interface that iterates the elements.
• Iterator can traverse elements in a collection only in forward direction.
• It is used to traverse the list and modify the elements. Iterator interface has three
methods:

• public boolean hasNext() – This method returns true if the iterator has
more elements.
• public object next() – It returns the element and moves the cursor pointer
to the next element.
• public void remove() – This method removes the last elements returned
by the iterator.
ListIterator
• ListIterator is an interface in a Collection framework, and it extends the Iterator interface.
• Using ListIterator, you can traverse the elements of the collection in
both forward and backwards directions.

[Link] 16
Methods in ListIterator
• void add(Object object): It inserts the object immediately before the element that is
returned by the next( ) function.
• boolean hasNext( ): It returns true if the list has a next element.
• boolean hasPrevious(): It returns true if the list has a previous element.
• Object next( ): It returns to the next element of the list. It throws
‘NoSuchElementException’ if there is no next element in the list.
• Object previous(): It returns the previous element of the list. It throws
‘NoSuchElementException’ if there is no previous element.
• void remove(): It removes the current element from the list. It throws
‘IllegalStateException’ if this function is called before the next() or previous( ) is invoked.

LinkedList Class
LinkedList is a class that implements the List interface and provides a doubly-linked list
implementation of the List interface. It allows for efficient insertion and deletion of elements at
any position within the list.

Features of LinkedList:
• Doubly Linked List: Each element in a LinkedList is stored as a node containing a
reference to the previous and next elements in the list. This allows for efficient traversal
in both forward and backward directions.
• Dynamic Size: LinkedList can grow or shrink dynamically as elements are added or
removed. Unlike arrays, LinkedList does not have a fixed size.
• Random Access: While LinkedList provides efficient insertion and deletion operations, it
does not provide constant-time random access to elements like an array. Accessing
elements by index in a LinkedList requires traversing the list from the beginning or end.

LinkedList class

[Link] 17
TreeSet class
TreeSet class implements the Set interface that uses a tree for storage.

• The objects of the TreeSet class are stored in ascending order.


• Java TreeSet class contains unique elements which means does not allow duplicate
elements.
• Java TreeSet class doesn't allow null elements.

Methods of TreeSet class:


• add (Object o): This method will add the specified element according to the same
sorting order mentioned during the creation of the TreeSet.
• addAll(Collection c): This method will add all elements of the specified Collection to the
set. Elements in the Collection should be homogeneous.
• clear (): This method will remove all the elements.
• contains (Object o): This method will return true if a given element is present in TreeSet
else it will return false.
• first (): This method will return the first element in TreeSet if TreeSet is not null else it will
throw NoSuchElementException.
• last (): This method will return the last element in TreeSet if TreeSet is not null else it will
throw NoSuchElementException.
• size (): This method is used to return the size of the set or the number of elements
present in the set.
import [Link].*;
public class Main
{
public static void main(String[] args)
{
TreeSet<String> t1=new TreeSet<String>();
[Link]("Guddu");
[Link]("Gauarv");
[Link]("Saurav ");
[Link]("Baibhav");
[Link]("Prince");
for(String str:t1)
{
[Link](str);
}
}
}

PriorityQueue Class
A PriorityQueue is used when the objects are supposed to be processed based on the priority. It
is known that a Queue follows the First-In-First-Out algorithm.

[Link] 18
Operations on PriorityQueue:
• Adding Elements: In order to add an element in a priority queue, we can use the add()
method.
• Removing Elements: In order to remove an element from a priority queue, we can use
the remove() method.
• Accessing the elements: Since Queue follows the First in First Out principle, we can
access only the head of the queue.
• Iterating the PriorityQueue: There are multiple ways to iterate through the
PriorityQueue. The most famous way is converting the queue to the array and traversing
using the for loop.
PriorityQueue<String> pq = new PriorityQueue<>();
[Link]("Samsung");
[Link]("Nokia");
[Link]("RealMe");
Iterator iterator = [Link]();
while ([Link]())
{
[Link]([Link]() + " ");
}

Comparable and Comparator


Comparable and Comparator both are interfaces and can be used to sort collection elements.

Properties class in Java


The Properties class is a subclass of Hashtable and represents a persistent set of properties.
Properties are key-value pairs that are typically used for configuration settings in Java
applications. The Properties class provides methods for reading and writing properties to and
from files, making it a convenient tool for managing application configuration.

Key Features

• Storing Configuration Settings: The Properties class is commonly used to store


configuration settings such as database connection parameters, application settings, and
user preferences. Each property consists of a key and its corresponding value.

[Link] 19
• Loading and Saving Properties: The load () and store () methods of the Properties
class are used to load properties from a file and save properties to a file, respectively.
Properties can be loaded from and saved to text files or XML files.
• Default Values: The Properties class supports default values for properties. If a property
is not found when retrieving its value, a default value can be specified to be returned
instead.
• Type Safety: Properties are stored as strings, but the Properties class provides methods
to convert property values to other data types such as integers, booleans, and dates.

Advantage of the properties file


Recompilation is not required if the information is changed from a properties file: If any
information is changed from the properties file, you don't need to recompile the java class.

Lambda expressions
Lambda expressions in Java provide a concise way to represent anonymous functions or
behaviors. They were introduced in Java 8 and are primarily used to implement functional
interfaces, which have a single abstract method (SAM). Lambda expressions enable developers
to write more readable and maintainable code by reducing the verbosity of anonymous classes.

Key features:
• Concise Syntax: Lambda expressions provide a shorter syntax compared to
anonymous classes, making code more readable and less cluttered.
• Functional Interfaces: Lambda expressions are typically used with functional
interfaces, which serve as a contract for the behavior to be implemented by the lambda
expression.
• Type Inference: Java compiler can infer the types of lambda expressions based on the
context in which they are used, reducing the need for explicit type declarations.
• Functional Programming: Lambda expressions facilitate functional programming
paradigms in Java, enabling operations like map, filter, and reduce to be applied more
easily to collections.

Lambda Expression Syntax


(argument-list) -> {body};

• Argument-list: It can be empty or non-empty.


• Arrow-token: It is used to link arguments-list and body of expression.
• Body: It contains expressions and statements for lambda expression.

[Link] 20
3
Multithreading

Overview

In this chapter, we explore multithreading in Java, explaining its role in


enabling concurrent execution of multiple threads within a program. Key
topics covered include parent-child multithreading, thread lifecycle,
synchronization, interthread communication, exception handling, and
the use of thread pools. Through concise explanations and code
examples, readers gain fundamental insights into the principles and
techniques of multithreading in Java.

[Link] 21
Multithreading in java
Multithreading in Java refers to the concurrent execution of multiple threads within a single
program, allowing for the simultaneous execution of multiple tasks or processes. This enables
developers to achieve multitasking, where different threads execute independent operations
concurrently. One significant advantage of multithreading is that each thread operates
independently of others, meaning that if an exception occurs in one thread, it does not affect the
execution of other threads. Additionally, because threads are independent entities, they do not
block the user from interacting with the application, allowing for smooth and responsive user
experiences. By leveraging multithreading, developers can perform multiple operations
simultaneously, significantly improving the efficiency and performance of their applications,
ultimately saving time and enhancing productivity.

Web/Internet Applications: Serving Many Users Simultaneously

Multithreading Parent Child:

import [Link];
class threadDemo extends Thread
{
public void run()
{
[Link]([Link]().getName()+" is
running...");
threadDemo1 o1 = new threadDemo1();
[Link]("GrandChild ");
[Link]();
[Link]([Link]().getName()+" is
stopped!");
}
}

class threadDemo1 extends threadDemo


{
public void run()
{
[Link]([Link]().getName()+" is
running...");

[Link] 22
[Link]([Link]().getName()+" is
stopped!");
}
}
class HelloWorld {
public static void main(String[] args) {
threadDemo o = new threadDemo();
[Link]("Child ");
[Link]();
[Link]([Link]().getName()+" is
running...");
[Link]([Link]().getName()+" is
stopped!");
}
}

Multithreading Child Parent:

import [Link];
class threadDemo extends Thread
{
Thread t1;
public threadDemo(String n){
t1 = new Thread(this, n);
[Link]();
}
public void run()
{
[Link]([Link]().getName()+" is
running...");
try
{
[Link](2000);
}
catch(Exception e)
{
[Link](e);
}
[Link]([Link]().getName()+" is
stopped!");
}
}

class threadDemo1 extends threadDemo


{
Thread t2;
public threadDemo1(String n){
super("Child");
t2 = new Thread(this, n);

[Link] 23
[Link]();
}
public void run()
{
[Link]([Link]().getName()+" is
running...");
[Link]([Link]().getName()+" is
stopped!");
}
}
class HelloWorld {
public static void main(String[] args) {
threadDemo1 o = new threadDemo1("Grand Child");
[Link]([Link]().getName()+" is
running...");
try
{
[Link](10000);
}
catch(Exception e)
{
[Link](e);
}
[Link]([Link]().getName()+" is
stopped!");
}
}

Threads and Runnable Interface:


Thread Class: In Java, multithreading is primarily achieved by creating instances of the ‘Thread’
class. A ‘Thread’ represents a separate flow of execution within a program. You can create a
thread by extending the ‘Thread’ class and overriding its ‘run()’ method, which contains the code
to be executed by the thread.
Runnable Interface: Alternatively, you can implement the ‘Runnable’ interface, which defines a
single method ‘run()’. This method contains the code that will be executed by the thread.
Implementing ‘Runnable’ allows for better separation of concerns and reusability.

Creating and Starting Threads:


Extending Thread Class:

class MyThread extends Thread {


public void run() {
// Code to be executed by the thread
}
}
// Create and start a thread
MyThread thread = new MyThread();

[Link] 24
[Link]();

Implementing Runnable Interface:

class MyRunnable implements Runnable {


public void run() {
// Code to be executed by the thread
}
}

// Create a Runnable instance and pass it to a Thread constructor


Runnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
[Link]();

Lifecycle of Thread:
• New: When a thread is created but not yet started.
• Runnable: When a thread is ready to run, it moves to the runnable state. It may or may
not be executing, depending on the availability of CPU time.
• Running: When a thread is executing its tasks.
• Blocked/Waiting: When a thread is waiting for a resource or event to continue
execution.
• Terminated: When a thread completes its execution or is terminated prematurely.

Newborn State
• When we create a thread, it will be in Newborn State.
• The thread has just been created, still it’s not running.
• We can move it to the running mode by invoking the start () method and it can be killed
by using the stop () method.

Runnable State
• It means that the thread is now ready for running and is waiting to give control.
• We can move control to another thread by the yield () method.

[Link] 25
• A thread that is ready to run is moved to a runnable state. In this state, a thread might 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.

Running State
• It means the thread is in its execution mode because the control of cpu is given to that
thread.
• It can be moved in three different situations from running mode.

Blocked/Waiting State
• A thread is called in Blocked State when it is not allowed to be entered in Runnable State
or Running State.
• It happens when the thread is in waiting mode, suspended or in sleeping mode.

Terminated/Dead State
• When a thread is completed executing its run () method, the life cycle of that thread
ends.
• We can kill the thread by invoking the stop () method for that thread and sending it to be
in Dead State.

Thread Synchronization:
• Java provides a way of creating threads and synchronizing their tasks using
synchronized blocks.
• Synchronized blocks in Java are marked with the synchronized keyword.
• A synchronized block in Java is synchronized on some object.
• All synchronized blocks synchronized on the same object can only have one thread
executing inside them at a time.
• All other threads attempting to enter the synchronized block are blocked until the thread
inside the synchronized block exits the block.

Example Thread Synchronization:


class Table {
synchronized void printTable(int n) {
// synchronized method
[Link]("Table of " + n + " is ");
for (int i = 1; i <= 5; i++) {
[Link](n * i);
try {
[Link](400);
} catch (InterruptedException e) {
[Link](e);
}
}
}
}

class MyThread1 extends Thread {


Table t;

[Link] 26
MyThread1(Table t) {
this.t = t;
}

public void run() {


[Link](5);
}

class MyThread2 extends Thread {


Table t;

MyThread2(Table t) {
this.t = t;
}

public void run() {


[Link](100);
}
}

public class HelloWorld {


public static void main(String[] args) {
Table obj = new Table(); // only one object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
[Link]();
[Link]();
}
}

Output

[Link] 27
Interthread Communication:
Interthread communication is important when you develop an application where two or more
threads exchange some information. Three methods make thread communication possible:

• wait (): It tells the calling thread to release the lock and go to sleep until some other
thread enters the same monitor and calls notify().
• notify (): It wakes up one single thread called wait() on the same object.
• notifyAll(): It wakes up all the threads that are called wait() on the same object.
All these methods belong to the object class as final. They must be used within a synchronized
block only.
Example:

We have created a class GunFight which contains a member variable bullet that is initialized to
10 and two methods fire () and reload (). The fire () method fires the number of bullets passed to
it until the bullets become 0 and when bullets become 0 it invokes the wait () method which
causes the calling thread to sleep and release the lock on the object while the reload() method
increased the bullets by 10 and invokes the notify() method which wakes up the waiting thread.

class GunFight {
private int bullets = 5;

synchronized public void fire(int bulletsToBeFired) {


for (int i = 1; i <= bulletsToBeFired; i++) {
if (bullets == 0) {
[Link](i - 1
+ " bullets fired and "
+ bullets + " remains");
[Link]("Invoking the wait() method");
try {
wait();
} catch (InterruptedException e) {
[Link]();
}
[Link]("Continuing the fire after
reloading");
}
[Link](i);
bullets--;
}
[Link]("The firing process is complete");
}

synchronized public void reload() {


[Link]("Reloading the magazine and resuming "
+ "the thread using notify()");
bullets += 5;
notify();
}

[Link] 28
}

public class HelloWorld {


public static void main(String[] args) {
GunFight gf = new GunFight();

// Creating a new thread and invoking our fire() method on it


new Thread() {
@Override
public void run() {
[Link](10);
}
}.start();

// Creating a new thread and invoking our reload method on it


new Thread() {
@Override
public void run() {
[Link]();
}
}.start();
}
}

Output:

Exception Handling where exceptions may occur.


int a=50/0;//ArithmeticException
String s=null; [Link]([Link]());//NullPointerException
String s="abc";
int i=[Link](s);//NumberFormatException
int a[]=new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException

[Link] 29
Thread Pools:
Executor Framework: Java provides the ‘[Link]’ framework for managing
and executing threads in a thread pool. Thread pools improve performance by reusing threads
rather than creating new ones for each task.

Five keywords used in Exception handling:

• try
• catch
• throw
• throws
• finally
try: The try block is used to enclose the code that might throw an exception. It allows you to
define a block of code in which exceptions may occur, and you want to handle them gracefully. If
an exception occurs within the ‘try’ block, the control is transferred to the corresponding ‘catch’
block or ‘finally’ block.

catch: The catch block is used to handle exceptions that occur within the corresponding ‘try’
block. It follows the ‘try’ block and specifies the type of exception that it can handle. If an
exception of the specified type is thrown within the ‘try’ block, the control is transferred to the
corresponding ‘catch’ block for handling.

throw: The throw keyword is used to explicitly throw an exception from a method or block of
code. It allows you to create and throw custom exceptions or to propagate exceptions that occur
within your code to the calling method or higher-level code for handling.

throws: The throws keyword is used in method declarations to specify that the method may
throw certain types of exceptions. It indicates that the method does not handle the exceptions
itself but instead propagates them to its caller. The caller method is responsible for handling the
exceptions thrown by the method with the ‘throws’ clause.

finally: The finally block is used to define code that needs to be executed regardless of whether
an exception occurs or not. It follows the ‘try’ block and/or ‘catch’ block and is guaranteed to be
executed even if an exception is thrown and caught, or if no exception occurs at all. The ‘finally’

[Link] 30
block is often used to release resources such as file handles or database connections that were
acquired within the ‘try’ block.

Methods to Print Exception Information


• printStackTrace(): This method prints exception information in the format of Name of the
exception: description of the exception, stack
import [Link].*;
class Exception {
public static void main (String[] args) {
int a=5;
int b=0;
try{
[Link](a/b);
}
catch(ArithmeticException e){
[Link]();
}
}
}

Output:

[Link]: / by zero at
[Link]([Link])

• toString(): This method prints exception information in the format of Name of the
exception: description of the exception.
import [Link].*;
class Exception {
public static void main (String[] args) {
int a=5;
int b=0;
try{
[Link](a/b);
}
catch(ArithmeticException e){
[Link]([Link]());
}
}
}

Output:

[Link]: / by zero

• getMessage(): This method prints only the description of the exception.


import [Link].*;
class Exception {

[Link] 31
public static void main (String[] args) {
int a=5;
int b=0;
try{
[Link](a/b);
}
catch(ArithmeticException e){
[Link]([Link]());
}
}
}

Output:

/ by zero

Finally Block
• The Finally block is a block that is always executed. It is mainly used to perform some
important tasks such as closing connections, streaming etc.
• Rule: For each try block there can be zero or more catch blocks, but only one finally
block.
There are 3 possible cases where finally block can be used:

• Case 1: When an exception does not arise.


• Case 2: When the exception rises anis, d handled by the catch block.
• Case 3: When exception rises and is not handled by the catch block.
Example:

import [Link].*;
class DemoFinally{
public static void main(String[] args)
{
try {
[Link]("inside try block");
// Throw an Arithmetic exception
[Link](34 / 0);
}
catch (ArithmeticException e) {
[Link](
"catch : exception handled.");
}
// Always execute
finally {
[Link]("finally : i execute always.");
}
}
}

[Link] 32
Throw and Throws keyword.
If a method does not handle a checked exception, the method must declare it using the throws
keyword. The throws keyword appears at the end of a method's signature.
The throw keyword is used to explicitly throw an exception. We can throw either checked or
unchecked exceptions. The throw keyword is mainly used to throw custom exception.

[Link] 33
4
Swings and Layouts

Overview

In this chapter, we delve into the realm of Java Swing, a robust


framework for desktop applications. It provides an overview of Swing
components like JButton, JTextField, JTextArea, and more, along
with their functionalities and implementation. The chapter guides
readers through the steps to create graphical user interfaces (GUIs)
using Swing, including setting up JFrame instances, adding
components, and making frames visible. Furthermore, it introduces
layout managers such as BorderLayout, GridLayout, FlowLayout,
and BoxLayout, offering insights into organizing components
effectively within containers.

[Link] 34
Java Swing
• Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract
Window Toolkit [AWT].
• Java swing is used to create window-based applications or desktop applications.
• The [Link] package provides classes : JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu etc.

Hierarchy of Java Swing Classes

Example

import [Link].*;
class MainClass {
public static void main(String[] args)
{
JFrame f=new JFrame();//creating an instance of JFrame

JButton b=new JButton("click");//creating instance of JButton


[Link](130,100,100, 40);//x axis, y axis, width, height

[Link](b);//adding button in JFrame

[Link](400,500);//400 width and 500 height


[Link](true);//making the frame visible.
}
}

Steps to create GUI:


• Create an instance of JFrame
• Set size of Jframe
• Set layout managers// if not then set null.
• Create an instance of Jbutton,JTextField etc..
• Set the position and size of a button,TextField etc
• Add component in Frame.
• Set Visible True for JFrame

[Link] 35
Component class Methods

setBounds()
The setBounds() method needs four arguments. The first two arguments are x and y
coordinates of the top-left corner of the component, the third argument is the width of the
component, and the fourth argument is the height of the component.

Syntax
setBounds(int x-coordinate, int y-coordinate, int width, int height)

JFrame
• There are two ways to create a frame:
• By creating the object of the Frame class
• By extending Frame class (inheritance)
JFrame jf=new JFrame("Book Details");
//[Link](400,400);
[Link](325,58,400,400);
[Link]().setBackground([Link]);
[Link](null);
[Link](true);

[Link] 36
Color c1 = new Color(102, 255, 102);
[Link]().setBackground(c1);

JButton Class
The JButton class is used to create a clickable button in a graphical user interface (GUI). It
represents a push-button component that acts when clicked by the user.

Syntax:
JButton button = new JButton("Button Text");

Constructors of JButton

Methods of JButton Class

Steps to perform Action on Button click.


Importing Packages:
import [Link].*;
import [Link].*;
import [Link].*;

Step 1: Create Class which Implementing ActionListener Interface: class classname implements
ActionListener.

[Link] 37
Step 2: Create Button and add in Frame, Registering ActionListener to the JButton: In this step,
we will add or can say register ActionListener to the JButton. For this, we must call the
addActionListener() method using the object of the JButton class.

Step 3: Override actionPerformed() method

JRadioButton Class
The JRadioButton class is used to create radio buttons. Radio buttons are components used in
groups where only one option can be selected at a time. They are typically grouped together
using a ‘ButtonGroup’ object. Each ‘JRadioButton’ can be customized for appearance and
behavior.

Syntax:
JRadioButton radioButton = new JRadioButton("Radio Button Text");

Methods of JRadioButton Class

Steps:
JRadioButton r1=new JRadioButton("Male");
JRadioButton r2=new JRadioButton("Female");
[Link](75,50,100,30);
[Link](75,100,100,30);
ButtonGroup bg=new ButtonGroup();
[Link](r1);
[Link](r2);
[Link](r1);
[Link](r2);

[Link] 38
JTextArea Class
The JTextArea class is used to create a multiline text area component, allowing users to input or
display multiple lines of text.

Syntax:
JTextArea textArea = new JTextArea(rows, columns);

Constructor

Methods of JTextArea Class

JComboBox Class
The JComboBox class is used to create a drop-down combo box component, allowing users to
select one option from a list of predefined options.

Syntax:
String[] options = {"Option 1", "Option 2", "Option 3"};
JComboBox<String> comboBox = new JComboBox<>(options);

Constructor

[Link] 39
Methods of JComboBox

JTable Class
The JTable class is used to display tabular data in a graphical user interface (GUI). It represents
a grid of cells organized into rows and columns, like a spreadsheet.

Syntax:
JTable table = new JTable(rows, columns);

Constructors in JTable:

• JTable(): A table is created with empty cells.


• JTable(int rows, int cols): Creates a table of size rows * cols.
• JTable(Object[ ][ ] data, Object [ ]Column): A table is created with the specified name
where [ ]Column defines the column names.

JTable Functions

• addColumn(TableColumn [ ]column): adds a column at the end of the JTable.


• clearSelection(): Selects all the selected rows and columns.
• editCellAt(int row, int col): edits the intersecting cell of the column number col and row
number row programmatically, if the given indices are valid and the corresponding cell is
editable.
• setValueAt(Object value, int row, int col): Sets the cell value as ‘value’ for the position
row, col in the JTable.

Example

[Link] 40
import [Link].*;

public class JTableExamples {


// frame
JFrame f;
// Table
JTable j;

// Constructor
JTableExamples()
{
// Frame initialization
f = new JFrame();

// Frame Title
[Link]("JTable Example");

// Data to be displayed in the JTable


String[][] data = {
{ "Kundan Kumar Jha", "4031", "CSE" },
{ "Anand Jha", "6014", "IT" }
};

// Column Names
String[] columnNames = { "Name", "Roll Number", "Department" };

// Initializing the JTable


j = new JTable(data, columnNames);
[Link](30, 40, 200, 300);

// adding it to JScrollPane
JScrollPane sp = new JScrollPane(j);
[Link](sp);
// Frame Size
[Link](500, 200);
// Frame Visible = true
[Link](true);
}
public static void main(String[] args)
{
new JTableExamples();
}
}

JColorChooser Class
The JColorChooser class is used to create a dialog box that allows users to select colors
interactively. It provides various options for selecting colors, including RGB values, HSB values,
and a palette of predefined colors.

[Link] 41
Syntax:
Color color = [Link](parentComponent, "Title",
initialColor);

Constructors in JTable:

• JColorChooser(): Creates a color chooser pane with an initial color of white.


• JColorChooser(Color initialColor): Creates a color chooser pane with the specified
initial color.
• JColorChooser(ColorSelectionModel model): Creates a color chooser pane with the
specified ColorSelectionModel.

Example
import [Link].*;
import [Link].*;
import [Link].*;

public class ColorChooserExample extends


JFrame implements ActionListener {

// create a button
JButton b = new JButton("color");

Container c = getContentPane();

// Constructor
ColorChooserExample()
{
// set Layout
[Link](new FlowLayout());

// add Listener
[Link](this);

// add button to the Container


[Link](b);
}

JProgressBar Class
The JProgressBar class is used to create a graphical progress bar component, indicating the
progress of a task or operation.

Syntax:
JProgressBar progressBar = new JProgressBar(minimum, maximum);
[Link](value);

Constructor in JProgressBar

[Link] 42
Methods of JProgressBar

Example

import [Link].*;
import [Link].*;
import [Link].*;
public class progress extends JFrame {
// create a frame
static JFrame f;
static JProgressBar b;
public static void main()
{
// create a frame
f = new JFrame("ProgressBar demo");
// create a panel
JPanel p = new JPanel();
// create a progressbar
b = new JProgressBar();
// set initial value
[Link](0);
[Link](true);
// add progressbar
[Link](b);
// add panel
[Link](p);
// set the size of the frame
[Link](500, 500);

[Link] 43
[Link](true);

fill();
}
// function to increase progress
public static void fill()
{
int i = 0;
try {
while (i <= 100) {
// fill the menu bar
[Link](i + 10);

// delay the thread


[Link](1000);
i += 20;
}
}
catch (Exception e) {
}
}
}

JSlider Class
The JSlider class is used to create a slider component that allows users to select a value from a
range. By using Slider, we can select a value from given range.
Syntax:
JSlider slider = new JSlider(minimum, maximum, initialValue);

Constructors of JSlider.
• JSlider(): creates a slider with default initial value 50 and range 0-100.
• JSlider(int orientation): Creates a slider with the specified orientation either
[Link] or [Link].
• JSlider(int min, int max): creates a horizontal slider using the given min and max.

[Link] 44
• JSlider(int min, int max, int values): develops a horizontal slider with specified min,
max, and values.
• JSlider(int orientation, int min, int max, int value): develop a slider with specified
orientation, that must be either [Link] or [Link].
• CardLayout(): creates a card layout with zero horizontal and vertical gap.
• CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical
gap.
• void setMinorTickSpacing(int p): sets the minor tick spacing in the slider.
• void SetMajorTickSpacing (int p): sets the major tick spacing.
• void setMinimum(int p): sets the minimum value of the slider.
• void setMaximum(int p): sets the maximum value of the slider.
• void setPaintsTicks(boolean bl): determines that tick mark is painted.
• void setPaintLabels(boolean bl): tests whether labels are painted.
• void setPaintTracks(boolean bl): determines whether the track is painted.

Example
import [Link].*;
import [Link].*;
import [Link].*;
class solve extends JFrame implements ChangeListener {
static JFrame f;
static JSlider b;
static JLabel l;
// main class
public static void main(String[] args)
{
f = new JFrame("frame");
solve s = new solve();
l = new JLabel();
JPanel p = new JPanel();
b = new JSlider(0, 200, 120);
// paint track, ticks and labels
[Link](true);
[Link](true);
[Link](true);
// set spacing
[Link](50);
[Link](5);
[Link](s);
[Link](b);
[Link](l);
[Link](p);
[Link]("value of Slider is =" + [Link]());
[Link](300, 300);
[Link](true);
}
// if JSlider value is changed

[Link] 45
public void stateChanged(ChangeEvent e)
{
[Link]("value of Slider is =" + [Link]());
}
}

Layout Managers
Layout managers in Java Swing are used to define the arrangement and positioning of
components within a container. They provide flexibility and control over the layout of GUI
components, ensuring that they are displayed correctly across different screen sizes and
resolutions.

BorderLayout
Divides the container into five regions: North, South, East, West, and Center. Components can
be added to each region, and they are resized according to the available space.

GridLayout
Arranges components in a grid with a specified number of rows and columns. Each cell in the
grid contains one component, and all components are the same size.

[Link] 46
FlowLayout
Places components in a row, wrapping them to the next line if necessary. Components are
aligned horizontally or vertically based on the specified alignment.

Constructors of FlowLayout.
• FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
• FlowLayout(int align): creates a flow layout with the given alignment and a default 5
unit horizontal and vertical gap.
• FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.

BoxLayout
The BoxLayout class is used to arrange the components either vertically (along Y-axis) or
horizontally (along X-axis).
In BoxLayout class, the components are put either in a single row or a single column. The
components will not wrap so, for example, a horizontal arrangement of components will stay
horizontally arranged when the frame is resized.

Fields of BoxLayout Class


• public static final int X_AXIS: This constant typically represents the horizontal axis. It's
used to specify alignment or arrangement along the horizontal direction. For example,
when using ‘BoxLayout’, you might use ‘X_AXIS’ to arrange components horizontally
from left to right.
• public static final int Y_AXIS: This constant represents the vertical axis. It's used to
specify alignment or arrangement along the vertical direction. In ‘BoxLayout’ or similar
layout managers, using ‘Y_AXIS’ arranges components vertically from top to bottom.
• public static final int LINE_AXIS: This constant represents the axis along a line
direction. It's used in more flexible layout managers such as ‘BoxLayout’ to arrange
components along a line, which could be either horizontal or vertical depending on the
container's orientation.
• public static final int PAGE_AXIS: This constant represents the axis along a page
direction. It's again used in layout managers like ‘BoxLayout’ to arrange components
along a page, which could be either horizontal or vertical depending on the container's
orientation.

Constructors of BoxLauout
• BoxLayout(Container c, int axis): Creates a BoxLayout class that arranges the
components with the X-axis or Y-axis.

[Link] 47
CardLayout
Manages multiple components by stacking them on top of each other like a deck of cards. Only
one component is visible at a time, and you can switch between components programmatically.

• CardLayout(): creates a card layout with zero horizontal and vertical gap.
• CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.

Methods of JProgressBar
• public void next (Container parent): is used to flip to the next card of the given
container.
• public void previous (Container parent): is used to flip to the previous card of the
given container.
• public void first (Container parent): is used to flip to the first card of the given
container.
• public void last (Container parent): is used to flip to the last card of the given
container.
• public void show (Container parent, String name): is used to flip to the specified card
with the given name.

Example CardLayout
// import statements
import [Link].*;
import [Link].*;
import [Link].*;

public class CardLayoutExample1 extends JFrame implements


ActionListener
{

CardLayout crd;

// button variables to hold the references of buttons


JButton btn1, btn2, btn3, btn4;
Container cPane;

// constructor of the class


CardLayoutExample1()
{

cPane = getContentPane();

//default constructor used


// therefore, components will
// cover the whole area
crd = new CardLayout();

[Link](crd);

[Link] 48
// creating the buttons
btn1 = new JButton("C Sharp Corner");
btn2 = new JButton("You can download free eBook");
btn3 = new JButton("Programming in JAVA eBook");
btn4 = new JButton("Yes Download this eBook");

// adding listeners to it
[Link](this);
[Link](this);
[Link](this);
[Link](this);

[Link]("a", btn1); // first card is the button btn1


[Link]("b", btn2); // first card is the button btn2
[Link]("c", btn3); // first card is the button btn3
[Link]("d", btn4); // first card is the button btn4

}
public void actionPerformed(ActionEvent e)
{
// Upon clicking the button, the next card of the container is shown
// after the last card, again, the first card of the container is shown
upon clicking
[Link](cPane);
}

// main method
public static void main(String argvs[])
{
// creating an object of the class CardLayoutExample1
CardLayoutExample1 crdl = new CardLayoutExample1();

// size is 300 * 300


[Link](500, 500);
[Link](true);
[Link](EXIT_ON_CLOSE);
}
}

NullLayout
NullLayout in Java permits manual positioning and sizing of components within a container. It
offers precise control but lacks automatic adjustment for resizing or varying screen sizes. While
useful for specific design needs, it's generally recommended to use other layout managers for
dynamic and responsive layouts.

[Link] 49
5
Managing data using JDBC

Overview

In this chapter, we will explore Java Database Connectivity (JDBC),


covering its architecture, JDBC drivers, essential interfaces such as
Connection, Statement, PreparedStatement, CallableStatement, and
ResultSet, along with practical examples for efficient database
interaction in Java applications.

[Link] 50
Java Database Connectivity
JDBC is a software tool known as an application programming interface(API) that is used to
interact with the database.

Need for Java JDBC


• For establishing stable database connectivity with the application API.
• To execute SQL(Structured Query Language) queries and DDL/DML commands.
• For viewing and modify data records

JDBC Architecture

JDBC API
The JDBC API (Java Database Connectivity) is a Java API that provides a standard interface for
connecting Java applications to relational databases. It enables Java programs to interact with
databases, execute SQL queries, and perform database operations such as inserting, updating,
deleting, and retrieving data. The JDBC API consists of a set of interfaces and classes that
facilitate database connectivity and interaction.

[Link] 51
Interfaces of JDBC API
• Driver interface
• Connection interface
• Statement interface
• PreparedStatement interface
• CallableStatement interface
• ResultSet interface
• ResultSetMetaData interface
• DatabaseMetaData interface
• RowSet interface

Classes of JDBC API


• DriverManager class
• Blob class
• Clob class
JDBC Driver manager: It loads a database-specific driver in an application to establish a
connection with a database. JDBC drivers are client-side adapters (installed on the client
machine, not on the server) that convert requests from Java programs to a protocol that the
DBMS can understand.

There are 4 types of JDBC drivers:

• Type-1 driver or JDBC-ODBC bridge driver.


• Type-2 driver or Native-API driver.
• Type-3 driver or Network Protocol driver.
• Type-4 driver or thin driver.

Type 1 − JDBC-ODBC Bridge Driver:


It provides a bridge to access the ODBC driver installed on each client. Using ODBC requires
configuring on your system a Data Source Name (DSN) that represents the target database.

Using the JDBC-ODBC bridge driver we can access the databases which support only ODBC.
Java application sends a request to the JDBC-ODBC bridge driver the request internally calls
the ODBC equivalent function, and the ODBC driver retrieves the result from the underlying
database and sends it back to the JDBC-ODBC bridge driver.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use
JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.

[Link] 52
Functionality:
The JDBC-ODBC Bridge driver works by translating JDBC calls into ODBC calls, which are then
executed by the ODBC driver. It relies on the ODBC driver manager and an installed ODBC
driver to establish a connection to the database. This driver facilitates database connectivity for
Java applications on platforms where a JDBC driver specific to the database is not available, as
it can leverage existing ODBC drivers.

Advantages:
• Ease of Use: The JDBC-ODBC Bridge driver is easy to set up and use since it is
included in the JDK and does not require additional configuration.
• Platform Independence: It allows Java applications to connect to any ODBC-compliant
database, making it platform-independent.
• Access to Legacy Databases: This driver enables Java applications to access legacy
databases for which JDBC drivers may not be available.

Disadvantages:
• Performance Overhead: The JDBC-ODBC Bridge driver introduces a performance
overhead due to the additional translation layer between JDBC and ODBC.
• Limited Support: The JDBC-ODBC Bridge driver is not recommended for production
use as it has been deprecated in newer versions of Java due to security and
performance concerns.
• Platform Dependency: While Java applications are platform-independent, the
availability and compatibility of ODBC drivers can vary across different platforms.

Connection Interface
Connection interface represents a session between java application and database. All SQL
statements are executed, and results are returned within the context of a Connection object. It
provides methods for creating statements, managing transactions, accessing database
metadata, and controlling the connection properties. You can also use it to retrieve the metadata
of a database like name of the database product, name of the JDBC driver, major and minor
version of the database etc.

Methods of Connection interface:

[Link] 53
createStatement():
• Creates a ‘Statement’ object for executing SQL statements without parameters.
• Returns a ‘Statement’ object that can be used to execute SQL queries or updates.
Statement statement = [Link]();

prepareStatement(String sql):
• Creates a ‘PreparedStatement’ object for executing parameterized SQL statements.
• Returns a ‘PreparedStatement’ object that can be used to execute SQL queries or
updates with parameters.
PreparedStatement preparedStatement =
[Link]("SELECT * FROM my_table WHERE id = ?");

close():
• Closes the connection to the database.
• Releases any database resources associated with the connection.
[Link]();

commit():
• Commits the current transaction, making all changes permanent.
[Link]();

rollback():
• Rolls back the current transaction, discarding all changes made since the last commit.
[Link]();

setAutoCommit(boolean autoCommit):
• Enables or disables auto-commit mode for the connection.
• When auto-commit mode is enabled, each SQL statement is committed immediately
after it is executed.
[Link](false);

getMetaData():
• Retrieves a ‘DatabaseMetaData’ object that contains metadata about the database to
which this connection is established.
• Provides information about the database such as its name, version, tables, columns, etc.
DatabaseMetaData metaData = [Link]();

Statement Interface
The statement interface is used to create SQL statements. It provides methods to execute SQL
queries, updates, and other statements, as well as retrieving result sets. This interface is used

[Link] 54
for executing static SQL statements that do not contain parameters. It's important to note that
Statement objects can pose a security risk due to SQL injection attacks when constructing SQL
statements dynamically with user input. Therefore, it's recommended to use PreparedStatement
for executing parameterized queries to prevent SQL injection attacks.

Types of statements that are used in JDBC.

Create a Statement:
• Statement
• PreparedStatement
• CallableStatement

Key Methods of the Statement Interface:


executeQuery(String sql):
• Executes the given SQL query and returns a ‘ResultSet’ object containing the result set
generated by the query.
• Used for executing SELECT queries.
ResultSet resultSet = [Link]("SELECT * FROM my_table");

executeUpdate(String sql):
• Executes the given SQL statement, which may be an INSERT, UPDATE, DELETE, or
other SQL statement.
• Returns the number of rows affected by the execution of the statement.
int rowsAffected = [Link]("INSERT INTO my_table (name)
VALUES ('John')");

execute(String sql):
• Executes the given SQL statement, which may be a query or an update.
• Returns a boolean indicating whether the first result is a ‘ResultSet’ object.
boolean isResultSet = [Link]("SELECT * FROM my_table");

addBatch(String sql):
• Adds the given SQL command to the current batch of statements for batch processing.
• Used for executing multiple SQL statements together as a batch.
[Link]("INSERT INTO my_table (name) VALUES ('John')");
[Link]("INSERT INTO my_table (name) VALUES ('Jane')");

clearBatch():
• Clears the current batch of statements.
[Link]();

[Link] 55
executeBatch():
• Executes all the statements in the current batch as a single batch.
• Returns an array of integers indicating the number of rows affected by each statement in
the batch.
int[] rowsAffected = [Link]();

close():
• Closes the statement, releasing any database resources associated with it.
[Link]();

Execute Queries
Create a Statement: It is generally used for general–purpose access to databases and is useful
while using static SQL statements at runtime.

Syntax:
Statement statement = [Link]();

Once the Statement object is created, there are three ways to execute it:

• boolean execute (String SQL)


• int executeUpdate(String SQL)
• ResultSet executeQuery(String SQL)

Types of Execute Queries.


Public ResultSet executeQuery(String SQL)
• Is used to execute SELECT queries. It returns the object of ResultSet.

Public Int executeUpdate(String SQL)


• Is used to execute specified query, it may be inserted, update or delete etc.
• Returns the number of rows affected by the execution of the SQL statement.
• Use this method to execute SQL statements, for which you expect to get several rows
affected – for example, an INSERT, UPDATE, or DELETE statement.

Public Boolean execute(String SQL)


• Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it
returns false.
• Use this method to execute SQL DDL statements or when you need to use truly dynamic
SQL.

Example:
import [Link].*;
class FetchRecord{
public static void main(String args[])throws Exception{

[Link] 56
[Link]("[Link]");
Connection con=[Link](
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Statement stmt=[Link]();

//[Link]("insert into emp765 values(33,'Irfan',50000)");


//int result=[Link](
"update emp765 set name='Vimal',salary=10000 where id=33");
int result=[Link]("delete from emp765 where id=33");
[Link](result+" records affected");
[Link]();
}}

PreparedStatement interface
Prepared Statement represents a recompiled SQL statement, that can be executed many times.
This accepts parameterized SQL queries, improving performance and security by preventing
SQL injection attecks. In this, “?” is used instead of the parameter, one can pass the parameter
dynamically by using the methods of PREPARED STATEMENT at run time.

Once the PreparedStatement object is created, there are three ways to execute it:

• boolean execute(String SQL)


• int executeUpdate(String SQL)
• ResultSet executeQuery(String SQL)

Key Methods of PreparedStatement interface


• setInt(int parameterIndex, int value):
• setString(int parameterIndex, String value):
• setDate(int parameterIndex, Date value):
• executeQuery():
• executeUpdate():
• addBatch():
• clearParameters():
• close():

Example:
import [Link].*;

public class PreparedStatementExample {


public static void main(String[] args) {
try {
// Establish connection
Connection connection =
[Link]("jdbc:mysql://localhost:3306/mydatabase",
"username", "password");

// Create prepared statement

[Link] 57
PreparedStatement preparedStatement =
[Link]("INSERT INTO my_table (id, name, dob)
VALUES (?, ?, ?)");

// Set parameters
[Link](1, 100);
[Link](2, “Baibhav");
[Link](3, [Link]("2024-03-07"));

// Execute update
int rowsAffected = [Link]();

// Close resources
[Link]();
[Link]();
} catch (SQLException e) {
[Link]();
}
}
}

CallableStatement interface
The CallableStatement interface is used to execute the SQL stored procedure in a database.
The JDBC API provides stored procedures to be called in a standard way for all RDBMS.

Syntax:
CallableStatement cstmt =
[Link]("{call Procedure_name(?, ?}");

ResultSet interface
It is used to store the data which are returned from the database table after the execution of the
SQL statements. The object of ResultSet maintains cursor point at the result data. In default, the
cursor positions before the first row of the result data.
The next() method is used to move the cursor to the next position in a forward direction. It will
return FALSE if there are no more records. It retrieves data by calling the executeQuery()
method using any of the statement objects.

[Link] 58
Methods of ResultSet

Note:

ResultSetMetaData Interface
Metadata means data about data i.e. we can get further information from the data.
If you must get metadata of a table like total number of columns, column name, column type etc,
ResultSetMetaData interface is useful because it provides methods to get metadata from the
ResultSet object.

Methods of ResultSetMetaData

[Link] 59
ResultSetMetaData interface
DatabaseMetaData interface provides methods to get meta data of a database such as
database product name, database product version, driver name, name of total number of tables,
name of total number of views etc.

DatabaseMetaData interface
The DatabaseMetaData interface in Java JDBC (Java Database Connectivity) provides methods
to retrieve metadata information about the database to which a connection is established.
Metadata includes information such as database name, version, tables, columns, primary keys,
foreign keys, and more.

Key Methods of DatabaseMetaData Interface:

getDatabaseProductName():
• Retrieves the name of the database product.
• Returns a ‘String’ representing the name of the database product.

getDatabaseProductVersion():
• Retrieves the version number of the database product.
• Returns a ‘String’ representing the version number of the database product.

getTables(String catalog, String schemaPattern, String tableNamePattern,


String[] types):
• Retrieves a ‘ResultSet’ object containing table information such as table name, table
type, and remarks.
• ‘catalog’, ‘schemaPattern’, and ‘tableNamePattern’ are search patterns for catalog,
schema, and table names respectively.
• ‘types’ is an array of table types (e.g., "TABLE", "VIEW", "SYSTEM TABLE", etc.).

getColumns(String catalog, String schemaPattern, String


tableNamePattern, String columnNamePattern):
• Retrieves a ‘ResultSet’ object containing column information for a specific table.
• ‘catalog’, ‘schemaPattern’, ‘tableNamePattern’, and ‘columnNamePattern’ are search
patterns for catalog, schema, table, and column names respectively.

[Link] 60
getPrimaryKeys(String catalog, String schema, String tableName):
• Retrieves a ‘ResultSet’ object containing primary key columns for a specific table.
• ‘catalog’, ‘schema’, and ‘tableName’ are the names of the catalog, schema, and table
respectively.

getImportedKeys(String catalog, String schema, String tableName):


• Retrieves a ‘ResultSet’ object containing foreign key columns that reference a specific
table.
• ‘catalog’, ‘schema’, and ‘tableName’ are the names of the catalog, schema, and table
respectively.

getExportedKeys(String catalog, String schema, String tableName):


• Retrieves a ‘ResultSet’ object containing foreign key columns in a specific table that
reference columns in other tables.
• ‘catalog’, ‘schema’, and ‘tableName’ are the names of the catalog, schema, and table
respectively.

getSchemas():
• Retrieves a ‘ResultSet’ object containing schema information for the database.
• Returns a ‘ResultSet’ object containing schema information.

getCatalogs():
• Retrieves a ‘ResultSet’ object containing catalog information for the database.
• Returns a ‘ResultSet’ object containing catalog information.

[Link] 61
6
Network Programming

Overview

In this Chapter, we delve into essential Java networking concepts


and classes. We explore key terminologies such as IP addresses,
protocols, and sockets, laying the foundation for understanding
network communication. Through detailed explanations, readers
gain insights into Java's Socket and ServerSocket classes, crucial
for establishing communication endpoints and managing
connections. Additionally, we cover URL and URLConnection
classes for managing resource locators and facilitating
communication with remote resources. Practical examples illustrate
the usage of these classes in real-world scenarios, enhancing
comprehension of network programming in Java.

[Link] 62
Network programming in Java encompasses the development of applications facilitating
communication across networks, including client-server, peer-to-peer, and distributed systems.
Leveraging Java's extensive APIs and libraries, developers can construct networked
applications efficiently. In essence, networking involves interconnecting computing devices to
enable resource sharing. Network programming extends this concept by enabling the creation of
programs that execute on multiple interconnected devices, allowing seamless communication
and collaboration.

Java networking terminologies


• IP Address
• Protocol
• Port Number
• MAC Address
• Connection-oriented and connection-less protocol
• Socket

IP Address
IP address is a unique number assigned to a node of a network e.g. [Link] . It is
composed of octets that range from 0 to 255. It is a logical address that can be changed.

Protocol
A protocol is a set of rules basically that is followed for communication. For example: TCP, FTP,
Telnet, SMTP, POP etc.

Port Number

Mac Address:
MAC (Media Access Control) Address is a unique identifier assigned to network interfaces for
communications on a network. It is a hardware address assigned to network adapters by the
manufacturer and is used for identifying devices on a network at the data link layer of the OSI
model. MAC addresses are typically expressed as a series of six pairs of hexadecimal digits,
separated by colons or hyphens, such as "00:1A:2B:3C:4D:5E". Each MAC address is unique,
allowing network devices to be uniquely identified on a network segment.

[Link] 63
Connection-oriented and connection-less protocol
• In connection-oriented protocol, acknowledgement is sent by the receiver. So, it is
reliable but slow. An example of connection-oriented protocol is TCP.
• But, in connection-less protocol, acknowledgement is not sent by the receiver. So, it is
not reliable but fast. An example of connection-less protocol is UDP.

Socket
• A socket is one endpoint between two-way communication link between two programs
running on the network.
• Socket Programming is used for communication between machines using a Transfer
Control Protocol (TCP). It can be connectionless or connection-oriented.
• ServerSocket and Socket classes are used for connection-oriented socket
programming.
• After creating a connection, the server develops a socket object on its end of the
connection. The server and client now starts communicating by writing to and reading
from the socket.

Networking

Socket Class
The Socket class allows us to create socket objects that help us in implementing all fundamental
socket operations. We can perform various networking operations such as sending, reading
data and closing connections.

[Link] 64
ServerSocket Class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.

URL Class
URL class in Java facilitates the management of Uniform Resource Locators, offering methods
for parsing, constructing, and manipulating URLs. It enables developers to extract different
components of a URL, establish connections to remote resources, and read data from URLs.
Additionally, the class provides functionality for encoding and decoding URL strings, making it
essential for network programming tasks in Java applications.

[Link]

URL Class Constructors


• URL(String spec): Creates a URL object from the specified URL string.
URL url = new URL("[Link]

• URL (String protocol, String host, int port, String file): Creates an instance of a URL
from the given protocol, host, port number, and file.
URL url = new URL("https", "[Link]", 8080, "/[Link]");

• URL (String protocol, String host, String file): Creates an instance of a URL from the
given protocol name, host name, and file name.
URL url = new URL("https", "[Link]", "/[Link]");

• URL(URL context, String spec): Creates a URL object by resolving the given URL
string against the specified context URL.
URL baseUrl = new URL("[Link]
URL relativeUrl = new URL(baseUrl, "/[Link]");

[Link] 65
Methods of URL Class

Example
import [Link];
public class URLClass {
public static void main(String[] args)
{
try{
// Creating a URL with string representation
URL url1 = new URL(
"[Link]
+ "WK26I4fT8gfth6CACg#q=geeks+for+geeks+java");
// Creating a URL with string
URL url3 = new URL(
"[Link]
+ "q=gnu&rlz=1C1CHZL_enIN71"
+ "4IN715&oq=gnu&aqs=chrome..69i57j6"
+ "9i60l5.653j0j7&sourceid=chrome&ie=UTF"
+ "-8#q=geeks+for+geeks+java");
// Creating a URL with a protocol,hostname,and path
URL url2 = new URL("http", "[Link]",
"/jvm-works-jvm-architecture/");
// Printing the string representation of the URL
[Link]([Link]());
[Link]([Link]());
[Link]();

// Printing Different Components of the URL

[Link] 66
// Retrieving the protocol for the URL
[Link]("Protocol:- " + [Link]());
// Retrieving the hostname of the url
[Link]("Hostname:- " + [Link]());
// Retrieving the default port
[Link]("Default port:- " + [Link]());
// Retrieving the query part of URL
[Link]("Query:- " + [Link]());
// Retrieving the path of URL
[Link]("Path:- " + [Link]());
// Retrieving the file name
[Link]("File:- " + [Link]());
// Retrieving the reference
[Link]("Reference:- " + [Link]());
}
catch(Exception e){[Link](e);}
}}

URL Connection Class


• URLConnection class represents a communication link between the URL and the
application. It can be used to read and write data to the specified resource referred to by
the URL.
• URLConnection is an abstract class. The two subclasses HttpURLConnection and
JarURLConnection makes the connetion between the client Java program and URL
resource on the internet.
• With the help of URLConnection class, a user can read and write to and from any
resource referenced by a URL object.

Steps of use URLConnection


• URL Creation: Create a URL object using any of the constructors given.
• Create Object: Invoke the openConnection() call to create the object of URLConnection.
• Display the Content: Either use the above-created object to display the information
about the resource or to read/write contents of the file to the console using
bufferedReader and InputStream of the open connection using getInputStream() method.
• Close Stream: Close the InputStream when done.

[Link] 67
Example 1
import [Link].*;
import [Link].*;
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("[Link]
URLConnection urlcon=[Link]();
InputStream stream=[Link]();
int i;
while((i=[Link]())!=-1){
[Link]((char)i);
}
}catch(Exception e){[Link](e);}
}
}

Example 2
class MyClass {
// main driver method
public static void main(String[] args)
{
try {
URL url = new URL(
"[Link]
URLConnection urlcon = [Link]();
// To get a map of all the fields of http header
Map<String, List<String> > header
= [Link]();

// Printing all the fields along with their value


for ([Link]<String, List<String> > mp :
[Link]()) {
[Link]([Link]() + " : ");
[Link](
[Link]().toString());
}
[Link]();
[Link](
"Complete source code of the URL is-");
[Link](
"---------------------------------");

// Getting the inputstream of the open


// connection
BufferedReader br
= new BufferedReader(new InputStreamReader(
[Link]()));

[Link] 68
String i;

// Printing the source code line by line


while ((i = [Link]()) != null) {

[Link](i);
}
}

HttpURL Connection Class


• The Java HttpURLConnection class is http specific URLConnection. It works for
HTTP/HTTPS protocol only.
• By the help of HttpURLConnection class, you can retrieve information of any HTTP URL
such as header information, status code, response code etc.
• The [Link] is subclass of URLConnection class.

Example
import [Link].*;
import [Link].*;
public class HttpURLConnectionDemo{
public static void main(String[] args){
try{
URL url=new URL("http:// [Link]
[Link]/article/datetime-manipulation-in-c-sharp");

HttpURLConnection huc=(HttpURLConnection)[Link]();
for(int i=1;i<=8;i++){
[Link]([Link](i)
+" = "+[Link](i));
}
[Link]();
}catch(Exception e){[Link](e);}
}
}

Output

[Link] 69
Datagram Socket Class
The DatagramSocket class in Java is a fundamental component of network programming,
particularly for communication over UDP (User Datagram Protocol). Serving as both a sending
and receiving point for datagram packets, it enables individual addressing and routing of each
packet. This class provides essential functionalities for sending and receiving datagrams,
making it ideal for scenarios where connectionless and unreliable communication is acceptable,
such as real-time applications or situations requiring minimal overhead.

Methods of Datagram Socket Class

Java Socket Programming


Java Socket programming is like a telephone system for applications. It helps them talk to each
other even if they're on different computers. There are two main types: connection-oriented,
which is like having a continuous phone call, and connection-less, which is more like sending
letters. For connection-oriented communication, we use Socket and ServerSocket classes, while
for connection-less communication, we use DatagramSocket and DatagramPacket classes.
These tools help applications exchange information easily and reliably.

In socket programming, the client needs to know two pieces of information:

• IP Address of Server.
• Port number.

Socket class.
A socket serves as an endpoint for communication between machines. In Java, the Socket class
facilitates the creation and management of sockets for establishing connections and exchanging
data between devices over a network.

ServerSocket class
The ServerSocket class is used to create a server socket, enabling communication with clients.
It listens for incoming client connections on a specified port and accepts them when requested,

[Link] 70
creating new Socket objects for communication. It serves as a vital component for establishing
server-side communication in socket programming.

Example

Creating Server:
To initiate the server application, an instance of the ServerSocket class is created. In this
example, port number 6666 is utilized for client-server communication, though alternative port
numbers can also be chosen. The accept () method within the ServerSocket instance awaits
client connections. Upon connection establishment with the specified port number, it returns a
Socket instance.

ServerSocket serverSocket = new ServerSocket(6666);


Socket socket = [Link](); // Establishes connection and
waits for the client

Creating Client:
For the client application, a Socket class instance is required. The client application needs to
specify the IP address or hostname of the server, along with the designated port number. In this
instance, "localhost" is used since the server is operating on the same system.

Socket socket = new Socket("localhost", 6666);

[Link] 71
OUR MISSION
Free Education is Our Basic Need! Our mission is to empower millions of developers worldwide by
providing the latest unbiased news, advice, and tools for learning, sharing, and career growth. We’re
passionate about nurturing the next young generation and help them not only to become great
programmers, but also exceptional human beings.

ABOUT US
CSharp Inc, headquartered in Philadelphia, PA, is an online global community of software
developers. C# Corner served 29.4 million visitors in year 2022. We publish the latest news and articles
on cutting-edge software development topics. Developers share their knowledge and connect via
content, forums, and chapters. Thousands of members benefit from our monthly events, webinars,
and conferences. All conferences are managed under Global Tech Conferences, a CSharp
Inc sister company. We also provide tools for career growth such as career advice, resume writing,
training, certifications, books and white-papers, and videos. We also connect developers with their poten-
tial employers via our Job board. Visit C# Corner

MORE BOOKS

You might also like