Ece JPG
Ece JPG
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
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.
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.
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.
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.
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
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.
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.*;
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.
3. java.util: Contains utility classes which implement data structures like Linked List, Dictionary
and support ; for Date / Time operations.
5. java.awt: Contain classes for implementing the components for graphical user interfaces
(like button , ;menus etc). 6)
obj.getNames(name);
}
}
Note : MyClass.java must be saved inside the myPackage directory since it is a part of the package.
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
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.
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.
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.
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.
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();
}
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.
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.
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.
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.
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.
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:
MyException(){}
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:
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
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;
num1 = scan.nextInt();
System.out.print("Enter second number(divisor): ");
num2 = scan.nextInt();
try {
System.out.println("Quotient: "+div);
}catch(ArithmeticException 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.
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.
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.
//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.
//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.
//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.
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.
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
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.
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.
Syntax:
Stream<T> stream;
Here T is either a class, object, or data type depending upon the declaration.
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.
1. Intermediate Operations
2. Terminate Operations
Intermediate Operations
Intermediate Operations are the types of operations in which multiple methods are chained
in a row.
It enables the concept of filtering where one method filters data and passes it to
another method after processing.
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.
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:
2. filter()
The filter method is used to select elements as per the Predicate passed as an argument.
Syntax:
3. sorted()
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.
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:
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;
10
11
12
13
14
);
15
16
18
19
20
21
22
23
24
25
26
27
28
29
// Print the intermediate results
30
System.out.println("Intermediate Results:");
31
intermediateResults.forEach(System.out::println);
32
33
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
Stream Operations:
filter(s -> s.startsWith("S")): Filters the strings to only include those that start
with “S”.
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.
1. collect()
The collect method is used to return the result of the intermediate operations performed on
the stream.
Syntax:
2. forEach()
The forEach method is used to iterate through every element of the stream.
Syntax:
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.
4. count()
Returns the count of elements in the stream.
Syntax:
long count()
5. findFirst()
Syntax:
Optional<T> findFirst()
6. allMatch()
Checks if all elements of the stream match a given predicate.
Syntax:
7. anyMatch()
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
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
Multitasking
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.
o A thread is lightweight.
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
2) void run()
5) void join()
6) int getPriority()
7) void setPriority()
8) String getName()
9) void setName()
static
35) getDefaultUncaughtExceptionHandler()
Thread.UncaughtExceptionHandler
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?
o It is optional.
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:
2. Algorithm
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.
o It is optional.
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:
2. Algorithm
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
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. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
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.
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:
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( ).
import java.applet.Applet;
import java.awt.Graphics;
@Override
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:
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.
java HelloWorld
There are two standard ways in which you can run an applet :
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>
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
//and again
import java.awt.*;//Graphic
//class is available in this package
// avoidable too.
>
With this approach, first compile HelloWorld.java file and then simply run the below
command to run applet :
appletviewer HelloWorld
To prove paint() method is called again and again, here is the code:
Java
//code to illustrate paint
//and again
import java.awt.*;//Graphic
// 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.
Due to security reasons, the following restrictions are imposed on Java applets:
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.
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.
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
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.
There are certain points from which Java Swing is different than Java AWT as mentioned
below:
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.
Execution Time is more than Swing. Execution Time is less than AWT.
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.
Lightweight Components
Platform Independent
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.
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
Rich controls– Swing provides a rich set of advanced controls like Tree
TabbedPane, slider, colorpicker, and table controls.
1. The way that the component looks when rendered on the screen.
Over the years, one component architecture has proven itself to be exceptionally
effective: – Model-View-Controller or MVC for short.
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 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.
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
import java.io.*;
import javax.swing.*;
// Main class
class GFG {
frame.add(button);
frame.setSize(500, 600);
frame.setLayout(null)
Output:
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.
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)
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:
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.
4. JDBC drivers: To communicate with a data source through JDBC, you need a
JDBC driver that intelligently communicates with the respective data source.
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 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:
Driver interface
Connection interface
Statement interface
PreparedStatement interface
CallableStatement interface
ResultSet interface
ResultSetMetaData interface
DatabaseMetaData interface
RowSet interface
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.
Java
package com.vinayak.jdbc;
import java.sql.*;
6
public class JDBCDemo {
10
11
String driverClassName
12
= "sun.jdbc.odbc.JdbcOdbcDriver";
13
14
15
16
String query
17
18
19
20
Class.forName(driverClassName);
21
22
// Obtain a connection
23
24
25
26
// Obtain a statement
27
Statement st = con.createStatement();
28
29
30
31
System.out.println(
32
33
+ count);
34
35
36
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.
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.
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.
Below are the steps that explains how to connect to Database in Java:
Let us discuss these steps in brief before implementing by writing suitable code to illustrate
connectivity steps for JDBC.
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())
user: Username from which your SQL command prompt can be accessed.
password: password from which the SQL command prompt can be accessed.
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.
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();
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:
Pseudo Code:
int m = st.executeUpdate(sql);
if (m==1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");
JDBC Drivers
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:
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:
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
Disadvantages
As a common driver is used in order to interact with different databases, the data
transferred through this driver is not so secured.
Type-1 driver isn’t written in java, that’s why it isn’t a portable 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
Disadvantages
Type-2 driver isn’t written in java, that’s why it isn’t a portable 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.
Disadvantages
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.
Disadvantage
If the database varies, then the driver will carry because it is database dependent.
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.