Java Programming Essentials Guide
Java Programming Essentials Guide
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
[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.
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.
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 {
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);
}
}
Types of Variables:
1) Local
2) Instance
3) Statics
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.");
}
}
• 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.
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
• Comparison operators:
[Link] 9
• Logical operators:
[Link] 10
• XOR Operator: If both side bit is opposite result will be On
• 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.
[Link] 12
2
Collection Framework
Overview
[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.
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.
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”)
• 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);
• 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.
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]() + " ");
}
Key Features
[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.
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.
[Link] 20
3
Multithreading
Overview
[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.
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!");
}
}
[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!");
}
}
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!");
}
}
[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!");
}
}
[Link] 24
[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.
[Link] 26
MyThread1(Table t) {
this.t = t;
}
MyThread2(Table t) {
this.t = t;
}
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;
[Link] 28
}
Output:
[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.
• 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.
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
[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:
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
[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.
Example
import [Link].*;
class MainClass {
public static void main(String[] args)
{
JFrame f=new JFrame();//creating an instance of 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
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.
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");
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
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 Functions
Example
[Link] 40
import [Link].*;
// Constructor
JTableExamples()
{
// Frame initialization
f = new JFrame();
// Frame Title
[Link]("JTable Example");
// Column Names
String[] columnNames = { "Name", "Roll Number", "Department" };
// 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:
Example
import [Link].*;
import [Link].*;
import [Link].*;
// create a button
JButton b = new JButton("color");
Container c = getContentPane();
// Constructor
ColorChooserExample()
{
// set Layout
[Link](new FlowLayout());
// add Listener
[Link](this);
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);
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.
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].*;
CardLayout crd;
cPane = getContentPane();
[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);
}
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();
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
[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.
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
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.
[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.
Create a Statement:
• Statement
• PreparedStatement
• CallableStatement
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:
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]();
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:
Example:
import [Link].*;
[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.
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.
[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.
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
[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.
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 (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]();
[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);}
}}
[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]();
[Link] 68
String i;
[Link](i);
}
}
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.
• 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.
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.
[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