Vous êtes sur la page 1sur 58

System.out.

println
System is a predefined class that provides acess to the system.
out is the outputstream that is connected to the console.
println() - Displays the String which is passed to it.

Public static void main


public - anyone in the program can access or call the particular function.
static- everything inside it is already define.
void-it means a function
main-this is indication that it is the begin of the program to be read

Session.1

Introduction to Java:
Introduction to Java
Java is a general -purpose , object oriented language developed by SunMicrosystem of USA in 1991. This
language was initially called “Oak” but was renamed “Java” in 1995.
In 1997 Sun release Java development kit 1.1(JDK1.1)
In 1998 Sun release Java 2 with version 1.2 of the software development kit(SDK1.2)
In 1999 Sun releases standard edition (J2SE) and enterprise edition (J2EE)
In 2000 J2SE with SDK 1.3 was released
In 2002 J2SE with SDK1.4 was released
In 2004 J2SE JDK 5.0 was released
• Java Platform, Standard Edition (Java SE)
• Java Platform, Enterprise Edition (Java EE)
• Java Platform, Micro Edition (Java ME)
NetBeans IDE
The NetBeans IDE is open source and is written in the Java programming language. It provides the
services common to creating desktop applications -- such as window and menu management, settings
storage -- and is also the first IDE to fully support JDK 6.0 features. The NetBeans platform and IDE are
free for commercial and noncommercial use, and they are supported by Sun Microsystems.
Features of Java
Platform Independent
The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important
key feature of java language that makes java as the most powerful language. Not even a single language
is idle to this feature but java is more closer to this feature. The programs written on one platform can run
on any platform provided the platform must have the JVM.
Simple
There are various features that makes the java as a simple language. Programs are easy to write and
debug because java does not use the pointers explicitly. It is much harder to write the java programs that
can crash the system but we can not say about the other programming languages. Java provides the bug
free system due to the strong memory management. It also has the automatic memory allocation and
deallocation system.
Object Oriented
To be an Object Oriented language, any language must follow at least the four characteristics.
 Inheritance: It is the process of creating the new classes and using the behavior of the existing
classes by extending them just to reuse the existing code and adding the additional features
as needed.
 Encapsulation: It is the mechanism of combining the information and providing the abstraction.
 Polymorphism: As the name suggest one name multiple form, Polymorphism is the way of
providing the different functionality by the
functions having the same name based on the signatures of the methods.
 Dynamic binding: Sometimes we don't have the knowledge of objects about their specific types
while writing our code. It is the way of providing the maximum functionality to a program about
the specific type at runtime.
 Robust
Java has the strong memory allocation and automatic garbage collection mechanism. It provides
the powerful exception handling and type checking mechanism as compare to other programming
languages. Compiler checks the program whether there any error and interpreter checks any run
time error and makes the system secure from crash. All of the above features makes the java
language robust.
 Distributed
The widely used protocols like HTTP and FTP are developed in java. Internet programmers can
call functions on these protocols and can get access the files from any remote machine on the
internet rather than writing codes on their local system.
 Portable
The feature Write-once-run-anywhere makes the java language portable provided that the
system must have interpreter for the JVM. Java also have the standard data size irrespective of
operating system or the processor. These features makes the java as a portable language.
 Dynamic
While executing the java program the user can get the required files dynamically from a local
drive or from a computer thousands of miles away from the user just by connecting with the
Internet.
 Secure
Java does not use memory pointers explicitly. All the programs in java are run under an area
known as the sand box. Security manager determines the accessibility options of a class like
reading and writing a file to the local disk. Java uses the public key encryption system to allow the
java applications to transmit over the internet in the secure encrypted form. The bytecode Verifier
checks the classes after loading.
 Performance
Java uses native code usage, and lightweight process called threads. In the beginning
interpretation of bytecode resulted the performance slow but the advance version of JVM uses
the adaptive and just in time compilation technique that improves the performance.
 Multithreaded
Java is also a Multithreaded programming language. Multithreading means a single program
having different threads executing independently at the same time. Multiple threads execute
instructions according to the program code in a process or a program. Multithreading works the
similar way as multiple processes run on one computer.
Multithreading programming is a very interesting concept in Java. In multithreaded programs not
even a single thread disturbs the execution of other thread. Threads are obtained from the pool of
available ready to run threads and they run on the system CPUs. This is how Multithreading
works in Java which you will soon come to know in details in later chapters.

Interpreted
We all know that Java is an interpreted language as well. With an interpreted language such as Java,
programs run directly from the source code.
The interpreter program reads the source code and translates it on the fly into computations. Thus, Java
as an interpreted language depends on an interpreter program.
Architecture Neutral
The term architectural neutral seems to be weird, but yes Java is an architectural neutral language as
well. The growing popularity of networks makes developers think distributed. In the world of network it is
essential that the applications must be able to migrate easily to different computer systems. Not only to
computer systems but to a wide variety of hardware architecture and Operating system architectures as
well.
Structure of JAVA Programme:-
• Document section
• Package statement
• Import statement
• Interface
• Class definition
Main Class
{
main method
}

1. Keywords:-
In the Java programming language, a keyword is one of 50 reserved words that have a predefined
meaning in the language; because of this, programmers cannot use keywords as names
for variables, methods, classes, or as any other identifier. Due to their special functions in the language,
most integrated development environments for Java use syntax highlighting to display keywords in a
different color for easy identification.
Ex: Abstract, continue, goto, package, synchronized, assert, default, if, private, this, boolean , do,
implements, protected, throw, Break, double, import, public, throws, Byte, else, instance of, return,
transient, Case, extends, int, short, try, Catch, final, interface, static, void, Char, finally, long, strictfp
,volatile, Class, float, native, super, while.
Constants: - Constants in Java are fixed values those are not changed during the Execution of
program java supports several types of Constants those are:
Numeric Constants
1) Integer Constants:-
Integer Constants refers to a Sequence of digits which Includes only negative or positive Values and
many other things those are as follows
 An Integer Constant must have at Least one Digit
 it must not have a Decimal value
 it could be either positive or Negative
 if no sign is Specified then it should be treated as Positive
 No Spaces and Commas are allowed in Name
2) Real Constants:-
 A Real Constant must have at Least one Digit
 it must have a Decimal value
 it could be either positive or Negative
 if no sign is Specified then it should be treated as Positive
 No Spaces and Commas are allowed in Name
Like 251, 234.890 etc are Real Constants
In The Exponential Form of Representation the Real Constant is represented in the two Parts The part
before appearing e is called mantissa whereas the part following e is called Exponent.
 In Real Constant The Mantissa and Exponent Part should be Separated by letter e
 The Mantissa Part may have either positive or Negative Sign
 Default Sign is Positive
2. Character constants
Single Character Constants:-
A Character is Single Alphabet a single digit or a Single Symbol that is enclosed within Single inverted
commas.
Like ‘S’,’1’ etc are Single Character Constants
String Constants:-
String is a Sequence of Characters Enclosed between double Quotes These Characters may be digits,
Alphabets Like “Hello”, “1234” etc.
Backslash Character Constants:-
Java Also Supports Backslash Constants those are used in output methods For Example \n is used for new
line Character These are also Called as escape Sequence or backslash character Constants For Ex:
\t For Tab ( Five Spaces in one Time )
\b Back Space etc.

Variable:-
A variable is a container that stores a meaningful value that can be used throughout a program. For
example, in a program that calculates tax on items you can have a few variables - one variable that stores
the regular price of an item and another variable that stores the total price of an item after the tax is
calculated on it. Variables store this information in a computer's memory and the value of a variable can
change all throughout a program. Variables are nothing but reserved memory locations to store values.
This means that when you create a variable you reserve some space in memory.
Based on the data type of a variable, the operating system allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to variables, you can store
integers, decimals, or characters in these variables.
There are two data types available in Java:
1. Primitive Data Types
2. Reference/Object Data Types
Primitive Data Types:
There are eight primitive data types supported by Java. Primitive data types are predefined by the language and
named by a key word. Let us now look into detail about the eight primitive data types.
Byte:
 Byte data type is an 8-bit signed two's complement integer.
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four
times smaller than an int.
 Example : byte a = 100 , byte b = -50
Short:
 Short data type is a 16-bit signed two's complement integer.
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767(inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is 2 times smaller than
an int
 Default value is 0.
 Example : short s= 10000 , short r = -20000
Int:
 Int data type is a 32-bit signed two's complement integer.
 Minimum value is - 2,147,483,648.(-2^31)
 Maximum value is 2,147,483,647(inclusive).(2^31 -1)
 Int is generally used as the default data type for integral values unless there is a concern about
memory.
 The default value is 0.
 Example : int a = 100000, int b = -200000
Long:
 Long data type is a 64-bit signed two's complement integer.
 Minimum value is -9,223,372,036,854,775,808.(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
 This type is used when a wider range than int is needed.
 Default value is 0L.
 Example : int a = 100000L, int b = -200000L
Float:
 Float data type is a single-precision 32-bit IEEE 754 floating point.
 Float is mainly used to save memory in large arrays of floating point numbers.
 Default value is 0.0f.
 Float data type is never used for precise values such as currency.
 Example : float f1 = 234.5f
Double:
 double data type is a double-precision 64-bit IEEE 754 floating point.
 This data type is generally used as the default data type for decimal values. generally the default
choice.
 Double data type should never be used for precise values such as currency.
 Default value is 0.0d.
 Example : double d1 = 123.4
Boolean:
 Boolean data type represents one bit of information.
 There are only two possible values: true and false.
 This data type is used for simple flags that track true/false conditions.
 Default value is false.
 Example : Boolean one = true
Char:
Char data type is a single 16-bit Unicode character.
Minimum value is '\u0000' (or 0).
Maximum value is '\uffff' (or 65,535 inclusive).
Char data type is used to store any character.
Example. char letterA ='A'
Reference Data Types:
 Reference variables are created using defined constructors of the classes. They are used to access
objects. These variables are declared to be of a specific type that cannot be changed. For example,
Employee, Puppy etc.
 Class objects, and various types of array variables come under reference data type.
 Default value of any reference variable is null.
 A reference variable can be used to refer to any object of the declared type or any compatible type.
 Example : Animal animal = new Animal("giraffe");
Operators
In real time, programs are required to perform a lot more than just simple input/output operations. Java
provides a rich set of operators to manipulate variables. We can divide all the Java operators into the
following groups:
 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Misc Operators
The Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.
The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20 then:
Show Examples
Description Example
Operator

+ Addition - Adds values on either side of the operator A + B will give 30

- Subtraction - Subtracts right hand operand from left A - B will give -10
hand operand

* Multiplication - Multiplies values on either side of the A * B will give 200


operator

/ Division - Divides left hand operand by right hand B / A will give 2


operand

% Modulus - Divides left hand operand by right hand B % A will give 0


operand and returns remainder

++ Increment - Increase the value of operand by 1 B++ gives 21

-- Decrement - Decrease the value of operand by 1 B-- gives 19

The Relational Operators:


There are following relational operators supported by Java language
Assume variable a holds 10 and variable B holds 20 then:
Show Examples
Operator Description Example

== Checks if the value of two operands are equal or not, if (A == B) is not true.
yes then condition becomes true.

!= Checks if the value of two operands are equal or not, if (A! = B) is true.
values are not equal then condition becomes true.

> Checks if the value of left operand is greater than the (A > B) is not true.
value of right operand, if yes then condition becomes
true.

< Checks if the value of left operand is less than the value (A < B) is true.
of right operand, if yes then condition becomes true.

>= Checks if the value of left operand is greater than or (A >= B) is not true.
equal to the value of right operand, if yes then
condition becomes true.

<= Checks if the value of left operand is less than or equal (A <= B) is true.
to the value of right operand, if yes then condition
becomes true.

The Bitwise Operators:


Java defines several bitwise operators which can be applied to the integer types, long, int, short, char, and
byte.
Bitwise operator works on bits and perform bit by bit operation. Assume if a = 60; and b = 13; Now in
binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13 then:
Show Examples

Operator Description Example

& Binary AND Operator copies a bit to the result if it (A & B) will give 12 which is 0000 1100
exists in both operands.

| Binary OR Operator copies a bit if it exists in eather (A | B) will give 61 which is 0011 1101
operand.

^ Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49 which is 0011 0001
operand but not both.

~ Binary Ones Complement Operator is unary and has (~A ) will give -60 which is 1100 0011
the effect of 'flipping' bits.

<< Binary Left Shift Operator. The left operands value is A << 2 will give 240 which is 1111 0000
moved left by the number of bits specified by the right
operand.

>> Binary Right Shift Operator. The left operands value is A >> 2 will give 15 which is 1111
moved right by the number of bits specified by the
right operand.

>>> Shift right zero fill operator. The left operands value is A >>>2 will give 15 which is 0000 1111
moved right by the number of bits specified by the
right operand and shifted values are filled up with
zeros.

The Logical Operators:


The following table lists the logical operators:
Assume Boolean variables a holds true and variable B holds false then:

Show Examples

Operator Description Example

&& Called Logical AND operator. If both the operands are (A && B) is false.
non zero then condition becomes true.

|| Called Logical OR Operator. If any of the two operands (A || B) is true.


are non zero then then condition becomes true.

! Called Logical NOT Operator. Use to reverses the !(A && B) is true.
logical state of its operand. If a condition is true then
Logical NOT operator will make false.

The Assignment Operators:


There are following assignment operators supported by Java language:
Show Examples

Operator Description Example

= Simple assignment operator, Assigns values C = A + B will assigne value of A + B into C


from right side operands to left side operand

+= Add AND assignment operator, It adds right C += A is equivalent to C = C + A


operand to the left operand and assign the result
to left operand

-= Subtract AND assignment operator, It subtracts C -= A is equivalent to C = C - A


right operand from the left operand and assign
the result to left operand

*= Multiply AND assignment operator, It multiplies C *= A is equivalent to C = C * A


right operand with the left operand and assign
the result to left operand

/= Divide AND assignment operator, It divides left C /= A is equivalent to C = C / A


operand with the right operand and assign the
result to left operand

%= Modulus AND assignment operator, It takes C %= A is equivalent to C = C % A


modulus using two operands and assign the
result to left operand

<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator C &= 2 is same as C = C & 2

^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2

|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

Misc Operators
There are few other operators supported by Java Language.

Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of three operands and
is used to evaluate boolean expressions. The goal of the operator is to decide which value should be
assigned to the variable. The operator is written as :
variable x = (expression) ? value if true : value if false

Following is the example:


public class Test {
public static void main(String args[]){
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}
}

This would produce following result:

Value of b is : 30
Value of b is : 20

Instance Of Operator:
This operator is used only for object reference variables. The operator checks whether the object is of a
particular type(class type or interface type). Instance Of operator is wriiten as:
( Object reference variable ) instance Of (class/interface type)

If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side then the result will be true. Following is the example:

String name = = 'James';


boolean result = name instance Of String;
// This will return true since name is type of String

This operator will still return true if the object being compared is the assignment compatible with the type
on the right. Following is one more example:

class Vehicle {}

public class Car extends Vehicle {


public static void main(String args[]){
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result);
}
}

This would produce following result:

true

Precedence of Java Operators:


Operator precedence determines the grouping of terms in an expression. This affects how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator
has higher precedence than the addition operator:

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedenace than +
so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedenace operators will be evaluated first.

Category Operator Associativity

Postfix () [] . (dot operator) Left to right

Unary ++ - - ! ~ Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift >> >>> << Left to right

Relational > >= < <= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left

Comma , Left to right

Expression
Expressions are essential building blocks of any Java program. They are built using values, variables, operators and
method calls. In terms of the syntax of the Java language, an expression is akin to a clause in the English language. A
clause portrays a specific meaning. With the right punctuation it can sometimes stand on its own or more often than
not become part of a sentence. Similarly, an expression in Java evaluates to a single value. Some expressions can
make statements by themselves (by adding a semicolon on the end) but more commonly make up part of a statement.
Classes, objects and methods
A class is a collection of fields (data) and methods (procedure or function) that operate on that data.
Objects:
Objects are created dynamically using the new keyword.
Syntax:- ClassName Object= new ClassName ();
Nested Classes and Inner Class
A class defined in another class.

Example: Class A
{
classB
{
}}
Wrapper classes:
A class that envelops the value of every primitive data type .
Example: an integer data type can represented as an integer class instances.
Java Inheritance
Java Inheritance defines an is-a relationship between a superclass and its subclasses. This
means that an object of a subclass can be used wherever an object of the superclass can be
used. Class Inheritance in javamechanism is used to build new classes from existing
classes. The inheritance relationship is transitive: if class xextends class y, then a class z,
which extends class x, will also inherit from class y.
Types of Inheritance:
They can be specified as
Single Inheritance
Single Inheritance where the features of one class are inherited by another class.
Multi level Inheritance
Multi level inheritance is when there are classes extending one another in a chain format. Ex:
Class A extends Class B, Class B extends Class C and so on...
Multiple Inheritance
There is one another form of inheritance called Multiple Inheritance. This is not supported by Java.
The authors of the Java language took a design decision to compromise multiple inheritance with
interfaces, the specifics of this decision may be covered in other sources. Practically, multiple
inheritance is difficult because of the ambiguities it can create when a class inherits from two
superclasses with the same method signature: which version should be called?
But there is a workaround for this problem. Java allows us to achieve partial multiple inheritance
using interfaces. A class can implement any number of interfaces and provide implementations for
them and achieve partial multiple inheritance. In simple words java supports simple, hierarchial,
multi level and hybrid inheritance but at the same time java also supports multiple inheritance with
the help of interfaces.

Control Statements in Java


The control statement are used to controll the flow of execution of the program . This execution order
depends on the supplied data values and the conditional logic. Java contains the following types of control
statements:
1- Selection Statements
2- Repetition Statements
3- Branching Statements
Selection statements:
1. If Statement:
This is a control statement to execute a single statement or a block of code, when the given
condition is true and if it is false then it skips if block and rest code of program is executed .
Syntax:
if(conditional_expression){
<statements>;
...;
...;
}
Example: If n%2 evaluates to 0 then the "if" block is executed. Here it evaluates to 0 so if block
is executed. Hence "This is even number" is printed on the screen.

int n = 10;

if(n%2 = = 0){

System.out.println("This
is even number");

2. If-else Statement:
The "if-else" statement is an extension of if statement that provides another option when 'if'
statement evaluates to "false" i.e. else block is executed if "if" statement is false.
Syntax:
if(conditional_expression){
<statements>;
...;
...;
}
else{
<statements>;
....;
....;
}

Example: If n%2 doesn't evaluate to 0 then else block is executed. Here n%2 evaluates to 1
that is not equal to 0 so else block is executed. So "This is not even number" is printed on the
screen.

int n = 11;

if(n%2 = = 0){

System.out.println("This
is even number");

}
else{

System.out.println("This
is not even number");

3. Switch Statement:
This is an easier implementation to the if-else statements. The keyword "switch" is followed by
an expression that should evaluates to byte, short, char or int primitive data types ,only. In a
switch block there can be one or more labeled cases. The expression that creates labels for the
case must be unique. The switch expression is matched with each case label. Only the matched
case is executed ,if no case matches then the default statement (if present) is executed.
Syntax:
switch(control_expression)
{
case expression 1:
<statement>;
case expression 2:
<statement>;
...
...
case expression n:
<statement>;
default:
<statement>;
}//end switch

Example: Here expression "day" in switch statement evaluates to 5 which matches with a case
labeled "5" so code in case 5 is executed that results to output "Friday" on the screen.
int day = 5;
switch (day)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thrusday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid
entry");
break;
}

Java Loops
Repetition Control structures
The while Loop:
A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:
The syntax of a while loop is:
while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true then the actions inside the loop will be executed.
This will continue as long as the expression result is true.

Here key point of the while loop is that the loop might not ever run. When the expression is tested and the
result is false, the loop body will be skipped and the first statement after the while loop will be executed.
Example:
public class Test {
public static void main(String args[]){
int x= 10;

while( x < 20 ){
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
This would produce following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

For Loop in Java


The for loop is the type of looping construct. It also works as while loop construct but it provide the
initialization, condition and the increment is same written in the for construct. All the statements which
has to be executed written in the for block. We can use the multiple for loop in a program or a for loop
also. When we write a loop under another loop then the second loop is called nested loop.

The Syntax for the For Loop:


for( initialization; termination; increment)
{
statements;
}

The given example illustrates that how to use the for loop for developing a application or a program. In
this program we will see that the initialization of the variable, condition and increment used for the for
loop. Initialization, Condition and Incrementation, all are optional but two semicolons are compulsory
which separates Initialization, Condition and Incrementation.
Initialization: It allows the variable to be initialize. Such as:
int i = 1;
int j = 1;
Termination (or condition): It allows to check the certain condition. If condition is true then all
statements and processes written in the for block will be executed otherwise ignored. Condition such as:
i <= 5;
j <= i;
Increment: It allows the how much increase the given variable. Such as:
i++;
j++;

Code of the program :


public class ForLoop{
public static void main(String[] args){
for(int i = 1;i <= 5;i++){
for(int j = 1;j <= i;j++){
System.out.print(i);
}
System.out.println();
}
}
}
Output of the program :
1
22
333
4444
55555
The do...while Loop:
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least
one time.
Syntax:
The syntax of a do...while loop is:
Do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute
once before the Boolean is tested.

If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop
execute again. This process repeats until the Boolean expression is false.

Example:
public class Test {
public static void main(String args[]){
int x= 10;

do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
This would produce following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
Branching statements
The break Keyword:
The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a
switch statement.

The break keyword will stop the execution of the innermost loop and start executing the next line of code
after the block.

Syntax:
The syntax of a break is a single statement inside any loop:
break;
Example:
public class Test {
public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ){
if( x == 30 ){
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This would produce following result:
10
20
The continue Keyword:
The continue keyword can be used in any of the loop control structures. It causes the loop to immediately
jump to the next iteration of the loop.
 In a for loop, the continue keyword causes flow of control to immediately jump to the update
statement.
 In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.

Syntax:
The syntax of a continue is a single statement inside any loop:
continue;
Example:
public class Test {
public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){
if( x == 30 ){
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This would produce following result:
10
20
40
50

Session.2,3,4
Array:
Array is the most important thing in any programming language. By definition, array is the static memory
allocation. It allocates the memory for the same data type in sequence. It contains multiple values of same
types. It also stores the values in memory at the fixed size. Multiple types of arrays are used in any
programming language such as: one - dimensional, two - dimensional or can say multi - dimensional.
One – dimensional
A one-dimensional array can be used for perfect sorting data structure because in a one-
diemensional array, data is organized into an indexible linear list.
EX: int salary[] = new int[5];

Two- diemensional
Multi-dimensional array are also referred to as arrays of arrays. 2D array is the
commonly used and simplest multi-dimensional array. 2D array represented in a row-
columns are used in computing.
EX: int two-dimensional [] [] = new int[2][3];
Declaration of an array:
int num[]; or int num = new int[2];
Some times user declares an array and it's size simultaneously. You may or may not be define the size in
the declaration time. such as:
int num[] = {50,20,45,82,25,63};

String array and methods


Strings are sequence of characters or a character array. In Java, strings are objects. The Java platform
uses the String class for the creation and manipulation of strings. The String class is found in the
java.lang package.

Creating Strings
• One simple form, in which the string can be created by using the String class is just by typing
the text within the double quotes. This is called a String literal.
“Hello, This is Java programming.”
a string object can also be created using the new keyword
String StringName = new String(“string”);
String Methods
A number of methods are defined in the String class. These methods are called as String methods , which
are used for different tasks of string manipulation.
• S2=S1.toLowerCase();
• S2=S1.toUpperCase();
• S2=S1.replace(‘x’, ‘y’);
• S2=S1.trim();
• S1.equals(S2);
• S1.Length();
• s1.concat (s2)
String Buffer Class
• While String creates strings of fixed length, String Buffer creates strings of flexible length that can
be modified in terms of both length and content.
String Buffer Methods
• S1.setCharAt(n, ’x’)
• S1.append(S2)
• S1.insert(n,S2)
• S1.setLength(n)
String Concatenation
• Java Strings can be concatenated (joined) using the + and += operators to create new
Strings.
• String language = "Java";
• String course = "Introduction to " + language;
• course += ", CS 101";

Packages
Packages are used in Java in-order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier etc.
A Package can be defined as a grouping of related types(classes, interfaces, enumerations and
annotations) providing access protection and name space management.
Some of the existing packages in Java are::
 java.lang - bundles the fundamental classes
 java.io - classes for input , output functions are bundled in this package

Creating a package:
 When creating a package, you should choose a name for the package and put a package
statement with that name at the top of every source file that contains the classes, interfaces,
enumerations, and annotation types that you want to include in the package.
 The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.
 If a package statement is not used then the class, interfaces, enumerations, and annotation types
will be put into an unnamed package.
Example:
Put an interface in the package animals:
/* File name : Animal.java */
package animals;

interface Animal {
public void eat();
public void travel();
}

Access protection
 Public modifier
 Protected modifier
 Default modifier
 Private modifier

Public Modifier
When a class, a method and the variables are declared as public, these methods, classes and variables are
visible from the subclasses in the same package, subclasses in the other packages, non-subclass in the
same package and non-subclass in the other packages.
Protected Modifier
When a class, a method and the variables are declared as protected, these methods, classes and variables
are visible from the subclasses in the same package, subclasses in the other packages, non-subclass in the
same package and are not visible from the non-subclass in the other packages.
Default Modifier
When there is no access modifier specified for a class, a method, or variable , then the methods, classes
and variables are considered as default. These methods, classes and variables are visible from the
subclasses in the same package and non-subclass in the same package, whereas they are not visible from
the subclasses in the other packages and the non subclass in the other packages.
Private Modifier
When a class, a method and the variables are declared as private, these methods, classes and variables are
not visible from any class or subclass outside the class.
The import Keyword:
If a class wants to use another class in the same package, the package name does not need to be used. Classes in the same
package find each other without any special syntax.
Example:
package payroll;

public class Boss


{
public void payEmployee(Employee e)
{
e.mailCheck();
}
}
Java API Packages
 Java API provides a large number of classes grouped into different packages
according to functionality.

Interface
An interface in the Java programming language is an abstract type that is used to specify an interface (in
the generic sense of the term) that classes must implement. Interfaces are declared using
the interface keyword, and may only contain method signatureand constant declarations (variable
declarations that are declared to be both static and final). An interface may never contain method
definitions.
Exceptions Handling
An exception is a problem that arises during the execution of a program. An exception can occur for many
different reasons, including the following:
 A user has entered invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications, or the JVM has run out of
memory.
Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.
To understand how exception handling works in Java, you need to understand the three categories of
exceptions:
 Checked exceptions: A checked exception is an exception that is typically a user error or a
problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the
file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time
of compilation.
 Runtime exceptions: A runtime exception is an exception that occurs that probably could have
been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are
ignored at the time of compilation.
 Errors: These are not exceptions at all, but problems that arise beyond the control of the user or
the programmer. Errors are typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored
at the time of compilation.
The throws/throw Keywords:
If a method does not handle a checked exception, the method must declare it using the throwskeyword.
The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by using
the throw keyword. Try to understand the different in throws and throw keywords.

The following method declares that it throws a RemoteException:

import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
The finally Keyword
The finally keyword is used to create a block of code that follows a try block. A finally block of code always
executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter
what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax:

try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
Session.5

Multithreading
Thread
Threads are light-weight processes within a process.
Java provides built-in support for multithreaded programming. A multithreaded program contains two
or more parts that can run concurrently. Each part of such a program is called a thread, and each thread
defines a separate path of execution.
A multithreading is a specialized form of multitasking. Multitasking threads require less overhead than
multitasking processes.
I need to define another term related to threads: process: A process consists of the memory space
allocated by the operating system that can contain one or more threads. A thread cannot exist on its own;
it must be a part of a process. A process remains running until all of the non-daemon threads are done
executing.
Multithreading enables you to write very efficient programs that make maximum use of the CPU, because
idle time can be kept to a minimum.

Single and Multithreaded


Processes
threads are light-weight processes within a process

Single-threaded Process Multiplethreaded Process


Threads of
Execution

Single instruction stream Multiple instruction stream


Common
Address Space

Life Cycle of a Thread:


A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then
dies. Following diagram shows complete life cycle of a thread.
Above mentioned stages are explained here:
 New: A new thread begins its life cycle in the new state. It remains in this state until the program
starts the thread. It is also referred to as a born thread.
 Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this
state is considered to be executing its task.
 Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another
thread to perform a task.A thread transitions back to the runnable state only when another thread
signals the waiting thread to continue executing.
 Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of
time. A thread in this state transitions back to the runnable state when that time interval expires
or when the event it is waiting for occurs.
 Terminated: A runnable thread enters the terminated state when it completes its task or
otherwise terminates.

Thread Priority

 In Java, each thread is assigned priority, which


affects the order in which it is scheduled for
running. The threads so far had same default
priority (NORM_PRIORITY) and they are served
using FCFS policy.
 Java allows users to change priority:
 ThreadName.setPriority(intNumber)
 MIN_PRIORITY = 1
 NORM_PRIORITY=5
 MAX_PRIORITY=10

28
Accessing Shared Resources

 Applications Access to Shared Resources need


to be coordinated.
 Printer (two person jobs cannot be printed at the
same time)
 Simultaneous operations on your bank account.
 Can the following operations be done at the same
time on the same account?
 Deposit()
 Withdraw()
 Enquire()

31

Shared Resources: synchronization

 When two or more threads need access


to a shared resource, they need some
way to ensure that the resource will be
used by only one thread at a time.
 The process by which this
synchronization is achieved is called
thread synchronization.

33
Shared Resources

 If one thread tries to read the data and other


thread tries to update the same data, it leads to
inconsistent state.
 This can be prevented by synchronising access
to the data.
 Use “Synchronized” method:
 public synchronized void update()
 {
 …
 }

34

Session.6
Java Basics - Input and Output

OVERVIEW OF I/O STREAMS

To bring in information, a program opens a stream on an


information source (a file, memory, a socket) and reads
the information sequentially, as shown in the following
figure.

1
OVERVIEW OF I/O STREAMS CONTD.
Similarly, a program can send information to an
external destination by opening a stream to a
destination and writing the information out
sequentially, as shown in the following figure.

OVERVIEW OF I/O STREAMS CONTD..

 The java.io package contains a collection of stream


classes that support algorithms for reading and
writing. To use these classes, a program needs to
import the java.io package.
 The stream classes are divided into two class
hierarchies, based on the data type (either characters
or bytes) on which they operate i.e Character Stream
and Byte Stream

3
CHARACTER STREAMS
 Reader and Writer are the abstract
superclasses for character streams in java.io.
 Reader provides the API and partial
implementation for readers ( streams that read
16-bit characters ) and Writer provides the API
and partial implementation for writers ( streams
that write 16-bit characters).

4
CHARACTER STREAMS CONTD.
 The following figure shows the class hierarchies
for the Reader and Writer classes.

BYTE STREAMS

 To read and write 8-bit bytes, programs should use


the byte streams, descendents of InputStream and
OutputStream .
 InputStream and OutputStream provide the API
and partial implementation for input streams
(streams that read 8-bit bytes) and output streams
(streams that write 8-bit bytes).

6
BYTE STREAMS (CONT.)

 These streams are typically used to read and


write binary data such as images and sounds.
 Two of the byte stream classes,
ObjectInputStream and ObjectOutputStream,
are used for object serialization.

BYTE STREAMS (CONT.)

 The class hierarchy for the Reader Class

8
BYTE STREAM (CONT.)

 Class hierarchy figure for Writer Class

DIFFERENCES:--
Byte Stream : Bytes stream reads or writes the data as byte( reads as
combination 0s and 1s ) from the underlying stream. Such a
underlying streams are Socket or file.
Character Stream : It reads or writes the data as character. But
internally it reads the bytes and converting into a character.
Bytes Stream:
============
It would be very useful when reading the file or socket and write into
another sockets or file. ( Don't need of conversion, but incase of if we
use character stream, it needs conversion in both operations)
Character Stream:
=================
It would be very useful when reading the data and directly so it into
user. ( User can understand only combination of character). So that
we don't need to explicit conversion from byte into character.

10
HOW TO USE FILE STREAMS
The file streams-- FileReader , FileWriter ,
FileInputStream , and FileOutputStream -- read or write
from a file on the native file system.
Here is simple code to create a file reader
File inputFile = new File("farrago.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
This reads characters from the reader as long as there's
more input in the input file and writes those characters
to the writer.

11

WORKING WITH RANDOM ACCESS FILES


 Random access means that the data can be read
from or written to random location in a file. In
the File class, data is read from and written
sequentially as continuous streams of data.
 The java.io package comprises a class known as
RandomAccessFile that allows performing
input/output operations to any location
within a file. This class also provides support for
permissions such as read and write, permitting
files to be accessed in read-only or read-write
modes.
12
STANDARD IO STREAMS
 There are three standard streams, all of which
are managed by the java.lang.System class
 Standard input--referenced by System.in
 Used for program input, typically reads input entered
by the user.
 Standard output--referenced by System.out
 Used for program output, typically displays information
to the user.
 Standard error--referenced by System.err
 Used to display error messages to the user.

13

Session.7
Java - Applet Basics
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because
it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application, including the following:
 An applet is a Java class that extends the java.applet.Applet class.
 A main() method is not invoked on an applet, and an applet class will not define main().
 Applets are designed to be embedded within an HTML page.
 When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user's
machine.
 A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate runtime
environment.
 The JVM on the user's machine creates an instance of the applet class and invokes various methods during the
applet's lifetime.
 Applets have strict security rules that are enforced by the Web browser. The security of an applet is often referred to
as sandbox security, comparing the applet to a child playing in a sandbox with various rules that must be followed.
 Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

Life Cycle of an Applet:


Four methods in the Applet class give you the framework on which you build any serious applet:
 init: This method is intended for whatever initialization is needed for your applet. It is called after the param tags
inside the applet tag have been processed.
 start: This method is automatically called after the browser calls the init method. It is also called whenever the user
returns to the page containing the applet after having gone off to other pages.
 stop: This method is automatically called when the user moves off the page on which the applet sits. It can,
therefore, be called repeatedly in the same applet.
 destroy: This method is only called when the browser shuts down normally. Because applets are meant to live on
an HTML page, you should not normally leave resources behind after a user leaves the page that contains the applet.
 paint: Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the
browser. The paint() method is actually inherited from the java.awt.

A "Hello, World" Applet:


The following is a simple applet named HelloWorldApplet.java:
import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends Applet


{
public void paint (Graphics g)
{
g.drawString ("Hello World", 25, 50);
}
}
These import statements bring the classes into the scope of our applet class:
 java.applet.Applet.
 java.awt.Graphics.
Without those import statements, the Java compiler would not recognize the classes Applet and Graphics, which the
applet class refers to.
The Applet CLASS:
Every applet is an extension of the java.applet.Applet class. The base Applet class provides methods that a derived
Applet class may call to obtain information and services from the browser context.
These include methods that do the following:
 Get applet parameters
 Get the network location of the HTML file that contains the applet
 Get the network location of the applet class directory
 Print a status message in the browser
 Fetch an image
 Fetch an audio clip
 Play an audio clip
 Resize the applet
Additionally, the Applet class provides an interface by which the viewer or browser obtains information about the
applet and controls the applet's execution. The viewer may:
 request information about the author, version and copyright of the applet
 request a description of the parameters the applet recognizes
 initialize the applet
 destroy the applet
 start the applet's execution
 stop the applet's execution
The Applet class provides default implementations of each of these methods. Those implementations may be
overridden as necessary.
The "Hello, World" applet is complete as it stands. The only method overridden is the paint method.

Invoking an Applet:
An applet may be invoked by embedding directives in an HTML file and viewing the file through an applet viewer or
Java-enabled browser.

The <applet> tag is the basis for embedding an applet in an HTML file. Below is an example that invokes the "Hello,
World" applet:

<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloWorldApplet.class" width="320" height="120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
Displaying Images:
An applet can display images of the format GIF, JPEG, BMP, and others. To display an image within the applet, you
use the drawImage() method found in the java.awt.Graphics class.

Following is the example showing all the steps to show images:

import java.applet.*;
import java.awt.*;
import java.net.*;
public class ImageDemo extends Applet
{
private Image image;
private AppletContext context;
public void init()
{
context = this.getAppletContext();
String imageURL = this.getParameter("image");
if(imageURL == null)
{
imageURL = "java.jpg";
}
try
{
URL url = new URL(this.getDocumentBase(), imageURL);
image = context.getImage(url);
}catch(MalformedURLException e)
{
e.printStackTrace();
// Display in browser status bar
context.showStatus("Could not load image!");
}
}
public void paint(Graphics g)
{
context.showStatus("Displaying image");
g.drawImage(image, 0, 0, 200, 84, null);
g.drawString("www.javalicense.com", 35, 100);
}
}

Now let us call this applet as follows:

<html>
<title>The ImageDemo applet</title>
<hr>
<applet code="ImageDemo.class" width="300" height="200">
<param name="image" value="java.jpg">
</applet>
<hr>
</html>
Based on the above examples, here is the live applet example: Applet Example.

Playing Audio:
An applet can play an audio file represented by the AudioClip interface in the java.applet package. The AudioClip
interface has three methods, including:
 public void play(): Plays the audio clip one time, from the beginning.
 public void loop(): Causes the audio clip to replay continually.
 public void stop(): Stops playing the audio clip.

To obtain an AudioClip object, you must invoke the getAudioClip() method of the Applet class. The getAudioClip()
method returns immediately, whether or not the URL resolves to an actual audio file. The audio file is not downloaded
until an attempt is made to play the audio clip.

Following is the example showing all the steps to play an audio:

import java.applet.*;
import java.awt.*;
import java.net.*;
public class AudioDemo extends Applet
{
private AudioClip clip;
private AppletContext context;
public void init()
{
context = this.getAppletContext();
String audioURL = this.getParameter("audio");
if(audioURL == null)
{
audioURL = "default.au";
}
try
{
URL url = new URL(this.getDocumentBase(), audioURL);
clip = context.getAudioClip(url);
}catch(MalformedURLException e)
{
e.printStackTrace();
context.showStatus("Could not load audio file!");
}
}
public void start()
{
if(clip != null)
{
clip.loop();
}
}
public void stop()
{
if(clip != null)
{
clip.stop();
}
}
}

Now let us call this applet as follows:

<html>
<title>The ImageDemo applet</title>
<hr>
<applet code="ImageDemo.class" width="0" height="0">
<param name="audio" value="test.wav">
</applet>
<hr>
</html>
The Swing layout management
The Java Swing toolkit has two kind of components. Containers and children. The
containers group children into suitable layouts. To create layouts, we use layout
managers. Layout managers are one of the most difficult parts of modern GUI
programming. Many beginning programmers have too much respect for layout
managers. Mainly because they are usually poorly documented. I believe, that GUI
builder's like Matisse cannot replace the proper understanding of layout managers.
Java Swing class hierarchy
The class JComponent, descended directly from Container, is the root class for most of
Swing’s user interface components.

Swing contains components that you’ll use to build a GUI. I am listing you some of the
commonly used Swing components. To learn and understand these swing programs, AWT
Programming knowledge is not required.
No manager
We can use no layout manager, if we want. There might be situations, where we might
not need a layout manager. For example, in my code examples, I often go without a
manager. It is because I did not want to make the examples too complex. But to create
truly portable, complex applications, we need layout managers.

Without layout manager, we position components using absolute values.

package zetcode;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class AbsoluteExample extends JFrame {

public AbsoluteExample() {

initUI();
}

public final void initUI() {

setLayout(null);

JButton ok = new JButton("OK");


ok.setBounds(50, 50, 80, 25);

JButton close = new JButton("Close");


close.setBounds(150, 50, 80, 25);

add(ok);
add(close);

setTitle("Absolute positioning");
setSize(300, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {


AbsoluteExample ex = new AbsoluteExample();
ex.setVisible(true);
}
});
}
}

This simple example shows two buttons.

setLayout(null);

We use absolute positioning by providing null to the setLayout() method.

ok.setBounds(50, 50, 80, 25);

The setBounds() method positions the ok button. The parameters are the x, y location
values and the width and height of the component.
FlowLayout manager
This is the simplest layout manager in the Java Swing toolkit. It is mainly used in
combination with other layout managers. When calculating its children size, a flow
layout lets each component assume its natural (preferred) size.
The manager puts components into a row. In the order, they were added. If they do not
fit into one row, they go into the next one. The components can be added from the right
to the left or vice versa. The manager allows to align the components. Implicitly, the
components are centered and there is 5px space among components and components
and the edges of the container.

FlowLayout()
FlowLayout(int align)
FlowLayout(int align, int hgap, int vgap)

There are three constructors available for the FlowLayout manager. The first one creates
a manager with implicit values. Centered with 5px horizontal and vertical spaces. The
others allow to specify those parametes.

package zetcode;

import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.SwingUtilities;

public class FlowLayoutExample extends JFrame {

public FlowLayoutExample() {

initUI();
}

public final void initUI() {

JPanel panel = new JPanel();

JTextArea area = new JTextArea("text area");


area.setPreferredSize(new Dimension(100, 100));
JButton button = new JButton("button");
panel.add(button);

JTree tree = new JTree();


panel.add(tree);

panel.add(area);

add(panel);

pack();

setTitle("FlowLayout Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

FlowLayoutExample ex = new FlowLayoutExample();


ex.setVisible(true);
}
});
}
}

The example shows a button, a tree and a text area component in the window.
Interesingly, if we create an empty tree component, there are some default values inside
the component.

JPanel panel = new JPanel();

The implicit layout manager of the JPanel component is a flow layout manager. We do
not have to set it manually.

JTextArea area = new JTextArea("text area");


area.setPreferredSize(new Dimension(100, 100));

The flow layout manager sets a preferred size for it's components. This means, that in
our case, the area component will have 100x100 px. If we didn't set the preferred size,
the component would have a size of its text. No more, no less. Without the text, the
component would not be visible at all. Try to write or delete some text in the area
component. The component will grow and shrink accordingly.
panel.add(area);

To put a component inside a container, we simply call the add() method.

Figure: FlowLaout manager


GridLayout
The GridLayout layout manager lays out components in a rectangular grid. The
container is divided into equally sized rectangles. One component is placed in each
rectangle.
package zetcode;

import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class GridLayoutExample extends JFrame {

public GridLayoutExample() {

initUI();
}

public final void initUI() {

JPanel panel = new JPanel();

panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panel.setLayout(new GridLayout(5, 4, 5, 5));

String[] buttons = {
"Cls", "Bck", "", "Close", "7", "8", "9", "/", "4",
"5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"
};

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


if (i == 2)
panel.add(new JLabel(buttons[i]));
else
panel.add(new JButton(buttons[i]));
}

add(panel);

setTitle("GridLayout");
setSize(350, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

GridLayoutExample ex = new GridLayoutExample();


ex.setVisible(true);
}
});
}
}

The example shows a skeleton of a simple calculator tool. It is an ideal example for this
layout manager. We put 19 buttons and one label into the manager. Notice, that each
button is of the same size.

panel.setLayout(new GridLayout(5, 4, 5, 5));

Here we set the grid layout manager for the panel component. The layout manager takes
four parameters. The number of rows, the number of columns and the horizontal and
vertical gaps between components.
Figure: GridLayout manager
BorderLayout
A BorderLayout manager is a very handy layout manager. I haven't seen it elsewhere. It
divides the space into five regions. North, West, South, East and Centre. Each region can
have only one component. If we need to put more components into a region, we can
simply put a panel there with a manager of our choice. The components in N, W, S, E
regions get their preferred size. The component in the centre takes up the whole space
left.

It does not look good, if child components are too close to each other. We must put some
space among them. Each component in Swing toolkit can have borders around it's
edges. To create a border, we either create a new instance of an EmptyBorder class or we
use a BorderFactory. Except for EmptyBorder, there are other types of borders as well.
But for layout management we will use only this one.

package zetcode;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Insets;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class BorderExample extends JFrame {

public BorderExample() {

initUI();
}

public final void initUI() {

JPanel panel = new JPanel(new BorderLayout());


JPanel top = new JPanel();

top.setBackground(Color.gray);
top.setPreferredSize(new Dimension(250, 150));
panel.add(top);

panel.setBorder(new EmptyBorder(new Insets(20, 20, 20, 20)));

add(panel);

pack();

setTitle("Border Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

BorderExample ex = new BorderExample();


ex.setVisible(true);
}
});
}
}

The example will display a gray panel and border around it.

JPanel panel = new JPanel(new BorderLayout());


JPanel top = new JPanel();

We place a panel into a panel. We used a BorderLayout manager for the first panel,
because this manager will resize its children.

panel.add(top);
Here we placed a top panel into the panel component. More precisely, we placed into the
center area of the BorderLayout manager.

panel.setBorder(new EmptyBorder(new Insets(20, 20, 20, 20)));

Here we created a 20px border around the panel. The border values are as follows: top,
left, bottom and right. They go counterclockwise.

Figure: Border example

The next example will show a typical usage of a border layout manager.

package zetcode;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Insets;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

public class BorderLayoutExample extends JFrame {

public BorderLayoutExample() {
initUI();
}

public final void initUI() {

JMenuBar menubar = new JMenuBar();


JMenu file = new JMenu("File");

menubar.add(file);
setJMenuBar(menubar);

JToolBar toolbar = new JToolBar();


toolbar.setFloatable(false);

ImageIcon exit = new ImageIcon("exit.png");


JButton bexit = new JButton(exit);
bexit.setBorder(new EmptyBorder(0 ,0, 0, 0));
toolbar.add(bexit);

add(toolbar, BorderLayout.NORTH);

JToolBar vertical = new JToolBar(JToolBar.VERTICAL);


vertical.setFloatable(false);
vertical.setMargin(new Insets(10, 5, 5, 5));

ImageIcon select = new ImageIcon("drive.png");


ImageIcon freehand = new ImageIcon("computer.png");
ImageIcon shapeed = new ImageIcon("printer.png");

JButton selectb = new JButton(select);


selectb.setBorder(new EmptyBorder(3, 0, 3, 0));

JButton freehandb = new JButton(freehand);


freehandb.setBorder(new EmptyBorder(3, 0, 3, 0));
JButton shapeedb = new JButton(shapeed);
shapeedb.setBorder(new EmptyBorder(3, 0, 3, 0));

vertical.add(selectb);
vertical.add(freehandb);
vertical.add(shapeedb);

add(vertical, BorderLayout.WEST);

add(new JTextArea(), BorderLayout.CENTER);

JLabel statusbar = new JLabel(" Statusbar");


statusbar.setPreferredSize(new Dimension(-1, 22));
statusbar.setBorder(LineBorder.createGrayLineBorder());
add(statusbar, BorderLayout.SOUTH);

setSize(350, 300);
setTitle("BorderLayout");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {


BorderLayoutExample ex = new BorderLayoutExample();
ex.setVisible(true);
}
});
}
}

The example shows a typical application skeleton. We show a vertical and horizontal
toolbars, a statusbar and a central component. (a text area)

A default layout manager for a JFrame component is BorderLayout manager. So we don't


have to set it.

add(toolbar, BorderLayout.NORTH);

Simply put the toolbar to the north of the layout.

add(vertical, BorderLayout.WEST);

Put the vertical toobar to the west.

add(new JTextArea(), BorderLayout.CENTER);

Put the text area to the center.

add(statusbar, BorderLayout.SOUTH);

Put the statusbar to the south.


Figure: BorderLayout manager
BoxLayout
BoxLayout is a powerful manager, that can be used to create sofisticated layouts. This
layout manager puts components into a row or into a column. It enables nesting, a
powerful feature, that makes this manager very flexible. It means, that we can put a box
layout into another box layout.

The box layout manager is often used with the Box class. This class creates several
invisible components, which affect the final layout.

 glue
 strut
 rigid area

Let's say, we want to put two buttons into the right bottom corner of the window. We
will use the boxlayut managers to accomplish this.

package zetcode;

import java.awt.Dimension;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TwoButtonsExample extends JFrame {

public TwoButtonsExample() {

initUI();
}

public final void initUI() {

JPanel basic = new JPanel();


basic.setLayout(new BoxLayout(basic, BoxLayout.Y_AXIS));
add(basic);

basic.add(Box.createVerticalGlue());

JPanel bottom = new JPanel();


bottom.setAlignmentX(1f);
bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS));

JButton ok = new JButton("OK");


JButton close = new JButton("Close");

bottom.add(ok);
bottom.add(Box.createRigidArea(new Dimension(5, 0)));
bottom.add(close);
bottom.add(Box.createRigidArea(new Dimension(15, 0)));

basic.add(bottom);
basic.add(Box.createRigidArea(new Dimension(0, 15)));

setTitle("Two Buttons");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {


TwoButtonsExample ex = new TwoButtonsExample();
ex.setVisible(true);
}
});
}
}

The following drawing illustrates the example.


Figure: Two buttons

We will create two panels. The basic panel has a vertical box layout. The bottom panel
has a horizontal one. We will put a bottom panel into the basic panel. We will right align
the bottom panel. The space between the top of the window and the bottom panel is
expandable. It is done by the vertical glue.

basic.setLayout(new BoxLayout(basic, BoxLayout.Y_AXIS));

Here we create a basic panel with the vertical BoxLayout.

JPanel bottom = new JPanel();


bottom.setAlignmentX(1f);
bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS));

The bottom panel is right aligned. This is done by the setAlignmentX() method. The
panel has a horizontal layout.

bottom.add(Box.createRigidArea(new Dimension(5, 0)));

We put some rigid space between the buttons.

basic.add(bottom);

Here we put the bottom panel with a horizontal box layout to the vertical basic panel.

basic.add(Box.createRigidArea(new Dimension(0, 15)));

We also put some space between the bottom panel and the border of the window.
Figure: Two buttons

When we use a BoxLayout manager, we can set a rigid area among our components.

package zetcode;

import java.awt.Dimension;

import java.awt.Insets;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;

public class RigidAreaExample extends JFrame {

public RigidAreaExample() {

initUI();
}

public final void initUI() {

JPanel panel = new JPanel();


panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

panel.setBorder(new EmptyBorder(new Insets(40, 60, 40, 60)));

panel.add(new JButton("Button"));
panel.add(Box.createRigidArea(new Dimension(0, 5)));
panel.add(new JButton("Button"));
panel.add(Box.createRigidArea(new Dimension(0, 5)));
panel.add(new JButton("Button"));
panel.add(Box.createRigidArea(new Dimension(0, 5)));
panel.add(new JButton("Button"));

add(panel);

pack();
setTitle("RigidArea");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {


RigidAreaExample ex = new RigidAreaExample();
ex.setVisible(true);
}
});
}
}

In this example, we display four buttons. By default, there is no space among the
buttons. To put some space among them, we add some rigid area.

panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

We use a vertical BoxLayout manager for our panel.

panel.add(new JButton("Button"));
panel.add(Box.createRigidArea(new Dimension(0, 5)));
panel.add(new JButton("Button"));

We add buttons and create a rigid area in between them.

Figure: Rigid area


Tip of the Day
JDeveloper has a dialog window called Tip of the Day.
Figure: Tip of the Day

We will create a similar dialog. We will use a combination of various layout managers.
Namely a border layout, flow layout and box layout manager.

package zetcode;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;

public class TipOfDayExample extends JDialog {


public TipOfDayExample() {

initUI();
}

public final void initUI() {

JPanel basic = new JPanel();


basic.setLayout(new BoxLayout(basic, BoxLayout.Y_AXIS));
add(basic);

JPanel topPanel = new JPanel(new BorderLayout(0, 0));


topPanel.setMaximumSize(new Dimension(450, 0));
JLabel hint = new JLabel("JDeveloper Productivity Hints");
hint.setBorder(BorderFactory.createEmptyBorder(0, 25, 0, 0));
topPanel.add(hint);

ImageIcon icon = new ImageIcon("jdev.png");


JLabel label = new JLabel(icon);
label.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
topPanel.add(label, BorderLayout.EAST);

JSeparator separator = new JSeparator();


separator.setForeground(Color.gray);

topPanel.add(separator, BorderLayout.SOUTH);

basic.add(topPanel);

JPanel textPanel = new JPanel(new BorderLayout());


textPanel.setBorder(BorderFactory.createEmptyBorder(15, 25, 15, 25));
JTextPane pane = new JTextPane();

pane.setContentType("text/html");
String text = "<p><b>Closing windows using the mouse wheel</b></p>" +
"<p>Clicking with the mouse wheel on an editor tab closes the
window. " +
"This method works also with dockable windows or Log window
tabs.</p>";
pane.setText(text);
pane.setEditable(false);
textPanel.add(pane);

basic.add(textPanel);

JPanel boxPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 20, 0));

JCheckBox box = new JCheckBox("Show Tips at startup");


box.setMnemonic(KeyEvent.VK_S);

boxPanel.add(box);
basic.add(boxPanel);

JPanel bottom = new JPanel(new FlowLayout(FlowLayout.RIGHT));


JButton ntip = new JButton("Next Tip");
ntip.setMnemonic(KeyEvent.VK_N);
JButton close = new JButton("Close");
close.setMnemonic(KeyEvent.VK_C);

bottom.add(ntip);
bottom.add(close);
basic.add(bottom);

bottom.setMaximumSize(new Dimension(450, 0));

setTitle("Tip of the Day");


setSize(new Dimension(450, 350));
setResizable(false);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {


TipOfDayExample ex = new TipOfDayExample();
ex.setVisible(true);
}
});
}
}

The example uses a mix of layout managers. Simply we put four panels into the
vertically organized basic panel.

JPanel basic = new JPanel();


basic.setLayout(new BoxLayout(basic, BoxLayout.Y_AXIS));
add(basic);

This is the very bottom panel. It has a vertical box layout manager. The basic panel is
added to the default JDialog component. This component has a border layout manager
by default.

JPanel topPanel = new JPanel(new BorderLayout(0, 0));

The topPanel panel has a border layout manager. We will put three components into it.
Two labels and a separator.

topPanel.setMaximumSize(new Dimension(450, 0));


If we want to have a panel, that is not greater than it's components, we must set it's
maximum size. The zero value is ignored. The manager calculates the necessary heights.

JPanel textPanel = new JPanel(new BorderLayout());


...
textPanel.add(pane);

The text pane component is added to the center area of the border layout manager. It
takes all space left. Exactly, as we wanted.

JPanel boxPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 20, 0));

The check box is shown in the boxPanel panel. It is left aligned. The flow layout manager
has a 20px horizontal gap. Other components have 25px. Why is that? It is because the
flow layout manager puts some space to between the component and the edge as well.

JPanel bottom = new JPanel(new FlowLayout(FlowLayout.RIGHT));


...
bottom.setMaximumSize(new Dimension(450, 0));

The bottom panel displays two buttons. It has a right aligned flow layout manager. In
order to show the buttons on the right edge of the dialog, the panel must stretch
horizontally from the beginning to the end.
Delegation event model
Event model is based on the concept of an 'Event Source' and 'Event Listeners'. Any object that is
interested in receiving messages (or events ) is called an Event Listener. Any object that generates
these messages ( or events ) is called an Event Source
Event Delegation Model is based on four concepts:
The Event Classes
The Event Listeners
Explicit Event Enabling
Adapters

The modern approach to handling events is based on the delegation event model, which defines
standard and consistent mechanisms to generate and process events. Its concept is quite simple: a
source generates an event and sends it to one or more listeners. In this scheme, the listener simply
waits until it receives an event. Once received, the listener processes the event and then returns. The
advantage of this design is that the application logic that processes events is cleanly separated from
the user interface logic that generates those events. A user interface element is able to "delegate"
the processing of an event to a separate piece of code.

Abstract Window Toolkit


The Abstract Window Toolkit (AWT) is Java's original platform-independent windowing,graphics,
and user-interface widget toolkit. The AWT is now part of the Java Foundation Classes (JFC) — the
standard API for providing a graphical user interface (GUI) for a Java program. AWT is also the GUI
toolkit for a number of Java ME profiles. For example,Connected Device Configuration profiles require
Java runtimes on mobile telephones to support AWT.

Windows form with some AWT examples

Vous aimerez peut-être aussi