0% found this document useful (0 votes)
27 views63 pages

Ece JPG

Uploaded by

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

Ece JPG

Uploaded by

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

Introduction to Object Oriented Programming,

The History and Evolution of Java, Introduction to Classes, Objects, Methods, Constructors, this
keyword, Garbage Collection, Data Types, Variables, Type Conversion and Casting, Arrays, Operators,
Control Statements, Method Overloading, Constructor Overloading, Parameter Passing, Recursion,
String Class and String handling methods

Inheritance

Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in


Java by which one class is allowed to inherit the features(fields and methods) of another class. In
Java, Inheritance means creating new classes based on existing ones. A class that inherits from
another class can reuse the methods and fields of that class.

 Class: Class is a set of objects which shares common characteristics/ behavior and common
properties/ attributes. Class is not a real-world entity. It is just a template or blueprint or
prototype from which objects are created.

 Super Class/Parent Class: The class whose features are inherited is known as a superclass(or
a base class or a parent class).

 Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a
derived class, extended class, or child class). The subclass can add its own fields and methods
in addition to the superclass fields and methods.

 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.

 How to Use Inheritance in Java?


 The extends keyword is used for inheritance in Java.
Using the extends keyword indicates you are derived from
an existing class. In other words, “extends” refers to
increased functionality.
 Syntax :
 class DerivedClass extends BaseClass
{
//methods and fields
}
Java Inheritance Types

Below are the different types of inheritance which are supported by Java.

1. Single Inheritance

2. Multilevel Inheritance

3. Hierarchical Inheritance

4. Multiple Inheritance

5. Hybrid Inheritance
1. Single Inheritance

In single inheritance, a sub-class is derived from only one super class. It inherits the properties and
behavior of a single-parent class. Sometimes, it is also known as simple inheritance. In the below
figure, ‘A’ is a parent class and ‘B’ is a child class. The class ‘B’ inherits all the properties of the class
‘A’.

2. Multilevel Inheritance

In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived
class also acts as the base class for other classes. In the below image, class A serves as a base class
for the derived class B, which in turn serves as a base class for the derived class C. In Java, a class
cannot directly access the grandparent’s members.

Multilevel Inheritance

3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass.
In the below image, class A serves as a base class for the derived classes B, C, and D.

4. Multiple Inheritance (Through Interfaces)

In Multiple inheritances, one class can have more than one superclass and inherit features from all
parent classes. Please note that Java does not support multiple inheritances with classes. In Java, we
can achieve multiple inheritances only through Interfaces. In the image below, Class C is derived from
interfaces A and B.

Multiple Inheritance

5. Hybrid Inheritance

It is a mix of two or more of the above types of inheritance. Since Java doesn’t support multiple
inheritances with classes, hybrid inheritance involving multiple inheritance is also not possible with
classes. In Java, we can achieve hybrid inheritance only through Interfaces if we want to involve
multiple inheritance to implement Hybrid inheritance.
However, it is important to note that Hybrid inheritance does not necessarily require the use of
Multiple Inheritance exclusively. It can be achieved through a combination of Multilevel Inheritance
and Hierarchical Inheritance with classes, Hierarchical and Single Inheritance with classes. Therefore,
it is indeed possible to implement Hybrid inheritance using classes alone, without relying on multiple
inheritance type.

Advantages Of Inheritance in Java:

1. Code Reusability: Inheritance allows for code reuse and reduces the amount of code that
needs to be written. The subclass can reuse the properties and methods of the superclass,
reducing duplication of code.

2. Abstraction: Inheritance allows for the creation of abstract classes that define a common
interface for a group of related classes. This promotes abstraction and encapsulation, making
the code easier to maintain and extend.

3. Class Hierarchy: Inheritance allows for the creation of a class hierarchy, which can be used to
model real-world objects and their relationships.

4. Polymorphism: Inheritance allows for polymorphism, which is the ability of an object to take
on multiple forms. Subclasses can override the methods of the superclass, which allows
them to change their behavior in different ways.

Disadvantages of Inheritance in Java:

1. Complexity: Inheritance can make the code more complex and harder to understand. This is
especially true if the inheritance hierarchy is deep or if multiple inheritances is used.

2. Tight Coupling: Inheritance creates a tight coupling between the superclass and subclass,
making it difficult to make changes to the superclass without affecting the subclass.

Conclusion

Let us check some important points from the article are mentioned below:
 Default superclass: Except Object class, which has no superclass, every class has one and
only one direct superclass (single inheritance). In the absence of any other explicit
superclass, every class is implicitly a subclass of the Object class.

 Superclass can only be one: A superclass can have any number of subclasses. But a subclass
can have only one superclass. This is because Java does not support multiple inheritances
with classes. Although with interfaces, multiple inheritances are supported by Java.

 Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested
classes) from its superclass. Constructors are not members, so they are not inherited by
subclasses, but the constructor of the superclass can be invoked from the subclass.

 Private member inheritance: A subclass does not inherit the private members of its parent
class. However, if the superclass has public or protected methods(like getters and setters) for
accessing its private fields, these can also be used by the subclass.

Packages

Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
Packages are used for:

 Preventing naming conflicts. For example there can be two classes with name Employee in
two packages, college.staff.cse.Employee and college.staff.ee.Employee

 Making searching/locating and usage of classes, interfaces, enumerations and annotations


easier

 Providing controlled access: protected and default have package level access control. A
protected member is accessible by classes in the same package and its subclasses. A default
member (without any access specifier) is accessible by classes in the same package only.

 Packages can be considered as data encapsulation (or data-hiding).

All we need to do is put related classes into packages. After that, we can simply write an import class
from existing packages and use it in our program. A package is a container of a group of related
classes where some of the classes are accessible are exposed and others are kept for internal
purpose. We can reuse existing classes from the packages as many time as we need it in our
program.

Packages help organize your Java code and prevent naming conflicts. If you’re looking to master
package creation and management in large Java applications, the Java Programming Course provides
comprehensive lessons and hands-on exercises

Package names and directory structure are closely related. For example if a package name
is college.staff.cse, then there are three directories, college, staffand cse such that cse is present
in staff and staff is present inside college. Also, the directory college is accessible
through CLASSPATH variable, i.e., path of parent directory of college is present in CLASSPATH. The
idea is to make sure that classes are easy to locate.

Package naming conventions : Packages are named in reverse order of domain names, i.e.,
org.geeksforgeeks.practice. For example, in a college, the recommended convention is
college.tech.cse, college.tech.ee, college.art.history, etc.
Adding a class to a Package : We can add more classes to a created package by using package name
at the top of the program and saving it in the package directory. We need a new java file to define a
public class, otherwise we can add the new class to an existing .java file and recompile it.

Subpackages: Packages that are inside another package are the subpackages. These are not
imported by default, they have to imported explicitly. Also, members of a subpackage have no access
privileges, i.e., they are considered as different package for protected and default access specifiers.

SYNTAX

import java.util.*;

util is a subpackage created inside java package.

Types of packages:

Built-in Packages

These packages consist of a large number of classes which are a part of Java API.Some of the
commonly used built-in packages are:

1. java.lang: Contains language support classes(e.g classes which defines primitive data types,
math operations). This package is automatically imported.

2. java.io: Contains classes for supporting input / output operations.

3. java.util: Contains utility classes which implement data structures like Linked List, Dictionary
and support ; for Date / Time operations.

4. java.applet: Contains classes for creating Applets.

5. java.awt: Contain classes for implementing the components for graphical user interfaces
(like button , ;menus etc). 6)

6. java.net: Contain classes for supporting networking operations.


User-defined packages: These are the packages that are defined by the user. First we create a
directory myPackage (name should be same as the name of the package). Then create
the MyClass inside the directory with the first statement being the package names.

// Name of the package must be same as the directory


// under which this file is saved
package myPackage;

public class MyClass


{
public void getNames(String s)
{
System.out.println(s);
}
}

Now we can use the MyClass class in our program.

/* import 'MyClass' class from 'names' myPackage */


import myPackage.MyClass;

public class PrintName


{
public static void main(String args[])
{
// Initializing the String variable
// with a value
String name = "GeeksforGeeks";

// Creating an instance of class MyClass in


// the package.
MyClass obj = new MyClass();

obj.getNames(name);
}
}

Note : MyClass.java must be saved inside the myPackage directory since it is a part of the package.

Using Static Import

Static import is a feature introduced in Java programming language ( versions 5 and above ) that
allows members ( fields and methods ) defined in a class as public static to be used in Java code
without specifying the class in which the field is defined. Following program demonstrates static
import:

Java

// Note static keyword after import.

import static java.lang.System.*;


class StaticImportDemo {

public static void main(String args[])

// We don't need to use 'System.out'

// as imported using static.

out.println("GeeksforGeeks");

Output:

GeeksforGeeKS

Interfaces

An Interface in Java programming language is defined as an abstract type used to specify the
behavior of a class. An interface in Java is a blueprint of a behavior. A Java interface contains static
constants and abstract methods.

What are Interfaces in Java?

The interface in Java is a mechanism to achieve abstraction. Traditionally, an interface could only
have abstract methods (methods without a body) and public, static, and final variables by default. It
is used to achieve abstraction and multiple inheritances in Java. In other words, interfaces primarily
define methods that other classes must implement. Java Interface also represents the IS-A
relationship.

To deepen your understanding of interfaces and how they are used in modern Java applications,
the Java Programming Course offers structured lessons and coding exercises to solidify your learning.

In Java, the abstract keyword applies only to classes and methods, indicating that they cannot be
instantiated directly and must be implemented.

When we decide on a type of entity by its behavior and not via attribute we should define it as an
interface.

Syntax for Java Interfaces

interface {
// declare constant fields
// declare methods that abstract
// by default.
}

To declare an interface, use the interface keyword. It is used to provide total abstraction. That means
all the methods in an interface are declared with an empty body and are public and all fields are
public, static, and final by default. A class that implements an interface must implement all the
methods declared in the interface. To implement the interface, use the implements keyword.

Uses of Interfaces in Java

Uses of Interfaces in Java are mentioned below:

 It is used to achieve total abstraction.

 Since java does not support multiple inheritances in the case of class, by using an interface it
can achieve multiple inheritances.

 Any class can extend only one class, but can implement multiple interfaces.

 It is also used to achieve loose coupling.

 Interfaces are used to implement abstraction.

So, the question arises why use interfaces when we have abstract classes?

The reason is, abstract classes may contain non-final variables, whereas variables in the interface are
final, public, and static.

// A simple interface
interface Player
{
final int id = 10;
int move();
}

Relationship Between Class and Interface

A class can extend another class, and similarly, an interface can extend another interface. However,
only a class can implement an interface, and the reverse (an interface implementing a class) is not
allowed.

Difference Between Class and Interface

Although Class and Interface seem the same there have certain differences between Classes and
Interface. The major differences between a class and an interface are mentioned below:
Class Interface

In class, you can instantiate variables and In an interface, you must initialize variables as
create an object. they are final but you can’t create an object.

A class can contain concrete (with The interface cannot contain concrete (with
implementation) methods implementation) methods.

The access specifiers used with classes are


In Interface only one specifier is used- Public.
private, protected, and public.

Advantages of Interfaces in Java

The advantages of using interfaces in Java are as follows:

 Without bothering about the implementation part, we can achieve the security of the
implementation.

 In Java, multiple inheritances are not allowed, however, you can use an interface to make use
of it as you can implement more than one interface.

Multiple Inheritance in Java Using Interface


Multiple Inheritance is an OOPs concept that can’t be implemented in Java using classes.
But we can use multiple inheritances in Java using Interface. let us check this with an
example.

Exception handling

Exception handling is one of the most important feature of java programming that
allows us to handle the runtime errors caused by exceptions. In this guide, you will
learn what is an exception, types of it, exception classes and how to handle exceptions
in java with examples.
What is an exception?

An Exception is an unwanted event that interrupts the normal flow of the program.
When an exception occurs program execution gets terminated. In such cases we get a
system generated error message.

The good thing about exceptions is that java developer can handle these exception in
such a way so that the program doesn’t get terminated abruptly and the user get a
meaningful error message.

For example: You are writing a program for division and both the numbers are
entered by user. In the following example, user can enter any number, if user enters
the second number (divisor) as 0 then the program will terminate and throw an
exception because dividing a number by zero gives undefined result. To get the user
input, we are using Scanner class. Notice the output of the program.

Types of Exception in Java with Examples

Java defines several types of exceptions that relate to its various class libraries. Java also
allows users to define their own exceptions.

Built-in Exceptions:

Built-in exceptions are the exceptions that are available in Java libraries. These exceptions
are suitable to explain certain error situations. Below is the list of important built-in
exceptions in Java.

1. ArithmeticException: It is thrown when an exceptional condition has occurred in


an arithmetic operation.
2. ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been
accessed with an illegal index. The index is either negative or greater than or equal
to the size of the array.
3. ClassNotFoundException: This Exception is raised when we try to access a class
whose definition is not found
4. FileNotFoundException: This Exception is raised when a file is not accessible or
does not open.
5. IOException: It is thrown when an input-output operation failed or interrupted
6. InterruptedException: It is thrown when a thread is waiting, sleeping, or doing
some processing, and it is interrupted.
7. NoSuchFieldException: It is thrown when a class does not contain the field (or
variable) specified
8. NoSuchMethodException: It is thrown when accessing a method that is not found.
9. NullPointerException: This exception is raised when referring to the members of a
null object. Null represents nothing
10. NumberFormatException: This exception is raised when a method could not
convert a string into a numeric format.
11. RuntimeException: This represents an exception that occurs during runtime.
12. StringIndexOutOfBoundsException: It is thrown by String class methods to
indicate that an index is either negative or greater than the size of the string
13. IllegalArgumentException : This exception will throw the error or error statement
when the method receives an argument which is not accurately fit to the given
relation or condition. It comes under the unchecked exception.
14. IllegalStateException : This exception will throw an error or error message when
the method is not accessed for the particular operation in the application. It comes
under the unchecked exception.

User-Defined Exceptions

Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In
such cases, the user can also create exceptions which are called ‘user-defined Exceptions’.

The following steps are followed for the creation of a user-defined Exception.

 The user should create an exception class as a subclass of the Exception class. Since
all the exceptions are subclasses of the Exception class, the user should also make
his class a subclass of it. This is done as:

class MyException extends Exception

 We can write a default constructor in his own exception class.

MyException(){}

 We can also create a parameterized constructor with a string as a parameter.


We can use this to store exception details. We can call the superclass(Exception)
constructor from this and send the string there.

MyException(String str)

super(str);

}
 To raise an exception of a user-defined type, we need to create an object to his
exception class and throw it using the throw clause, as:

MyException me = new MyException(“Exception details”);

throw me;

 The following program illustrates how to create your own exception class
MyException.
 Details of account numbers, customer names, and balance amounts are taken in the
form of three arrays.
 In main() method, the details are displayed using a for-loop. At this time, a check is
done if in any account the balance amount is less than the minimum balance amount
to be apt in the account.
 If it is so, then MyException is raised and a message is displayed “Balance amount
is less”.

Exception handling

Exception Handling in Java

Here, we are trying to handle the exception that is raised in the above program. You can see
that the program ran fine and gave a meaningful error message which can be understood by
the user.

Note: Do not worry about the try and catch blocks as we have covered these topics in detail
in separate tutorials. For now just remember that the code that can throw exception needs to
be inside try block and the catch block follows the try block, where the exception error
message is set.

import java.util.Scanner;

public class JavaExample {

public static void main(String[] args) {

int num1, num2;

Scanner scan = new Scanner(System.in);

System.out.print("Enter first number(dividend): ");

num1 = scan.nextInt();
System.out.print("Enter second number(divisor): ");

num2 = scan.nextInt();

try {

int div = num1 / num2;

System.out.println("Quotient: "+div);

}catch(ArithmeticException e){

System.out.println("Do not enter divisor as zero.");

System.out.println("Error Message: "+e);

Output:

If an exception occurs, which has not been handled by programmer then program execution
gets terminated and a system generated error message is shown to the user.

These system generated messages are not user friendly so a user will not be able to
understand what went wrong. In order to let them know the reason in simple language, we
handle exceptions. We handle such exceptions and then prints a user friendly warning
message to user, which lets them correct the error as most of the time exception occurs due
to bad data provided by user.

Why we handle the exceptions?

Exception handling ensures that the flow of the program doesn’t break when an exception
occurs. For example, if a program has bunch of statements and an exception occurs mid
way after executing certain statements then the statements, that occur after the statement
that caused the exception will not execute and the program will terminate abruptly. By
handling we make sure that all the statements execute and the flow of execution of program
doesn’t break.
Why an exception occurs?

There can be several reasons that can cause a program to throw exception. For
example: Opening a non-existing file in your program, Network connection problem, bad
input data provided by user etc. Let’s see few scenarios:
1. ArithmeticException:
We have already seen this exception in our example above. This exception occurs when we
divide a number by zero. If we divide any number by zero.

int num = 25/0;//ArithmeticException

2. NullPointerException:
When a variable contains null value and you are performing an operation on the variable.
For example, if a string variable contains null and you are comparing with another string.
Another example is when you are trying to print the length of the string that contains null.

String str = null;

//NullPointerException

System.out.println(str.length());

3. NumberFormatException:
This exception occurs where there is a type mismatch. Let’s say you are trying to perform
an arithmetic operator on a string variable.

String str = "beginnersbook.com";

//NumberFormatException

int num=Integer.parseInt(str);

4. ArrayIndexOutOfBoundsException:
When you are trying to access the array index which is beyond the size of array. Here, we
are trying to access the index 8 (9th element) but the size of the array is only 3. This
exception occurs when you are accessing index which doesn’t exist.

int arr[]=new int[3];

//ArrayIndexOutOfBoundsException

arr[8]=100;
Difference between error and exception

Errors indicate that something went wrong which is not in the scope of a programmer to
handle. You cannot handle an error. Also, the error doesn’t occur due to bad data entered by
user rather it indicates a system failure, disk crash or resource unavailability.

Exceptions are events that occurs during runtime due to bad data entered by user or an
error in programming logic. A programmer can handle such conditions and take necessary
corrective actions. Few examples:
NullPointerException – When you try to use a reference that points to null.
ArithmeticException – When bad data is provided by user, for example, when you try to
divide a number by zero this exception occurs because dividing a number by zero is
undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an array out
of its bounds, for example array size is 5 (which means it has five elements) and you are
trying to access the 10th element.

Types of exceptions
There are two types of exceptions in Java:
1) Checked exceptions
2) Unchecked exceptions

I have covered these topics in detail in a separate tutorial: Checked and Unchecked
exceptions in Java.

1) Checked exceptions

All exceptions other than Runtime Exceptions are known as Checked exceptions as the
compiler checks them during compilation to see whether the programmer has handled them
or not. If these exceptions are not handled/declared in the program, you will get
compilation error. For example, SQLException, IOException, ClassNotFoundException
etc.

2) Unchecked Exceptions

Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not
checked at compile-time so compiler does not check whether the programmer has handled
them or not but it’s the responsibility of the programmer to handle these exceptions and
provide a safe exit.

For example, ArithmeticException, NullPointerException,


ArrayIndexOutOfBoundsException etc. The examples that we seen above were unchecked
exceptions.
Note: Compiler doesn’t enforce you to catch such exceptions or ask you to declare it in the
method using throws keyword.

Frequently used terms in Exception handling


try: The code that can cause the exception, is placed inside try block. The try block detects
whether the exception occurs or not, if exception occurs, it transfer the flow of program to
the corresponding catch block or finally block. A try block is always followed by either a
catch block or finally block.

catch: The catch block is where we write the logic to handle the exception, if it occurs. A
catch block only executes if an exception is caught by the try block. A catch block is
always accompanied by a try block.

finally: This block always executes whether an exception is occurred or not.

throw: It is used to explicitly throw an exception. It can be used to throw a checked or


unchecked exception.

throws: It is used in method signature. It indicates that this method might throw one of the
declared exceptions. While calling such methods, we need to handle the exceptions using
try-catch block.
STREAM I/O BASED
Stream In Java

Last Updated : 04 Oct, 2024


Introduced in Java 8, Stream API is used to process collections of objects. A stream in Java
is a sequence of objects that supports various methods that can be pipelined to produce the
desired result.

Use of Stream in Java:

The uses of Stream in Java are mentioned below:

1. Stream API is a way to express and process collections of objects.

2. Enable us to perform operations like filtering, mapping, reducing, and sorting.

How to Create Java Stream?

Java Stream Creation is one of the most basic steps before considering the functionalities of
the Java Stream. Below is the syntax given for declaring Java Stream.

Streams in Java make data processing more efficient by supporting functional-style


operations. To understand how to use streams effectively in different scenarios, the Java
Programming Course provides a complete guide with examples of stream operations and
optimizations.

Syntax:
Stream<T> stream;

Here T is either a class, object, or data type depending upon the declaration.

Java Stream Features

The features of Java stream are mentioned below:

 A stream is not a data structure instead it takes input from the Collections, Arrays or
I/O channels.

 Streams don’t change the original data structure, they only provide the result as per
the pipelined methods.

 Each intermediate operation is lazily executed and returns a stream as a result, hence
various intermediate operations can be pipelined. Terminal operations mark the end
of the stream and return the result.

Different Operations On Streams

There are two types of Operations in Streams:

1. Intermediate Operations

2. Terminate Operations

Intermediate Operations

Intermediate Operations are the types of operations in which multiple methods are chained
in a row.

Characteristics of Intermediate Operations


 Methods are chained together.

 Intermediate operations transform a stream into another stream.

 It enables the concept of filtering where one method filters data and passes it to
another method after processing.

Benefit of Java Stream

There are some benefits because of which we use Stream in Java as mentioned below:

 No Storage

 Pipeline of Functions

 Laziness

 Can be infinite

 Can be parallelized

 Can be created from collections, arrays, Files Lines, Methods in Stream, IntStream
etc.

Important Intermediate Operations

There are a few Intermediate Operations mentioned below:

1. map()

The map method is used to return a stream consisting of the results of applying the given
function to the elements of this stream.

Syntax:

<R> Stream<R> map(Function<? super T, ? extends R> mapper)

2. filter()

The filter method is used to select elements as per the Predicate passed as an argument.

Syntax:

Stream<T> filter(Predicate<? super T> predicate)

3. sorted()

The sorted method is used to sort the stream.

Syntax:
Stream<T> sorted()
Stream<T> sorted(Comparator<? super T> comparator)

4.flatMap()

Syntax:

The flatMap operation in Java Streams is used to flatten a stream of collections into a single
stream of elements.

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)

5. distinct ()
Removes duplicate elements. It returns a stream consisting of the distinct elements
(according to Object.equals(Object)).

Syntax:

Stream<T> distinct()

6. peek()

Performs an action on each element without modifying the stream. It returns a stream
consisting of the elements of this stream, additionally performing the provided action on
each element as elements are consumed from the resulting stream.

Syntax:

Stream<T> peek(Consumer<? super T> action)

Java program that demonstrates the use of all the intermediate operations

Java

import java.util.Arrays;

import java.util.HashSet;

import java.util.List;

4
import java.util.Set;

import java.util.stream.Collectors;

public class StreamIntermediateOperationsExample {

public static void main(String[] args) {

// List of lists of names

10

List<List<String>> listOfLists = Arrays.asList(

11

Arrays.asList("Reflection", "Collection", "Stream"),

12

Arrays.asList("Structure", "State", "Flow"),

13

Arrays.asList("Sorting", "Mapping", "Reduction", "Stream")

14

);

15

16

// Create a set to hold intermediate results


17

Set<String> intermediateResults = new HashSet<>();

18

19

// Stream pipeline demonstrating various intermediate operations

20

List<String> result = listOfLists.stream()

21

.flatMap(List::stream) // Flatten the list of lists into a single stream

22

.filter(s -> s.startsWith("S")) // Filter elements starting with "S"

23

.map(String::toUpperCase) // Transform each element to uppercase

24

.distinct() // Remove duplicate elements

25

.sorted() // Sort elements

26

.peek(s -> intermediateResults.add(s)) // Perform an action (add to set) on each


element

27

.collect(Collectors.toList()); // Collect the final result into a list

28

29
// Print the intermediate results

30

System.out.println("Intermediate Results:");

31

intermediateResults.forEach(System.out::println);

32

33

// Print the final result

34

System.out.println("Final Result:");

35

result.forEach(System.out::println);

36

37

Output

Intermediate Results:

STRUCTURE

STREAM

STATE

SORTING

Final Result:

SORTING
STATE

STREAM

STRUCTURE

Explanation of the above Program:

List of Lists Creation:

 The listOfLists is created as a list containing other lists of strings.

Stream Operations:

 flatMap(List::stream): Flattens the nested lists into a single stream of strings.

 filter(s -> s.startsWith("S")): Filters the strings to only include those that start
with “S”.

 map(String::toUpperCase): Converts each string in the stream to uppercase.

 distinct(): Removes any duplicate strings.

 sorted(): Sorts the resulting strings alphabetically.

 peek(...): Adds each processed element to the intermediateResults set for


intermediate inspection.

 collect(Collectors.toList()): Collects the final processed strings into a list


called result.

The program prints the intermediate results stored in the intermediateResults set. Finally, it
prints the result list, which contains the fully processed strings after all stream operations.

This example showcases how Java Streams can be used to process and manipulate
collections of data in a functional and declarative manner, applying transformations and
filters in a sequence of operations.

Terminal Operations

Terminal Operations are the type of Operations that return the result. These Operations are
not processed further just return a final result value.

Important Terminal Operations

There are a few Terminal Operations mentioned below:

1. collect()
The collect method is used to return the result of the intermediate operations performed on
the stream.

Syntax:

<R, A> R collect(Collector<? super T, A, R> collector)

2. forEach()

The forEach method is used to iterate through every element of the stream.

Syntax:

void forEach(Consumer<? super T> action)

3. reduce()

Syntax:

The reduce method is used to reduce the elements of a stream to a single value. The reduce
method takes a BinaryOperator as a parameter.

T reduce(T identity, BinaryOperator<T> accumulator)


Optional<T> reduce(BinaryOperator<T> accumulator)

4. count()
Returns the count of elements in the stream.

Syntax:

long count()

5. findFirst()

Returns the first element of the stream, if present.

Syntax:

Optional<T> findFirst()

6. allMatch()
Checks if all elements of the stream match a given predicate.

Syntax:

boolean allMatch(Predicate<? super T> predicate)

7. anyMatch()

Checks if any element of the stream matches a given predicate.


Syntax:

boolean anyMatch(Predicate<? super T> predicate)

Here ans variable is assigned 0 as the initial value and i is added to it.

Multithreading in Java
1. Multithreading
2. Multitasking
3. Process-based multitasking
4. Thread-based multitasking
5. What is Thread

Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared


memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a


single thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking


to utilize the CPU. Multitasking can be achieved in two ways:
o Process-based Multitasking (Multiprocessing)

o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


o Each process has an address in memory. In other words, each process allocates a
separate memory area.

o A process is heavyweight.
o Cost of communication between the process is high.

o Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)


o Threads share the same address space.

o A thread is lightweight.

o Cost of communication between the thread is low.

Note: At least one process is required for each thread.


What is Thread in java

A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of


execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.
Advertisement

As shown in the above figure, a thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS, and one
process can have multiple threads.
Note: At a time one thread is executed only.
Java Thread class

Java provides Thread class to achieve thread programming. Thread class


provides constructors and methods to create and perform operations on a thread. Thread
class extends Object class and implements Runnable interface.
Java Thread Methods
S.N. Modifier and Type Method
1) void start()

2) void run()

3) static void sleep()

4) static Thread currentThread()

5) void join()

6) int getPriority()

7) void setPriority()

8) String getName()

9) void setName()

10) long getId()

11) boolean isAlive()

12) static void yield()

13) void suspend()

14) void resume()

15) void stop()


16) void destroy()

17) boolean isDaemon()

18) void setDaemon()

19) void interrupt()

20) boolean isinterrupted()

21) static boolean interrupted()

22) static int activeCount()

23) void checkAccess()

24) static boolean holdLock()

25) static void dumpStack()

26) StackTraceElement[] getStackTrace()


27) static int enumerate()

28) Thread.State getState()

29) ThreadGroup getThreadGroup()

30) String toString()

31) void notify()

32) void notifyAll()

33) void setContextClassLoader()

34) ClassLoader getContextClassLoader()

static
35) getDefaultUncaughtExceptionHandler()
Thread.UncaughtExceptionHandler

36) static void setDefaultUncaughtExceptionHandler()


Collections in Java
The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
What is Collection in Java?

A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java?

A framework provides a ready-made structure of classes and interfaces for building


software applications efficiently. It simplifies adding new features by offering reusable
components that perform similar tasks, eliminating the need to create a framework from
scratch for each new project. This approach enhances object-oriented design, making
development quicker, more consistent, and reliable.

o It provides readymade architecture.

o It represents a set of classes and interfaces.

o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It enhances code efficiency and readability by offering various data
structures, including arrays, linked lists, trees, and hash tables, tailored to different
programming needs. It has:

1. Interfaces and its implementations, i.e., classes

2. Algorithm

Why Collection Framework?

Before the Collection Framework was introduced in JDK 1.2, Java's approach to collections
was using Arrays, Vectors, and Hash tables lacked a common interface. This meant each
type of collection had its own set of methods, syntax, and constructors, with no
standardization or correlation between them.

This made it difficult for users to remember the diverse functionalities of each collection
type and hindered code consistency and reusability. The disparate nature of these
collections highlighted the need for a unified Collection Framework to simplify and
standardize collection operations in Java.

What is a framework in Java?

A framework provides a ready-made structure of classes and interfaces for building


software applications efficiently. It simplifies adding new features by offering reusable
components that perform similar tasks, eliminating the need to create a framework from
scratch for each new project. This approach enhances object-oriented design, making
development quicker, more consistent, and reliable.

o It provides readymade architecture.

o It represents a set of classes and interfaces.

o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It enhances code efficiency and readability by offering various data
structures, including arrays, linked lists, trees, and hash tables, tailored to different
programming needs. It has:

1. Interfaces and its implementations, i.e., classes

2. Algorithm

Why Collection Framework?

Before the Collection Framework was introduced in JDK 1.2, Java's approach to collections
was using Arrays, Vectors, and Hash tables lacked a common interface. This meant each
type of collection had its own set of methods, syntax, and constructors, with no
standardization or correlation between them.

This made it difficult for users to remember the diverse functionalities of each collection
type and hindered code consistency and reusability. The disparate nature of these
collections highlighted the need for a unified Collection Framework to simplify and
standardize collection operations in Java.

Applet

Let’s understand first how many Package does GUI support:

1. AWT(Abstract Window Toolkit)


2. Swing

Throwback of making GUI application:


Java was launched on 23-Jan-1996(JDK 1.0) and at that time it only supported
CUI(Character User Interface) application. But in 1996 VB(Visual Basic) of Microsoft was
preferred for GUI programming. So the Java developers in hurry(i.e within 7 days) have
given the support for GUI from Operating System(OS). Now, the components like button,
etc. were platform-dependent(i.e in each platform there will be different size, shape button).
But they did the intersection of such components from all platforms and gave a small
library which contains these intersections and it is available in AWT(Abstract Window
Toolkit) technology but it doesn’t have advanced features like dialogue box, etc.

Now to run Applet, java needs a browser and at that time only “Internet Explorer” was
there of Microsoft but Microsoft believes in monopoly. So “SUN Micro-System”(the
company which developed Java) contracted with other company known as
“Netscape”(which developed Java Script) and now the “Netscape” company is also known
as “Mozilla Firefox” which we all know is a browser. Now, these two companies have
developed a technology called “SWING” and the benefit is that the SWING components
are produced by Java itself. Therefore now it is platform-independent as well as some
additional features have also been added which were not in AWT technology. So we can
say that SWING is much more advanced as compared to AWT technology.

What is Applet?
An applet is a Java program that can be embedded into a web page. It runs inside the web
browser and works at client side. An applet is embedded in an HTML page using the
APPLET or OBJECT tag and hosted on a web server.
Applets are used to make the website more dynamic and entertaining.

Important points :

1. All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.


2. Applets are not stand-alone programs. Instead, they run within either a web browser
or an applet viewer. JDK provides a standard applet viewer tool called applet
viewer.
3. In general, execution of an applet does not begin at main() method.
4. Output of an applet window is not performed by System.out.println(). Rather it is
handled with various AWT methods, such as drawString().

Life cycle of an applet :


It is important to understand the order in which the various methods shown in the above
image are called. When an applet begins, the following methods are called, in this
sequence:

1. init( )
2. start( )
3. paint( )

When an applet is terminated, the following sequence of method calls takes place:

1. stop( )
2. destroy( )

Let’s look more closely at these methods.


1. init( ) : The init( ) method is the first method to be called. This is where you should
initialize variables. This method is called only once during the run time of your applet.

2. start( ) : The start( ) method is called after init( ). It is also called to restart an applet
after it has been stopped. Note that init( ) is called once i.e. when the first time an applet is
loaded whereas start( ) is called each time an applet’s HTML document is displayed
onscreen. So, if a user leaves a web page and comes back, the applet resumes execution
at start( ).

3. paint( ) : The paint( ) method is called each time an AWT-based applet’s output must be
redrawn. This situation can occur for several reasons. For example, the window in which
the applet is running may be overwritten by another window and then uncovered. Or the
applet window may be minimized and then restored.
paint( ) is also called when the applet begins execution. Whatever the cause, whenever the
applet must redraw its output, paint( ) is called.
The paint( ) method has one parameter of type Graphics. This parameter will contain the
graphics context, which describes the graphics environment in which the applet is running.
This context is used whenever output to the applet is required.
Note: This is the only method among all the method mention above, which is
parameterized. It’s prototype is
public void paint(Graphics g)
where g is an object reference of class Graphic.

Now the Question Arises:

Q. In the prototype of paint() method, we have created an object reference without creating
its object. But how is it possible to create object reference without creating its object?

Ans. Whenever we pass object reference in arguments then the object will be provided by
its caller itself. In this case the caller of paint() method is browser, so it will provide an
object. The same thing happens when we create a very basic program in normal Java
programs. For Example:

public static void main(String []args){}

Here we have created an object reference without creating its object but it still runs because
it’s caller,i.e JVM will provide it with an object.

4. stop( ) : The stop( ) method is called when a web browser leaves the HTML document
containing the applet—when it goes to another page, for example. When stop( ) is called,
the applet is probably running. You should use stop( ) to suspend threads that don’t need to
run when the applet is not visible. You can restart them when start( ) is called if the user
returns to the page.

5. destroy( ) : The destroy( ) method is called when the environment determines that your
applet needs to be removed completely from memory. At this point, you should free up any
resources the applet may be using. The stop( ) method is always called before destroy( ).

Creating Hello World applet :


Let’s begin with the HelloWorld applet :
 Java

// A Hello World Applet

// Save file as HelloWorld.java

import java.applet.Applet;

import java.awt.Graphics;

// HelloWorld class extends Applet

public class HelloWorld extends Applet

// Overriding paint() method

@Override

public void paint(Graphics g)

g.drawString("Hello World", 20, 20);

Explanation:

1. The above java program begins with two import statements. The first import
statement imports the Applet class from applet package. Every AWT-based(Abstract
Window Toolkit) applet that you create must be a subclass (either directly or
indirectly) of Applet class. The second statement import the Graphics class from
AWT package.
2. The next line in the program declares the class HelloWorld. This class must be
declared as public because it will be accessed by code that is outside the program.
Inside HelloWorld, paint( ) is declared. This method is defined by the AWT and
must be overridden by the applet.
3. Inside paint( ) is a call to drawString( ), which is a member of the Graphics class.
This method outputs a string beginning at the specified X,Y location. It has the
following general form:

void drawString(String message, int x, int y)

Here, message is the string to be output beginning at x,y. In a Java window, the upper-left
corner is location 0,0. The call to drawString( ) in the applet causes the message “Hello
World” to be displayed beginning at location 20,20.

Notice that the applet does not have a main( ) method. Unlike Java programs, applets do
not begin execution at main( ). In fact, most applets don’t even have a main( ) method.
Instead, an applet begins execution when the name of its class is passed to an applet viewer
or to a network browser.

Running the HelloWorld Applet :


After you enter the source code for HelloWorld.java, compile in the same way that you
have been compiling java programs(using javac command). However, running HelloWorld
with the java command will generate an error because it is not an application.

java HelloWorld

Error: Main method not found in class HelloWorld,

please define the main method as:

public static void main(String[] args)

There are two standard ways in which you can run an applet :

1. Executing the applet within a Java-compatible web browser.


2. Using an applet viewer, such as the standard tool, applet-viewer. An applet viewer
executes your applet in a window. This is generally the fastest and easiest way to
test your applet.

Each of these methods is described next.

1. Using java enabled web browser : To execute an applet in a web browser we have to
write a short HTML text file that contains a tag that loads the applet. We can use APPLET
or OBJECT tag for this purpose. Using APPLET, here is the HTML file that executes
HelloWorld :

<applet code="HelloWorld" width=200 height=60>

</applet>
The width and height statements specify the dimensions of the display area used by the
applet. The APPLET tag contains several other options. After you create this html file, you
can use it to execute the applet.

NOTE : Chrome and Firefox no longer supports NPAPI (technology required for Java
applets). Refer here

2. Using appletviewer : This is the easiest way to run an applet. To execute HelloWorld
with an applet viewer, you may also execute the HTML file shown earlier. For example, if
the preceding HTML file is saved with
RunHelloWorld.html, then the following command line will run HelloWorld :

appletviewer RunHelloWorld.html

3. appletviewer with java source file : If you include a comment at the head of your Java
source code file that contains the APPLET tag then your code is documented with a
prototype of the necessary HTML statements, and you can run your compiled applet merely
by starting the applet viewer with your Java source code file. If you use this method, the
HelloWorld source file looks like this :

 Java

//code to illustrate paint

//method gets called again

//and again

import java.applet.*;// used

//to access showStatus()

import java.awt.*;//Graphic
//class is available in this package

import java.util.Date;// used

//to access Date object

public class GFG extends Applet

public void paint(Graphics g)

Date dt = new Date();

super.showStatus("Today is" + dt);

//in this line, super keyword is

// avoidable too.

>

With this approach, first compile HelloWorld.java file and then simply run the below
command to run applet :

appletviewer HelloWorld

To prove above mentioned point,i.e paint is called again and again.

To prove this, let’s first study what is “Status Bar” in Applet:


“Status Bar” is available in the left bottom window of an applet. To use the status bar and
write something in it, we use method showStatus() whose prototype is
public void showStatus(String)
By default status bar shows “Applet Started”
By default background color is white.

To prove paint() method is called again and again, here is the code:

Note: This code is with respect to Netbeans IDE.

 Java
//code to illustrate paint

//method gets called again

//and again

import java.applet.*;// used

//to access showStatus()

import java.awt.*;//Graphic

//class is available in this package

import java.util.Date;// used

//to access Date object

public class GFG extends Applet

public void paint(Graphics g)

Date dt = new Date();

super.showStatus("Today is" + dt);

//in this line, super keyword is

// avoidable too.

Note:- Here we can see that if the screen is maximized or minimized we will get an updated
time. This shows that paint() is called again and again.

Features of Applets over HTML

 Displaying dynamic web pages of a web application.


 Playing sound files.
 Displaying documents
 Playing animations

Restrictions imposed on Java applets

Due to security reasons, the following restrictions are imposed on Java applets:

1. An applet cannot load libraries or define native methods.


2. An applet cannot ordinarily read or write files on the execution host.
3. An applet cannot read certain system properties.
4. An applet cannot make network connections except to the host that it came from.
5. An applet cannot start any program on the host that’s executing it.

Introduction to Java Swing

Last Updated : 30 Jul, 2024



Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window
Toolkit [AWT]. Java Swing offers much-improved functionality over AWT, new
components, expanded components features, and excellent event handling with drag-and-
drop support.

Introduction of Java Swing

Swing has about four times the number of User Interface [UI] components as AWT and is
part of the standard Java distribution. By today’s application GUI requirements, AWT is a
limited implementation, not quite capable of providing the components required for
developing complex GUIs required in modern commercial applications. The AWT
component set has quite a few bugs and does take up a lot of system resources when
compared to equivalent Swing resources. Netscape introduced its Internet Foundation
Classes [IFC] library for use with Java. Its Classes became very popular with programmers
creating GUI’s for commercial applications.

 Swing is a Set of API (API- Set of Classes and Interfaces)

 Swing is Provided to Design Graphical User Interfaces

 Swing is an Extension library to the AWT (Abstract Window Toolkit)

 Includes New and improved Components that have been enhancing the looks and
Functionality of GUIs’

 Swing can be used to build (Develop) The Standalone swing GUI Apps as Servlets
and Applets

 It Employs model/view design architecture.


 Swing is more portable and more flexible than AWT, the Swing is built on top of
the AWT.

 Swing is Entirely written in Java.

 Java Swing Components are Platform-independent, and The Swing Components are
lightweight.

 Swing Supports a Pluggable look and feel and Swing provides more powerful
components.

 such as tables, lists, Scrollpanes, Colourchooser, tabbed pane, etc.

 Further Swing Follows MVC.

Difference between Java Swing and Java AWT

There are certain points from which Java Swing is different than Java AWT as mentioned
below:

Java AWT Java Swing

Java AWT is an API to develop GUI Swing is a part of Java Foundation Classes
applications in Java. and is used to create various applications.

The components of Java Swing are


Components of AWT are heavy weighted.
lightweight.

Components are platform dependent. Components are platform independent.

Execution Time is more than Swing. Execution Time is less than AWT.

AWT components require java.awt Swing components requires javax.swing


package. package.

To know more about the topic, refer to Java Swing vs Java AWT .

What is JFC?

JFC stands for Java Foundation Classes. JFC is the set of GUI components that simplify
desktop Applications. Many programmers think that JFC and Swing are one and the same
thing, but that is not so. JFC contains Swing [A UI component package] and quite a number
of other items:
 Cut and paste: Clipboard support.

 Accessibility features: Aimed at developing GUIs for users with disabilities.

 The Desktop Colors Features were first introduced in Java 1.1

 Java 2D: it has Improved colors, images, and text support.

Features Of Swing Class

 Pluggable look and feel.

 Uses MVC architecture.

 Lightweight Components

 Platform Independent

 Advanced features such as JTable, JTabbedPane, JScollPane, etc.

 Java is a platform-independent language and runs on any client machine, the GUI
look and feel, owned and delivered by a platform-specific O/S, simply does not
affect an application’s GUI constructed using Swing components.

 Lightweight Components: Starting with the JDK 1.1, its AWT-supported


lightweight component development. For a component to qualify as lightweight, it
must not depend on any non-Java [O/s based) system classes. Swing components
have their own view supported by Java’s look and feel classes.

 Pluggable Look and Feel: This feature enable the user to switch the look and feel
of Swing components without restarting an application. The Swing library supports
components’ look and feels that remain the same across all platforms wherever the
program runs. The Swing library provides an API that gives real flexibility in
determining the look and feel of the GUI of an application

 Highly customizable – Swing controls can be customized in a very easy way as


visual appearance is independent of internal representation.

 Rich controls– Swing provides a rich set of advanced controls like Tree
TabbedPane, slider, colorpicker, and table controls.

Swing Classes Hierarchy


The MVC Connection

 In general, a visual component is a composite of three distinct aspects:

1. The way that the component looks when rendered on the screen.

2. The way such that the component reacts to the user.

3. The state information associated with the component.

 Over the years, one component architecture has proven itself to be exceptionally
effective: – Model-View-Controller or MVC for short.

 In MVC terminology, the model corresponds to the state information associated


with the Component.

 The view determines how the component is displayed on the screen, including any
aspects of the view that are affected by the current state of the model.

 The controller determines how the component reacts to the user.

The simplest Swing components have capabilities far beyond AWT components as
follows:

 Swing buttons and labels can be displaying images instead of or in addition to text.

 The borders around most Swing components can be changed easily. For example, it
is easy to put a 1-pixel border around the outside of a Swing label.

 Swing components do not have to be rectangular. Buttons, for example, can be


round.

 Now The Latest Assertive technologies such as screen readers can easily get
information from Swing components. Example: A screen reader tool can easily
capture the text that is displayed on a Swing button or label.
Example of Java Swing Programs

Example 1: Develop a program using label (swing) to display the message “GFG WEB
Site Click”:

Java

// Java program using label (swing)

// to display the message “GFG WEB Site Click”

import java.io.*;

import javax.swing.*;

// Main class

class GFG {

// Main driver method

public static void main(String[] args)

// Creating instance of JFrame

JFrame frame = new JFrame();

// Creating instance of JButton

JButton button = new JButton(" GFG WebSite Click");

// x axis, y axis, width, height

button.setBounds(150, 200, 220, 50);

// adding button in JFrame

frame.add(button);

// 400 width and 500 height

frame.setSize(500, 600);

// using no layout managers

frame.setLayout(null)

// making the frame visible


frame.setVisible(true);

Output:

Introduction to JDBC (Java Database Connectivity)


Last Updated : 10 Jun, 2024

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and
execute the query with the database. It is a specification from Sun Microsystems that
provides a standard abstraction(API or Protocol) for Java applications to communicate with
various databases. It provides the language with Java database connectivity standards. It is
used to write programs required to access databases. JDBC, along with the database driver,
can access databases and spreadsheets. The enterprise data stored in a relational
database(RDB) can be accessed with the help of JDBC APIs.

Definition of JDBC(Java Database Connectivity)


JDBC is an API(Application programming interface) used in Java programming to interact
with databases. The classes and interfaces of JDBC allow the
application to send requests made by users to the specified database. The current version
of JDBC is JDBC 4.3, released on 21st September 2017.

Purpose of JDBC

Enterprise applications created using the JAVA EE technology need to interact with
databases to store application-specific information. So, interacting with a database requires
efficient database connectivity, which can be achieved by using the ODBC(Open database
connectivity) driver. This driver is used with JDBC to interact or communicate with various
kinds of databases such as Oracle, MS Access, Mysql, and SQL server database.

Components of JDBC

There are generally four main components of JDBC through which it can interact with a
database. They are as mentioned below:

1. JDBC API: It provides various methods and interfaces for easy communication with the
database. It provides two packages as follows, which contain the java SE and Java EE
platforms to exhibit WORA(write once run anywhere) capabilities. The java.sql package
contains interfaces and classes of JDBC API.

java.sql: This package provides APIs for data access and data process in a relational
database, included in
Java Standard Edition (java SE)
javax.sql: This package extends the functionality of java package by providing datasource
interface for
establishing connection pooling, statement pooling with a data source, included
in
Java Enterprise Edition (java EE)

It also provides a standard to connect a database to a client application.

2. JDBC Driver manager: It loads a database-specific driver in an application to establish


a connection with a database. It is used to make a database-specific call to the database to
process the user request.

3. JDBC Test suite: It is used to test the operation(such as insertion, deletion, updation)
being performed by JDBC Drivers.

4. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. This bridge
translates the JDBC method call to the ODBC function call. It makes use of
the sun.jdbc.odbc package which includes a native library to access ODBC characteristics.

Architecture of JDBC
Description:

1. Application: It is a java applet or a servlet that communicates with a data source.

2. The JDBC API: The JDBC API allows Java programs to execute SQL statements
and retrieve results. Some of the important interfaces defined in JDBC API are as
follows: Driver interface , ResultSet Interface , RowSet Interface ,
PreparedStatement interface, Connection inteface, and cClasses defined in JDBC
API are as follows: DriverManager class, Types class, Blob class, clob class.

3. DriverManager: It plays an important role in the JDBC architecture. It uses some


database-specific drivers to effectively connect enterprise applications to databases.

4. JDBC drivers: To communicate with a data source through JDBC, you need a
JDBC driver that intelligently communicates with the respective data source.

Types of JDBC Architecture(2-tier and 3-tier)

The JDBC architecture consists of two-tier and three-tier processing models to access a
database. They are as described below:

1. Two-tier model: A java application communicates directly to the data source. The
JDBC driver enables the communication between the application and the data
source. When a user sends a query to the data source, the answers for those queries
are sent back to the user in the form of results.
The data source can be located on a different machine on a network to which a user
is connected. This is known as a client/server configuration, where the user’s
machine acts as a client, and the machine has the data source running acts as the
server.

2. Three-tier model: In this, the user’s queries are sent to middle-tier services, from
which the commands are again sent to the data source. The results are sent back to
the middle tier, and from there to the user.
This type of model is found very useful by management information system
directors.

What is API?

Before jumping into JDBC Drivers, let us know more about API.

API stands for Application Programming Interface. It is essentially a set of rules and
protocols which transfers data between different software applications and allow different
software applications to communicate with each other. Through an API one application can
request information or perform a function from another application without having direct
access to it’s underlying code or the application data.

JDBC API uses JDBC Drivers to connect with the database.

JDBC Drivers

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:

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

2. Type-2 driver or Native-API driver (partially java driver)

3. Type-3 driver or Network Protocol driver (fully java driver)

4. Type-4 driver or Thin driver (fully java driver)

Interfaces of JDBC API

A list of popular interfaces of JDBC API is given below:

 Driver interface

 Connection interface

 Statement interface

 PreparedStatement interface

 CallableStatement interface

 ResultSet interface
 ResultSetMetaData interface

 DatabaseMetaData interface

 RowSet interface

Classes of JDBC API

A list of popular classes of JDBC API is given below:

 DriverManager class

 Blob class

 Clob class

 Types class

Working of JDBC

Java application that needs to communicate with the database has to be programmed using
JDBC API. JDBC Driver supporting data sources such as Oracle and SQL server has to be
added in java application for JDBC support which can be done dynamically at run time.
This JDBC driver intelligently communicates the respective data source.

Creating a simple JDBC application:

Java

//Java program to implement a simple JDBC application

package com.vinayak.jdbc;

import java.sql.*;

6
public class JDBCDemo {

public static void main(String args[])

throws SQLException, ClassNotFoundException

10

11

String driverClassName

12

= "sun.jdbc.odbc.JdbcOdbcDriver";

13

String url = "jdbc:odbc:XE";

14

String username = "scott";

15

String password = "tiger";

16

String query

17

= "insert into students values(109, 'bhatt')";

18
19

// Load driver class

20

Class.forName(driverClassName);

21

22

// Obtain a connection

23

Connection con = DriverManager.getConnection(

24

url, username, password);

25

26

// Obtain a statement

27

Statement st = con.createStatement();

28

29

// Execute the query

30

int count = st.executeUpdate(query);

31
System.out.println(

32

"number of rows affected by this query= "

33

+ count);

34

35

// Closing the connection as per the

36

// requirement with connection is completed

37

con.close();

38

} // class

The above example demonstrates the basic steps to access a database using JDBC. The
application uses the JDBC-ODBC bridge driver to connect to the database. You must
import java.sql package to provide basic SQL functionality and use the classes of the
package.

What is the need of JDBC?

JDBC is a Java database API used for making connection between java applications with
various databases. Basically, JDBC used for establishing stable database connection with
the application API. To execute and process relational database queries (SQL or Oracle
queries), multiple application can connect to different types of databases which supports
both standard (SE) and enterprise (EE) edition of java.

Establishing JDBC Connection in Java

Last Updated : 17 Nov, 2023



Before Establishing JDBC Connection in Java (the front end i.e your Java Program and
the back end i.e the database) we should learn what precisely a JDBC is and why it came
into existence. Now let us discuss what exactly JDBC stands for and will ease out with the
help of real-life illustration to get it working.

What is JDBC?

JDBC is an acronym for Java Database Connectivity. It’s an advancement for ODBC
( Open Database Connectivity ). JDBC is a standard API specification developed in order to
move data from the front end to the back end. This API consists of classes and interfaces
written in Java. It basically acts as an interface (not the one we use in Java) or channel
between your Java program and databases i.e it establishes a link between the two so that a
programmer can send data from Java code and store it in the database for future use.

Illustration: Working of JDBC co-relating with real-time

Why JDBC Come into Existence?

As previously told JDBC is an advancement for ODBC, ODBC being platform-dependent


had a lot of drawbacks. ODBC API was written in C, C++, Python, and Core Java and as
we know above languages (except Java and some part of Python )are platform-dependent.
Therefore to remove dependence, JDBC was developed by a database vendor which
consisted of classes and interfaces written in Java.

Steps to Connect Java Application with Database

Below are the steps that explains how to connect to Database in Java:

Step 1 – Import the Packages


Step 2 – Load the drivers using the forName() method
Step 3 – Register the drivers using DriverManager
Step 4 – Establish a connection using the Connection class object
Step 5 – Create a statement
Step 6 – Execute the query
Step 7 – Close the connections

Java Database Connectivity

Let us discuss these steps in brief before implementing by writing suitable code to illustrate
connectivity steps for JDBC.

Step 1: Import the Packages

Step 2: Loading the drivers

In order to begin with, you first need to load the driver or register it before using it in the
program. Registration is to be done once in your program. You can register a driver in one
of two ways mentioned below as follows:

2-A Class.forName()

Here we load the driver’s class file into memory at the runtime. No need of using new or
create objects. The following example uses Class.forName() to load the Oracle driver as
shown below as follows:

Class.forName(“oracle.jdbc.driver.OracleDriver”);

2-B DriverManager.registerDriver()
DriverManager is a Java inbuilt class with a static member register. Here we call the
constructor of the driver class at compile time. The following example uses
DriverManager.registerDriver()to register the Oracle driver as shown below:

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())

Step 3: Establish a connection using the Connection class object

After loading the driver, establish connections as shown below as follows:

Connection con = DriverManager.getConnection(url,user,password)

 user: Username from which your SQL command prompt can be accessed.

 password: password from which the SQL command prompt can be accessed.

 con: It is a reference to the Connection interface.

 Url: Uniform Resource Locator which is created as shown below:

String url = “ jdbc:oracle:thin:@localhost:1521:xe”

Where oracle is the database used, thin is the driver used, @localhost is the IP Address
where a database is stored, 1521 is the port number and xe is the service provider. All 3
parameters above are of String type and are to be declared by the programmer before
calling the function. Use of this can be referred to form the final code.

Step 4: Create a statement

Once a connection is established you can interact with the database. The JDBCStatement,
CallableStatement, and PreparedStatement interfaces define the methods that enable you to
send SQL commands and receive data from your database.
Use of JDBC Statement is as follows:

Statement st = con.createStatement();

Note: Here, con is a reference to Connection interface used in previous step .

Step 5: Execute the query

Now comes the most important part i.e executing the query. The query here is an SQL
Query. Now we know we can have multiple types of queries. Some of them are as follows:

 The query for updating/inserting a table in a database.

 The query for retrieving data.


The executeQuery() method of the Statement interface is used to execute queries of
retrieving values from the database. This method returns the object of ResultSet that can be
used to get all the records of a table.
The executeUpdate(sql query) method of the Statement interface is used to execute queries
of updating/inserting.

Pseudo Code:

int m = st.executeUpdate(sql);
if (m==1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");

JDBC Drivers

Last Updated : 20 Nov, 2023



Java Database Connectivity (JDBC) is an application programming interface (API) for


the programming language Java, which defines how a client may access any kind of tabular
data, especially a relational database. JDBC Drivers uses JDBC APIs which was
developed by Sun Microsystem, but now this is a part of Oracle. There are 4 types of JDBC
drivers. It is part of the Java Standard Edition platform, from Oracle Corporation. It acts as
a middle-layer interface between Java applications and databases.

The JDBC classes are contained in the Java Package java.sql and javax.sql.

JDBC helps you to write Java applications that manage these three programming activities:

1. Connect to a data source, like a database.

2. Send queries and update statements to the database

3. Retrieve and process the results received from the database in answer to your query

Structure of JDBC
JDBC Drivers

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. JDBC drivers are the software components which implements interfaces in
JDBC APIs to enable java application to interact with the database. Now we will learn how
many JDBC driver types does Sun defines? There are four types of JDBC drivers defined
by Sun Microsystem that are mentioned below:

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

2. Type-2 driver or Native-API driver

3. Type-3 driver or Network Protocol driver

4. Type-4 driver or Thin driver

1. JDBC-ODBC bridge driver – Type 1 driver

Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the database.
The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.
Type-1 driver is also called Universal driver because it can be used to connect to any of the
databases.
Advantages

 This driver software is built-in with JDK so no need to install separately.

 It is a database independent driver.

Disadvantages

 As a common driver is used in order to interact with different databases, the data
transferred through this driver is not so secured.

 The ODBC bridge driver is needed to be installed in individual client machines.

 Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.

2. Native-API driver – Type 2 driver ( Partially Java driver)

The Native API driver uses the client -side libraries of the database. This driver converts
JDBC method calls into native calls of the database API. In order to interact with different
database, this driver needs their local API, that’s why data transfer is much more secure as
compared to type-1 driver. This driver is not fully written in Java that is why it is also
called Partially Java driver.
Advantage

 Native-API driver gives better performance than JDBC-ODBC bridge driver.

Disadvantages

 Driver needs to be installed separately in individual client machines

 The Vendor client library needs to be installed on client machine.

 Type-2 driver isn’t written in java, that’s why it isn’t a portable driver

 It is a database dependent driver.

3. Network Protocol driver – Type 3 driver (fully Java driver)

The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. Here all the database
connectivity drivers are present in a single server, hence no need of individual client-side
installation.
Advantages

 Type-3 drivers are fully written in Java, hence they are portable drivers.

 No client side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.

 Switch facility to switch over from one database to another database.

Disadvantages

 Network support is required on client machine.

 Maintenance of Network Protocol driver becomes costly because it requires


database-specific coding to be done in the middle tier.

4. Thin driver – Type 4 driver (fully Java driver)

Type-4 driver is also called native protocol driver. This driver interact directly with
database. It does not require any native database library, that is why it is also known as
Thin Driver.
Advantages

 Does not require any native library and Middleware server, so no client-side or
server-side installation.

 It is fully written in Java language, hence they are portable drivers.

Disadvantage

 If the database varies, then the driver will carry because it is database dependent.

Which Driver to use When?

 If you are accessing one type of database, such as Oracle, Sybase, or IBM, the
preferred driver type is type-4.

 If your Java application is accessing multiple types of databases at the same time,
type 3 is the preferred driver.

 Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not
available yet for your database.

 The type 1 driver is not considered a deployment-level driver, and is typically used
for development and testing purposes only.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy