0% found this document useful (0 votes)
19 views314 pages

Java Intro

Uploaded by

Techni Hemanth
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
19 views314 pages

Java Intro

Uploaded by

Techni Hemanth
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 314

What is Java?

The Java programming


language was developed
by James Gosling Sun
Microsystems in the early
1990s.
Java is a popular
programming language,
created in 1995.
It is owned by Oracle, and
more than 3 billion devices
run Java.
It is used for:
 Mobile applications
(specially Android apps)
 Desktop applications
 Web applications
 Web servers and
application servers
 Games
 Database connection
 And much, much more!
Why Use Java?
 Java works on different
platforms (Windows, Mac,
Linux, Raspberry Pi, etc.)
 It is one of the most
popular programming
language in the world
 It is easy to learn and
simple to use
 It is open-source and free
 It is secure, fast and
powerful
 It has a huge community
support (tens of millions of
developers)
 Java is an object oriented
language which gives a
clear structure to programs
and allows code to be
reused, lowering
development costs
 As Java is close to C+
+ and C#, it makes it easy
for programmers to switch
to Java or vice versa
Java virtual machine
A Java virtual
machine (JVM) is a virtual
machine that enables a
computer to run Java
programs as well as
programs written in other
languages that are also
compiled to Java bytecode.
Java Syntax
we created a Java file
called Main.java, and we
used the following code to
print "Hello World" to the
screen:
public class Main {
public static void
main(String[] args) {
System.out.println("Hello
World");
}
}
Every line of code that runs in
Java must be inside a class. In
our example, we named the
class Main. A class should
always start with an
uppercase first letter.
Note: Java is case-sensitive:
"MyClass" and "myclass"
has different meaning.
The name of the java file must
match the class name. When
saving the file, save it using
the class name and add
".java" to the end of the
filename.
The main Method
The main() method is
required and you will see it
in every Java program:

public static void


main(String[] args)
Any code inside
the main() method will be
executed. You don't have to
understand the keywords
before and after main.
System.out.println()
Inside the main() method,
we can use
the println() method to
print a line of text to the
screen:
public static void
main(String[] args) {
System.out.println("Hello
World");
}
Java Comments
Comments can be used to
explain Java code, and to
make it more readable. It can
also be used to prevent
execution when testing
alternative code.
Single-line Comments
Single-line comments start
with two forward slashes (//).
Any text between // and the
end of the line is ignored by
Java (will not be executed).
This example uses a single-
line comment before a line of
code:
Java Multi-line Comments
Multi-line comments start
with /* and ends with */.
Any text
between /* and */ will be
ignored by Java.
Java Variables
In Java, there are
different types of variables,
for example:
 String - stores text, such as
"Hello". String values are
surrounded by double
quotes
 int - stores integers (whole
numbers), without
decimals, such as 123 or -
123
 float - stores floating point
numbers, with decimals,
such as 19.99 or -19.99
 char - stores single
characters, such as 'a' or
'B'. Char values are
surrounded by single
quotes
 boolean - stores values with
two states: true or false
Declaring (Creating)
Variables

To create a variable, you


must specify the type and
assign it a value:
Syntax
type variable = value;

Example
public class Main {
public static void
main(String[] args) {
String name = "John";
System.out.println(name);
}
}
To create a variable that
should store a number, look
at the following example:
Create a variable
called myNum of
type int and assign it the
value 15:
public class Main {
public static void
main(String[] args) {
int myNum = 15;
System.out.println(myNum
);
}
}
Other Types
A demonstration of how to
declare variables of other
types:
int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";
Display Variables
The println() method is often
used to display variables.
To combine both text and a
variable, use the + character:
public class Main {
public static void
main(String[] args) {
String name = "John";
System.out.println("Hello "
+ name);
}
}
You can also use
the + character to add a
variable to another variable:
Example
public class Main {
public static void
main(String[] args) {
String firstName = "John
";
String lastName =
"Doe";
String fullName =
firstName + lastName;
System.out.println(fullNam
e);
}
}
For numeric values,
the + character works as a
mathematical operator
(notice that we
use int (integer) variables
here):

public class Main {


public static void
main(String[] args) {
int x = 5;
int y = 6;
System.out.println(x +
y); // Print the value of x + y
}
}
Declare Many Variables
To declare more than one
variable of the same type,
use a comma-separated list:
public class Main {
public static void
main(String[] args) {
int x = 5, y = 6, z = 50;
System.out.println(x + y
+ z);
}
}
Java Identifiers
All Java variables must
be identified with unique
names.
These unique names are
called identifiers.
public class Main {
public static void
main(String[] args) {
// Good
int minutesPerHour = 60;
// OK, but not so easy to
understand what m actually
is
int m = 60;

System.out.println(minutes
PerHour);
System.out.println(m);
}
}
Java Data Types
variable in Java must be a
specified data type:
public class Main {
public static void
main(String[] args) {
int myNum =
5; // integer (whole
number)
float myFloatNum =
5.99f; // floating point
number
char myLetter = 'D';
// character
boolean myBool = true;
// boolean
String myText = "Hello";
// String
System.out.println(myNum
);
System.out.println(myFloat
Num);
System.out.println(myLette
r);
System.out.println(myBool)
;
System.out.println(myText)
;
}
}
Data types are divided into
two groups:
 Primitive data types -
includes byte, short, int, lon
g, float, double, boolean an
d char
 Non-primitive data types -
such
as String, Arrays and Class
es (you will learn more
about these in a later
chapter)
Booleans
A boolean data type is
declared with
the boolean keyword and
can only take the
values true or false:
public class Main {
public static void
main(String[] args) {
boolean isJavaFun =
true;
boolean isFishTasty =
false;
System.out.println(isJavaF
un);
System.out.println(isFishTa
sty);
}
}
Characters
The char data type is used
to store a single character.
The character must be
surrounded by single
quotes, like 'A' or 'c':
public class Main {
public static void
main(String[] args) {
char myGrade = 'B';
System.out.println(myGrad
e);
}
}
Alternatively, you can use
ASCII values to display
certain characters:
public class Main {
public static void
main(String[] args) {
char a = 65, b = 66, c =
67;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
Strings
The String data type is used
to store a sequence of
characters (text). String
values must be surrounded
by double quotes:
public class Main {
public static void
main(String[] args) {
String greeting = "Hello
World";
System.out.println(greeting
);
}
}
Non-Primitive Data Types
Non-primitive data types are
called reference types because
they refer to objects.
The main difference
between primitive and non-
primitive data types are:
 Primitive types are
predefined (already
defined) in Java. Non-
primitive types are created
by the programmer and is
not defined by Java (except
for String).
Java Type Casting
Type casting is when you
assign a value of one primitive
data type to another type.
In Java, there are two types of
casting:
 Widening
Casting (automatically) -
converting a smaller type to
a larger type size
byte -> short -> char -> int -
> long -> float -> double
 Narrowing
Casting (manually) -
converting a larger type to
a smaller size type
double -> float -> long -> in
t -> char -> short -> byte
Widening Casting

 Widening casting is done


automatically when passing
a smaller size type to a
larger size type:
public class Main {
public static void
main(String[] args) {
int myInt = 9;
double myDouble =
myInt; // Automatic
casting: int to double

System.out.println(myInt);
System.out.println(myDoub
le);
}
}
Narrowing Casting
Narrowing casting must be
done manually by placing the
type in parentheses in front of
the value:
public class Main {
public static void
main(String[] args) {
double myDouble =
9.78d;
int myInt = (int)
myDouble; // Explicit
casting: double to int

System.out.println(myDoub
le);
System.out.println(myInt);
}
}
Java Operators
Operators are used to
perform operations on
variables and values.
In the example below, we use
the + operator to add together
two values:
public class Main {
public static void
main(String[] args) {
int sum1 = 100 + 50;
int sum2 = sum1 + 250;
int sum3 = sum2 + sum2;
System.out.println(sum1);
System.out.println(sum2);
System.out.println(sum3);
}
}
Java Assignment Operators
Assignment operators are
used to assign values to
variables.
In the example below, we use
the assignment operator (=) to
assign the value 10 to a
variable called x:
public class Main {
public static void
main(String[] args) {
int x = 10;
System.out.println(x);
}
}
Java Comparison Operators
Comparison operators are
used to compare two
values:

public class Main {


public static void
main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x ==
y); // returns false because 5
is not equal to 3
}
}

Java Logical Operators


Logical operators are used
to determine the logic
between variables or
values:
public class Main {
public static void
main(String[] args) {
int x = 5;
System.out.println(x > 3
&& x < 10); // returns true
because 5 is greater than 3
AND 5 is less than 10
}
}

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:
Syntax
String[] cars;
Example
String[] cars = {"Volvo",
"BMW", "Ford",
"Mazda"};
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.
Example
public class Main {
public static void
main(String[] args) {
String[] cars =
{"Volvo", "BMW",
"Ford", "Mazda"};
System.out.println(car
s[0]);
}
}
Array Length
To find out how many
elements an array has,
use
the length property:
Example
public class Main {
public static void
main(String[] args) {
String[] cars =
{"Volvo", "BMW",
"Ford", "Mazda"};
System.out.println(car
s.length);
}
}

Loop Through an Array


You can loop through
the array elements
with the for loop, and
use the length property
to specify how many
times the loop should
run.
The following example
outputs all elements in
the cars array:
Example
public class Main {
public static void
main(String[] args) {
String[] cars =
{"Volvo", "BMW",
"Ford", "Mazda"};
for (int i = 0; i <
cars.length; i++) {
System.out.println(car
s[i]);
}
}
}
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:
Example
public class Main {
public static void
main(String[] args) {
int[][] myNumbers
= { {1, 2, 3, 4}, {5, 6,
7} };
int x =
myNumbers[1][2];
System.out.println(x);
}
}

Java Classes/Objects
Java is an object-
oriented programming
language.
Everything in Java is
associated with
classes and objects,
along with its
attributes and
methods.
Create a Class
To create a class, use
the keyword class:
Example
Create a class named
"Main" with a variable
x:
public class Main {
int x = 5;
}
Create an Object
In Java, an object is
created from a class.
We have already
created the class
named Main, so now
we can use this to
create objects.
To create an object
of Main, specify the
class name, followed
by the object name,
and use the
keyword new:
Example:
Create an object called
"myObj" and print the
value of x
public class Main {
int x = 5;
public static void
main(String[] args) {
Main myObj = new
Main();
System.out.println(my
Obj.x);
}
}
Multiple Objects
You can create
multiple objects of one
class:
Example
public class Main {
int x = 5;
public static void
main(String[] args) {
Main myObj1 = new
Main();
Main myObj2 = new
Main();
System.out.println(my
Obj1.x);
System.out.println(my
Obj2.x);
}
}
Using Multiple Classes
You can also create an
object of a class and
access it in another
class. This is often
used for better
organization of classes
(one class has all the
attributes and
methods, while the
other class holds
the main() method
(code to be
executed)).
Remember that the
name of the java file
should match the class
name. In this example,
we have created two
files in the same
directory/folder:
 Main.java
 Second.java
Example
public class Main {
int x = 5;
}
Main.java
class Second {

public static void


main(String[] args) {
Main myObj = new
Main();
System.out.println(my
Obj.x);
}
}
Second.java
When both files have
been compiled:
C:\Users\Your
Name>javac Main.java
C:\Users\Your
Name>javac
Second.java
Run the Second.java
file:
C:\Users\Your
Name>java Second
Java Class Attributes
In the previous
chapter, we used the
term "variable" for x in
the example (as
shown below). It is
actually an attribute of
the class. Or you could
say that class
attributes are
variables within a
class:
Example
Create a class called
"Main" with two
attributes: x and y:
public class Main {
int x = 5;
int y = 3;
}
Accessing Attributes
You can access
attributes by creating
an object of the class,
and by using the dot
syntax (.):
The following example
will create an object of
the Main class, with the
name myObj. We use
the x attribute on the
object to print its
value:
Example
Create an object called
"myObj" and print the
value of x:
public class Main {
int x = 5;
public static void
main(String[] args) {
Main myObj = new
Main();
System.out.println(my
Obj.x);
}
}
Modify Attributes
You can also modify
attribute values:
Example
Set the value of x to
40:
public class Main {
int x;

public static void


main(String[] args) {
Main myObj = new
Main();
myObj.x = 40;
System.out.println(my
Obj.x);
}
}
Multiple Objects
If you create multiple
objects of one class,
you can change the
attribute values in one
object, without
affecting the attribute
values in the other:
Example
public class Main {
int x = 5;
public static void
main(String[] args) {
Main myObj1 = new
Main();
Main myObj2 = new
Main();
myObj2.x = 25;
System.out.println(my
Obj1.x);
System.out.println(my
Obj2.x);
}
}
Java Class Methods
The Java
Methods chapter that
methods are declared
within a class, and
that they are used to
perform certain
actions:
Example:
public class Main {
static void
myMethod() {
System.out.println("H
ello World!");
}

public static void


main(String[] args) {
myMethod();
}
}
Access Methods With an
Object
Example:
Create a Car object
named myCar. Call the
fullThrottle() and
speed() methods on
the myCar object, and
run the program:
// Create a Main class
public class Main {
// Create a
fullThrottle() method
public void
fullThrottle() {
System.out.println("Th
e car is going as fast
as it can!");
}
// Create a speed()
method and add a
parameter
public void speed(int
maxSpeed) {
System.out.println("M
ax speed is: " +
maxSpeed);
}
// Inside main, call
the methods on the
myCar object
public static void
main(String[] args) {
Main myCar = new
Main(); // Create a
myCar object
myCar.fullThrottle();
// Call the
fullThrottle() method
myCar.speed(200);
// Call the speed()
method
}
}
Java Constructors
A constructor in Java
is a special
method that is used to
initialize objects. The
constructor is called
when an object of a
class is created. It can
be used to set initial
values for object
attributes:
Example:
// Create a Main class
public class Main {
int x;

// Create a class
constructor for the
Main class
public Main() {
x = 5;
}

public static void


main(String[] args) {
Main myObj = new
Main();
System.out.println(my
Obj.x);
}
}
Java Modifiers
By now, you are quite
familiar with
the public keyword
that appears in almost
all of our examples:
public class Main
The public keyword is
an access modifier,
meaning that it is used
to set the access level
for classes, attributes,
methods and
constructors.
We divide modifiers
into two groups:
 Access Modifiers -
controls the access
level
 Non-Access
Modifiers - do not
control access level,
but provides other
functionality
 Access Modifiers
For classes, you can
use either public .
For attributes,
methods and
constructors, you can
use the one of the
following:
Private:
public class Main {
private String fname
= "John";
private String lname
= "Doe";
private String email
= "john@doe.com";
private int age = 24;

public static void


main(String[] args) {
Main myObj = new
Main();
System.out.println("N
ame: " + myObj.fname
+ " " + myObj.lname);
System.out.println("E
mail: " +
myObj.email);
System.out.println("A
ge: " + myObj.age);
}
}
Protected:
class Person {
protected String
fname = "John";
protected String
lname = "Doe";
protected String
email =
"john@doe.com";
protected int age =
24;
}

class Student extends


Person {
private int
graduationYear =
2018;
public static void
main(String[] args) {
Student myObj =
new Student();
System.out.println("N
ame: " + myObj.fname
+ " " + myObj.lname);
System.out.println("E
mail: " +
myObj.email);
System.out.println("A
ge: " + myObj.age);
System.out.println("Gr
aduation Year: " +
myObj.graduationYear
);
}
}
Non-Access Modifiers
For classes, you can
use
either final or abstract
:
1.final--The class
cannot be inherited by
other classes.
2.abstract--The class
cannot be used to
create objects.
Abstract Classes and
Methods
Data abstraction is the
process of hiding
certain details and
showing only essential
information to the
user.
The abstract keyword
is a non-access
modifier, used for
classes and methods:
 Abstract class: is a
restricted class that
cannot be used to
create objects (to
access it, it must be
inherited from
another class).
 Abstract
method: can only be
used in an abstract
class, and it does not
have a body. The
body is provided by
the subclass
(inherited from).
Java User Input
The Scanner class is
used to get user input,
and it is found in
the java.util package.
To use
the Scanner class,
create an object of the
class and use any of
the available methods
found in
the Scanner class
documentation. In our
example, we will use
the nextLine() method,
which is used to read
Strings:
Example
import
java.util.Scanner; //
import the Scanner
class
class Main {
public static void
main(String[] args) {
Scanner myObj =
new
Scanner(System.in);
String userName;
// Enter username
and press Enter
System.out.println("En
ter username");
userName =
myObj.nextLine();
System.out.println("U
sername is: " +
userName);
}
}

Input Types

Method Descriptio
n

nextBoole Reads
an() a boolean v
alue from
the user

nextByte( Reads
) a byte valu
e from the
user

nextDoubl Reads
e() a double va
lue from
the user

nextFloat Reads
() a float val
ue from
the user

nextInt() Reads
a int value
from the
user

nextLine( Reads
) a String va
lue from
the user

nextLong( Reads
) a long valu
e from the
user

nextShort Reads
() a short val
ue from
the user
Example:
import
java.util.Scanner;
class Main {
public static void
main(String[] args) {
Scanner myObj =
new
Scanner(System.in);
System.out.println("En
ter name, age and
salary:");
// String input
String name =
myObj.nextLine();
// Numerical input
int age =
myObj.nextInt();
double salary =
myObj.nextDouble();
// Output input by
user
System.out.println("N
ame: " + name);
System.out.println("A
ge: " + age);
System.out.println("Sa
lary: " + salary);
}
}
Java Methods
A method is a block of
code which only runs
when it is called.
You can pass data,
known as parameters,
into a method.
Methods are used to
perform certain
actions, and they are
also known
as functions.
Create a Method
A method must be
declared within a
class. It is defined
with the name of the
method, followed by
parentheses (). Java
provides some pre-
defined methods, such
as System.out.println(),
but you can also
create your own
methods to perform
certain actions:
Example
Create a method inside
Main:
public class Main {
static void
myMethod() {
// code to be
executed
}
}
Call a Method
To call a method in
Java, write the
method's name
followed by two
parentheses () and a
semicolon;
In the following
example, myMethod() is
used to print a text
(the action), when it is
called:
Example
public class Main {
static void
myMethod() {
System.out.println("I
just got executed!");
}

public static void


main(String[] args) {
myMethod();
}
}
Method Overloading
With method
overloading, multiple
methods can have the
same name with
different parameters:
Example:
public class Main {
static int
plusMethodInt(int x,
int y) {
return x + y;
}
static double
plusMethodDouble(do
uble x, double y) {
return x + y;
}
public static void
main(String[] args) {
int myNum1 =
plusMethodInt(8, 5);
double myNum2 =
plusMethodDouble(4.3
, 6.26);
System.out.println("in
t: " + myNum1);
System.out.println("do
uble: " + myNum2);
}
}

Conditional Statements
Java has the following
conditional
statements:
 Use if to specify a
block of code to be
executed, if a
specified condition is
true
 Use else to specify a
block of code to be
executed, if the
same condition is
false
 Use else if to
specify a new
condition to test, if
the first condition is
false
 Use switch to specify
many alternative
blocks of code to be
executed
The if Statement
Use the if statement
to specify a block of
Java code to be
executed if a
condition is true.

Syntax
if (condition) {
// block of code to
be executed if the
condition is true
}

NOTE:Note that if is
in lowercase letters.
Uppercase letters (If
or IF) will generate
an error.

Example
public class Main {
public static void
main(String[] args)
{
if (20 > 18) {
System.out.println("
20 is greater than
18"); // obviously
}
}
}

The else Statement


Use
the else statement to
specify a block of
code to be executed
if the condition
is false.

Syntax

if (condition) {
// block of code to
be executed if the
condition is true
} else {
// block of code to
be executed if the
condition is false
}

Example

public class Main {


public static void
main(String[] args)
{
int time = 20;
if (time < 18) {
System.out.println("
Good day.");
} else {
System.out.println("
Good evening.");
}
}
}

The else if Statement


Use the else
if statement to
specify a new
condition if the first
condition is false.

Syntax

if (condition1) {
// block of code to
be executed if
condition1 is true
} else if (condition2)
{
// block of code to
be executed if the
condition1 is false
and condition2 is
true
} else {
// block of code to
be executed if the
condition1 is false
and condition2 is
false
}
Program

public class Main {


public static void
main(String[] args)
{
int time = 22;
if (time < 10) {
System.out.println("
Good morning.");
} else if (time <
20) {
System.out.println("
Good day.");
} else {
System.out.println("
Good evening.");
}
}
}
Java Switch
Use
the switch statement
to select one of
many code blocks to
be executed.

Syntax

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

Program
This is how it works:
 The switch expressio
n is evaluated once.
 The value of the
expression is
compared with the
values of each case.
 If there is a match,
the associated block
of code is executed.
 The break and default
keywords are
optional, and will be
described later in
this chapter
The example below
uses the weekday
number to calculate
the weekday name:
public class Main {
public static void
main(String[] args)
{
int day = 3;
switch (day) {
case 1:
System.out.println("
Monday");
break;
case 2:
System.out.println("
Tuesday");
break;
case 3:
System.out.println("
Wednesday");
break;
case 4:
System.out.println("
Thursday");
break;
case 5:
System.out.println("
Friday");
break;
case 6:
System.out.println("
Saturday");
break;
case 7:
System.out.println("
Sunday");
break;
}
}
}
The break Keyword
When Java reaches
a break keyword, it
breaks out of the
switch block.

Program
public class Main {
public static void
main(String[] args)
{
int day = 4;
switch (day) {
case 6:
System.out.println("
Today is Saturday");
break;
case 7:
System.out.println("
Today is Sunday");
break;
default:
System.out.println("
Looking forward to
the Weekend");
}
}
}

Loops
Loops can execute a
block of code as long
as a specified
condition is reached.
Loops are handy
because they save
time, reduce errors,
and they make code
more readable.
Java While Loop
The while loop loops
through a block of
code as long as a
specified condition
is true:
Syntax

while (condition) {
// code block to be
executed
}

Program

public class Main {


public static void
main(String[] args)
{
int i = 0;
while (i < 5) {
System.out.println(i)
;
i++;
}
}
}

The Do/While Loop


The do/while loop is a
variant of
the while loop. This
loop will execute the
code block once,
before checking if the
condition is true, then
it will repeat the loop
as long as the
condition is true.
Syntax:
do {
// code block to be
executed
}
while (condition);

Program

public class Main {


public static void
main(String[] args)
{
int i = 0;
do {
System.out.println(i)
;
i++;
}
while (i < 5);
}
}

Java For Loop


When you know
exactly how many
times you want to
loop through a block
of code, use
the for loop instead
of a while loop:
Syntax

for (statement 1;
statement 2;
statement 3) {
// code block to be
executed
}
Example:
public class Main {
public static void
main(String[] args) {
for (int i = 0; i <= 5;
i++) {
System.out.println(i);
}
}
}
Another Example
public class Main {
public static void
main(String[] args) {
for (int i = 0; i <=
10; i = i + 2) {
System.out.println(i);
}
}
}
For-Each Loop
There is also a "for-
each" loop, which is
used exclusively to
loop through elements
in an array:

Syntax:
for (type
variableName :
arrayName) {
// code block to be
executed
}
Program:
public class Main {
public static void
main(String[] args) {
String[] cars =
{"Volvo", "BMW",
"Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
}
}
Java Break
You have already seen
the break statement
used in an earlier
chapter of this
tutorial. It was used to
"jump out" of
a switch statement.
The break statement
can also be used to
jump out of a loop.
Example
public class Main {
public static void
main(String[] args) {
for (int i = 0; i < 10;
i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
}
}
Java Continue
The continue statement
breaks one iteration
(in the loop), if a
specified condition
occurs, and continues
with the next iteration
in the loop.
Example
public class Main {
public static void
main(String[] args) {
for (int i = 0; i < 10;
i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
}
}

Java Packages & API

A package in Java is
used to group related
classes. Think of it
as a folder in a file
directory. We use
packages to avoid
name conflicts, and to
write a better
maintainable code.
Packages are divided
into two categories:
 Built-in Packages
(packages from the
Java API)
 User-defined
Packages (create
your own packages)
Built-in Packages
The Java API is a
library of prewritten
classes, that are free
to use, included in the
Java Development
Environment.
The library is divided
into packages and clas
ses. Meaning you can
either import a single
class (along with its
methods and
attributes), or a whole
package that contain
all the classes that
belong to the specified
package.
To use a class or a
package from the
library, you need to
use
the import keyword:
Syntax
import
package.name.Class;
// Import a single
class
import
package.name.*; //
Import the whole
package

Import a Class

If you find a class you


want to use, for
example,
the Scanner class, whic
h is used to get user
input, write the
following code:
import
java.util.Scanner;
In the example
above, java.util is a
package,
while Scanner is a class
of
the java.util package.
To use
the Scanner class,
create an object of the
class and use any of
the available methods
found in
the Scanner class
documentation. In our
example, we will use
the nextLine() method,
which is used to read a
complete line:
Example:
Using the Scanner class
to get user input:
import
java.util.Scanner; //
import the Scanner
class
class Main {
public static void
main(String[] args) {
Scanner myObj =
new
Scanner(System.in);
String userName;
// Enter username
and press Enter
System.out.println("En
ter username");
userName =
myObj.nextLine();

System.out.println("U
sername is: " +
userName);
}
}
Import a Package

There are many


packages to choose
from. In the previous
example, we used
the Scanner class from
the java.util package.
This package also
contains date and time
facilities, random-
number generator and
other utility classes.
To import a whole
package, end the
sentence with an
asterisk sign (*). The
following example will
import ALL the classes
in
the java.util package:
Example:
import java.util.*; // import
the java.util package
class Main
{
public static void
main(String[] args) {
Scanner myObj = new
Scanner(System.in);
String userName;

// Enter username and


press Enter
System.out.println("Enter
username");
userName =
myObj.nextLine();
System.out.println("Userna
me is: " + userName);
}
}

User-defined Packages

To create your own


package, you need to
understand that Java
uses a file system
directory to store
them. Just like folders
on your computer:
EXAMPLE
└── root
└── mypack
└──
MyPackageClass.java
To create a package,
use
the package keyword:
package mypack;
class MyPackageClass
{
public static void
main(String[] args) {
System.out.println("Th
is is my package!");
}
}
Save the file
as MyPackageClass.jav
a, and compile it:
Open the command
prompt
C:\Users\Your
Name>javac
MyPackageClass.java
Then compile the
package:
C:\Users\Your
Name>javac .
MyPackageClass.java
To run
the MyPackageClass.ja
va file, write the
following:
C:\Users\Your
Name>java main
Applets
An applet is a Java
program that runs in a
Web browser. ..
Applets are small Internet-
based program written in
Java, a programming
language for the Web and
can be downloaded by any
computer. The applet is
also capable of running in
HTML. The applet is
usually embedded in an
HTML page on a Web site
and can be executed from
within a browser.
Benefits
 They are very secure.
 It works at client side so
less response time.
 Applets can be executed
by browsers running
under different platforms.
Life cycle of applet
 init() method
 start() method
 paint() method
 stop() method
 destroy() method
program
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld
extends Applet {
public void
paint(Graphics g) {
g.drawString("Hello
World!", 50, 25);
}
}
Save file as
HelloWorld.java
Now you have to create an
HTML File that Includes
the Applet.

Program
<html>

<head>
<TITLE> A Simple
Program </TITLE>
</head>

<body>
Here is the output of my
program:
<applet
code="HelloWorld.class"
width="150"
height="25"></applet>
</body>

</html>

Save the file


HelloWorld.html

 Open the command


prompt
 Set the path
 Javac
filename.java(Compi
le)
 Appletviewer
filename.html (run)

Java Exceptions

When executing Java


code, different errors
can occur: coding
errors made by the
programmer, errors
due to wrong input, or
other unforeseeable
things.
When an error occurs,
Java will normally stop
and generate an error
message. The
technical term for this
is: Java will throw
an exception (throw
an error).
Java try and catch

The try statement


allows you to define a
block of code to be
tested for errors while
it is being executed.
The catch statement
allows you to define a
block of code to be
executed, if an error
occurs in the try block.
The try and catch keyw
ords come in pairs:
Syntax:

try {
// Block of code to
try
}
catch(Exception e) {
// Block of code to
handle errors
}

Program:

public class Main {


public static void
main(String[ ] args)
{
int[] myNumbers
= {1, 2, 3};
System.out.println(
myNumbers[10]); //
error!
}
}
This will generate an
error, because
myNumbers[10]
does not exist.
Example

public class Main {


public static void
main(String[] args)
{
try {
int[] myNumbers
= {1, 2, 3};
System.out.println(
myNumbers[10]);
} catch (Exception
e) {
System.out.println("
Something went
wrong.");
}
}
}
o/p

Something went
wrong

Finally
The finally statement
lets you execute code,
after try...catch,
regardless of the
result:

public class Main {


public static void
main(String[] args) {
try {
int[] myNumbers =
{1, 2, 3};
System.out.println(my
Numbers[10]);
} catch (Exception
e) {
System.out.println("So
mething went
wrong.");
} finally {
System.out.println("Th
e 'try catch' is
finished.");
}
}
}

o/p
Something went
wrong.
The 'try catch' is
finished.

Java Annotations

Java Annotation is a

tag that represents

the metadata i.e. attached with

class, interface, methods or


fields to indicate some

additional information which

can be used by java compiler

and JVM.

There are 4 categories of


Annotations:-
1. Marker Annotations:
The only purpose is to
mark a declaration. These
annotations contain no
members and do not
consist any data. Thus, its
presence as an annotation
is sufficient. Since, marker
interface contains no
members, simply
determining whether it is
present or absent is
sufficient. @Override is an
example of Marker
Annotation.
Example: -
@TestAnnotation()
2. Single value
Annotations:
These annotations contain
only one member and
allow a shorthand form of
specifying the value of the
member. We only need to
specify the value for that
member when the
annotation is applied and
don’t need to specify the
name of the member.
However in order to use
this shorthand, the name
of the member must
be value.
Example: -
@TestAnnotation(“testin
g”);
3. Full Annotations:
These annotations consist
of multiple data members/
name, value, pairs.
Example:-
@TestAnnotation(owner=”
Rahul”, value=”Class
Geeks”)
4. Type Annotations:
These annotations can be
applied to any place where
a type is being used. For
example, we can annotate
the return type of a
method. These are
declared annotated
with @Target annotation.

Program

class Animal {
public void displayInfo() {
System.out.println("I am
an animal.");
}
}
class Dog extends Animal {
@Override
public void displayInfo() {
System.out.println("I am
a dog.");
}
}

class Main {
public static void
main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}

Generics in Java
Generics mean
parameterized types. The
idea is to allow type
(Integer, String, … etc, and
user-defined types) to be a
parameter to methods,
classes, and interfaces.
Using Generics, it is
possible to create classes
that work with different
data types
The Java

Generics programming is

introduced in J2SE 5 to

deal with type-safe

objects.
Advantage of Java Generics
1) Type-safety: We can
hold only a single type of
objects in generics. It
doesn?t allow to store
other objects. Without
Generics, we can store
any type of objects.
2) 2) Type casting is not
required: There is no
need to typecast the
object.
Before Generics, we need
to type cast.
3) Compile-Time
Checking: It is checked at
compile time so problem
will not occur at runtime.
The good programming
strategy says it is far
better to handle the
problem at compile time
than runtime.
Syntax
Class Or Interface<Type>
Example
Generic class
A class that can refer to
any type is known as a
generic class. Here, we are
using the T type parameter
to create the generic class
of specific type.
class MyGen<T>{
T obj;
void add(T obj)
{this.obj=obj;}
T get(){return obj;}
}
Type Parameters
The type parameters
naming conventions are
important to learn generics
thoroughly. The common
type parameters are as
follows:
1. T - Type
2. E - Element
3. K - Key
4. N - Number
5. V - Value
Generic Method
Like the generic class, we
can create a generic
method that can accept
any type of arguments.
Example

public class TestGenerics4{

public static < E > void pr


intArray(E[] elements) {
for ( E element : eleme
nts){
System.out.println(e
lement );
}
System.out.println();
}
public static void main( S
tring args[] ) {
Integer[] intArray = { 1
0, 20, 30, 40, 50 };
Character[] charArray
= { 'J', 'A', 'V', 'A', 'T','P','O',
'I','N','T' };

System.out.println( "P
rinting Integer Array" );
printArray( intArray );

System.out.println( "Pr
inting Character Array" );
printArray( charArray )
;
}
}

Collections
The Collection in Java is a
framework that provides
an architecture to store
and manipulate the group
of objects.
Java Collections can
achieve all the operations
that you perform on a data
such as searching, sorting,
insertion, manipulation,
and deletion.
Java Collection means a
single unit of objects. Java
Collection framework
provides many interfaces
(Set, List, Queue, Deque)
and classes (ArrayList,
Vector, LinkedList, Priority
Queue, HashSet,
LinkedHashSet, TreeSet).

LinkedList
LinkedList implements the

Collection interface. It uses

a doubly linked list

internally to store the

elements. It can store the

duplicate elements
List Interface

List interface is the child

interface of Collection

interface. It inhibits a list

type data structure in

which we can store the


ordered collection of

objects. It can have

duplicate values.

List <data-type> list1= new

ArrayList();

List <data-type> list2 = new

LinkedList();
List <data-type> list3 = new

Vector();

List <data-type> list4 = new

Stack();

Program:

import java.io.*;

import java.util.*;
class GFG {
public static void
main(String[] args)
{

// Declaring the
LinkedList
LinkedList<Integer> ll
= new
LinkedList<Integer>();
// Appending new
elements at
// the end of the
list
for (int i = 1; i <=
5; i++)
ll.add(i);

// Printing
elements
System.out.println(ll);
// Remove element
at index 3
ll.remove(3);

// Displaying the
List
// after deletion
System.out.println(ll);

// Printing
elements one by one
for (int i = 0; i <
ll.size(); i++)
System.out.print(ll.get(i)
+ " ");
}
}
JAVA THREADING
Threads allows a
program to operate
more efficiently by
doing multiple things
at the same time.
Creating a Thread
There are two ways to
create a thread.
It can be created by
extending
the Thread class and
overriding
its run() method:

Extend Syntax
public class Main
extends Thread {
public void run() {
System.out.println("Th
is code is running in a
thread");
}
}
Another way to create
a thread is to
implement
the Runnable interface:
Implement syntax

public class Main


implements Runnable
{
public void run() {
System.out.println("Th
is code is running in a
thread");
}
}
Life cycle of a Thread
(Thread States)
The life cycle of the thread
in java is controlled by
JVM. The java thread states
are as follows:
1. NEW – a newly created thread
that has not yet started the
execution
2. RUNNABLE – either running
or ready for execution but it's
waiting for resource allocation
3. WAITING – waiting for some
other thread to perform a
particular action without any time
limit
4. TIMED_WAITING – waiting
for some other thread to perform
a specific action for a specified
period
5. TERMINATED – has
completed its execution

Example:
class
MultithreadingDemo
extends Thread{
public void run(){
System.out.println("My
thread is in running
state.");
}
public static void
main(String args[]){
MultithreadingDemo
obj=new
MultithreadingDemo();
obj.start();
}
}

Serialization and
Deserialization in Java
Serialization in Java is a
mechanism of writing the
state of an object into a
byte-stream. It is mainly
used in Hibernate, RMI,EJB
technologies.
The reverse operation of
serialization is
called deserialization wher
e byte-stream is converted
into an object. The
serialization and
deserialization process is
platform-independent, it
means you can serialize an
object on one platform and
deserialize it on a different
platform.
For serializing the object,
we call
the writeObject() method
of ObjectOutputStream clas
s, and for deserialization
we call
the readObject() method
of ObjectInputStream class.
Advantages of Java
Serialization
It is mainly used to travel
object's state on the
network
Serialization
import java.io.*;
class Persist{
public static void
main(String args[]){
try{
//Creating the object
Student s1 =new
Student(211,"ravi");
//Creating stream and
writing the object
FileOutputStream
fout=new
FileOutputStream("f.txt");
ObjectOutputStream
out=new
ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
System.out.println("succe
ss");
}catch(Exception e)
{
System.out.println(e);}
}
}
Deserialization
import java.io.*;
class Depersist{
public static void
main(String args[]){
try{
//Creating stream to read
the object
ObjectInputStream
in=new
ObjectInputStream(new
FileInputStream("f.txt"));
Student
s=(Student)in.readObject();
//printing the data of the
serialized object
System.out.println(s.id+"
"+s.name);
//closing the stream
in.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}

SOCKET
A socket is simply an
endpoint for
communications between
the machines.
The Socket class can be
used to create a socket.
Java Socket programming
can be connection-oriented
or connection-less.
1. IP Address ->An IP
address is a unique
address that identifies a
device on the internet or
a local network.
2. Port number.->Port
number is the part of the
addressing information
used to identify the
senders and receivers of
messages
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.
he 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 Descriptio

1) public returns

InputStream the

getInputStrea InputStrea

m() m

attached
with this

socket.

2) public returns

OutputStream the

getOutputStre OutputStr

am() eam

attached
with this

socket.

3) public closes

synchronized this socket

void close()

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

1) public returns the

Socket socket and

accept() establish a
connection

between

server and

client.

2) public closes the

synchronize server

d void
close() socket.

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
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);
Example
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.getInpu
tStream());
String
str=(String)dis.readUTF();
System.out.println("messa
ge= "+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);
DataOutputStream
dout=new
DataOutputStream(s.getOu
tputStream());
dout.writeUTF("Hello
Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e)
{System.out.println(e);}
}
}
To execute this program
open two command
prompts and execute each
program at each command
prompt as displayed in the
below figure.
After running the client
application, a message will
be displayed on the server
console.
JDBC
Java Database
Connectivity (JDBC) is
an application
programming interface
(API) for the programming
language Java, which
defines how a client may
access a database. It is a
Java-based data access
technology used for Java
database connectivity.
JDBC API
It contains group of
interfaces and classes
Using API developers,
write a code to interact
with a database and
retrieve the
information using the
SQL statements
A class which is
responsible for JDBC
connection with the
database is JDBC Driver
Manager.
JDBC Driver Manager
A connection factory
for executing
statements such as SQL
INSERT, UPDATE and
DELETE.
Driver Manager is the
backbone of the JDBC
architecture.
In short JDBC helps the
programmers to write
java applications that
manage these three
programming activities:
Connecting to a
database
Executing queries and
updating statements
to the database
Retrieving and
processing the results
received from the
database.
Why JDBC needed?
Installable, Portable and
Secure
“Language Portability”
across different Database
vendor languages
Provides “Write one time
and run at any time”
capability for the
application which
requires access to
database.
Connecting to Relational
Database
RDBMS
Advanced concept of
the DBMS
Stores both data and
also the relationship
among the data in the
form of table
Each record in the
table is called Tuple.
Use referential
integrity constraint to
place the records into
table.
Tuple: Each record (All
the Information about
a person)
Attribute: Each column
(Particular information
about the entire
person)
Table: Collection of Tuple
and Attribute
DBMS
records are not
arranged in uniform
manner
RDBMS
records are arranged in
sequential manner
It can be retrieved
more efficiently and
quickly
Keys:
A attribute or
collection of attribute
to identify a record
Keys are essential in
RDBMS
Types of Keys
Primary Key – To
identify a unique row
in a table ( Eg:
Employee ID in
Employee table)
Foreign Key - An
attribute in a table to
uniquely identify a
record in another
table. This relates one
table with other.
Candidate Key –
Attribute that acts as a
primary key.
Alternate Key - Any
candidate key which is
not selected to be the
primary key.
Super Key - A set of
attributes that no two
distinct tuples have a
same value for the
attributes in the set.
Types of Keys
Primary Key – To
identify a unique row
in a table ( Eg:
Employee ID in
Employee table)
Foreign Key - An
attribute in a table to
uniquely identify a
record in another
table. This relates one
table with other.
Candidate Key –
Attribute that acts as a
primary key.
Alternate Key - Any
candidate key which is
not selected to be the
primary key.
Super Key - A set of
attributes that no two
distinct tuples have a
same value for the
attributes in the set.
CUSTMOER
Cus Phone
Na Addre
tomer numb
me ss
ID er

In CUSTOMER table Customer ID should be unique;

ACCOUNT
Acco Acco Balan Custo
unt unt ce mer ID
ID numb
er

In ACCOUNT table,
Account ID is the primary
key and
Customer ID is foreign key
which refers the
CUSTOMER table.
SQL statement is
classified into four types:
Data Definition
Language (DDL)
Data Manipulation
Language (DML)
Data Control Language
(DCL)
Transaction Control
(TCL)
Data Definition
Language (DDL)
To create the schema of
the database and it used to
create the rows, columns,
tables, indexes
CREATE - Used to
create a database
object like table, view,
etc.
ALTER - This
command modifies the
structure of the table
in the database.
DROP - It is used to
remove the objects
from the database
such as table, column
etc.
TRUNCATE - Removes
all records from a table
SYNTAX: (CREATE)
CREATE TABLE <table

name> (

<attribute name

1><data type 1>,

...

<attribute name

n><data type n>


);

Example

Create TABLE Sample (

Pid integer,

Name varchar(10),

Place varchar(15)

);
SYNTAX: (ALTER)

ALTER TABLE <table

name>

ADD CONSTRAINT

<constraint name>

PRIMARY KEY (<attribute

list>);
Example

ALTER TABLE Sample

ADD sample_pk

PRIMARY KEY (Pid);

SYNTAX: (DROP)

DROP TABLE <table

name>;
To fetch and

manipulation (such as

update, delete, insert)

the data in the database.

SELECT - It is used for

fetch the data from a

table.
INSERT - This

command is used for

inserting records or

data into a table.

UPDATE - It is used to

update the existing

data within a table.


DELETE - Used to

delete records from a

table.

SYNTAX: (INSERT)

INSERT INTO <table

name>
VALUES (<value 1>, ...

<value n>);

Example

INSERT into Sample

VALUES (1, “ABC”,

“XYZ”);

SYNTAX: (UPDATE)
UPDATE <table name>

SET <attribute> =

<expression>

WHERE

<condition>;

Example

UPDATE Sample
SET Place=”XXX”

WHERE Pid=5;

SYNTAX: (DELETE)

DELETE FROM <table

name>

WHERE

<condition>;
For Example,

DELETE from Sample

WHERE

Pid=10;

DCL
DCL is short name of Data
Control Language which
includes commands such
as GRANT and mostly
concerned with rights,
permissions and other
controls of the database
system.
 GRANT - allow users
access privileges to the
database
 REVOKE - withdraw users
access privileges given by
using the GRANT
command
TCL
TCL is short name of

Transaction Control

Language which deals with

a transaction within a

database.

 COMMIT - commits a
Transaction
 ROLLBACK - rollback a
transaction in case of any
error occurs
 SAVEPOINT - to rollback
the transaction making
points within groups
Data Query Language
DQL is used to fetch the
data from the database.
It uses only one command:
o SELECT
SYNTAX
Select * from <Table
name>
Java security
model:
The Java security

model is based on

controlling the operations

that a class can perform


when it is loaded into a

running environment.

Java security includes

a large set of APIs, tools,

and implementations of

commonly-used security

algorithms, mechanisms,

and protocols. The Java


security APIs span a wide

range of areas, including

cryptography, public key

infrastructure, secure

communication,

authentication, and access

control
 Core Java 2 Security
Architecture. ...
 Java Cryptography
Architecture (JCA) ...
 Java Cryptographic
Extension (JCE) ...
 Java Secure Socket
Extension (JSSE) ...
 Java Authentication and
Authorization Service
(JAAS)

The architecture of the


Java security model
The Java 2 security

platform is formed by two

parts: Core Java 2 Security

Architecture and Java

Cryptography

Architecture. The bottom

layer components are the

two main parts of the Java


2 security platform, and

the top layer consists of

the security extensions.

Three security extensions

were separately available

until Java 1.3.1, but

starting with Java 1.4, they

were integrated into J2SE.


Core Java 2 Security

Architecture

This is a part of the Java

platform, and it includes

the byte code verifier,


class loader, security

manager, access

controller, access rights

facilities, policy

description tools, and so

on. Here's a look at the

process of Java code

execution in Core Java 2


Security Architecture

components.

Java Cryptography

Architecture (JCA)

It provides the

infrastructure for

executing the main

cryptographic services in
the Java platform,

including digital

signatures, message

digests, ciphers, message

authentication codes key

generators, and key

factories. JCA also

ensures data integrity and


provides APIs for all listed

features.

CA starting with Java 1.4,

and it is fully integrated

into the standard Java

package. It supports a

wide range of standard

algorithms including RSA,


DSA, AES, Triple DES,

SHA, is an extensible, full

featured API for building

secure applications.

Java Cryptographic

Extension (JCE)

This is a Sun

Microsystems extension
for ciphering and

deciphering data blocks

and is a part of JCA

implementation. JCE was

made a Java extension as

a conditional of U.S.

encryption technologies'
export conditions to third-

party countries.

Java Secure Socket

Extension (JSSE)

The Secure Sockets Layer

(SSL) has become the

most widely used data

protocol with supported


data integrity through

encryption. JSSE is a

standard interface and

reference implementation

of the SSL protocol.

Java Authentication and

Authorization Service

(JAAS)
This implements access

limiting based on user

authentication. Together

with Access Control, it

provides abstract

authentication APIs that

incorporate a wide range

of login mechanisms
through a pluggable

architecture.

Java AWT
Tutorial
Java AWT (Abstract Window
Toolkit) is an API to develop
Graphical User Interface (GUI) or
windows-based applications in
Java.
Java AWT components are
platform-dependent
Container
The Container is a component in
AWT that can contain another
components like buttons
There are four types of containers
in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
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. We need to create an
instance of Window class to create
this container.
Panel
The Panel is the container that
doesn't contain title bar, border or
menu bar. It is generic container
for holding the components. It can
have other components like
button, text field etc. An instance
of Panel class creates a container,
in which we can add components.
Frame
The Frame is the container that
contain title bar and border and
can have menu bars. It can have
other components like button, text
field, scrollbar etc. Frame is most
widely used container while
developing an AWT application.

Useful Methods
of Component
Class
Method
public void add(Component c) I

co

public void setSize(int width,int S

height) co

public void D

setLayout(LayoutManager m) co

public void setVisible(boolean C


status) co

AWT Example by
Inheritance
import java.awt.*;

// extending Frame
class to our class
AWTExample1
public class
AWTExample1 extends
Frame {

// initializing using
constructor
AWTExample1() {

// creating a button
Button b = new
Button("Click Me!!");
// setting button
position on screen
b.setBounds(30,100
,80,30);

// adding button
into frame
add(b);
// frame size 300
width and 300 height
setSize(300,300);

// setting the title of


Frame
setTitle("This is
our basic AWT
example");
// no layout
manager
setLayout(null);

// now frame will be


visible, by default it is
not visible
setVisible(true);
}

// main method
public static void
main(String args[]) {

// creating instance of
Frame class
AWTExample1 f = new
AWTExample1();

}
Output
Event and
Listener (Java
Event
Handling)
Changing the state of an object

is known as an event. For example,

click on button, dragging mouse

etc. The java.awt.event package


provides many event classes and

Listener interfaces for event

handling

Java Event
classes and
Listener
interfaces
Event Classes Listener In
ActionEvent ActionListen

MouseEvent MouseListen

MouseWheelEvent MouseWhee

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener
AdjustmentEvent AdjustmentL

WindowEvent WindowListe

ComponentEvent Component

ContainerEvent ContainerLis

FocusEvent FocusListene
Java event handling
by implementing
ActionListener
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame
implements ActionListener{
TextField tf;
AEvent(){

//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click
me");
b.setBounds(100,120,80,30);

//register listener
b.addActionListener(this);//
passing current instance

//add components and set size,


layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void
actionPerformed(ActionEvent
e){
tf.setText("Welcome");
}
public static void main(String
args[]){
new AEvent();
}
}
Example 2
// importing awt class
import java.awt.*;

// class to construct a frame


and containing main method
public class CanvasExample
{
// class constructor
public CanvasExample()
{
// creating a frame
Frame f = new
Frame("Canvas Example");
// adding canvas to frame
f.add(new MyCanvas());

// setting layout, size and


visibility of frame
f.setLayout(null);
f.setSize(400, 400);
f.setVisible(true);
}
// main method
public static void main(String
args[])
{
new CanvasExample();
}
}

// class which inherits the


Canvas class
// to create Canvas
class MyCanvas extends
Canvas
{
// class constructor
public MyCanvas() {
setBackground
(Color.GRAY);
setSize(300, 200);
}

// paint() method to draw


inside the canvas
public void paint(Graphics g)
{

// adding specifications
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}
OUTPUT
Java
MouseListener
Interface
The Java MouseListener is notified
whenever you change the state of
mouse. It is notified against
MouseEvent. The MouseListener
interface is found in java.awt.event
package. It has five methods.

Methods of
MouseListener
interface
The signature of 5 methods found
in MouseListener interface are
given below:
public abstract void mouseClicke
d(MouseEvent e);
public abstract void mouseEntere
d(MouseEvent e);
public abstract void mouseExited
(MouseEvent e);
public abstract void mousePresse
d(MouseEvent e);
public abstract void mouseReleas
ed(MouseEvent e);

Example
import java.awt.*;
import java.awt.event.*;
public class
MouseListenerExample extends
Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);

l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void
mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void
mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void
mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void
mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void
mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[]
args) {
new MouseListenerExample();
}
}
OUTPUT

EXAMPLE 2
import java.awt.*;
import java.awt.event.*;
public class
MouseListenerExample2 extends
Frame implements MouseListener{
MouseListenerExample2(){
addMouseListener(this);

setSize(300,300);
setLayout(null);
setVisible(true);
}
public void
mouseClicked(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,3
0);
}
public void
mouseEntered(MouseEvent e) {}
public void
mouseExited(MouseEvent e) {}
public void
mousePressed(MouseEvent e) {}
public void
mouseReleased(MouseEvent e) {}
public static void main(String[]
args) {
new MouseListenerExample2();
}
}
OUTPUT
Java
MouseMotionLi
stener
Interface
The Java MouseMotionListener is
notified whenever you move or
drag mouse. It is notified against
MouseEvent. The
MouseMotionListener interface is
found in java.awt.event package. It
has two methods.

Methods of
MouseMotionList
ener interface
The signature of 2 methods found
in MouseMotionListener interface
are given below:
public abstract void mouseDragg
ed(MouseEvent e);
public abstract void mouseMove
d(MouseEvent e);

Java
MouseMotionList
ener Example
import java.awt.*;
import java.awt.event.*;
public class
MouseMotionListenerExample
extends Frame implements
MouseMotionListener{
MouseMotionListenerExample(){
addMouseMotionListener(thi
s);

setSize(300,300);
setLayout(null);
setVisible(true);
}
public void
mouseDragged(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void
mouseMoved(MouseEvent e) {}

public static void main(String[]


args) {
new
MouseMotionListenerExample();
}
}
OUTPUT

You might also like