Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Java Programming Notes

Uploaded by

SMS VIP TV World
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Java Programming Notes

Uploaded by

SMS VIP TV World
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 123

JAVA

PROGRAMMING
OOP Concepts

Object Oriented Programming is a paradigm that provides many concepts


such as inheritance, data binding, polymorphism etc.

Simula is considered as the first object-oriented programming language. The programming

r
paradigm where everything is represented as an object is known as truly object-oriented
programming language.

de
Smalltalk is considered as the first truly object-oriented programming language.

o
OOPs (Object Oriented Programming System)

bC
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is
a methodology or paradigm to design a program using classes and objects. It simplifies the

e
software development and maintenance by providing some concepts:

W
o Object

y
o Class

B
o
Inheritance
o

h
Polymorphism
o

c
o Abstraction

e
Encapsulation

T
Object

Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.

Class

Collection of objects is called class. It is a logical entity.

Inheritance

When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

@techbywebcoder
Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.

In java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Abstraction

er
Hiding internal details and showing functionality is known as abstraction. For example: phone

d
call, we don't know the internal processing.

o
In java, we use abstract class and interface to achieve abstraction.

C
Encapsulation

eb
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.

yW
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.

hB
Benefits of Inheritance

ec
One of the key benefits of inheritance is to minimize the amount of duplicate code in an

T
application by sharing common code amongst several subclasses. Where equivalent code
exists in two related classes, the hierarchy can usually be refactored to move the common
code up to a mutual superclass. This also tends to result in a better organization of code and
smaller, simpler compilation units.
 Inheritance can also make application code more flexible to change because classes that
inherit from a common superclass can be used interchangeably. If the return type of a
method is superclass
 Reusability - facility to use public methods of base class without rewriting the same.
 Extensibility - extending the base class logic as per business logic of the derived class.

@techbywebcoder
 Data hiding - base class can decide to keep some data private so that it cannot be
altered by the derived class
Procedural and object oriented programming paradigms

er
od
bC
e
yW
hB
ec
T

@techbywebcoder
Java Programming- History of Java
The history of java starts from Green Team. Java team members (also known
as Green Team), initiated a revolutionary task to develop a language for digital
devices such as set-top boxes, televisions etc.

For the green team members, it was an advance concept at that time. But, it was
suited for internet programming. Later, Java technology as incorporated by
Netscape.

r
Currently, Java is used in internet programming, mobile devices, games, e-business

e
solutions etc. There are given the major points that describes the history of java.

d
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java

o
language project in June 1991. The small team of sun engineers called Green

C
Team.

b
2) Originally designed for small, embedded systems in electronic appliances like set-

e
top boxes.

W
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.

y
4) After that, it was called Oak and was developed as a part of the Green

B
project.

h
Java Version History

ec
There are many java versions that has been released. Current stable release of Java
is Java SE 8.

T
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10.Java SE 8 (18th March, 2014)

@techbywebcoder
Features of Java
There is given many features of java. They are also known as java buzzwords. The Java Features
given below are simple and easy to understand.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust

r
7. Architecture neutral

e
8. Dynamic

d
9. Interpreted

o
10. High Performance

C
11. Multithreaded

b
12. Distributed

e
W
Java Comments

y
The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, meth

B
any statement. It can also be used to hide program code for specific time.

ch
Types of Java Comments

e
There are 3 types of comments in java.

T
1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment

Java Single Line Comment

The single line comment is used to comment only one line.

Syntax:

1. //This is single line comment

@techbywebcoder
Example:

public class CommentExample1 {


public static void main(String[] args) {
int i=10;//Here, i is a variable
System.out.println(i);
}
}

Output:

10

er
d
Java Multi Line Comment

o
The multi line comment is used to comment multiple lines of code.

C
b
Syntax:

e
/*

W
This
is

y
multi line

B
comment

h
*/

c
Example:

Te
public class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
}}

Output:

10

@techbywebcoder
Java Documentation Comment

The documentation comment is used to create documentation API. To create documentation API, you need
to use javadoc tool.

Syntax:

/**
This
is

r
documentation

e
comment
*/

Example:

od
C
/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/

b
public class Calculator {

e
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b){return a+b;}

W
/** The sub() method returns subtraction of given numbers.*/

y
public static int sub(int a, int b){return a-b;}

B
}

h
Compile it by javac tool:

ec
javac Calculator.java

T
Create Documentation API by javadoc tool:

javadoc Calculator.java

Now, there will be HTML files created for your Calculator class in the current directory. Open the HTML
files and see the explanation of Calculator class provided through documentation comment.

@techbywebcoder
Data Types
Data types represent the different values to be stored in the variable. In java, there are two types of data types:

o Primitive data types


o Non-primitive data types

er
od
bC
e
Data Type Default Value Default size

W
boolean False 1 bit

y
char '\u0000' 2 byte

byte 0 1 byte

B
short 0 2 byte

h
int 0 4 byte

c
long 0L 8 byte

e
float 0.0f 4 byte

T
double 0.0d 8 byte

Java Variable Example: Add Two Numbers


class Simple{ public static void
main(String[] args){ int a=10; int
b=10; int c=a+b;
System.out.println(c); }}
Output:20

@techbywebcoder
Variables and Data Types in Java
Variable is a name of memory location. There are three types of variables in java: local, instance
and static.
There are two types of data types in java: primitive and non-primitive.

Types of Variable
There are three types of variables in java:

o local variable

r
o instance variable
o static variable

1) Local Variable

de
o
A variable which is declared inside the method is called local variable.

C
2) Instance Variable

b
A variable which is declared inside the class but outside the method, is called instance variable . It
is not declared as static.

e
3) Static variable

W
A variable that is declared as static is called static variable. It cannot be local.

y
We will have detailed learning of these variables in next chapters.

B
Example to understand the types of variables in java

class A{

ch
e
int data=50;//instance variable
static int m=100;//static variable

T
void method(){
int n=90;//local variable
}
}//end of class

Constants in Java

A constant is a variable which cannot have its value changed after declaration. It uses the 'final'
keyword.

Syntax
modifier final dataType variableName = value; //global constant
modifier static final dataType variableName = value; //constant within a c

@techbywebcoder
Scope and Life Time of Variables
The scope of a variable defines the section of the code in which the variable is visible.
As a general rule, variables that are defined within a block are not accessible outside
that block. The lifetime of a variable refers to how long the variable exists before it is
destroyed. Destroying variables refers to deallocating the memory that was allotted
to the variables when declaring it. We have written a few classes till now. You might
have observed that not all variables are the same. The ones declared in the body of a
method were different from those that were declared in the class itself. There are
three types of variables: instance variables, formal parameters or local variables and
local variables.

r
Instance variables

e
Instance variables are those that are defined within a class itself and not in any method

d
or constructor of the class. They are known as instance variables because every
instance of the class (object) contains a copy of these variables. The scope of instance

o
variables is determined by the access specifier that is applied to these variables. We

C
have already seen about it earlier. The lifetime of these variables is the same as the
lifetime of the object to which it belongs. Object once created do not exist for ever. They

b
are destroyed by the garbage collector of Java when there are no more reference to that

e
object. We shall see about Java's automatic garbage collector later on.
Argument variables

yW
These are the variables that are defined in the header oaf constructor or a method.

B
The scope of these variables is the method or constructor in which they are defined.
The lifetime is limited to the time for which the method keeps executing. Once the

h
method finishes execution, these variables are destroyed.

c
Local variables

Te
A local variable is the one that is declared within a method or a constructor (not in the
header). The scope and lifetime are limited to the method itself.
One important distinction between these three types of variables is that access

specifiers can
be applied to instance variables only and not to argument or local variables.
In addition to the local variables defined in a method, we also have variables that are

defined
in bocks life an if block and an else block. The scope and is the same as that of the
block
itself.

@techbywebcoder
Operators in java

Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in java which are given below:

o Unary Operator,
o Arithmetic Operator,
o
shift Operator,
o
Relational Operator,

r
o
Bitwise Operator,

e
o
o Logical Operator,

d
o Ternary Operator and

o
Assignment Operator.

C
Operators Hierarchy

b
e
yW
hB
ec
T

@techbywebcoder
Expressions
Expressions are essential building blocks of any Java program, usually created to produce a new
value, although sometimes an expression simply assigns a value to a variable. Expressions are
built using values, variables, operators and method calls.
Types of Expressions

While an expression frequently produces a result, it doesn't always. There are three types of
expressions in Java:

r
 Those that produce a value, i.e. the result of (1 + 1)

e
 Those that assign a variable, for example (v = 10)

d
 Those that have no result but might have a "side effect" because an expression can include
a wide range of elements such as method invocations or increment operators that modify

Co
the state (i.e. memory) of a program.

Java Type casting and Type conversion

eb
Widening or Automatic Type Conversion Widening conversion takes place when two
data types are automatically converted. This happens when:

W

The two data types are compatible.

y
When we assign value of a smaller data type to a bigger data type.

B
For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not

h
compatible with each other.

ec
T Narrowing or Explicit Conversion
If we want to assign a value of larger data type to a smaller data type we perform explicit type
casting or narrowing.
 This
Here,istarget-type
useful for incompatible
specifies thedata
types where automatic conversion cannot
desired type to convert the specified value to. be done.



@techbywebcoder
Java Enum

Enum in java is a data type that contains fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST)
etc. The java enum constants are static and final implicitly. It is available from JDK 1.5.

Java Enums can be thought of as classes that have fixed set of constants.

r
Simple example of java enum

e
class EnumExample1{

d
public enum Season { WINTER, SPRING, SUMMER, FALL }

Co
public static void main(String[] args) {
for (Season s : Season.values())

b
System.out.println(s);

e
}}
Output:

W
WINTER

y
SPRING

B
SUMMER
FALL

ch
Control Flow Statements

Te
The control flow statements in Java allow you to run or skip blocks of code when special
conditions are met.

The “if” Statement


The “if” statement in Java works exactly like in most programming languages. With the
help of
“if” you can choose to execute a specific block of code when a predefined condition is

met. The
structure of the “if”
if (condition) { statement in Java looks like this:
// execute this code
}

@techbywebcoder
The condition is Boolean. Boolean means it may be true or false. For example you may put a
mathematical equation as condition. Look at this full example:

er
od
Creating a Stand-Alone Java Application

bC
1. Write a main method that runs your program. You can write this method anywhere. In this
example, I'll write my main method in a class called Main that has no other methods. For

e
example:
2. public class Main

W
3. {
4. public static void main(String[] args)

y
5. {
6. Game.play();

B
7. }}

h
8. Make sure your code is compiled, and that you have tested it thoroughly. 9. If you're
using Windows, you will need to set your path to include Java, if you haven't

c
done so already. This is a delicate operation. Open Explorer, and look inside
C:\ProgramFiles\Java, and you should see some version of the JDK. Open this folder,

e
and

T
then open the bin folder. Select the complete path from the top of the Explorer
window, and
press Ctrl-C to copy it.
Next, find the "My Computer" icon (on your Start menu or desktop), right-click it, and

select
properties. Click on the Advanced tab, and then click on the Environment variables
button.
Look at the variables listed for all users, and click on the Path variable. Do not delete
the
contents
end, of this variable! Instead, edit the contents by moving the cursor to the right
entering a semicolon (;), and pressing Ctrl-V to paste the path you copied earlier.

@techbywebcoder
12. Now we want to change to the directory/folder that contains your compiled code. Look at
the listing of sub-directories within this directory, and identify which one contains your code.
Type cd followed by the name of that directory, to change to that directory. For example, to
change to a directory called Desktop, you would type:
cd Desktop

To change to the parent directory, type:

cd ..

Every time you change to a new directory, list the contents of that directory to see where to go
next. Continue listing and changing directories until you reach the directory that contains

r
your .class files.

e
13. If you compiled your program using Java 1.6, but plan to run it on a Mac, you'll need to
recompile your code from the command line, by typing:

d
javac -target 1.5 *.java

o
14. Now we'll create a single JAR file containing all of the files needed to run your program.

C
b
Arrays

e
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often

W
more useful to think of an array as a collection of variables of the same type.

y
Instead of declaring individual variables, such as number0, number1, ..., and number99,

B
you

h
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,

c
numbers[99] to represent individual variables.

e
This tutorial introduces how to declare array variables, create arrays, and process

T
arrays using
Declaring Array Variables:
indexed variables.
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:

dataType[] arrayRefVar; // preferred way.


or
dataType arrayRefVar[]; // works but not preferred way.
style dataType
Note: The style
arrayRefVar[]
dataType[] comes
arrayRefVar
from theisC/C++
preferred.
language and
Thewas adopted in Java to
accommodate C/C++ programmers.

Example:

@techbywebcoder
The following code snippets are examples of this syntax:

double[] myList; // preferred way.


or
double myList[]; // works but not preferred way.
Creating Arrays:
You can create an array by using the new operator with the following syntax:

arrayRefVar = new dataType[arraySize];


The above statement does two things:

r
 It creates an array using new dataType[arraySize];

e
 It assigns the reference of the newly created array to the variable arrayRefVar.

d
Declaring an array variable, creating an array, and assigning the reference of the array to the

o
variable can be combined in one statement, as shown below:

C
dataType[] arrayRefVar = new dataType[arraySize];

b
Alternatively you can create arrays as follows:

e
W
dataType[] arrayRefVar = {value0, value1, ..., valuek};

y
The array elements are accessed through the index. Array indices are 0-based; that is, they start
from 0 to arrayRefVar.length-1.

hB
Example:

ec
Following statement declares an array variable, myList, creates an array of 10 elements of

T
double type and assigns its reference to myList:

double[] myList = new double[10];


Following picture represents array myList. Here, myList holds ten double values and the indices
are from 0 to 9.

@techbywebcoder
r
Processing Arrays:

e
When processing array elements, we often use either for loop or for each loop because all of the

d
elements in an array are of the same type and the size of the array is known.

o
Example:
Here is a complete example of showing how to create, initialize and process arrays:

public class TestArray


{

bC
e
public static void main(String[] args) {

W
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements

y
for (int i = 0; i < myList.length; i++) {

B
System.out.println(myList[i] + " ");

h
}

c
// Summing all elements
double total = 0;

e
for (int i = 0; i < myList.length; i++) {

T
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}

@techbywebcoder
This would produce the following result:

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
public class TestArray {
public static void main(String[] args) {

r
double[] myList = {1.9, 2.9, 3.4, 3.5};

e
// Print all the array elements
for (double element: myList) {

d
System.out.println(element);

o
}}}

Java Console Class

bC
e
The Java Console class is be used to get input from console. It provides methods to read texts and
passwords.

yW
If you read password using Console class, it will not be displayed to the user.

B
The java.io.Console class is attached with system console internally. The Console class is

h
introduced since 1.5.

ec
Let's see a simple example to read text from console.

T
1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);

Java Console Example

import java.io.Console;
class ReadStringTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n); } }

@techbywebcoder
Output

Enter your name: Nakul Jain


Welcome Nakul Jain

Constructors

Constructor in java is a special type of method that is used to initialize the object.

r
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.

de
There are basically two rules defined for the constructor.

o
1. Constructor name must be same as its class name

C
2. Constructor must have no explicit return type

b
Types of java constructors

e
There are two types of constructors:

yW
1. Default constructor (no-arg constructor)

B
2. Parameterized constructor

ch
Java Default Constructor

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

Syntax of default constructor:


1. <class_name>(){}

Example of default constructor

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

@techbywebcoder
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.
class Student4{
int id;
String name;

Student4(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}

r
public static void main(String args[]){

e
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");

d
s1.display();

o
s2.display();
}}

C
Output:

b
111 Karan

e
222 Aryan

W
Constructor Overloading in Java

y
Constructor overloading is a technique in Java in which a class can have any number of

B
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.

h
Example of Constructor Overloading

c
class Student5{
int id;

e
String name;

T
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();

@techbywebcoder
s2.display();
}}

Output:

111 Karan 0
222 Aryan 25
Java Copy Constructor

There is no copy constructor in java. But, we can copy the values of one object to another like
copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:

o By constructor

er
o By assigning the values of one object into another

d
o By clone() method of Object class

o
In this example, we are going to copy the values of one object into another using java

C
constructor.
class Student6{

b
int id;

e
String name;
Student6(int i,String n){
id = i;

W
name = n;
}

id = s.id;

By
Student6(Student6 s){

h
name =s.name;
}

c
void display(){System.out.println(id+" "+name);}

e
public static void main(String args[]){

T
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}}

Output:

111 Karan
111 Karan

@techbywebcoder
Java - Methods
A Java method is a collection of statements that are grouped together to perform an
operation. When you call the System.out.println() method, for example, the system
actually executes several statements in order to display a message on the console.

Now you will learn how to create your own methods with or without return values, invoke a
method with or without parameters, and apply method abstraction in the program design.

Creating Method
Considering the following example to explain the syntax of a method −

r
Syntax

de
public static int methodName(int a, int b) {

o
// body
}

C
Here,

eb
 public static − modifier

 int − return type

W
 methodName − name of the method

y
 a, b − formal parameters

B
h
 int a, int b − list of parameters

c
Method definition consists of a method header and a method body. The same is shown in the

e
following syntax −

T
Syntax

modifier returnType nameOfMethod (Parameter List) {


// method body
}
The syntax shown above includes −

 modifier − It defines the access type of the method and it is optional to use.

 returnType − Method may return a value.

 nameOfMethod − This is the method name. The method signature consists of the method
name and the parameter list.

@techbywebcoder
Parameter List − The list of parameters, it is the type, order, and number of parameters

of a method. These are optional, method may contain zero parameters.

 method body − The method body defines what the method does with the statements.

Call by Value and Call by Reference in Java


There is only call by value in java, not call by reference. If we call a method passing a
value, it is known as call by value. The changes being done in the called method, is not
affected in the calling method.

Example of call by value in java

r
In case of call by value original value is not changed. Let's take a simple example:

e
class Operation{

d
int data=50;

o
void change(int data){
data=data+100;//changes will be in the local variable only

C
}

b
public static void main(String args[]){

e
Operation op=new Operation();
System.out.println("before change "+op.data);

W
op.change(500);

y
System.out.println("after change "+op.data);

B
}
}

h
Output:before change 50

c
after change 50

Te
In Java, parameters are always passed by value. For example, following program prints
i = 10, j = 20.
// Test.java
class Test {
// swap() doesn't swap i and j
public static void swap(Integer i, Integer j) {
Integer temp = new Integer(i);
i = j;
j = temp;
}
public static void main(String[] args) {
Integer i = new Integer(10);
Integer j = new Integer(20);
swap(i, j);
System.out.println("i = " + i + ", j = " + j);

@techbywebcoder
}
}

Static Fields and Methods

The static keyword in java is used for memory management mainly. We can apply java
static keyword with variables, methods, blocks and nested class. The static keyword
belongs to the class than instance of the class.

r
The static can be:

de
1. variable (also known as class variable)

o
2. method (also known as class method)
3. block

C
4. nested class

Java static variable

eb
W
If you declare any variable as static, it is known static variable.

y
o The static variable can be used to refer the common property of all objects (that is not unique for

B
each object) e.g. company name of employees,college name of students etc.

h
o The static variable gets memory only once in class area at the time of class loading.

c
Advantage of static variable

Te
It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable


1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }

Example of static variable


//Program of static variable
class Student8{
int rollno;

@techbywebcoder
String name; static String
college ="ITS";
Student8(int r,String n){
rollno = r; name = n; }

void display (){System.out.println(rollno+" "+name+" "+college);}


public static void main(String args[]){
Student8 s1 = new Student8(111,"Karan");

r
Student8 s2 = new Student8(222,"Aryan");

s1.display()
;

de
o
s2.display()

C
;}} Output:111 Karan ITS

b
222 Aryan ITS

e
Java static method

W
If you apply static keyword with any method, it is known as static method.

y
o A static method belongs to the class rather than object of a class.

B
o A static method can be invoked without the need for creating an instance of a class.

h
o
static method can access static data member and can change the value of it.

ec
Example of static method
//Program of changing the common property of all objects(static field).

class Student9{

static
T
int rollno; String name;
String college =
"ITS"; static void change(){
college = "BBDIT"; }
Student9(int r, String n){
rollno = r; name = n;

@techbywebcoder
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change(); Student9 s1 = new
Student9 (111,"Karan"); Student9 s2 =
new Student9 (222,"Aryan"); Student9
s3 = new Student9 (333,"Sonoo");
s1.display(); s2.display(); s3.display(); } }

er
Output:111 Karan BBDIT

d
222 Aryan BBDIT

o
333 Sonoo BBDIT

C
Java static block

o
o

eb
Is used to initialize the static data member.
It is executed before main method at the time of class loading.

W
Example of static block

y
class A2{

B
static{System.out.println("static block is invoked");}

h
public static void main(String args[]){

c
System.out.println("Hello main");
}}

e
Output: static block is invoked

T
Hello main

Access Control
Access Modifiers in java

There are two types of modifiers in java: access modifiers and non-access modifiers.

The access modifiers in java specifies accessibility (scope) of a data member, method, constructor
or class.
There are 4 types of java access modifiers:

@techbywebcoder
1. private 2.
default 3.
protected 4.
public

private access modifier


The private access modifier is accessible only within class.

Simple example of private access modifier


In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,

r
so there is compile time error.

e
class A{

d
private int data=40;

o
private void msg(){System.out.println("Hello java");} }
public class Simple{

C
public static void main(String args[]){

b
A obj=new A();

e
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error

W
}}

y
2) default access modifier

B
If you don't use any modifier, it is treated as default bydefault. The default modifier is

h
accessible only within package.

c
Example of default access modifier

e
In this example, we have created two packages pack and mypack. We are accessing the A

T
class from outside its package, since A class is not public, so it cannot be accessed from outside
the package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;

@techbywebcoder
class B{
public static void main(String
args[]){ A obj = new A();//Compile
Time Error obj.msg();//Compile Time
Error } }
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.

3) protected access modifier

r
The protected access modifier is accessible within package and outside the package but through

e
inheritance only.

d
The protected access modifier can be applied on the data member, method and constructor. It can'

o
be applied on the class.

C
Example of protected access modifier

b
In this example, we have created the two packages pack and mypack. The A class of pack

e
package is public, so can be accessed from outside the package. But msg method of this package

W
is declared as protected, so it can be accessed from outside the class only through inheritance.

y
//save by A.java

B
package pack;

h
public class A{
protected void msg(){System.out.println("Hello");} }

c
//save by B.java

e
package mypack;

T
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}}
Output:Hello

4) public access modifier


The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.

@techbywebcoder
Example of public access modifier
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");} }
//save by B.java
package mypack;
import pack.*;
class B{

r
public static void main(String args[]){
A obj = new A();

e
obj.msg();

d
}}

o
Output:Hello

C
Understanding all java access modifiers

b
e
Let's understand the access modifiers by a simple table.

W
Access within within outside package by outside

y
Modifier class package subclass only package

Private

hB Y N N N

c
Default Y Y N N

T
Protected

Public
e Y

Y
Y

Y
Y

Y
N

this keyword in java

Usage of java this keyword

Here is given the 6 usage of java this keyword.

1.this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.

@techbywebcoder
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;

r
}
void display(){System.out.println(rollno+" "+name+" "+fee);}

e
}
class TestThis2{

d
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);

o
Student s2=new Student(112,"sumit",6000f);
s1.display();

C
s2.display();

b
}}

e
Output:
111 ankit 5000

W
112 sumit 6000

y
Difference between constructor and method in java

B
ch
e
Java Constructor Java Method

T
Constructor is used to initialize the state of an object. Method is used to expose behaviour
of an object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor if you Method is not provided by compiler in
don't have any constructor. any case.

Constructor name must be same as the class name. Method name may or may not be

@techbywebcoder
same as class name.
There are many differences between constructors and methods. They are given belo

Constructor Overloading in Java

Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors

r
by taking into account the number of parameters in the list and their type.

class Student5{

de
Example of Constructor Overloading

o
int id; String

C
name; int
age;

b
Student5(int i,String n){

e
id = i;
name = n;

W
}

y
Student5(int i,String n,int a){

B
id = i;

h
name = n;
age=a;

c
}

e
void display(){System.out.println(id+" "+name+" "+age);}

T
public static void main(String args[]){
Student5 s1 =
Student5(111,"Karan"); Student5 s2 =
new

new Student5(222,"Aryan",25);
s1.display(); s2.display();
}
}

Output:

@techbywebcoder
111 Karan 0
222 Aryan 25

Method Overloading in java

If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

er
d
Method Overloading: changing no. of arguments

o
In this example, we have created two methods, first add() method performs addition of two

C
numbers and second add method performs addition of three numbers.

b
In this example, we are creating static methods so that we don't need to create instance for calling

e
methods.

W
class Adder{

y
static int add(int a,int b){return a+b;}

B
static int add(int a,int b,int c){return a+b+c;}
}

h
class TestOverloading1{

c
public static void main(String[] args){

e
System.out.println(Adder.add(11,11));

T
System.out.println(Adder.add(11,11,11));
}}

Output:

22
33

Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.

@techbywebcoder
Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A method in java that
calls itself is called recursive method.

Java Recursion Example 1: Factorial Number

public class RecursionExample3 {


static int factorial(int n){
if (n == 1)

r
return 1;

e
else

d
return(n * factorial(n-1));

o
}}
public static void main(String[] args) {

C
System.out.println("Factorial of 5 is: "+factorial(5));

b
}}

Output:

e
W
Factorial of 5 is: 120

By
Java Garbage Collection

h
In java, garbage means unreferenced objects.

ec
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other

T
words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.

Advantage of Garbage Collection


o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.

gc() method

@techbywebcoder
The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.

public static void gc(){}

Simple Example of garbage collection in java


public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new

r
TestGarbage1(); TestGarbage1

e
s2=new TestGarbage1(); s1=null;
s2=null; System.gc();

}}

od
C
object is garbage collected

b
object is garbage collected
Java String

e
string is basically an object that represents sequence of char values. An array of characters works

W
same as java string. For example:

y
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);

ssame as:

hB
c
1. String s="javatpoint";

e
2. Java String class provides a lot of methods to perform operations on string such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()

T
etc.
3. The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.

CharSequence Interface

@techbywebcoder
The CharSequence interface is used to represent sequence of characters. It is implemented
by String, StringBuffer and StringBuilder classes. It means, we can create string in java by
using these 3 classes.

The java String is immutable i.e. it cannot be changed. Whenever we change any
string, a new instance is created. For mutable string, you can use StringBuffer and StringBuilder

r
classes.

e
There are two ways to create String object:
1. By string literal

d
2. By new keyword

o
String Literal

C
Java String literal is created by using double quotes. For Example:

eb
1. String s="welcome";

Each time you create a string literal, the JVM checks the string constant pool first. If the string

W
already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in

y
the pool, a new string instance is created and placed in the pool. For example:

B
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance

h
By new keyword

c
1. String s=new String("Welcome");//creates two objects and one reference variable

e
In such case, JVM will create a new string object in normal (non pool) heap memory and the

T
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object
in heap (non pool).

Java String Example


public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
java

@techbywebcoder
strings
example
Immutable String in Java

In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.

Once string object is created its data or state can't be changed but a new string object is created.

Let's try to understand the immutability concept by the example given below:

class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";

r
s.concat(" Tendulkar");//concat() method appends the string at the end

e
System.out.println(s);//will print Sachin because strings are immutable objects
}}

d
Output:Sachin
class Testimmutablestring1{

o
public static void main(String args[]){
String s="Sachin";

C
s=s.concat(" Tendulkar");

b
System.out.println(s);
} } Output:Sachin Tendulkar

e
yW
hB
ec
T

@techbywebcoder
Inheritance in
Java

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors
of parent object. Inheritance represents the IS-A relationship, also known as parent-
child relationship.

r
Why use inheritance in java

e
o For Method Overriding (so runtime polymorphism can be achieved).

d
o For Code Reusability.

o
Syntax of Java Inheritance

C
1. class Subclass-name extends Superclass-name
2. {

b
3. //methods and fields
4. }

e
The extends keyword indicates that you are making a new class that derives from an existing

W
class. The meaning of "extends" is to increase the functionality.

By
ch
Te
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}}

Programmer salary is:40000.0

@techbywebcoder
Bonus of programmer is:10000

Types of inheritance in java

er
d
Single Inheritance Example

o
File: TestInheritance.java

C
class Animal{

b
void eat(){System.out.println("eating...");}

e
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}

W
}

y
class TestInheritance{
public static void main(String args[]){

B
Dog d=new Dog();
d.bark();

h
d.eat();
}}

c
Output:

e
barking...
eating...

T
File: TestInheritance2.java
Multilevel Inheritance Example

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{

@techbywebcoder
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.e at();
}}

Output:

weeping...
barking...
eating...

r
Hierarchical Inheritance Example

e
File: TestInheritance3.java

d
class Animal{

o
void eat(){System.out.println("eating...");}

C
}
class Dog extends Animal{

b
void bark(){System.out.println("barking...");}
}

e
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}

W
class TestInheritance3{

y
public static void main(String args[]){
Cat c=new Cat();

B
c.meow();
c.eat();

h
//c.bark();//C.T.Error

c
}}

e
Output:

T
meowing...
eating...

@techbywebcoder
Member access and Inheritance

A subclass includes all of the members of its super class but it cannot access those members of
the super class that have been declared as private. Attempt to access a private variable would
cause compilation error as it causes access violation. The variables declared as private, is only
accessible by other members of its own class. Subclass have no access to it.

r
super keyword in java

e
The super keyword in java is a reference variable which is used to refer immediate parent class

d
object.

Co
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.

1
eb
Usage of java super Keyword

super can be used to refer immediate parent class instance variable.

W
. super can be used to invoke immediate parent class method.

y
2 super() can be used to invoke immediate parent class constructor.

B
.

h
super is used to refer immediate parent class instance variable.
3

c
class
. Animal{ String color="white"; } class Dog extends

e
Animal{ String color="black"; void printColor(){

T
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal
class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();

@techbywebcoder
d.printColor();
}}

Output:

black
white

Final Keyword in Java


The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be:

er
d
1 variable

o
. method

2 class

C
.

b
The final keyword can be applied with the variables, a final variable that have no value it is called
3

e
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The
. final variable can be static also which will be initialized in the static block only.
blank

W
Object class in Java

By
The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.

ch
The Object class is beneficial if you want to refer any object whose type you don't know. Notice

e
that parent class reference variable can refer the child class object, know as upcasting.

T
Let's take an example, there is getObject() method that returns an object but it can be of any type
like Employee,Student etc, we can use Object class reference to refer that object. For example:

1. Object obj=getObject();//we don't know what object will be returned from this method

The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.
Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.

@techbywebcoder
Usage of Java Method Overriding
o Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

er
Example of method overriding
Class Vehicle{

d
void run(){System.out.println("Vehicle is running");}
}

o
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}

C
public static void main(String args[]){

b
Bike2 obj = new Bike2();
obj.run();

e
}

W
Output:Bike is running safely

y
1. class Bank{
int getRateOfInterest(){return 0;}

B
}
class SBI extends Bank{

h
int getRateOfInterest(){return 8;}

c
}
class ICICI extends Bank{

e
int getRateOfInterest(){return 7;}

T
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}}

Output:
SBI Rate of Interest: 8

@techbywebcoder
ICICI Rate of Interest:
7 AXIS Rate of
Interest: 9
Abstract class in Java

A class that is declared with abstract keyword is known as abstract class in java. It can have
abstract and non-abstract methods (method with body). It needs to be extended and its
method implemented. It cannot be instantiated.

Example abstract class


1. abstract class A{}

abstract method

er
d
1. abstract void printStatus();//no body and abstract

o
Example of abstract class that has abstract method

C
abstract class Bike{

b
abstract void run();
}

e
class Honda4 extends Bike{

W
void run(){System.out.println("running safely..");}
public static void main(String args[]){

y
Bike obj = new Honda4();

B
obj.run();

h
}

c
1. }

e
running safely..
Interface in Java

T
An interface in java is a blueprint of a class. It has static constants and abstract methods.

The interface in java is a mechanism to achieve abstraction. There can be only abstract

methods
in the java in
interface not method body. It is used to achieve abstraction and multiple
inheritance
Java.

Java Interface also represents IS-A relationship.

It cannot be instantiated just like abstract class.


o
o are mainly three reasons to use interface. They are given below.
There
o

@techbywebcoder
Internal addition by compiler

Understanding relationship between classes and interfaces

er
od
//Interface declaration: by first user

C
interface Drawable{
void draw();

b
}

e
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}

W
}
class Circle implements Drawable{

y
public void draw(){System.out.println("drawing circle");}
}

B
//Using interface: by third user

h
class TestInterface1{
public static void main(String args[]){

c
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
d.draw();

e
}}

T
Output:drawing circle

Multiple inheritance in Java by interface

interface Printable{

@techbywebcoder
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}}

Output:Hello
Welcome

er
d
Abstract class Interface

o
1) Abstract class can have abstract Interface can have only abstract methods. Since
and non-abstract methods. Java 8, it can have default and static

C
methods also.

b
2) Abstract class doesn't support Interface supports multiple inheritance.

e
multiple inheritance.
3) Abstract class can have final, non- Interface has only static and final variables.

W
final, static and non-static variables.

y
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.

B
5) The abstract keyword is used to The interface keyword is used to declare

h
declare abstract class. interface.

c
6) Example: Example:
public abstract class Shape{ Drawable{

e
public interface
public abstract void draw(); void draw();

T
} }

Java Inner Classes


Java inner class or nested class is a class which is declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.
Syntax of Inner class
1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. } }

@techbywebcoder
Advantage of java inner classes

There are basically three advantages of inner classes in java. They are as follows:

1) Nested classes represent a special type of relationship that is it can access all the members
(data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3) Code Optimization: It requires less code to write.

Difference between nested class and inner class in Java

r
Inner class is a part of nested class. Non-static nested classes are known as inner classes.

de
Types of Nested classes

o
There are two types of nested classes non-static and static nested classes.The non-static nested

C
classes are also known as inner classes.

b
o Non-static nested class (inner class)
1. Member inner class

e
2. Anonymous inner class
3. Local inner class

W
o Static nested class

Java Package

By
A java package is a group of similar types of classes, interfaces and sub-packages.

ch
Package in java can be categorized in two form, built-in package and user-defined package.

e
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

T
Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.

3) Java package removes naming collision.

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

@techbywebcoder
er
od
C
How to compile java package

b
If you are not using any IDE, you need to follow the syntax given below:

e
javac -d directory javafilename

W
How to run java package program

y
To Compile: javac -d . Simple.java

B
To Run: java mypack.Simple

h
Using fully qualified name

c
Example of package by import fully qualified name

Te
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");} }
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello

@techbywebcoder
Exception Handling
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
What is exception
In java, exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the
application. Exception normally disrupts the normal flow of the application that is why
we use exception handling.
Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between checked and unchecked exceptions

1) Checked Exception: The classes that extend Throwable class except RuntimeException and Error
are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked
at compile-time.

2) Unchecked Exception: The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

3) Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.


Hierarchy of Java Exception classes

er
od
bC
e
Checked and UnChecked Exceptions

yW
hB
ec
T

@techbywebcoder
Java try block

Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
Java try block must be followed by either catch or finally block.

Syntax of java try-catch

1. try{

r
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}

e
Syntax of try-finally block

1. try{

od
2. //code that may throw exception

C
3. }finally{}

b
Java catch block

e
Java catch block is used to handle the Exception. It must be used after the try block only.

W
You can use multiple catch block with a single try.

y
Problem without exception handling

B
Let's try to understand the problem if we don't use try-catch block.

h
public class Testtrycatch1{

c
public static void main(String args[]){

e
int data=50/0;//may throw exception
System.out.println("rest of the code...");
Output:

T
}}
Exception in thread main java.lang.ArithmeticException:/ by zero

As displayed in the above example, rest of the code is not executed (in such case, rest of the
code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be
executed.

Solution by exception handling

Let's see the solution of above problem by java try-catch block.

public class Testtrycatch2{

@techbywebcoder
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}}
1. Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.

r
Java Multi catch block

e
If you have to perform different tasks at the occurrence of different Exceptions, use java multi

d
catch block.

o
Let's see a simple example of java multi-catch block.

C
1. public class TestMultipleCatchBlock{

b
2. public static void main(String args[]){
3. try{

e
4. int a[]=new int[5];
5. a[5]=30/0;

W
6. }
7. catch(ArithmeticException e){System.out.println("task1 is completed");}

y
8. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");
9. }

B
10. catch(Exception e){System.out.println("common task completed");
11. }

h
12. System.out.println("rest of the code...");

c
13. } }

e
Output:task1 completed

T
rest of the code...
Java nested try example

Let's see a simple example of java nested try block.

class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}

try{

@techbywebcoder
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
1. }
Java finally block

Java finally block is a block that is used to execute important code such as closing connection,
stream etc.

r
Java finally block is always executed whether exception is handled or not.

e
Java finally block follows try or catch block.

od
C
Usage of Java finally

b
Case 1

e
Let's see the java finally example where exception doesn't occur.

W
class TestFinallyBlock{

y
public static void main(String args[]){
try{

B
int data=25/5;
System.out.println(data);

h
}
catch(NullPointerException e){System.out.println(e);}

c
finally{System.out.println("finally block is always executed");}

e
System.out.println("rest of the code...");
}

T
}
Output:5
finally block is always executed
rest of the code...

Java throw keyword

The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.
The syntax of java throw keyword is given below.

1. throw exception;

@techbywebcoder
Java throw keyword example

In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.

1. public class TestThrow1{


static void validate(int age){

r
if(age<18)
throw new ArithmeticException("not valid");

e
else

d
System.out.println("welcome to vote");
}

o
public static void main(String args[]){
validate(13);

C
System.out.println("rest of the code...");
}}

Output:

eb
Exception in thread main java.lang.ArithmeticException:not valid

W
Java throws keyword

y
The Java throws keyword is used to declare an exception. It gives an information to the

B
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.

h
Exception Handling is mainly used to handle the checked exceptions. If there occurs any

c
unchecked exception such as NullPointerException, it is programmers fault that he is not

e
performing check up before the code being used.

T
Syntax of java throws
1. return_type method_name() throws exception_class_name{
2. //method code
3. }
4.

Java throws example

Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception

@techbywebcoder
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow..."); } }

r
Output:

e
exception handled
normal flow...

o
Java Custom Exception
d
C
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.

b
By the help of custom exception, you can have your own exception and message.

e
Let's see a simple example of java custom exception.

yW
class InvalidAgeException extends Exception{
InvalidAgeException(String s){

B
super(s);
}}

h
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{

c
if(age<18)

e
throw new InvalidAgeException("not valid");
else

T
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}

System.out.println("rest of the code...");


}}

Output:Exception occured: InvalidAgeException:not valid rest of the code...

@techbywebcoder
Multithreading

Multithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.

er
Java Multithreading is mostly used in games, animation etc.

d
Advantages of Java Multithreading

o
1) It doesn't block the user because threads are independent and you can perform multiple

C
operations at same time.

b
2) You can perform many operations together so it saves time.

e
3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.

W
Life cycle of a Thread (Thread States)

By
A thread can be in one of the five states. According to sun, there is only 4 states in thread life

h
cycle in java new, runnable, non-runnable and terminated. There is no running state.

c
But for better understanding the threads, we are explaining it in the 5 states.

Te
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

@techbywebcoder
er
od
bC
e
yW
How to create thread

B
There are two ways to create a thread:

ch
1. By extending Thread class
2. By implementing Runnable interface.

Te
Thread class:

Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

@techbywebcoder
Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.

r
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.

e
11. public int getId(): returns the id of the thread.

d
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.

o
14. public void yield(): causes the currently executing thread object to temporarily pause and allow

C
other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).

b
16. public void resume(): is used to resume the suspended thread(depricated).

e
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.

W
20. public void interrupt(): interrupts the thread.

y
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

hB
c
Runnable interface:

e
The Runnable interface should be implemented by any class whose instances are intended to be

T
executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.

Starting a thread:

start() method of Thread class is used to start a newly created thread. It performs following
tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

@techbywebcoder
Java Thread Example by extending Thread class

class Multi extends Thread{


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

r
Java Thread Example by implementing Runnable interface

public void run(){

de
class Multi3 implements Runnable{

o
System.out.println("thread is running...");
}

C
public static void main(String args[]){
Multi3 m1=new Multi3();

b
Thread t1 =new Thread(m1);
t1.start();

e
}}
Output:thread is running...

yW Priority of a Thread (Thread Priority):


Each thread have a priority. Priorities are represented by a number between 1 and 10. In most

B
cases, thread schedular schedules the threads according to their priority (known as preemptive

h
scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.

ec
3 constants defined in Thread class:

T
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and


the value of MAX_PRIORITY is 10.
Example of priority of a Thread:
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){

@techbywebcoder
TestMultiPriority1 m1=new
TestMultiPriority1(); TestMultiPriority1
m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start(); m2.start(); } }

Output:running thread name is:Thread-0


running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

r
Java synchronized method

e
If you declare any method as synchronized, it is known as synchronized method.

d
Synchronized method is used to lock an object for any shared resource.

Co
When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.

b
Example of inter thread communication in java

e
Let's see the simple example of inter thread communication.

W
class Customer{

y
int amount=10000;
synchronized void withdraw(int amount){

B
System.out.println("going to withdraw...");

h
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");

c
try{wait();}catch(Exception e){}

e
}
this.amount-=amount;

T
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){

@techbywebcoder
public void run(){c.deposit(10000);}
}
start();
}}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
ThreadGroup in Java

Java provides a convenient way to group multiple threads in a single object. In such way, we can

r
suspend, resume or interrupt group of threads by a single method call.

e
Note: Now suspend(), resume() and stop() methods are deprecated.

od
Java thread group is implemented by java.lang.ThreadGroup class.

C
Constructors of ThreadGroup class

b
There are only two constructors of ThreadGroup class. ThreadGroup(String name)

e
ThreadGroup(ThreadGroup parent, String name)
Let's see a code to group multiple threads.

W
ThreadGroup tg1 = new ThreadGroup("Group A");

y
Thread t1 = new Thread(tg1,new MyRunnable(),"one");
1 Thread t2 = new Thread(tg1,new MyRunnable(),"two");

B
. Thread t3 = new Thread(tg1,new MyRunnable(),"three");

h
2 Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable
.

c
3 is the

e
.
class that implements Runnable interface and "one", "two" and "three" are the thread
4 names.

T
. Now we can interrupt all threads by a single line of code only.

Thread.currentThread().getThreadGroup().interrupt();
1.

@techbywebcoder
java.net
The term network programming refers to writing programs that execute across multiple
devices (computers), in which the devices are all connected to each other using a network.

The java.net package of the J2SE APIs contains a collection of classes and interfaces that
provide the low-level communication details, allowing you to write programs that focus on
solving the problem at hand.

The java.net package provides support for the two common network protocols −

 TCP − TCP stands for Transmission Control Protocol, which allows for reliable

r
communication between two applications. TCP is typically used over the Internet

e
Protocol, which is referred to as TCP/IP.

d
 UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows

o
for packets of data to be transmitted between applications.

C
This chapter gives a good understanding on the following two subjects −

b
 Socket Programming − This is the most widely used concept in Networking and it has

e
been explained in very detail.

W
 URL Processing − This would be covered separately.

y
java.text

B
The java.text package is necessary for every java developer to master because it has a lot of
classes that is helpful in formatting such as dates, numbers, and messages.

ch
e
java.text Classes

T
The following are the classes available for java.text package

[table]
Class|Description
SimpleDateFormat|is a concrete class that helps in formatting and parsing of dates.
[/table]

@techbywebcoder
Collection Framework in Java

Collections in java is a framework that provides an architecture to store and manipulate the
group of objects.

er
All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.

od
Java Collection simply means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,

C
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).

eb
What is framework in java
o provides readymade architecture.

W
o represents set of classes and interface.

y
o is optional.

B
What is Collection framework

ch
Collection framework represents a unified architecture for storing and manipulating group of

e
objects. It has:

T
1. Interfaces and its implementations i.e. classes
2. Algorithm

@techbywebcoder
Hierarchy of Collection Framework

er
od
bC
Java ArrayList class

e
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class

W
and implements List interface.

y
The important points about Java ArrayList class are:

hB
Java ArrayList class can contain duplicate elements.

c
o Java ArrayList class maintains insertion order.
o

e
Java ArrayList class is non synchronized.
o

T
Java ArrayList allows random access because array works at the index basis.
o
In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred
if any element is removed from the array list.

@techbywebcoder
ArrayList class declaration

Let's see the declaration for java.util.ArrayList class.

Constructors of Java ArrayList

Constructor Description

r
ArrayList() It is used to build an empty array list.

c)

de
ArrayList(Collection It is used to build an array list that is initialized with the
elements of the collection c.

ArrayList(int
capacity)

Co It is used to build an array list that has the specified


initial capacity.

eb
Java ArrayList Example
import java.util.*;

W
class TestCollection1{

y
public static void main(String args[]){

B
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist

h
list.add("Vijay");

c
list.add("Ravi");

e
list.add("Ajay");

T
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); } }}

Ravi
Vijay
Ravi
Ajay

@techbywebcoder
vector
ArrayList and Vector both implements List interface and maintains insertion order.

But there are many differences between ArrayList and Vector classes that are given below.

ArrayList Vector

1) ArrayList is not synchronized. Vector is synchronized.

r
2)ArrayList increments 50% of Vector increments 100% means doubles the array

e
current array size if number of size if total number of element exceeds than its

d
element exceeds from its capacity. capacity.

o
3)ArrayList is not a legacy class, Vector is a legacy class.

C
it is introduced in JDK 1.2.

b
4) ArrayList is fast because it is Vector is slow because it is synchronized i.e. in

e
non-synchronized. multithreading environment, it will hold the other
threads in runnable or non-runnable state until

W
current thread releases the lock of object.

By
5) ArrayLis tuses Iterator interface
to traverse the elements.
Vector uses Enumeration interface to traverse the
elements. But it can use Iterator also.

ch
e
Example of Java Vector

T
Let's see a simple example of java Vector class that uses Enumeration interface.

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

Vector<String> v=new Vector<String>();//creating


vector
v.add("umesh");//method of Collection
v.addElement("irfan");//method of Vector
v.addElement("kumar");
//traversing elements using Enumeration

@techbywebcoder
9. Enumeration e=v.elements();
10. while(e.hasMoreElements()){
11. System.out.println(e.nextElement());
12. } } }

Output:

umesh
irfan
kumar

er
d
Java Hashtable class

o
Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary

C
class and implements the Map interface.

b
The important points about Java Hashtable class are:

e
A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is

W
identified by calling the hashcode() method. A Hashtable contains values based on the

y
key.

B
o It contains only unique elements.

h
o It may have not have any null key or value.
o

c
It is synchronized.

e
Hashtable class declaration

T
Let's see the declaration for java.util.Hashtable class.

1. public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Ser


ializable
Hashtable class Parameters

Let's see the Parameters for java.util.Hashtable class.

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.

@techbywebcoder
Constructors of Java Hashtable class

Constructor Description

Hashtable() It is the default constructor of hash table it instantiates the


Hashtable class.

Hashtable(int size) It is used to accept an integer parameter and creates a hash table
that has an initial size specified by integer value size.

r
Hashtable(int size, float It is used to create a hash table that has an initial size specified by

e
fillRatio) size and a fill ratio specified by fillRatio.

d
Java Hashtable Example

o
import java.util.*;
class TestCollection16{

C
public static void main(String args[]){

b
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();

e
hm.put(100,"Amit");
hm.put(102,"Ravi");

W
hm.put(101,"Vijay");

y
hm.put(103,"Rahul");

B
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());

h
}}}

Output:

ec
T
103 Rahul
102 Ravi
101 Vijay
100 Amit

Stack

Stack is a subclass of Vector that implements a standard last-in, first-out stack.

Stack only defines the default constructor, which creates an empty stack. Stack includes all the
methods defined by Vector, and adds several of its own.

@techbywebcoder
Stack( )
Example
The following program illustrates several of the methods supported by this collection −

import java.util.*;

public class StackDemo {

static void showpush(Stack st, int a) {

st.push(new Integer(a));

r
System.out.println("push(" + a + ")");

de
System.out.println("stack: " + st);}

o
static void showpop(Stack st) {

C
System.out.print("pop -> ");

b
Integer a = (Integer) st.pop();

e
System.out.println(a);

W
System.out.println("stack: " + st); }

y
public static void main(String args[]) {

B
Stack st = new Stack();

h
System.out.println("stack: " + st);

c
showpush(st, 42);

e
showpush(st, 66);

T
showpush(st, 99);

showpop(st);

showpop(st);

showpop(st);

try {

showpop(st);

} catch (EmptyStackException e) {

System.out.println("empty stack");

@techbywebcoder
}}}

This will produce the following result −

Output
stack: [ ] push(42) stack: [42] push(66) stack: [42, 66] push(99) stack: [42, 66, 99]
pop -> 99 stack: [42, 66] pop -> 66 stack: [42] pop -> 42 stack: [ ] pop -> empty stack
Enumeration
The Enumeration Interface The Enumeration interface defines the methods by which

r
you can enumerate (obtain one at a

e
time) the elements in a collection of objects.

od
bC
e
yW
hB
The methods declared by Enumeration are summarized in the following table −

Sr.No.

ec Method & Description

T
boolean hasMoreElements( )

When implemented, it must return true while there are still more elements to extract, and
false when all the elements have been enumerated.

2
Object nextElement( )
This returns the next object in the enumeration as a generic Object reference.

Example

@techbywebcoder
Following is an example showing usage of Enumeration.

import java.util.Vector;

import java.util.Enumeration;

public class EnumerationTester {

public static void main(String args[]) {

Enumeration days;

Vector dayNames = new Vector();

er
dayNames.add("Sunday");

d
dayNames.add("Monday");

o
dayNames.add("Tuesday");

C
dayNames.add("Wednesday");

b
dayNames.add("Thursday");

e
dayNames.add("Friday");

W
dayNames.add("Saturday");

y
days = dayNames.elements();

B
while (days.hasMoreElements()) {

h
System.out.println(days.nextElement());

c
} }}

Te
This will produce the following result −

Output

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Iterator

@techbywebcoder
It is a universal iterator as we can apply it to any Collection object. By using Iterator, we
can perform both read and remove operations. It is improved version of Enumeration with
additional functionality of remove-ability of a element. Iterator must be used whenever we
want to enumerate elements in all Collection framework implemented interfaces like Set,
List, Queue, Deque and also in all implemented classes of Map interface. Iterator is the only
cursor available for entire collection framework. Iterator object can be created by calling
iterator() method present in Collection interface.
// Here "c" is any Collection object. itr is of
// type Iterator interface and refers to "c"
Iterator itr = c.iterator();
Iterator interface defines three methods:

r
// Returns true if the iteration has more elements

e
public boolean hasNext();

d
// Returns the next element in the iteration

o
// It throws NoSuchElementException if no more

C
// element present
public Object next();

b
// Remove the next element in the iteration

e
// This method can be called only once per call
// to next()

W
public void remove();

y
remove() method can throw two exceptions

B
 UnsupportedOperationException
IllegalStateException : If the next:method
If the remove operation
has not yet beeniscalled,
not supported by thismethod
or the remove iterator

h

has already been called after the last call to the next method

c
Limitations of Iterator:
 Only forward direction iterating is possible.

e
Replacement and addition of new element is not supported by Iterator.

T
StringTokenizer in Java

The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to
break string.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc.

Constructors of StringTokenizer class

There are 3 constructors defined in the StringTokenizer class.

@techbywebcoder
Constructor Description

StringTokenizer(String str) creates StringTokenizer with specified string.

StringTokenizer(String str, creates StringTokenizer with specified string and


String delim) delimeter.

StringTokenizer(String str, creates StringTokenizer with specified string, delimeter


String delim, boolean and returnValue. If return value is true, delimiter

r
returnValue) characters are considered to be tokens. If it is false,

e
delimiter characters serve to separate tokens.

od
Methods of StringTokenizer class

C
The 6 useful methods of StringTokenizer class are as follows:

Public method

eb Description

W
boolean hasMoreTokens() checks if there is more tokens available.

By
String nextToken() returns the next token from the StringTokenizer object.

h
String nextToken(String delim) returns the next token based on the delimeter.

c
boolean hasMoreElements() same as hasMoreTokens() method.

Te
Object nextElement()

int countTokens()
same as nextToken() but its return type is Object.

returns the total number of tokens.

Simple example of StringTokenizer class

Let's see the simple example of StringTokenizer class that tokenizes a string "my name is khan"
on the basis of whitespace.

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

@techbywebcoder
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}}}
Output:my
name
is
khan
Example of nextToken(String delim) method of StringTokenizer class

r
import java.util.*;

e
public class Test {

d
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("my,name,is,khan");

o
// printing next token

C
System.out.println("Next token is : " + st.nextToken(","));

b
} }

e
Output:Next token is : my

W
java.util.Random

y
 For using this class to generate random numbers, we have to first create an instance of this
class and then invoke methods such as nextInt(), nextDouble(), nextLong() etc using that

B
instance.

h
We can generate random numbers of types integers, float, double, long, booleans using this
class.

c
We can pass arguments to the methods for placing an upper bound on the range of the

e
numbers to be generated. For example, nextInt(6) will generate numbers in the range 0 to 5
both inclusive.

T
// A Java program to demonstrate random number generation
// using java.util.Random;
import java.util.Random;

public class generateRandom{

public static void main(String args[])


{
// create instance of Random class
Random rand = new Random();
// Generate random integers in range 0 to 999
int rand_int1 = rand.nextInt(1000);
int rand_int2 = rand.nextInt(1000);

@techbywebcoder
// Print random integers
System.out.println("Random Integers:
"+rand_int1); System.out.println("Random
Integers: "+rand_int2);
// Generate Random doubles
double rand_dub1 = rand.nextDouble();
double rand_dub2 = rand.nextDouble();

// Print random doubles


System.out.println("Random
"+rand_dub1); Doubles:
}} System.out.println("Random Doubles:
Output:

r
"+rand_dub2);

e
Random Integers: 547

d
Random Integers: 126
Random Doubles: 0.8369779739988428

o
Random Doubles: 0.5497554388209912

C
b
Java Scanner class

e
There are various ways to read input from the keyboard, the java.util.Scanner class is one of

W
them. The Java Scanner class breaks the input into tokens using a delimiter that is
whitespace bydefault. It provides many methods to read and parse various primitive

y
values.

B
Java Scanner class is widely used to parse text for string and primitive types using regular

h
expression.

c
Java Scanner class extends Object class and implements Iterator and Closeable interfaces.

Te
Commonly used methods of Scanner class

There is a list of commonly used Scanner class methods:

Method Description

public String next() it returns the next token from the scanner.

public String nextLine() it moves the scanner position to the next line and returns the value
as a string.

public byte nextByte() it scans the next token as a byte.

@techbywebcoder
public short nextShort() it scans the next token as a short value.

public int nextInt() it scans the next token as an int value.

public long nextLong() it scans the next token as a long value.

public float nextFloat() it scans the next token as a float value.

public double it scans the next token as a double value.


nextDouble()

er
Java Scanner Example to get input from console

od
Let's see the simple example of the Java Scanner class which reads the int, string and double

C
value as an input:

b
import java.util.Scanner;

e
class ScannerTest{
public static void main(String args[]){

W
Scanner sc=new Scanner(System.in);

y
System.out.println("Enter your rollno");

B
int rollno=sc.nextInt();
System.out.println("Enter your name");

h
String name=sc.next();

c
System.out.println("Enter your fee");

e
double fee=sc.nextDouble();

T
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();
} } Output:
Enter your rollno
111
Enter your name
Ratan
Enter
450000
Rollno:111 name:Ratan fee:450000

@techbywebcoder
Java Calendar Class
Java Calendar class is an abstract class that provides methods for converting date between
a specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It
inherits Object class and implements the Comparable interface.
Java Calendar class declaration

Let's see the declaration of java.util.Calendar class.

r
1 public abstract class Calendar extends Object
. implements Serializable, Cloneable, Comparable<Calendar>

e
2 Java Calendar Class Example

d
.

o
import java.util.Calendar;

C
public class CalendarExample1 {

b
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();

e
System.out.println("The current date is : " + calendar.getTime());

W
calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: " + calendar.getTime());

y
calendar.add(Calendar.MONTH, 4);

B
System.out.println("4 months later: " + calendar.getTime());

h
calendar.add(Calendar.YEAR, 2);

c
System.out.println("2 years later: " + calendar.getTime());
}}

Output:

Te
The current date is : Thu Jan 19 18:47:02 IST 2017
15 days ago: Wed Jan 04 18:47:02 IST 2017
4 months later: Thu May 04 18:47:02 IST 2017
2 years later: Sat May 04 18:47:02 IST 2019

@techbywebcoder
Java - Files and I/O
The java.io package contains nearly every class you might ever need to perform input and
output (I/O) in Java. All these streams represent an input source and an output
destination. The stream in the java.io package supports many data such as primitives,
object, localized characters, etc.
Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −

r
 InPutStream − The InputStream is used to read data from a source.

e
 OutPutStream − The OutputStream is used for writing data to a destination.

od
Java provides strong but flexible support for I/O related to files and networks but this

C
tutorial covers very basic functionality related to streams and I/O. We will see the most

b
commonly used examples one by one −

e
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there

W
are many
classes classesto are,
related FileInputStream
byte streams but and
the FileOutputStream.
most frequently Following
used is an

y
example which makes use of these two classes to copy an input file into an output file

B

h
Example

c
import java.io.*;

Te
public class CopyFile {

public static void main(String args[]) throws IOException {

FileInputStream in = null;

FileOutputStream out = null;

try {

in = new FileInputStream("input.txt");

out = new FileOutputStream("output.txt");

int c;

while ((c = in.read()) != -1) {

@techbywebcoder
out.write(c);

}finally {

if (in != null) {

in.close();

if (out != null) {

r
out.close();

}} }}

de
o
Now let's have a file input.txt with the following content −

C
This is test for copy file.

b
As a next step, compile the above program and execute it, which will result in creating output.txt

e
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java
file and do the following −

yW
$javac CopyFile.java
$java CopyFile

B
Character Streams

h
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java

c
Character streams are used to perform input and output for 16-bit unicode. Though there

e
are many classes related to character streams but the most frequently used classes are,

T
FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads
two bytes at a time and FileWriter writes two bytes at a time.

We can re-write the above example, which makes the use of these two classes to copy an

input
file (having unicode characters) into an output file −
Example
import java.io.*;

public class CopyFile {

public static void main(String args[]) throws IOException {

@techbywebcoder
FileReader in =

null; FileWriter out

= null; try {

in = new FileReader("input.txt");

out = new FileWriter("output.txt");

int c;

while ((c = in.read()) != -1) {

r
out.write(c);}

}finally {

de
o
if (in != null) {

C
in.close();}

b
if (out != null) {

e
out.close();

}} }}

yW
Now let's have a file input.txt with the following content −

B
This is test for copy file.

h
As a next step, compile the above program and execute it, which will result in creating output.txt

c
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java

e
file and do the following −

T
$javac CopyFile.java
$java CopyFile
Standard Streams

All the programming languages provide support for standard I/O where the user's
program can take input from a keyboard and then produce an output on the computer
screen. Java provides the following three standard streams −

 Standard Input − This is used to feed the data to user's program and usually a keyboard
is used as standard input stream and represented asSystem.in.

@techbywebcoder
 Standard Output − This is used to output the data produced by the user's program
and usually a computer screen is used for standard output stream and represented
as System.out.

 Standard Error − This is used to output the error data produced by the user's program
and usually a computer screen is used for standard error stream and represented
as System.err.

Following is a simple program, which creates InputStreamReader to read standard input stream
until the user types a "

r
Example

e
import java.io.*;

od
public class ReadConsole {

public static void main(String args[]) throws IOException {

bC
InputStreamReader cin = null;

e
try {

cin = new InputStreamReader(System.in);

yW
System.out.println("Enter characters, 'q' to quit.");

B
char c;

h
do {

c
c = (char) cin.read();

e
System.out.print(c);

T
} while(c != 'q');

}finally {

if (cin != null) {

cin.close();

} } }}

This program continues to read and output the same character until we press 'q' −

$javac ReadConsole.java
$java ReadConsole

@techbywebcoder
Enter characters, 'q' to quit.
1
1
e
e
q
q

Reading and Writing Files


As described earlier, a stream can be defined as a sequence of data. The InputStream is used to

r
read data from a source and the OutputStream is used for writing data to a destination.

e
Here is a hierarchy of classes to deal with Input and Output streams.

od
bC
e
yW
hB
ec
T
The two important streams are FileInputStream and FileOutputStream

FileInputStream
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.

Following constructor takes a file name as a string to create an input stream object to read the
file −

InputStream f = new FileInputStream("C:/java/hello");

@techbywebcoder
Following constructor takes a file object to create an input stream object to read the file. First we
create a file object using File() method as follows −

File f = new File("C:/java/hello");


InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can be
used to read to stream or to do other operations on the stream.

 ByteArrayInputStream

r
 DataInputStream

e
FileOutputStream

d
FileOutputStream is used to create a file and write data into it. The stream would create a file, if
it doesn't already exist, before opening it for output.

o
Here are two constructors which can be used to create a FileOutputStream object.

C
b
Following constructor takes a file name as a string to create an input stream object to write the
file −

e
OutputStream f = new FileOutputStream("C:/java/hello")

yW
Following constructor takes a file object to create an output stream object to write the file. First,
we create a file object using File() method as follows −

hB
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);

ec
Once you have OutputStream object in hand, then there is a list of helper methods, which can be
used to write to stream or to do other operations on the stream.

T
 ByteArrayOutputStream
 DataOutputStream

Example

Following is the example to demonstrate InputStream and OutputStream −

import java.io.*;

public class fileStreamTest {

public static void main(String args[]) {

try {

@techbywebcoder
byte bWrite [] = {11,21,3,40,5};

OutputStream os = new FileOutputStream("test.txt");

for(int x = 0; x < bWrite.length ; x++) {

os.write( bWrite[x] ); // writes the bytes}

os.close();

InputStream is = new FileInputStream("test.txt");

int size = is.available();

r
for(int i = 0; i < size; i++) {

e
System.out.print((char)is.read() + " "); }

d
o
is.close();

C
} catch (IOException e) {

b
System.out.print("Exception");

e
} }}

W
Java.io.RandomAccessFile Class

y
The Java.io.RandomAccessFile class file behaves like a large array of bytes stored in the file

B
system.Instances of this class support both reading and writing to a random access file.

h
Class declaration

c
Following is the declaration for Java.io.RandomAccessFile class −

e
public class RandomAccessFile

T
extends Object
implements DataOutput, DataInput, Closeable
Class constructors
S.N. Constructor & Description

1
RandomAccessFile(File file, String mode)
This creates a random access file stream to read from, and optionally to write to, the file
specified by the File argument.

@techbywebcoder
2
RandomAccessFile(File file, String mode)
This creates a random access file stream to read from, and optionally to write to, a file with
the specified name.

Methodsinherited
This class inherits methods from the following classes −

 Java.io.Object

er
Java.io.File Class in Java

d
The File class is Java’s representation of a file or directory path name. Because file and

o
directory names have different formats on different platforms, a simple string is not
adequate to name them. The File class contains several methods for working with the path

C
name, deleting and renaming files, creating new directories, listing the contents of a
directory, and determining several common attributes of files and directories.

b
 It is an abstract representation
abstract or in string form can beof file and
either directory
absolute pathnames.
or relative. A pathname, whether
The parent

e
 of an abstract pathname may be obtained by invoking the getParent() method of this
 class.

W
First
nameof all, we should create the File class object by passing the filename or directory

y
to it. A file system may implement restrictions to certain operations on the actual file-
system object, such as reading, writing, and executing. These restrictions are

B
 collectively
known as access permissions.

h
Instances
pathname of the File class are immutable; that is, once created, the abstract

c
represented by a File object will never change.

e
File a = new File("/usr/local/bin/geeks");

T
defines an abstract file name for the geeks file in directory /usr/local/bin. This is an absolute
abstract file name.
Program to check if a file or directory physically exist or not.
// In this program, we accepts a file or directory name
from // command line arguments. Then the program
will check if // that file or directory physically exist or
not and // it displays the property of that file or
directory. *import java.io.File;
// Displaying file property
class fileProperty
{
public static void main(String[] args) {

@techbywebcoder
//accept file name or directory name through command line args
String fname =args[0];
//pass the filename or directory name to File object
File f = new File(fname);
//apply File class methods on File object
System.out.println("File name :"+f.getName());
System.out.println("Path: "+f.getPath());
System.out.println("Absolute path:" +f.getAbsolutePath());
System.out.println("Parent:"+f.getParent());
System.out.println("Exists :"+f.exists());
if(f.exists())
{

er
System.out.println("Is writeable:"+f.canWrite());
System.out.println("Is readable"+f.canRead());

d
System.out.println("Is a directory:"+f.isDirectory());
System.out.println("File Size in bytes "+f.length());

o
}
}

C
}

b
Output:

e
File name :file.txt

W
Path: file.txt

y
Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\file.txt
Parent:null

B
Exists :true

h
Is writeable:true

c
Is readabletrue

e
Is a directory:false

T
File Size in bytes 20

Connceting to DB

Whatis JDBCDriver?
JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.
For example, using JDBC drivers enable you to open database connections and to interact with it
by sending SQL or database commands then receiving results with Java.

@techbywebcoder
The Java.sql package that ships with JDK, contains various classes with their behaviours
defined and their actual implementaions are done in third-party drivers. Third party
vendors implements the java.sql.Driver interface in their database driver.

JDBC Drivers Types


JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into
four categories, Types 1, 2, 3, and 4, which is explained below −

Type 1: JDBC-ODBCBridge Driver

r
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client

e
machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that

d
represents the target database.

o
When Java first came out, this was a useful driver because most databases only supported

C
ODBC

b
access but now this type of driver is recommended only for experimental use or when
no other

e
alternative is available.

yW
hB
ec
T
Type 2: JDBC-Native API
The JDBC-ODBC Bridge that comes with
JDK 1.2 is a good example of this kind of driver.

In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are
unique to the database. These drivers are typically provided by the database vendors and
used in the same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be
installed on each client machine.

@techbywebcoder
If we change the Database, we have to change the native API, as it is specific to a
database and they are mostly obsolete now, but you may realize some speed increase
with a Type 2 driver, because it eliminates ODBC's overhead.

er
od
bC
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

e
Type 3: JDBC-Net pure Java
In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use

W
standard network sockets to communicate with a middleware application server. The

y
socket information is then translated by the middleware application server into the call

B
format required by the DBMS, and forwarded to the database server.

h
This kind of driver is extremely flexible, since it requires no code installed on the client

c
and a

e
single driver can actually provide access to multiple databases.

@techbywebcoder
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the
client application. As a result, you need some knowledge of the application server's configuration
in order to effectively use this driver type.

Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.

Type 4: 100% Pure Java


In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's
database through socket connection. This is the highest performance driver available

r
for the database and is usually provided by the vendor itself.

e
This kind of driver is extremely flexible, you don't need to install special software on the

d
client

o
or server. Further, these drivers can be downloaded dynamically.

bC
e
yW
hB
ec
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their

T
network protocols, database vendors usually supply type 4 drivers.

Which Driver should be Used?


If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver
type is 4.

If your Java application is accessing multiple types of databases at the same time, type 3 is the
preferred driver.
Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for
your database.

@techbywebcoder
The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.

Example to connect to the mysql database in java

For connecting java application with the mysql database, you need to follow 5 steps to perform
database connectivity.

In this example we are using MySql as the database. So we need to know following informations
for the mysql database:

r
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.

e
2. Connection
database URL: The connection URL for the mysql

d
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,

o
localhost is the server name on which mysql is running, we may also use IP address, 3306

C
is the port number and sonoo is the database name. We may use any database, in such
case, you need to replace the sonoo with your database name.

b
3. Username: The default username for the mysql database is root.

e
4. Password: Password is given by the user at the time of installing the mysql database. In

W
this example, we are going to use root as the password.

y
Let's first create a table in the mysql database, but before creating table, we need to create

B
database first.

h
1 create database sonoo;

c
. use sonoo;

e
2 create table emp(id int(10),name varchar(40),age int(3));

T
. Example to Connect Java Application with mysql database
3
In this example, sonoo is the database name, root is the username and password.
.

import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password

@techbywebcoder
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}}

The above example will fetch all the records of emp table.

r
To connect java application with the mysql database mysqlconnector.jar file is required to be

e
loaded.

d
Two ways to load the jar file:

o
1. paste the mysqlconnector.jar file in jre/lib/ext folder

C
2. set classpath

b
1) paste the mysqlconnector.jar file in JRE/lib/ext folder:

e
Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.

W
2) set classpath:

y
There are two ways to set the classpath:

B
1.temporary 2.permanent

h
How to set the temporary classpath

c
open command prompt and write:

e
1. C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;

T
How to set the permanent classpath

Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.; as
C:\folder\mysql-connector-java-5.0.8-bin.jar;

JDBC-Result Sets

The SQL statements that read data from a database query, return the data in a result
set. The SELECT statement is the standard way to select rows from a database and
view them in a result set. The java.sql.ResultSet interface represents the result set of
a database query.

@techbywebcoder
A ResultSet object maintains a cursor that points to the current row in the result set. The term
"result set" refers to the row and column data contained in a ResultSet object.

The methods of the ResultSet interface can be broken down into three categories −

 Navigational methods: Used to move the cursor around.

 Get methods: Used to view the data in the columns of the current row being pointed by
the cursor.

 Update methods: Used to update the data in the columns of the current row. The updates

r
can then be updated in the underlying database as well.

e
The cursor is movable based on the properties of the ResultSet. These properties are designated

d
when the corresponding Statement that generates the ResultSet is created.

o
JDBC provides the following connection methods to create statements with desired ResultSet −

C
 createStatement(int RSType, int RSConcurrency);

b
 prepareStatement(String SQL, int RSType, int RSConcurrency);

e
 prepareCall(String sql, int RSType, int RSConcurrency);

W
The first argument indicates the type of a ResultSet object and the second argument is one of two

y
ResultSet constants for specifying whether a result set is read-only or updatable.

hB
Type of ResultSet

c
The possible RSType are given below. If you do not specify any ResultSet type, you will

e
automatically get one that is TYPE_FORWARD_ONLY.

T
Type Description

ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result


set.

ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forward and backward, and


the result set is not sensitive to changes made by
others to the database that occur after the result set
was created.

@techbywebcoder
ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and backward, and
the result set is sensitive to changes made by
others to the database that occur after the result set
was created.

Concurrencyof ResultSet
The possible RSConcurrency are given below. If you do not specify any Concurrency type, you
will automatically get one that is CONCUR_READ_ONLY.

Concurrency Description

er
ResultSet.CONCUR_READ_ONLY Creates a read-only result set. This is the default

od
ResultSet.CONCUR_UPDATABLE Creates an updateable result set.

bC
e
Viewinga Result Set
The ResultSet interface contains dozens of methods for getting the data of the current row.

W
There is a get method for each of the possible data types, and each get method has two versions

y
 One that takes in a column

B
h
name.  One that takes in a

c
Forcolumn index.
example, if the column you are interested in viewing contains an int, you need to use one of

e
the getInt() methods of ResultSet −

T
S.N. Methods & Description

1 public int getInt(String columnName) throws SQLException

Returns the int in the current row in the column named columnName.

2 public int getInt(int columnIndex) throws SQLException


Returns the int in the current row in the specified column index. The column index starts
at 1, meaning the first column of a row is 1, the second column of a row is 2, and so on.

@techbywebcoder
Similarly, there are get methods in the ResultSet interface for each of the eight Java
primitive types, as well as common types such as java.lang.String, java.lang.Object, and
java.net.URL.

There are also methods for getting SQL data types java.sql.Date, java.sql.Time,
java.sql.TimeStamp, java.sql.Clob, and java.sql.Blob. Check the documentation for more
information about using these SQL data types.

For a better understanding, let us study Viewing - Example Code.


Updatinga Result Set
The ResultSet interface contains a collection of update methods for updating the data of a result

r
set.

e
As with the get methods, there are two update methods for each data type −

d
o
 One that takes in a column name.

C
 One that takes in a column index.

eb
yW
hB
ec
T

@techbywebcoder
For example, to update a String column of the current row of a result set, you would use one of
the following updateString() methods −

S.N. Methods & Description

1 public void updateString(int columnIndex, String s) throws SQLException

Changes the String in the specified column to the value of s.

r
2 public void updateString(String columnName, String s) throws SQLException
Similar to the previous method, except that the column is specified by its name instead of

e
its index.

od
There are update methods for the eight primitive data types, as well as String, Object, URL, and
the SQL data types in the java.sql package.

C
Updating a row in the result set changes the columns of the current row in the ResultSet object,

b
but not in the underlying database. To update your changes to the row in the database, you need

e
to invoke one of the following methods.

W
S.N. Methods & Description

By
public void updateRow()

ch
Updates the current row by updating the corresponding row in the database.

e
2 public void deleteRow()

T
Deletes the current row from the database

3 public void refreshRow()


Refreshes the data in the result set to reflect any recent changes in the database.

4 public void cancelRowUpdates()


Cancels any updates made on the current row.

5 public void insertRow()


Inserts a row into the database. This method can only be invoked when the cursor is
pointing to the insert row.

@techbywebcoder
GUI Programming with java
The AWT Class hierarchy

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based


applications in java.

r
Java AWT components are platform-dependent i.e. components are displayed according to the

e
view of operating system. AWT is heavyweight i.e. its components are using the resources of OS.

d
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,

o
RadioButton, CheckBox, Choice, List etc.

C
Java AWT Hierarchy

eb
The hierarchy of Java AWT classes are given below.

yW
hB
ec
T

@techbywebcoder
Container

The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such
as Frame, Dialog and Panel.

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.

r
Panel

de
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.

Frame

Co
b
The Frame is the container that contain title bar and can have menu bars. It can have other

e
components like button, textfield etc.

W
Useful Methods of Component class
Method

y
Description

hB
public void add(Component c) inserts a component on this component.

c
public void setSize(int width,int height) sets the size (width and height) of the component.

m)

Te
public void setLayout(LayoutManager

public void setVisible(boolean status)


defines the layout manager for the component.

changes the visibility of the component, by default


false.

Java AWT Example

To create simple awt example, you need a frame. There are two ways to create a frame in AWT.

o By extending Frame class (inheritance)


o By creating the object of Frame class (association)

@techbywebcoder
AWT Example by Inheritance

Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing
Button component on the Frame.

import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position

r
add(b);//adding button into frame

e
setSize(300,300);//frame size 300 width and 300 height

d
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible

o
}

C
public static void main(String args[]){

b
First f=new First();

e
}}

The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example that

W
sets the position of the awt button.

By
ch
Te
Java Swing
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create
window- based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API
and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

@techbywebcoder
Difference between AWT and Swing.

No. Java AWT Java Swing

1) AWT components are platform- Java swing components are platform-


dependent. independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable look Swing supports pluggable look and

r
and feel. feel.

e
4) AWT provides less components than Swing provides more powerful

d
Swing. componentssuch as tables, lists,

o
scrollpanes, colorchooser, tabbedpane
etc.

5)

bC
AWT doesn't follows MVC(Model View Swing follows MVC.

e
Controller) where model represents data,
view represents presentation and

W
controller acts as an interface between

y
model and view.

B
Commonly used Methods of Component class

h
Method Description

ec
public void add(Component c) add a component on another component.

T
public void setSize(int width,int height)

public void setLayout(LayoutManager


m)
sets size of the component.

sets the layout manager for the component.

public void setVisible(boolean b) sets the visibility of the component. It is by default


false.

@techbywebcoder
Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.

er
od
bC
e
yW
hB
Java Swing Examples

ec
There are two ways to create a frame:

T
o By creating the object of Frame class (association)
o By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example

Let's see a simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.

File: FirstSwingExample.java

@techbywebcoder
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers

r
f.setVisible(true);//making the frame visible
}}

de Containers

o
Java JFrame

C
The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class.

b
JFrame works like the main window where components like labels, buttons, textfields are

e
added to create a GUI.

W
Unlike Frame, JFrame has the option to hide or close the window with the help of

y
setDefaultCloseOperation(int) method.

B
JFrame Example

h
import java.awt.FlowLayout;

c
import javax.swing.JButton;

e
import javax.swing.JFrame;

T
import javax.swing.JLabel;
import javax.swing.Jpanel;
public class JFrameExample {
public static void main(String s[]) {
JFrame frame = new JFrame("JFrame Example");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabel label = new JLabel("JFrame By Example");
JButton button = new JButton();
button.setText("Button");
panel.add(label);

@techbywebcoder
panel.add(button);
frame.add(panel);
frame.setSize(200, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}}
JApplet
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing.

r
The JApplet class extends the Applet class.

e
Example of EventHandling in JApplet:

import java.applet.*;
import javax.swing.*;

od
C
import java.awt.event.*;

b
public class EventJApplet extends JApplet implements ActionListener{

e
JButton b;
JTextField tf;

W
public void init(){

y
tf=new JTextField();
tf.setBounds(30,40,150,20);

B
b=new JButton("Click");

h
b.setBounds(80,150,70,40);

c
add(b);add(tf);

e
b.addActionListener(this);

T
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}}

In the above example, we have created all the controls in init() method because it is invoked
only once.

myapplet.html
1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">

@techbywebcoder
</applet>
</body>
</html>

JDialog

The JDialog control represents a top level window with a border and a title used to take some
form of input from the user. It inherits the Dialog class.

Unlike JFrame, it doesn't have maximize and minimize buttons.

r
JDialog class declaration

de
Let's see the declaration for javax.swing.JDialog class.

o
1. public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneConta

C
iner
Commonly used Constructors:

Constructor

eb Description

JDialog()

yW It is used to create a modeless dialog without a title and


without a specified Frame owner.

hB
JDialog(Frame owner) It is used to create a modeless dialog with specified

c
Frame as its owner and an empty title.

e
JDialog(Frame owner, String title, It is used to create a dialog with the specified title,

T
boolean modal) owner Frame and modality.

@techbywebcoder
Java JDialog Example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static JDialog d;
DialogExample() {
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );

r
JButton b = new JButton ("OK");

e
b.addActionListener ( new ActionListener()

d
{
public void actionPerformed( ActionEvent e )

o
{

bC
DialogExample.d.setVisible(false);

});
e Output:

yW
d.add( new JLabel ("Click button to continue."));

B
d.add(b);
d.setSize(300,300);

h
d.setVisible(true);

c
}

e
public static void main(String args[])

T
{
new DialogExample();
}}

JPanel
The JPanel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the JComponents class.

It doesn't have title bar.

@techbywebcoder
JPanel class declaration

1. public class JPanel extends JComponent implements Accessible

Java JPanel Example

import java.awt.*;
import javax.swing.*;
public class PanelExample {
PanelExample()
{

r
JFrame f= new JFrame("Panel Example");

e
JPanel panel=new JPanel();

d
panel.setBounds(40,80,200,200);

o
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");

C
b1.setBounds(50,100,80,30);

b
b1.setBackground(Color.yellow);

e
JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);

W
b2.setBackground(Color.green);

y
panel.add(b1); panel.add(b2);

B
f.add(panel);

h
f.setSize(400,400);
f.setLayout(null);

c
f.setVisible(true);

e
}

T
public static void main(String args[])
{
new PanelExample();
}}
Overview of some Swing Components

Java JButton

The JButton class is used to create a labeled button that has platform independent implementation. The
application result in some action when the button is pushed. It inherits AbstractButton class.

@techbywebcoder
JButton class declaration
Let's see the declaration for javax.swing.JButton class.

1. public class JButton extends AbstractButton implements Accessible

Java JButton Example

import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {

r
JFrame f=new JFrame("Button Example");

e
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);

d
f.add(b);

o
f.setSize(400,400);

C
f.setLayout(null);
f.setVisible(true); } }

Java JLabel

eb
The object of JLabel class is a component for placing text in a container. It is used to

W
display a single line of read only text. The text can be changed by an application but a
user cannot edit it directly. It inherits JComponent class.

By
JLabel class declaration

h
Let's see the declaration for javax.swing.JLabel class.

c
1. public class JLabel extends JComponent implements SwingConstants, Accessible

e
Commonly used Constructors:

T
Constructor
Description

JLabel() Creates a JLabel instance with no image and with an


empty string for the title.

JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

JLabel(String s, Icon i, int Creates a JLabel instance with the specified text,
horizontalAlignment) image, and horizontal alignment.

@techbywebcoder
Commonly used Methods:
Methods
Description

String getText() t returns the text string that a label displays.

void setText(String text) It defines the single line of text this component will
display.

void setHorizontalAlignment(int It sets the alignment of the label's contents along

r
alignment) the X axis.

e
Icon getIcon() It returns the graphic image that the label displays.

od
int getHorizontalAlignment() It returns the alignment of the label's contents along
the X axis.

bC
Java JLabel Example

e
import javax.swing.*;

W
class LabelExample
{

y
public static void main(String args[])

B
{

h
JFrame f= new JFrame("Label Example");

c
JLabel l1,l2;

e
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);

T
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}

@techbywebcoder
JTextField
The object of a JTextField class is a text component that allows the editing of a single line text. It
inherits JTextComponent class.
JTextField class declaration

Let's see the declaration for javax.swing.JTextField class.

1. public class JTextField extends JTextComponent implements SwingConstants

r
Java JTextField Example

import javax.swing.*;
class TextFieldExample

de
o
{

C
public static void main(String args[])

b
{
JFrame f= new JFrame("TextField Example");

e
JTextField t1,t2;

W
t1=new JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);

y
t2=new JTextField("AWT Tutorial");

B
t2.setBounds(50,150, 200,30);

h
f.add(t1); f.add(t2);

c
f.setSize(400,400);
f.s etLayout(null);

e
f.setVisible(true);

T
} }
Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits JTextComponent class
JTextArea class declaration
Let's see the declaration for javax.swing.JTextArea class.

public class JTextArea extends JTextComponent

1.

Java JTextArea Example

@techbywebcoder
import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);

r
f.setLayout(null);

e
f.setVisible(true);
}

d
public static void main(String args[])

o
{

C
new TextAreaExample();

b
}}

e
W
Simple Java Applications

y
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

B
public class Example extends JFrame {

ch
public Example() {
setTitle("Simple example");

e
setSize(300, 200);

T
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Example ex = new Example();
ex.setVisible(true);
}}

@techbywebcoder
Layout Management
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is
an interface that is implemented by all the classes of layout managers.

BorderLayout
The BorderLayout provides five constants for each region:

1. public static final int NORTH

r
2. public static final int SOUTH

e
3. public static final int EAST
4. public static final int WEST

d
5. public static final int CENTER

o
Constructors of BorderLayout class:

C
o BorderLayout(): creates a border layout but with no gaps between the components.

b
o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and

e
vertical gaps between the components.

Example of BorderLayout class:

W
import java.awt.*; Output:

y
import javax.swing.*;
public class Border

B
{
JFrame f;

h
Border()

c
{
f=new JFrame();

e
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;

T
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new Border();
}}

@techbywebcoder
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
Constructors of GridLayout class

1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns alongwith given horizontal and vertical gaps.

r
Example of GridLayout class

e
1. import java.awt.*;
2. import javax.swing.*;

d
public class MyGridLayout{
JFrame f;

o
MyGridLayout(){
f=new JFrame(); JButton b1=new

C
JButton("1"); JButton b2=new JButton("2");
JButton b3=new JButton("3");

b
JButton b4=new JButton("4");

e
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");

W
JButton b8=new JButton("8");
JButton b9=new JButton("9");

y
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(

B
b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);

h
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns

c
f.setSize(300,300);

e
f.s etVisible(true);
}

T
public static void main(String[] args) {
new MyGridLayout(); }}
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the
default layout of applet or panel.

Fields of FlowLayout class


public static final int LEFT
public static final int RIGHT
public static final int CENTER
public static final int LEADING
public static final int TRAILING

@techbywebcoder
Constructors of FlowLayout class
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5
unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.

Example of FlowLayout class


import java.awt.*;
import javax.swing.*;
public class MyFlowLayout{

r
JFrame f;
MyFlowLayout(){

e
f=new JFrame();

d
JButton b1=new JButton("1");
JButton b2=new JButton("2");

o
JButton b3=new JButton("3");
JButton b4=new JButton("4");

C
JButton b5=new JButton("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);

b
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment

e
f.setSize(300,300);
f.s etVisible(true);

W
}
public static void main(String[] args) {

y
new MyFlowLayout();
}}

B
Event Handling

h
c
Event and Listener (Java Event Handling)

e
Changing the state of an object is known as an event. For example, click on button,

T
dragging mouse etc. The java.awt.event package provides many event classes and
Listener interfaces for event handling.

Types of Event

The events can be broadly classified into two categories:

 Foreground Events - Those events which require the direct interaction of user.They are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering
a character through keyboard,selecting an item from list, scrolling the page etc.

 Background Events - Those events that require the interaction of end user are known as

@techbywebcoder
background events. Operating system interrupts, hardware or software failure, timer
expires, an operation completion are the example of background events.

Event Handling

Event Handling is the mechanism that controls the event and decides what should
happen if an event occurs. This mechanism have the code which is known as event
handler that is executed when an event occurs. Java Uses the Delegation Event Model to
handle the events. This model defines the standard mechanism to generate and handle
the events.Let's have a brief introduction to this model.

r
The Delegation Event Model has the following key participants namely:

de
 Source - The source is an object on which event occurs. Source is responsible for
providing information of the occurred event to it's handler. Java provide as with classes

o
for source object.

C
 Listener - It is also known as event handler. Listener is responsible for generating

b
response to an event. From java implementation point of view the listener is also an

e
object. Listener waits until it receives an event. Once the event is received , the listener
process the event an then returns.

yW
Event classes and Listener interfaces:

B
Event Classes Listener Interfaces

h
ActionEvent ActionListener MouseListener and

c
MouseEvent MouseMotionListener

e
MouseWheelEven MouseWheelListener KeyListener

T
t KeyEvent ItemListener TextListener

ItemEvent AdjustmentListener WindowListener

TextEvent ComponentListener ContainerListener

AdjustmentEvent FocusListener

WindowEvent

ComponentEvent

ContainerEvent

FocusEvent

@techbywebcoder
Steps to perform Event Handling
Following steps are required to perform event handling:

1. Implement the Listener interface and overrides its methods


2. Register the component with the Listener

For registering the component with the Listener, many classes provide the registration methods.
For example:

o Button

r
o public void addActionListener(ActionListener a){}

e
o MenuItem

d
o public void addActionListener(ActionListener a){}

o
o TextField
o public void addActionListener(ActionListener a){}

C
o public void addTextListener(TextListener a){}

b
o TextArea

e
o public void addTextListener(TextListener a){}
o Checkbox

W
o public void addItemListener(ItemListener a){}

y
o Choice

B
o public void addItemListener(ItemListener a){}
List

h
o
o public void addActionListener(ActionListener a){}

c
o public void addItemListener(ItemListener a){}

T
1.
e
EventHandling Codes:
We can put the event handling code into one of the following places:
Same class 2.
Other class 3.
Annonymous class

Example of event handling within class:


import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;

@techbywebcoder
AEvent(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
b.addActionListener(this);
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);

r
}
public void actionPerformed(ActionEvent e){

e
tf.setText("Welcome");

d
}

o
public static void main(String args[]){
new AEvent();

C
}}

b
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the

e
above example that sets the position of the component it may be button, textfield etc.

Java event handling by implementing ActionListener

yW
import java.awt.*; import java.awt.event.*; class
AEvent extends Frame implements ActionListener{

B
TextField tf; AEvent(){ //create components tf=new
TextField();

h
tf.setBounds(60,50,170,20);

c
Button b=new Button("click me");
b.setBounds(100,120,80,30);

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

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

@techbywebcoder
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

1 below: public abstract void mouseClicked(MouseEvent e);

r
. public abstract void mouseEntered(MouseEvent e);
2 public abstract void mouseExited(MouseEvent e);

e
. public abstract void mousePressed(MouseEvent e);
3 public abstract void mouseReleased(MouseEvent e);

d
.

o
4 Java MouseListener Example
.

C
5
import java.awt.*;
.import java.awt.event.*;

b
public class MouseListenerExample extends Frame implements MouseListener{

e
Label l;
MouseListenerExample(){
addMouseListener(this);

W
l=new Label();
l.setBounds(20,50,100,20);

y
add(l);
setSize(300,300);

B
setLayout(null);

h
setVisible(true);
}

c
public void mouseClicked(MouseEvent e) {

e
l.setText("Mouse Clicked");
}

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

@techbywebcoder
Java KeyListener Interface
The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. The KeyListener interface is found in java.awt.event package. It has three methods.
Methods of KeyListener interface
The signature of 3 methods found in KeyListener interface are given below:
public abstract void keyPressed(KeyEvent e);
public abstract void keyReleased(KeyEvent e);
public abstract void keyTyped(KeyEvent e);

1
.
2
.

r
3 Java KeyListener Example

e
.
import java.awt.*;

d
import java.awt.event.*;

o
public class KeyListenerExample extends Frame implements KeyListener{
Label l;

C
TextArea area;
KeyListenerExample(){

b
l=new Label();
l.setBounds(20,50,100,20);

e
area=new TextArea();
area.setBounds(20,80,300, 300);

W
area.addKeyListener(this);
add(l);add(area);

y
setSize(400,400);
setLayout(null);

B
setVisible(true);

h
}
public void keyPressed(KeyEvent e) {

c
l.setText("Key Pressed");
}

e
public void keyReleased(KeyEvent e) {

T
l.setText("Key Released");
}
public void keyTyped(KeyEvent e) {
l.setText("Key Typed");
}
public static void main(String[] args) {
new KeyListenerExample(); } }
Java Adapter Classes
Java adapter classes provide the default implementation of listener interfaces. If you
inherit the adapter class, you will not be forced to provide the implementation of all the
methods of listener interfaces. So it saves code.

@techbywebcoder
java.awt.event Adapter classes

Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

r
MouseMotionAdapter MouseMotionListener

FocusAdapter

de FocusListener

o
ComponentAdapter ComponentListener

C
ContainerAdapter ContainerListener

eb
HierarchyBoundsAdapter HierarchyBoundsListener

W
Java WindowAdapter Example

B
1. import java.awt.*;
y
import java.awt.event.*;

h
public class AdapterExample{

c
Frame f;

e
AdapterExample(){

T
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
f.dispose(); } });
f.s etSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new AdapterExample();
}}

@techbywebcoder
Applets
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:

It works at client side so less response time.


Secured
It can
o be executed by browsers running under many plateforms, including Linux,
o
Windows, Mac Os etc.

r
o

Drawback of Applet

de
o
o Plugin is required at client browser to execute applet.

C
Lifecycle of Java Applet Hierarchy of Applet

b
1 Applet is initialized.

e
. Applet is started.
2 Applet is painted.

W
. Applet is stopped.

y
3 Applet is destroyed.

B
.
Lifecycle methods for Applet:

h
4

c
The. java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life

e
cycle methods for an applet.
5

T
java.applet.Applet
. class

For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods
of applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

@techbywebcoder
java.awt.Component class

The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.

Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.

1. //First.java

er
d
import java.applet.Applet;

o
import java.awt.Graphics;
public class First extends Applet{

C
public void paint(Graphics g){

b
g.drawString("welcome",150,150);

e
}
}

W
Simple example of Applet by appletviewer tool:

By
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is

h
for testing purpose only.

e
1. //First.java
c
T
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/

@techbywebcoder
To execute the applet by appletviewer tool, write in command prompt:

c:\>javac First.java
c:\>appletviewer First.java

Difference between Applet and Application programming

er
od
bC
e
yW
hB
ec
T

@techbywebcoder
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet class
provides a method named getParameter(). Syntax:

1. public String getParameter(String parameterName)

Example of using parameter in Applet:

1. import java.applet.Applet;
2. import java.awt.Graphics;
3. public class UseParam extends Applet

r
4. {

e
5. public void paint(Graphics g)
6. {

d
7. String str=getParameter("msg");
8. g.drawString(str,50, 50);

o
9. } }

C
myapplet.html
1. <html>

b
2. <body>
3. <applet code="UseParam.class" width="300" height="300">

e
4. <param name="msg" value="Welcome to applet">
5. </applet>

W
6. </body>
7. </html>

By
ch
Te

@techbywebcoder

You might also like