Java Intro
Java Intro
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):
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
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:
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
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 {
// Create a class
constructor for the
Main class
public Main() {
x = 5;
}
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!");
}
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
}
}
}
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
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
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
Program
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);
}
}
}
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
System.out.println("U
sername is: " +
userName);
}
}
Import a Package
User-defined Packages
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>
Java Exceptions
try {
// Block of code to
try
}
catch(Exception e) {
// Block of code to
handle errors
}
Program:
Something went
wrong
Finally
The finally statement
lets you execute code,
after try...catch,
regardless of the
result:
o/p
Something went
wrong.
The 'try catch' is
finished.
Java Annotations
Java Annotation is a
and JVM.
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
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
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
duplicate elements
List Interface
interface of Collection
duplicate values.
ArrayList();
LinkedList();
List <data-type> list3 = new
Vector();
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
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
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
accept() establish a
connection
between
server and
client.
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
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
...
<attribute name
Example
Pid integer,
Name varchar(10),
Place varchar(15)
);
SYNTAX: (ALTER)
name>
ADD CONSTRAINT
<constraint name>
list>);
Example
ADD sample_pk
SYNTAX: (DROP)
name>;
To fetch and
manipulation (such as
table.
INSERT - This
inserting records or
UPDATE - It is used to
table.
SYNTAX: (INSERT)
name>
VALUES (<value 1>, ...
<value n>);
Example
“XYZ”);
SYNTAX: (UPDATE)
UPDATE <table name>
SET <attribute> =
<expression>
WHERE
<condition>;
Example
UPDATE Sample
SET Place=”XXX”
WHERE Pid=5;
SYNTAX: (DELETE)
name>
WHERE
<condition>;
For Example,
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
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
running environment.
and implementations of
commonly-used security
algorithms, mechanisms,
infrastructure, secure
communication,
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)
Cryptography
Architecture
manager, access
facilities, policy
components.
Java Cryptography
Architecture (JCA)
It provides the
infrastructure for
cryptographic services in
the Java platform,
including digital
signatures, message
features.
package. It supports a
secure applications.
Java Cryptographic
Extension (JCE)
This is a Sun
Microsystems extension
for ciphering and
a conditional of U.S.
encryption technologies'
export conditions to third-
party countries.
Extension (JSSE)
encryption. JSSE is a
reference implementation
Authorization Service
(JAAS)
This implements access
authentication. Together
provides abstract
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
height) co
public void D
setLayout(LayoutManager m) 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);
// 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
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
// 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) {}