KEMBAR78
Java 2024 Full | PDF | Java (Programming Language) | Java Virtual Machine
0% found this document useful (0 votes)
16 views72 pages

Java 2024 Full

The document is a syllabus for a Java programming course, outlining four main modules covering Java basics, inheritance, exception handling, and applet development. It includes a history of Java, object-oriented programming concepts, special features, types of applications, and Java architecture. Additionally, it details data types, variables, and operators in Java.

Uploaded by

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

Java 2024 Full

The document is a syllabus for a Java programming course, outlining four main modules covering Java basics, inheritance, exception handling, and applet development. It includes a history of Java, object-oriented programming concepts, special features, types of applications, and Java architecture. Additionally, it details data types, variables, and operators in Java.

Uploaded by

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

Programming in Java 2024

CS1341: PROGRAMMING IN JAVA


Syllabus
Module I: Java Introduction: Object Oriented Programming concepts, Features of Java
language, Types of Java programs, Java architecture, Program Structure, Literals, Data Types
and variables, Operators,Control Statements, Arrays, Classes and objects: Class, Objects,
Defining a class, Method declaration Constructor, Method overloading.

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.

Page 1 Muslim Association College of Arts & Science


Programming in Java 2024

Module I: Java Introduction:


Object Oriented Programming concepts, Features of Java language, Types of Java programs,
Java architecture, Program Structure, Literals, Data Types and variables, Operators,Control
Statements, Arrays, Classes and objects: Class, Objects, Defining a class, Method declaration
Constructor, Method overloading.

Page 2 Muslim Association College of Arts & Science


Programming in Java 2024

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. Keep it simple, familiar and object oriented.


2. Keep it Robust and Secure.
3. Keep it architecture-neural and portable.
4. Executable with High Performance.
5. Interpreted, threaded and dynamic

Object Oriented Programming Concepts

Here are the main concepts of Object-Oriented Programming (OOP):

1. Class
2. Object
3. Encapsulation
4. Inheritance
5. Polymorphism
6. Abstraction

1. Class

 Blueprint or template for creating objects.


 Defines properties (attributes) and methods (functions) for objects.
 A class is a user-defined data type.

Page 3 Muslim Association College of Arts & Science


Programming in Java 2024

 Can contain constructors to initialize objects.


 Can be instantiated to create multiple objects.
 Defines the structure and behavior of an object.

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

 Mechanism to create a new class from an existing class.


 The new class (child) inherits attributes and methods of the parent class.
 Promotes code reuse and avoids redundancy.
 Allows for specialization and extension of existing functionality.
 Child class can override parent methods to modify behavior.
 Supports hierarchical relationships between classes.

5. Polymorphism

 Ability of a method to do different things based on the object it is acting upon.


 Achieved through method overriding (runtime) and method overloading (compile-time).
 Allows the same method name to behave differently for different objects.
 Supports flexibility and scalability in the codebase.
 Increases code reusability by allowing one interface to work with many classes.

Page 4 Muslim Association College of Arts & Science


Programming in Java 2024

 Can be implemented using interfaces, abstract classes, or method overriding.

6. Abstraction

 Hiding complex implementation details and exposing only essential features.


 Allows focusing on what an object does, not how it does it.
 Achieved using abstract classes and interfaces.
 Simplifies code by reducing complexity.
 Protects user from unnecessary information overload.
 Supports flexibility and changeability of underlying implementation.

Special Features of Java


1.General Purpose
Java capabilities are not limited to any specific application domain rather it can be used in
various application domain and hence it is called General Purpose Programming Language.
2.Class based
Java is a class based/oriented programming language which means Java supports inheritance
feature of object-oriented Programming Language.
3.Object oriented
Java is object-oriented means software developed in Java are combination of different types
of object.
4.Platform Independent
A Java code will run on any JVM (Java Virtual Machine). Literally you can run same Java
code on Windows JVM, Linux JVM, Mac JVM or any other JVM practically and get same
result every time
5.Architecturally Neutral
A Java code is not dependent upon Processor Architecture. A Java Application compiled on
64 bit architecture of any platform will run on 32 bit (or any other architecture) system
without any issue.
6.Multithreaded
A thread in Java refers to an independent program. Java supports multithread which means
Java is capable of running many tasks simultaneously, sharing the same memory.
7.Dynamic

Page 5 Muslim Association College of Arts & Science


Programming in Java 2024

Java is a Dynamic programming language which means it executes many programming


behavior at Runtime and don’t need to be passed at compile time as in the case of static
programming.
8.Distributed
Java Supports distributed System which means we can access files over Internet just by
calling the methods.
9.Portable
A Java program when compiled produce bytecodes. Bytecodes are magic. These bytecodes
can be transferred via network and can be executed by any JVM, hence came the concept of
‘Write once, Run Anywhere(WORA)’.
10.Robust
Java is a robust programming Language which means it can cope with error while the
program is executing as well as keep operating with abnormalities to certain extent.
Automatic Garbage collection, strong memory management, exception handling and type
checking further adds to the list.
11.Interpreted
Java is a compiled programming Language which compiles the Java program into Java byte
codes. This JVM is then interpreted to run the program.
12.Security
Unlike other programming Language where Program interacts with OS using User runtime
environment of OS, Java provides an extra layer of security by putting JVM between
Program and OS.
13.Simple Syntax
Java is an improved c++ which ensures friendly syntax but with removed unwanted features
and inclusion of Automatic Garbage collection.
14.High Level Programming Language
Java is a High Level Programming Language the syntax of which is human readable. Java
lets programmer to concentrate on what to achieve and not how to achieve. The JVM
converts a Java Program to Machine understandable language.
15.High Performance
Java make use of Just-In-Time compiler for high performance. Just-In-Time compiler is a
computer program that turns Java byte codes into instructions that can directly be sent to
compilers.

Page 6 Muslim Association College of Arts & Science


Programming in Java 2024

Types of Java Applications

1. Standalone Applications (Console Applications)

 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.

2. Graphical User Interface (GUI) Applications

 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).

Page 7 Muslim Association College of Arts & Science


Programming in Java 2024

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).

Key Components of Java Architecture:

1.Java Development Kit (JDK):

The JDK is a software development kit that includes the Java Runtime Environment (JRE),
compilers, and other tools needed to develop Java applications.

2.Java Runtime Environment (JRE):

The JRE provides the necessary libraries and components to run Java applications. It includes
the JVM, core libraries, and other supporting files.

3.Java Virtual Machine (JVM):

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 source code is compiled into bytecode, a platform-independent, intermediate


representation. The bytecode is then executed by the JVM, ensuring that Java applications are
portable across different operating systems.

5.Java APIs (Application Programming Interfaces):

Java provides a rich set of libraries and frameworks (APIs) for various functionalities like
networking, database connectivity, GUI design, etc.

Page 8 Muslim Association College of Arts & Science


Programming in Java 2024

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.

Page 9 Muslim Association College of Arts & Science


Programming in Java 2024

Java Program Structure

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.

 Integer Literals: int, long (e.g., 100, 0xFF)


 Floating-Point Literals: float, double (e.g., 3.14, 1.5e2)
 Character Literals: char (e.g., 'A')
 String Literals: String (e.g., "Hello")
 Boolean Literals: boolean (e.g., true, false)
 Null Literal: null (e.g., null)

Data Types in Java

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.

Page 10 Muslim Association College of Arts & Science


Programming in Java 2024

1.Primitive Data Types


1.1 Numeric data Type
In Java, numeric data types are used to represent numbers, and they are classified into two
main categories:

1. Integer types: Used to store whole numbers.

1. byte: 1 byte, range: -128 to 127

Example: byte a = 100;


2. short: 2 bytes, range: -32,768 to 32,767

Example: short b = 10000;


3. int: 4 bytes, range: -2^31 to 2^31-1

Example: int c = 100000;


4. long: 8 bytes, range: -2^63 to 2^63-1

Example: long d = 10000000000L;

2. Floating-point types: Used to store numbers with decimals.

1. float: 4 bytes, range: ~±3.40282347 × 10^38

Example: float e = 10.5f;


2. double: 8 bytes, range: ~±1.7976931348623157 × 10^308

Example: double f = 10.5;

Page 11 Muslim Association College of Arts & Science


Programming in Java 2024

1.2 Non Numeric Data Type


In Java, non-numeric data types represent values that are not numbers:
1. char: 2 bytes, represents a single Unicode character. Example: char c = 'A';
2. boolean: 1 bit, represents true or false values. Example: boolean isTrue = true;

2.Non Primitive Data Type


In Java, non-primitive (reference) data types are used to store objects and references:
1. String: Variable size, represents a sequence of characters.
Example: String name = "John";
2. Arrays: Variable size, stores multiple elements of the same type.
Example: int[] numbers = {1, 2, 3};
3. Classes: User-defined types representing objects with properties and methods.
Example: class Person { String name; int age; }
4. Interfaces: Defines a contract for classes to implement.
Example: interface Animal { void sound(); }
5. Object : It is the data type values derived from class

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.

Page 12 Muslim Association College of Arts & Science


Programming in Java 2024

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)

 != (Not equal to)

 > (Greater than)

 < (Less than)

 >= (Greater than or equal to)

 <= (Less than or 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)

Page 13 Muslim Association College of Arts & Science


Programming in Java 2024

 +=, -=, *=, /=, %= (Compound assignment operators)

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)

 << (Left shift)

 >> (Right shift)

 >>> (Unsigned right shift)

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

Page 14 Muslim Association College of Arts & Science


Programming in Java 2024

Control Statements in Java

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:

1.IF STATEMENT : Executes a block of code if the condition is true.

Syntax :
if (condition)
{
// Code to execute if condition is true
}
Example:

int age = 18;


if (age >= 18)
{
System.out.println("You are eligible to vote.");
}
Description: The program checks if age is greater than or equal to 18. If true, it prints "You
are eligible to vote."

2.IF-ELSE STATEMENT : Provides an alternative block of code if the condition is false.

Page 15 Muslim Association College of Arts & Science


Programming in Java 2024

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.

Looping Statements in Java


Looping statements in Java allow repeated execution of a block of code as long as a specified
condition is met. This reduces redundancy and improves efficiency in programs. Here are the
main types of loops in Java with examples:

1. for Loop : Used when the number of iterations is known beforehand.


Syntax:
for (initialization; condition; update)
{
// Code to execute
}
Example:
for (int i = 1; i <= 5; i++)
{
System.out.println("Iteration: " + i);
}
Description:
 Initialization: Sets the starting point (int i = 1).
 Condition: Runs the loop while i <= 5.
 Update: Increments i after each iteration (i++).

Page 17 Muslim Association College of Arts & Science


Programming in Java 2024

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);

Page 18 Muslim Association College of Arts & Science


Programming in Java 2024

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)

Page 19 Muslim Association College of Arts & Science


Programming in Java 2024

{
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};

Access the Elements of an Array


 You access an array element by referring to the index number.
 This statement accesses the value of the first element in cars:
String[ ] myarray = {"abi", "anu", "jeeva", "shiva"};
System.out.println(myarray [0]);
The above statement will display the value “volvo”
Array Length
To find out how many elements an array has, use the length property:
Page 20 Muslim Association College of Arts & Science
Programming in Java 2024

String[ ] myarray = {"abi", "anu", "jeeva", "shiva"};

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

Class and Object in Java


Class
 A class in Java is a blueprint or template for creating objects. It defines the properties
(fields) and behaviors (methods) that the objects of the class will have.
Object
 An object is an instance of a class. It represents a real-world entity and is used to
access the fields and methods defined in the class.

Page 21 Muslim Association College of Arts & Science


Programming in Java 2024

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()

System.out.println("Name: " + name);

System.out.println("Age: " + age);

Page 22 Muslim Association College of Arts & Science


Programming in Java 2024

Example program to demonstrate class and object creation and calling


member function
class student
{
String name;
int age;
void getdata(String s, int a)
{
name=s;
age=a;
}
void putdata()
{
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}

public static void main(String[ ] args)


{
student ob = new student( );
ob.getdata(“abi”,33);
ob.putdata( );
}
}

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:

1. Default constructor (no-argu constructor)

2. Parameterized constructor

Page 23 Muslim Association College of Arts & Science


Programming in Java 2024

1.Java Default Constructor

A constructor that have no parameter is known as default constructor.

Syntax of default constructor:


class_name()
{
}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.
class Bike1
{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}

Output:
Bike is created

Q) What is the purpose of default constructor?


Default constructor provides the default values to the object like 0, null etc.
depending on the type. Example of default constructor that displays the default
values

Page 24 Muslim Association College of Arts & Science


Programming in Java 2024

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.

2.Java parameterized constructor

 A constructor that have parameters is known as parameterized constructor.


 Parameterized constructor is used to provide different values to the distinct objects.
 In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
class Student4
{
int id;
String name;

Page 25 Muslim Association College of Arts & Science


Programming in Java 2024

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

Page 26 Muslim Association College of Arts & Science


Programming in Java 2024

Method Overloading in Java


 Method overloading in Java allows a class to have more than one method with the
same name, but with different parameter lists (different number or types of
parameters).
 The correct method is chosen based on the number or type of arguments passed when
calling the method.

Example: Method Overloading with Sum of Integers


class Calculator
{
public int sum(int a, int b)
{
return( a + b);
}
public int sum(int a, int b, int c)
{
return( a + b + c);
}

public static void main(String[] args)


{
Calculator calc = new Calculator();
System.out.println("Sum of 2 and 3: " + calc.sum(2, 3));
System.out.println("Sum of 2, 3, and 4: " + calc.sum(2, 3, 4));

}
}
OUTPUT
Sum of 2 and 3 is 5
Sum of 2,3 and 4 is 9

****************** END OF MODULE 1 ******************

Page 27 Muslim Association College of Arts & Science


Programming in Java 2024

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.

Page 28 Muslim Association College of Arts & Science


Programming in Java 2024

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).

Benefits of Inheritance in Java:

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
{
.....
.....
}
}

Page 29 Muslim Association College of Arts & Science


Programming in Java 2024

Following is an example demonstrating Java inheritance.


class A
{
int num = 42;

public void printA()


{
System.out.println("In ClassA: The value of num is " + num);
}
}
class B extends A
{
public void printB()
{
System.out.println("In ClassB: The value of num is " + num);
}
}

public class Main


{
public static void main(String[ ] args)
{
B objB = new B(); //Creating object of class B
objB.printA(); //calling function of class A using object of class B
objB.printFromClassB();//calling function of class Busing object of class B
}
}

Output
In ClassA: The value of num is 42
In ClassB: The value of num is 42

Page 30 Muslim Association College of Arts & Science


Programming in Java 2024

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.

Page 31 Muslim Association College of Arts & Science


Programming in Java 2024

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

Page 32 Muslim Association College of Arts & Science


Programming in Java 2024

Example

Class A
{
................
...............
}
Class B extends A
{
..............
.................
}
Class C extends A
{
..............
.................
}
Class D extends A
{
..............
.................
}
4.Hybrid Inheritance (Not Supported in Java)

 It is a combination of multiple and multilevel inheritance.


 Java does not support hybrid inheritance directly because of complexity issues like the
diamond problem.
 Hybrid inheritance is often avoided in Java, but can be simulated using interfaces.

Page 33 Muslim Association College of Arts & Science


Programming in Java 2024

Method- Overriding (Runtime Polymorphism)


 Method overriding occurs when a subclass provides its own specific implementation
of a method that is already defined in its superclass.

 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

Page 34 Muslim Association College of Arts & Science


Programming in Java 2024

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:

1. Access Parent Class Constructor

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();

2. Access Parent Class Methods

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();

3. Access Parent Class Fields

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;

4. Access Parent Class Object


You can use super to refer to the parent class’s object from within the subclass.

 super() is used to call the parent class constructor.


 super.method() is used to call a method of the parent class.
 super.field is used to refer to a field of the parent class if it is shadowed by a field in
the subclass.
 super can be used to refer to the parent class object explicitly.

Page 35 Muslim Association College of Arts & Science


Programming in Java 2024

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).

1. Final Variables (Constants)


When applied to a variable, the final keyword means that the variable's value cannot be
changed once it is assigned. This is commonly used to create constants.
final int localVar = 50;
2. Final Methods
When a method is declared as final, it cannot be overridden by any subclass. This is useful
when you want to ensure that a method’s behavior remains consistent and is not altered by
subclasses.
final void methodname()
{
}
3. Final Classes
When a class is declared as final, it cannot be subclassed (i.e., no other class can inherit from
it). This is useful when you want to ensure that the behavior of the class cannot be modified
through inheritance.
final class Classname
{
}

Page 36 Muslim Association College of Arts & Science


Programming in Java 2024

Abstract Classes in Java


 An abstract class in Java is a class that cannot be instantiated on its own and is meant
to be subclassed by other classes.
 It can contain both abstract methods (methods without implementation) and
concrete methods (methods with implementation).
 Abstract classes are used to define a common template or blueprint for subclasses,
enforcing that certain methods are implemented in any subclass, while also providing
shared functionality.
 An abstract class can have abstract methods, which are declared without an
implementation (i.e., no method body).
 Subclasses that extend the abstract class must provide concrete implementations for
all abstract methods, unless the subclass is also abstract.
Example
abstract class Animal
{
abstract void sound();
void eat()
{
System.out.println("This animal eats food.");
}
}

class Dog extends Animal


{
void sound()
{
System.out.println("The dog barks.");
}
}
Hera dog class create the definiation of abstract method sound ()

Page 37 Muslim Association College of Arts & Science


Programming in Java 2024

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.

Advantage of Java Package

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.

The package keyword is used to create a package in java.

//save as Simple.java

package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}

Page 38 Muslim Association College of Arts & Science


Programming in Java 2024

How to access package from another package?

 We can invoke package in our program Using packagename.*


 If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
 The import keyword is used to make the classes and interface of another package
accessible to the current package.

Example of package that import the

packagename.* STEP 1: Create Package

//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

STEP 2: Call Package to Program

//save by B.java
import pack.*;
class B
{

public static void main(String args[])

{
A obj = new A();
obj.msg();
}
}

Output:Hello

Page 39 Muslim Association College of Arts & Science


Programming in Java 2024

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;

Access Modifiers in Java


 In Java, access modifiers are keywords that determine the visibility or accessibility of
classes, methods, constructors, and fields.
 They specify where a particular class, method, or field can be accessed from within
the code, ensuring proper encapsulation and security.

There are four main types of access modifiers in Java:


1. public:
o The public modifier allows unrestricted access to the class, method, or field
from anywhere in the program, whether it's within the same package or from
other packages.
o A public class or member is accessible by any other class in the system.
2. private:
o The private modifier restricts access to the class, method, or field to only
within the same class where it is defined.
o It cannot be accessed from outside the class, not even by subclasses or classes
in the same package.
3. protected:
o The protected modifier allows access within the same package and by
subclasses (including those in different packages).

o It provides more accessibility than private but less than public.

Page 40 Muslim Association College of Arts & Science


Programming in Java 2024

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.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?

An interface is declared by using the interface keyword.

Syntax:

interface <interface_name>

{
………..
}

Page 41 Muslim Association College of Arts & Science


Programming in Java 2024

Java Interface Example

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");
}

public static void main(String args[])

{
B obj = new B();
obj.print();
}
}

Java I/O (Input/Output) Packages


 In Java, Input/Output (I/O) refers to the processes of reading from and writing to
external sources
 Java provides a rich set of classes and interfaces for performing I/O operations,
primarily found in the java.io package.
 There are two types of IO Packages in java

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:

Page 42 Muslim Association College of Arts & Science


Programming in Java 2024

 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.

2. Key Interfaces in java.io:


 Serializable: This interface is used to mark classes whose objects can be serialized
(converted into a byte stream) and deserialized (converted back to an object).
 Closeable: This interface is implemented by classes that can be closed after their
operations are done
 Readable and Writable: These interfaces define methods for reading and writing
data. They are implemented by character streams like Reader and Writer.

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.

Page 43 Muslim Association College of Arts & Science


Programming in Java 2024

File class in Java


 The File class in Java is used for representing and manipulating files and directories in the file
system.
 It provides a variety of methods to interact with files and directories, but it does not provide
methods for reading or writing file contents.
 Instead, it's mainly used for tasks like file creation, deletion, renaming, checking properties,
and navigating the file system.
Here's a breakdown of its primary uses:

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.

***************** END OF MODULE 2 *****************

Page 44 Muslim Association College of Arts & Science


Programming in Java 2024

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.

Page 45 Muslim Association College of Arts & Science


Programming in Java 2024

Exception Handling in Java


 The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that normal flow of the application can be
maintained.
 In this page, we will learn about Java exceptions, its type and the difference
between checked and unchecked exceptions.
What is Exception in Java
 Exception is an abnormal condition.
 In Java, an exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
What is Exception Handling
 Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Advantage of Exception Handling
 The core advantage of exception handling is to maintain the normal flow of the
application.
 An exception normally disrupts the normal flow of the application that is why we
use exception handling.
Exception Handling Technique
There are 4 keywords which are used in handling exceptions in Java.
Try
"try" keyword is used to specify a block where we should place exceptioncode.
Catch
The "catch" block is used to handle the exception.
finally
The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.
throw
The "throw" keyword is used to throw an exception.

Page 46 Muslim Association College of Arts & Science


Programming in Java 2024

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.");
}
}
}

Page 47 Muslim Association College of Arts & Science


Programming in Java 2024

Creating Your Own Exceptions


 In Java, you can create your own custom exceptions by defining a new class that
extends either Exception
 This allows you to create exceptions that are specific to your application's needs.
Steps to Create Your Own Exception in Java:
1. Extend the Exception Class:
To create a custom exception, extend the Exception class (or
RuntimeException for unchecked exceptions).
2. Provide a Constructor:
Define a constructor in your custom exception class to accept an error message
or other details.
3. Optionally, Add Custom Methods:
You can add methods to your custom exception class if you need additional
functionality (e.g., to store specific data).
// Custom Exception Class
public class MyException extends Exception
{
public MyException(String message)
{
super(message);
}
}

Page 48 Muslim Association College of Arts & Science


Programming in Java 2024

Thread in java
 A thread is a lightweight sub process, a 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 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.

Life cycle of a Thread (Thread States)

 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.

Page 49 Muslim Association College of Arts & Science


Programming in Java 2024

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.

Page 50 Muslim Association College of Arts & Science


Programming in Java 2024

4.Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5.Terminated

A thread is in terminated or dead state when its run() method exits.

Creation of new Threads


There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.

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

class Multi extends Thread


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}

Page 51 Muslim Association College of Arts & Science


Programming in Java 2024

}
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...

Multithreaded Programming in Java


 Multithreaded programming in Java allows a program to perform multiple tasks
concurrently by using multiple threads.
 Each thread runs a part of the program independently, enabling more efficient use of
system resources and faster execution, especially on multi-core processors.
 A thread is the smallest unit of execution in a program. A Java program can have
multiple threads running simultaneously.
 The Java Virtual Machine (JVM) and the underlying operating system manage thread
scheduling, deciding the order in which threads are executed.

Page 52 Muslim Association College of Arts & Science


Programming in Java 2024

 Java provides higher-level concurrency utilities in the java.util.concurrent package,


such as ExecutorService, CountDownLatch, and Semaphore, to simplify
multithreading and manage thread execution efficiently
Benefits of Multithreading:
 Improved Performance: Concurrent tasks can be executed on multi-core processors,
speeding up execution.
 Better Resource Utilization: Multithreading allows better use of system resources
(e.g., CPU and memory).
 Responsiveness: It makes applications more responsive (e.g., UI applications can
continue running while performing background tasks).

Thread Priorities in Java


In Java, thread priority determines the likelihood of a thread being selected for execution
before other threads.

It helps control the order in which threads are scheduled, especially when there are multiple
threads competing for CPU time.

Priority Range:

 Java threads have priorities ranging from Thread.MIN_PRIORITY (1) to


Thread.MAX_PRIORITY (10), with the default being Thread.NORM_PRIORITY
(5).

Setting Thread Priority:

 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.

Page 53 Muslim Association College of Arts & Science


Programming in Java 2024

Default Priority:

 By default, all threads have a priority of Thread.NORM_PRIORITY (5).

******************** END OF MODULE 3 ********************

Page 54 Muslim Association College of Arts & Science


Programming in Java 2024

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.

Page 55 Muslim Association College of Arts & Science


Programming in Java 2024

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

Structure of an Applet Program


The basic structure of an applet program in Java follows a defined life cycle, and it
typically consists of several key components. Here’s a simple structure of a Java applet
program
1. Importing the Necessary Packages
 To use applet-related classes and components, you need to import the java.applet
package and possibly java.awt for GUI components.
import java.applet.Applet;
import java.awt.Graphics;

Page 56 Muslim Association College of Arts & Science


Programming in Java 2024

2. Applet Class Definition


 Your applet class must extend the Applet class or its subclass. This class contains the
methods that define the behavior of the applet.
public class MyApplet extends Applet
{
}
3. Override the paint() Method
 The paint() method is used to display content (like graphics or text) on the applet
window. It is called every time the applet needs to redraw its display.
public void paint(Graphics g)
{
g.drawString("Hello, Applet!", 20, 20);
}
Example of a java program to show the text in window as I Love MACAS

Import java.applet.*;
import java.awt.*;
public class myapplet extends Applet
{
public void pain(Graphics g)
{
g.drawString ("I Love MACAS", 25,
50);
}
}

Page 57 Muslim Association College of Arts & Science


Programming in Java 2024

Life Cycle of Applet


The life cycle of an applet defines the sequence of events that occur from the time the applet
is loaded into the browser or applet viewer until it is unloaded.
1. init() — Initialization Phase:
 This method is called once when the applet is first loaded.
 It is used to initialize the applet
 It is automatically by the browser or applet viewer when the applet is loaded.
2. start() — Start Phase:
 This method is called after init() and every time the applet becomes visible.
 It is used to start or resume tasks, like animations or threads.
 It is called automatically after init()
3. paint(Graphics g) — Painting Phase:
 This method is called whenever the applet needs to draw its content
 The paint() method is used to display graphics, text, or other visual content.
4. stop() — Stop Phase:
 It is used to stop tasks, like halting animations or threads, and release resources.
 It is called automatically when the applet is hidden or the user leaves the page.
5. destroy() — Destroy Phase:
 This method is called when the applet is unloaded from memory
 It called automatically when the applet is destroyed (usually when the browser is
closed or the applet is removed).

Page 58 Muslim Association College of Arts & Science


Programming in Java 2024

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.

Page 59 Muslim Association College of Arts & Science


Programming in Java 2024

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();
}
}

Page 60 Muslim Association College of Arts & Science


Programming in Java 2024

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.

Page 61 Muslim Association College of Arts & Science


Programming in Java 2024

 JDialog: For creating dialog boxes.

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

Event Delegation Model


 The Event Delegation Model in Java is the primary approach used for handling
events in graphical user interface (GUI) applications.
 This model is based on the Observer Pattern, where events are "delegated" to
listeners that are registered to handle them.
Key Concepts of the Event Delegation Model:
1. Event Source:
 This is the object that generates the event, such as a button, text field, or
window.
 For example, when a user clicks a button, the button is the event source.
2. Event Listener:
 An interface that contains methods to handle specific events.
 Listeners are registered with the event source and are notified when the event
occurs. Common listener interfaces include:
o ActionListener for button clicks.
o MouseListener for mouse events.
o KeyListener for keyboard events.

Page 62 Muslim Association College of Arts & Science


Programming in Java 2024

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.

Different Events and Corresponding Listeners/Adapters


1. Action Event
 Event: Triggered when a user interacts with a button, menu item, or other
components that can "perform an action."
 Listener: ActionListener
o Method: actionPerformed(ActionEvent e)
 Example: Button click, menu selection.

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.)

Page 63 Muslim Association College of Arts & Science


Programming in Java 2024

 Methods: mouseClicked(MouseEvent e), mousePressed(MouseEvent


e), mouseReleased(MouseEvent e), mouseEntered(MouseEvent e),
mouseExited(MouseEvent e)
o MouseMotionListener (for mouse movement or dragging)
 Methods: mouseMoved(MouseEvent e), mouseDragged(MouseEvent
e)

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)

Page 64 Muslim Association College of Arts & Science


Programming in Java 2024

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.

Why use JDBC


Before JDBC, ODBC API was the database API to connect and execute query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).

JDBC Components
The JDBC API provides the following interfaces and classes –

Page 65 Muslim Association College of Arts & Science


Programming in Java 2024

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.

Page 66 Muslim Association College of Arts & Science


Programming in Java 2024

Java Socket Programming


 Java Socket programming is used for communication between the applications
running on different JRE.
 Java Socket programming can be connection-oriented or connection-less.
 Socket and ServerSocket classes are used for connection-oriented socket
programming and DatagramSocket and DatagramPacket classes are used for
connection-less socket programming.

The client in socket programming must know two information

1. IP Address of Server, and


2. Port number.

Working of client –server programming using socket programming

Page 67 Muslim Association College of Arts & Science


Programming in Java 2024

 Here, we are going to make one-way client and server communication.


 In this application, client sends a message to the server, server reads the message and
prints it.
 Here, two classes are being used: Socket and ServerSocket.
 The Socket class is used to communicate client and server.
 Through this class, we can read and write message.
 The ServerSocket class is used at server-side.
 The accept() method of ServerSocket class blocks the console until the client is
connected. After the successful connection of client, it returns the instance of Socket
at server-side.

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()

3) public synchronized void


closes this socket
close()

Page 68 Muslim Association College of Arts & Science


Programming in Java 2024

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

returns the socket and establish a


1) public Socket accept()
connection between server and client.

2) public synchronized void close() closes the server socket.

Example of Java Socket Programming


Creating Server:

 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.

ServerSocket ss=new ServerSocket(6666);


Socket s=ss.accept();//establishes connection and waits for the client

Page 69 Muslim Association College of Arts & Science


Programming in Java 2024

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.

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

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);

Page 70 Muslim Association College of Arts & Science


Programming in Java 2024

DataOutputStream dout=new DataOutputStream(s.getOutputStream());


dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}

************************* END OF MODULE 4 *************************

Page 71 Muslim Association College of Arts & Science

You might also like