Java 2024 Full
Java 2024 Full
Module II: Inheritance: Creating subclasses, Method Over-riding, Super keyword, Final
keyword, Abstract Classes. Packages and Interfaces: Package, Import statement, Access
Modifiers, Interfaces. IO Packages, Java Input Stream Classes, Java Output Stream Classes,
File Class.
Module III: Exception: Introduction, exception handling techniques, creating your own
exceptions.Threads: Multitasking, Creation of new Threads, State of a thread, Multithreaded
programming, Thread Priorities.
Module IV: Applets- Introduction, Applet class, Applet Structure, Example Applet Program,
Applet LifeCycle, Graphics, Stand-alone GUI applications with Awt/swing components,
Event handling- Event delegation model, different Events and corresponding
Listeners/Adapters. JDBC, Socket Programming-Socket class, Server Socket class, example
client/server program.
History of Java
Java Programming Language was written by James Gosling along with two other
person ‘Mike Sheridan‘ and ‘Patrick Naughton‘, while they were working at Sun
Microsystems.
It was Initially it was named oak .
The latest Releases is : Java Version 1.8 is the current stable release which
was released this year (2015).
Java is implemented over a number of places in modern world. It is implemented
as Standalone Application, Web Application, Enterprise Application and Mobile
Application. Games, Smart Card, Embedded System, Robotics, Desktop, etc.
Five Goals which were taken into consideration while developing Java:
1. Class
2. Object
3. Encapsulation
4. Inheritance
5. Polymorphism
6. Abstraction
1. Class
2. Object
An instance of a class.
Represents real-world entities or concepts.
Has attributes (state) and methods (behavior).
Objects can interact with each other.
Each object has its own identity, state, and behavior.
Created by calling the class constructor.
3. Encapsulation
Bundling of data and methods that operate on the data into a single unit (class).
Restricts direct access to some of the object's components.
Achieved using access modifiers (e.g., private, protected, public).
Protects object integrity by preventing unauthorized access or modification.
Provides a public interface for interaction with the object.
Promotes modularity and maintainability.
4. Inheritance
5. Polymorphism
6. Abstraction
Description: These are basic Java programs that run in the command-line interface
(CLI) or terminal. They do not require a graphical user interface (GUI) and are
usually used for simple tasks, calculations, or backend processing.
Example: A program that calculates the sum of two numbers input by the user.
Description: These programs provide a visual interface that allows users to interact
with the application through windows, buttons, text fields, and other graphical
components. They are built using Java libraries like Swing or JavaFX.
Example: A desktop application like a calculator or a file explorer.
3. Web Applications
Description: Java web applications run on a web server and are accessed through a
browser. They typically use Java Enterprise Edition (Java EE) or Java frameworks
like Spring, JSF (JavaServer Faces), or Servlets.
Example: Online shopping websites, banking applications, or social media platforms.
4. Mobile Applications
Description: These are Java programs specifically designed to run on mobile devices,
particularly for Android development. Java is one of the primary languages used for
Android apps (via Android SDK).
Example: A fitness tracking app or a messaging app for smartphones.
5. Applets
Description: Small programs that run within a web browser, typically for providing
interactive features. However, applets are now deprecated and rarely used due to
security concerns and the evolution of web technologies.
Example: A small game or interactive animation on a web page (historically).
Java Architecture
Java architecture refers to the structure and components that enable Java programs to run
across different platforms. It is based on the principle of Write Once, Run Anywhere
(WORA), which means that Java applications can run on any device or operating system that
has a compatible Java Virtual Machine (JVM).
The JDK is a software development kit that includes the Java Runtime Environment (JRE),
compilers, and other tools needed to develop Java applications.
The JRE provides the necessary libraries and components to run Java applications. It includes
the JVM, core libraries, and other supporting files.
The JVM is the heart of Java architecture. It interprets and executes compiled Java bytecode.
It provides platform independence by abstracting the underlying operating system and
hardware, enabling Java programs to run on any platform that has a JVM implementation.
4.Bytecode:
Java provides a rich set of libraries and frameworks (APIs) for various functionalities like
networking, database connectivity, GUI design, etc.
Architecture Overview:
Compilation: Java source code (.java) is compiled into bytecode (.class) by the Java
compiler.
Execution: The JVM loads and executes the bytecode, making the Java application
platform-independent.
Garbage Collection: The JVM also handles memory management, including
automatic garbage collection, which cleans up unused objects.
In essence, the combination of the JDK, JRE, JVM, and bytecode enables Java applications to
be platform-neutral and run on virtually any device or operating system.
In the previous chapter, we created a Java file called MyClass.java, and we used the
following code to print "Hello World" to the screen:
class MyClass
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
Java Literal
In Java, literals are the fixed values that appear directly in the code. They represent constant
values of a particular type. Java has several types of literals, categorized based on the type of
data they represent.
Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte,
short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes,
Interfaces, and Arrays.
Variable
In Java, variables are used to store data values that can be referenced and manipulated during
program execution. Each variable has a type that determines the kind of data it can hold (e.g.,
integer, string, boolean).
Example: int a;
Rules for defining a variable in Java:
1. Name: Must start with a letter.
2. Case-sensitive: Variable names are case-sensitive (age is different from Age).
3. No reserved keywords: Cannot use Java keywords (e.g., int, class, public).
o Example: int class; is invalid.
4. Cannot start with a digit: A variable name cannot begin with a number.
o Example: int 1stNumber; is invalid.
Operators in Java
Operators in Java are symbols that perform operations on variables and values. Here’s a
breakdown of the different types of operators in Java:
1.Arithmetic Operators : Used for basic mathematical calculations.
+ (Addition)
- (Subtraction)
(Multiplication)
/ (Division)
% (Modulo, remainder)
Example:
int a = 10, b = 3;
int sum = a + b; // sum = 13
int mod = a % b; // mod = 1
2.Relational (Comparison) Operators : Used to compare two values.
== (Equal to)
Example
int x = 5, y = 10;
boolean result = x < y; // result = true
3.Logical Operators :Used for logical operations on boolean values.
&& (Logical AND)
|| (Logical OR)
! (Logical NOT)
Example:
boolean a = true, b = false;
boolean result = a && b; // result = false
4.Assignment Operators :Used to assign values to variables.
= (Simple assignment)
Example:
int a = 5;
a += 3; // a = a + 3, so a = 8
5.Bitwise Operators : Operate on individual bits of integer values.
& (Bitwise AND)
| (Bitwise OR)
^ (Bitwise XOR)
~ (Bitwise NOT)
Example:
int x = 5, y = 3;
int result = x & y; // result = 1 (in binary, 0101 & 0011 = 0001)
6.Conditional Operator : A shorthand for if-else statements.
condition ? expr1 : expr2 (If condition is true, return expr1; otherwise, return
expr2)
Example:
int a = 10, b = 20;
int max = (a > b) ? a : b; // max = 20
1.CONDITIONAL STATEMENT
Conditional statements in Java control the flow of a program based on certain conditions.
They allow the program to make decisions and execute different blocks of code based on
whether a condition evaluates to true or false. The primary conditional statements in Java are:
Syntax :
if (condition)
{
// Code to execute if condition is true
}
Example:
Syntax :
if (condition)
{
// Code to execute if condition is true
}
else
{
// Code to execute if condition is false
}
Example:
int number = 10;
if (number % 2 == 0) {
System.out.println("The number is even.");
} else {
System.out.println("The number is odd.");
}
The program checks if number is divisible by 2. If true, it prints "The number is even";
otherwise, it prints "The number is odd."
3.SWITCH STATEMENT : Selects one of many code blocks to execute based on the value
of a variable or expression.
Syntax :
switch (variable)
{
case value1:
// Code for case value1
break;
case value2:
// Code for case value2
break;
default:
// Code if no cases match
}
Example
int day = 3;
switch (day)
{
case 1:
System.out.println("Monday");
Page 16 Muslim Association College of Arts & Science
Programming in Java 2024
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
The program matches day with the cases. If day == 3, it prints "Wednesday"; otherwise, it
prints the relevant case or the default message.
2. while Loop :Used when the number of iterations is not fixed, and the condition is
checked before the loop executes.
Syntax:
while (condition)
{
// Code to execute
}
Example:
int i= 1;
while (i <= 5)
{
System.out.println("Count: " + i);
i++;
}
Description:
The loop continues as long as the condition (i <= 5) is true. The condition is checked before
each iteration.
3. do-while Loop : Similar to the while loop, but the block of code executes at least once
because the condition is checked after the loop.
Syntax:
Do
{
// Code to execute
}
while (condition);
Example:
int it = 1;
do {
System.out.println("Count: " + i);
i++;
}
while (i <= 5);
Description:
The block executes once before checking the condition (i <= 5), ensuring at least one
execution.
3.Jumping statements
Jumping statements in Java are used to transfer control to another part of the program,
bypassing the normal flow of execution. These statements help manage loops, conditional
statements, and other control structures.
1. break Statement
Used to terminate the nearest enclosing loop or switch statement prematurely.
Syntax:
break;
Example:
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
break;
}
System.out.println("i: " + i);
}
Out put
1
2
Description:
The break statement stops the loop when i equals 3, and control jumps to the code after the
loop.
2. continue Statement
Used to skip the current iteration of a loop and proceed with the next iteration.
Syntax:
continue;
Example:
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
continue;
}
System.out.println("i: " + i);
}
Out put
1
2
4
5
Description:
The continue statement skips printing when i equals 3 and moves to the next iteration of the
loop.
Java Arrays
Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
To declare an array, define the variable type with square brackets:
Example String[ ] myarray;
We have now declared a variable that holds an array of strings. To insert values to it,
we can use an array literal - place the values in a comma-separated list, inside curly
braces:
Example 1 :
String[ ] myarray = {"Volvo","BMW","Ford", "Mazda"};
Example 2:
int[ ] myNum = {10, 20, 30, 40};
System.out.println(myarray.length);
// Outputs is 4
Display Array Elements : For displaying array elements we can use for loop
String[ ] myarray = {"abi", "anu", "jeeva", "shiva"};
for (int i = 0; i < myarray.length; i++)
{
System.out.println(myarray [i]);
}
Output
abi
ani
jeeva
shiva
Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.
To create a two-dimensional array, add each array within its own set of curly braces:
int[ ][ ] myarr= { {1, 2, 3, 4}, {5, 6, 7} };
myarr is now an array with two arrays as its elements.
To access the elements of the myarr array, specify two indexes: one for the
array, and one for the element inside that array.
This example accesses the third element (2) in the second array (1) of myarr:
int[ ][ ] myarr = { {15, 72, 63, 84}, {75, 46, 57} };
System.out.println(myarr[2][1]);
The above statement will print element 46
Defining a class
A class cna be defined using the keyword class .
The sytanx for defining a class with attributes and methds as follows
Creatining Object of a Class
An object of a class can be created using new keyword
Syntax: Classname objectname=new classname();
Example: student ob=new student();
Creatining a Class Definition
Syntax :
class ClassName
{
datatype attribute1;
datatype attribute2;
returnType methodName()
{
// Method body
}
}
Example :
class student
String name;
int age;
void displayDetails()
OUTPUT:
Abi
33
Constructor
Constructor in java is a special type of method that is used to initialize the object.Java
constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
Rules for creating java constructor :There are basically two rules defined for the constructor.
Constructor name must be same as its class name
Constructor must have no explicit return type
Types of java constructors : There are two types of constructors:
2. Parameterized constructor
Output:
Bike is created
class Student3
{
int id;
String name; void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler
provides you a default constructor.Here 0 and null values are provided by default
constructor.
Student4(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
}
}
OUTPUT
Sum of 2 and 3 is 5
Sum of 2,3 and 4 is 9
Module II
Inheritance: Creating subclasses, Method Over-riding, Super keyword, Final keyword,
Abstract Classes. Packages and Interfaces: Package, Import statement, Access Modifiers,
Interfaces. IO Packages, Java Input Stream Classes, Java Output Stream Classes, File Class.
Inheritance
Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another.
With the use of inheritance the information is made manageable in a hierarchical
order.
The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass
(base class, parent class).
1. Code Reusability: Subclasses can reuse methods and fields of the superclass,
reducing the need to rewrite code.
2. Extensibility: You can extend the functionality of a superclass in the subclass by
overriding methods.
3. Improved Maintainability: Modifying a method in the superclass can automatically
propagate the change to all subclasses that inherit from it.
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the
syntax of extends keyword
Syntax for creating a new class named B from an Existing class named A
class A
{
.....
.....
}
class B extends A
{
.....
.....
}
}
Output
In ClassA: The value of num is 42
In ClassB: The value of num is 42
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Hybrid Inheritance
1.Single Inheritance
In single inheritance, subclasses inherit the features of one superclass. In image
below, the class A serves as a base class for the derived class B.
Example
Class A
{
................
...............
}
Class B extends A
{
..............
.................
}
2.Multilevel Inheritance:
In Multilevel Inheritance, a derived class will be inheriting a base class and as well
as the derived class also act as the base class to other class.
In 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.
Example
Class A
{
................
...............
}
Class B extends A
{
..............
.................
}
Class C extends B
{
..............
.................
}
3.Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass
(base class) for more than one subclass. In below image, class A serves as a base class for
the derived class B, C, and D
B C D
Example
Class A
{
................
...............
}
Class B extends A
{
..............
.................
}
Class C extends A
{
..............
.................
}
Class D extends A
{
..............
.................
}
4.Hybrid Inheritance (Not Supported in Java)
The method signature (name, return type, and parameters) in the subclass must match
the method signature in the superclass.
It allows the subclass to modify or extend the behavior of the superclass method,
providing specific functionality suited to the subclass.
Method overriding is a key feature of runtime polymorphism. The method that gets
invoked is determined at runtime based on the object type (whether it's the superclass
or subclass).
class Animal
{
public void move()
{
System.out.println("Animals can move");
}
}
class Dog extends Animal
{
public void move()
{
System.out.println("Dogs can walk and run");
}
}
public class A
{
public static void main(String args[ ])
{
Animal ob1=new Animal();
ob1.move();
Dog ob2=new Dog();
ob2.move();
}
Output
Animals can move
Dogs can walk and run
Super Keyword
In Java, the super keyword is used to refer to the immediate parent class of the current object.
It has several important uses:
You can use super() to call the constructor of the parent class. This is often done in the
constructor of a subclass to initialize the parent class.
Syntax : super();
You can use super to call a method defined in the parent class, even if it is overridden in the
child class.
Syntax : super.methodname();
If a field is present in the parent class and is hidden (shadowed) by a field with the same
name in the subclass, you can use super to access the parent class's field.
Syntax :super.fieldname;
Final Keyword
The final keyword in Java is used to define constants, prevent method overriding, and
restrict inheritance.
It is a versatile keyword that can be applied to variables, methods, and classes, each
with a different purpose.
final prevents reassignment of variables (constants).
final prevents method overriding (method behavior remains fixed).
final prevents inheritance (class behavior cannot be modified).
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined
package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
import pack.*;
class B
{
{
A obj = new A();
obj.msg();
}
}
Output:Hello
Import Statement
In Java, the import statement is used to bring other classes or entire packages into the
current file so that you can use them without needing to specify their fully qualified
names.
The import statement makes the code more readable and avoids the need to repeatedly
use the full path of a class when referencing it.
Syntax
import packageName.ClassName;
Example
import java.util.Scanner;
4. Default (Package-Private):
o When no access modifier is specified, it is called the default or package-
private access level.
o The members with default access are accessible only within classes that
belong to the same package. They are not accessible outside the package or by
subclasses in other packages.
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract
methods.
The interface in Java is a mechanism to achieve abstraction. There can be only
abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
There are mainly three reasons to use interface. They are given below.
Syntax:
interface <interface_name>
{
………..
}
In this example, the interface A has only one method, and its implementation is provided
in B class class.
interface A
{
void print();
}
class B implements A
{
public void print()
{
System.out.println("Hello");
}
{
B obj = new B();
obj.print();
}
}
1. java.io Package:
The java.io package provides the essential classes for reading and writing data to files,
memory, and other I/O sources.
Stream Classes: Java I/O is based on streams, which are sequences of data. The two
types of streams are:
Reader/Writer Classes: These are specialized classes for handling character data.
They handle encoding and decoding between bytes and characters.
File I/O: The File class is used to represent files and directories. It provides methods
for checking file properties, creating and deleting files, and working with directories.
OutputStream vs InputStream
OutputStream
Java application uses an output stream to write data to a destination, it
may be a file, an array, peripheral device or socket.
OutputStream class is an abstract class. It is the super class of all classes
representing an output streamof bytes. An output stream accepts output bytes and
sends them to some sink.
InputStream
Java application uses an input stream to read data from a source, it may be a
file, an array, peripheral device or socket.
InputStream class is an abstract class. It is the super class of all classes
representing an input stream of bytes.
1. Represents Files and Directories: The File class represents file and directory
pathnames in the file system.
2. File Creation: You can create a new file using createNewFile() which returns true if the
file was created successfully.
3. Directory Creation: Use mkdir() to create a directory, or mkdirs() to create the
directory and any missing parent directories.
4. Checking File or Directory Type: Use isFile() to check if it's a file and isDirectory() to
check if it's a directory.
5. File Deletion: The delete() method is used to delete a file or empty directory. It returns
true if the deletion was successful.
6. File Renaming/Moving: The renameTo(File dest) method allows you to rename or move
a file.
Module III
Exception: Introduction, exception handling techniques, creating your own
exceptions.Threads: Multitasking, Creation of new Threads, State of a thread, Multithreaded
programming, Thread Priorities.
Syntax
try
{
block ,where exceptiopn may occur
}
catch(exception type)
{
code to handle exception
}
finaly
{
……………
}
Example
public class A
{
public static void main(String[] args)
{
try
{
int result = 10 / 0; // This will cause an ArithmeticException
}
catch (ArithmeticException e)
{
System.out.println("Cannot divide by zero!");
}
finally
{
System.out.println("This will always execute.");
}
}
}
Thread in java
A thread is a lightweight sub process, a smallest unit of processing.
Threads are independent, if there occurs exception in one thread, it doesn't affect
other threads. It shares a common memory area.
As shown in the above figure, 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.
A thread can be in one of the five states. According to sun, there is only 4 states in
thread life cycle in javanew, runnable, non-runnable and terminated. There is no
running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1.New
The thread is in new state if you create an instance of Thread class but before the
invocation ofstart() method.
2.Runnable
The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
3.Running
The thread is in running state if the thread scheduler has selected it.
4.Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5.Terminated
1.Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.
Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
Java Thread Example by extending Thread class
}
Output:thread is running...
2.Runnable interface:
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread.
Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.
Java Thread Example by implementing Runnable interface
class Multi3 implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output:thread is running...
It helps control the order in which threads are scheduled, especially when there are multiple
threads competing for CPU time.
Priority Range:
You can set the priority of a thread using the setPriority(int priority) method, where
priority is an integer value between 1 and 10.
Thread Scheduler:
The JVM and underlying operating system manage the thread scheduler. A higher-
priority thread is more likely to run before lower-priority threads, but the exact
scheduling behavior depends on the system and JVM.
Default Priority:
Module IV:
Applets- Introduction, Applet class, Applet Structure, Example Applet Program, Applet
LifeCycle, Graphics, Stand-alone GUI applications with Awt/swing components, Event
handling- Event delegation model, different Events and corresponding Listeners/Adapters.
JDBC, Socket Programming-Socket class, Server Socket class, example client/server
program.
Applet in java
An applet is a small Java program that runs within a web browser or applet viewer.
It is typically embedded in a web page and provides interactive features like
animations, games, or real-time content updates.
Applets run within a security sandbox, which restricts access to local resources, like
the file system or network, to prevent malicious behavior.
This makes applets more secure but also limits their functionality.
Applets are typically embedded in HTML pages using the <applet> tag (deprecated in
HTML5).
Applets were once popular for adding interactive content to web pages but are now
largely obsolete due to security concerns and the development of more advanced web
technologies
Applet Class
The Applet class in Java is a special class that provides methods for creating and
managing applets, which are small programs designed to run within a web browser or
applet viewer.
The Applet class is part of the java.applet package and serves as the base class for
applet-based applications.
It defines methods like init(), start(), stop(), and destroy() to manage the applet's life
cycle
Import java.applet.*;
import java.awt.*;
public class myapplet extends Applet
{
public void pain(Graphics g)
{
g.drawString ("I Love MACAS", 25,
50);
}
}
Java AWT
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based
applications in java.
Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system.
AWT is heavyweight i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT api such as TextField,
Label, TextArea, RadioButton, CheckBox, Choice, List etc.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.
Container
The Container is a component in AWT that can contain another components like
buttons, textfields, labels etc.
Window
The window is the container that have no borders and menu bars. You must
use frame, dialog or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have
other components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have
other components like button, textfield etc.
AWT Example
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are
showing Button component on the Frame.
import java.awt.*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting
button position add(b);//adding button
into frame setSize(300,300);//frame
size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[])
{
First f=new First();
}
}
Output
Java Swing
Java Swing is used to create window-based applications.
Swing is built on top of AWT (Abstract Window Toolkit) and provides a richer
set of components and more flexible design options.
Unlike AWT, Swing is entirely written in Java, which allows it to be platform-
independent.
It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight
components.
The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Swing Architecture : Swing follows a model-view-controller (MVC) design pattern:
Model: Represents the data.
View: Represents the GUI components.
Controller: Handles user input and updates the view.
Key Classes in Swing:
JFrame: Represents the main window of the application.
JPanel: A container for other components.
JButton, JLabel, JTextField, etc.: These are the basic components for user
interaction.
JMenuBar, JMenu, JMenuItem: Used for adding menus.
Event handling
Event handling in Java is a mechanism that allows programs to respond to user
actions, such as mouse clicks, key presses, or window events.
It follows an event-driven programming model, where events are generated by user
interactions.
To handle these events, Java uses event listeners—interfaces that listen for specific
types of events (e.g., ActionListener, MouseListener).
These listeners are attached to components (like buttons or text fields) and contain
methods that define the actions to take when the event occurs.
When an event is triggered, the corresponding listener method is executed, enabling
dynamic interaction in the application
3. Event Object:
When an event occurs, an event object is created, which contains information about
the event, such as the source of the event and the specific action (e.g., which button
was clicked).
4. Event Handling:
Once an event occurs, the event is passed to the registered listener, which then
performs the required action.
The listener handles the event by implementing the methods from the event
listener interface.
For example, an ActionListener will implement the actionPerformed() method
to define what happens when the event is triggered.
How the Event Delegation Model Works:
1. Step 1: An event source (like a button) generates an event when the user interacts
with it.
2. Step 2: The event is passed to the registered listener, which is an object that
implements an event listener interface.
3. Step 3: The listener's method is called, and the appropriate action is taken in response
to the event.
2. Mouse Events
Event: Triggered by various mouse actions such as clicking, pressing, or moving the
mouse.
Listeners:
o MouseListener (for mouse clicks, press, release, etc.)
3. Key Events
Event: Triggered by keyboard actions such as key presses and releases.
Listeners:
o KeyListener (for key press, release, and typing)
Methods: keyTyped(KeyEvent e), keyPressed(KeyEvent e),
keyReleased(KeyEvent e)
4. Window Events
Event: Triggered when actions occur on a window, such as opening, closing, or
changing the focus.
Listeners:
o WindowListener (for various window actions)
Methods: windowOpened(WindowEvent e),
windowClosing(WindowEvent e), windowClosed(WindowEvent e),
windowIconified(WindowEvent e), windowDeiconified(WindowEvent
e), windowActivated(WindowEvent e),
windowDeactivated(WindowEvent e)
5. Focus Events
Event: Triggered when a component gains or loses focus.
Listeners:
o FocusListener (for focus gained or lost)
Methods: focusGained(FocusEvent e), focusLost(FocusEvent e)
Java JDBC
Java JDBC is a java API to connect and execute query with the database. JDBC API uses
jdbc drivers to connect with the database.
JDBC Components
The JDBC API provides the following interfaces and classes –
1.DriverManager
The DriverManager class manages a list of database drivers. It is responsible for
selecting an appropriate database driver when establishing a connection to a database.
2.Connection
The Connection interface represents a session between the Java application and the
database.
3.Statement
The Statement interface is used to execute basic SQL queries (like SELECT,
INSERT, UPDATE, DELETE) against the database.
4.ResultSet
The ResultSet interface represents the result set of a query (usually a SELECT
statement). It provides methods for retrieving the data returned by the query.
5.SQLException
SQLException is an exception that provides information about database-related
errors. It is thrown by JDBC methods when a database operation fails or a query
results in an error.
6.DataSource
DataSource is an alternative to DriverManager for obtaining a database connection. It
is generally preferred for enterprise applications because it allows for connection
pooling and better resource management.
Socket Class
A socket is simply an endpoint for communications between the machines. The Socket class
can be used to create a socket.
Important methods
Method Description
1) public InputStream
returns the InputStream attached with this socket.
getInputStream()
2) public OutputStream
returns the OutputStream attached with this socket.
getOutputStream()
ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.
Important methods
Method Description
To create the server application, we need to create the instance of ServerSocket class.
Here, we are using 6666 port number for the communication between the client and
server.
You may also choose any other port number.
The accept() method waits for the client. If clients connects with the given port
number, it returns an instance of Socket.
Creating Client:
To create the client application, we need to create the instance of Socket class.
Here, we need to pass the IP address or hostname of the Server and a port number.
Here, we are using "localhost" because our server is running on same system.
Let's see a simple of Java socket programming where client sends a text and server receives
and prints it.
File: MyServer.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);