Вы находитесь на странице: 1из 36

Java Tutorial - Java Hello WorldLet's start by

compiling and running the following short sample program.


/*ThisisasimpleJavaprogram.Callthisfile"Main.java".
*/

When Java source code is compiled, each individual class is put into its own file
namedclassname.class.

A Closer Look at the Main.java


The first part is a comment.

publicclassMain{
//Yourprogrambeginswithacalltomain().

/*

publicstaticvoidmain(Stringargs[]){

ThisisasimpleJavaprogram.Callthisfile"Main.java".

System.out.println("Java.");

*/

Comment is a remark for a program. The contents of a comment are ignored by the
compiler. The next line of code in the program is shown here:

In Java, a source file is called a compilation unit. It is a text file that contains one or
more class definitions. The Java compiler requires that a source file use the .java
filename extension.
In Java, all code must reside inside a class. By convention, the name of the public
class should match the its file name. And Java is case-sensitive.

publicclassMain{

The keyword class declares that a new class is being defined. Main is the name of
the class. The entire class definition is between the opening curly brace ({) and the
closing curly brace (}). The next line in the program is the single-line comment,
shown here:

The code above generates the following result.


//Yourprogrambeginswithacalltomain().

Compiling the Program


To compile the program, execute the compiler, javac, specifying the name of the
source file on the command line:
C:\>javacMain.java

The javac compiler creates a file called Main.class. Main.class contains the byte
code version of the program.
To run the program, use the Java interpreter, called java. Pass the class
name Mainas a command-line argument, as shown here:
C:\>javaMain

When the program is run, the following output is displayed:

A single-line comment begins with a // and ends at the end of the line. The next line
of code is shown here:
publicstaticvoidmain(Stringargs[]){

Java applications begin execution by calling main(Stringargs[]). Java is casesensitive. Thus, Main is different from main.

A Short Program with a variable


A variable is a memory location that may be assigned a value. The value of a
variable is changeable.
The following code defines a variable and change its value by assigning a new value
to it.

publicclassMain{

publicstaticvoidmain(Stringargs[]){

publicstaticvoidmain(Stringargs[]){

intnum,num2;

intnum;//avariablecallednum

num=100;//assignsnumthevalue100

num=100;

num2=200;

System.out.println("Thisisnum:"+num);

System.out.println("Thisisnum:"+num);

num=num*2;

System.out.println("Thisisnum2:"+num2);

System.out.print("Thevalueofnum*2is");

System.out.println(num);

When the program is run, the following output is displayed:

When you run this program, you will see the following output:

Using Blocks of Code


The following snippet declares an integer variable called num. Java requires that
variables must be declared before they can be used.
intnum;//thisdeclaresavariablecallednum

Following is the general form of a variable declaration:


typevarname;

In the program, the line assigns to num the value 100.


num=100;//thisassignsnumthevalue100

Java can group two or more statements into blocks of code. Code block is enclosing
the statements between opening and closing curly braces({}).
For example, a block can be a target for Java's if and for statements. Consider
thisif statement:
publicclassMain{
publicstaticvoidmain(Stringargs[]){
intx,y;
x=10;
y=20;
if(x<y){//beginablock
x=y;

Define more than one variable with comma

y=0;

To declare more than one variable of the specified type, you may use a commaseparated list of variable names.

System.out.println("y="+y);

System.out.println("x="+x);

}//endofblock
publicclassMain{

}
}

Here is the output of the code above:

Example
A block of code as the target of a for loop.
publicclassMain{

publicstaticvoidmain(Stringargs[]){
inti,y;

Full list of keywords in Java

y=20;
for(i=0;i<10;i++){//thetargetofthisloopisablock
System.out.println("Thisisi:"+i);

A keyword is a word whose meaning is defined by the programming language. Java


keywords and reserved Words:

System.out.println("Thisisy:"+y);

abstractclassextendsimplementsnullstrictfptrue

y=y1;

assertconstfalseimportpackagesupertry

booleancontinuefinalinstanceofprivateswitchvoid

breakdefaultfinallyintprotectedsynchronizedvolatile

bytedofloatinterfacepublicthiswhile

casedoubleforlongreturnthrow
catchelsegotonativeshortthrows

The output generated by this program is shown here:

charenumifnewstatictransient

An identifier is a word used by a programmer to name a variable, method, class, or


label. Keywords and reserved words may not be used as identifiers. An identifier
must begin with a letter, a dollar sign ($), or an underscore (_); subsequent
characters may be letters, dollar signs, underscores, or digits.
Some examples are:
foobar//legal
Myclass//legal

$a//legal

Java variable type

3_a//illegal:startswithadigit
!theValue//illegal:bad1stchar

In Java, all variables must be declared before they can be used. The basic form of a
variable declaration is shown here:

typeidentifier[=value][,identifier[=value]...];

Java Identifiers are case sensitive. For example, myValue and MyValue are distinct
identifiers.

There are three parts in variable definition:

Using identifiers

type could be int or float.


identifier is the variable's name.

Initialization includes an equal sign and a value.

Identifiers are used for class names, method names, and variable names. An
identifier may be any sequence of uppercase and lowercase letters, numbers, or the
underscore and dollar-sign characters. Identifiers must not begin with a number.
Java Identifiers are case-sensitive. The following code illustrates some examples of
valid identifiers:

To declare more than one variable of the specified type, use a comma-separated
list.

publicclassMain{

intd=3,e,f=5;//declaresthreemoreints,initializingdandf.

publicstaticvoidmain(String[]argv){

inta,b,c;//declaresthreeints,a,b,andc.

The following variables are defined and initialized in one expression.

intATEST,count,i1,$Atest,this_is_a_test;
}

publicclassMain{

publicstaticvoidmain(String[]argv){

bytez=2;//initializesz.
doublepi=3.14;//declaresanapproximationofpi.

The following code shows invalid variable names include:

charx='x';//thevariablexhasthevalue'x'.

publicclassMain{

publicstaticvoidmain(String[]argv){

int2count,hl,a/b,

Variable cannot be used prior to its declaration.

publicclassMain{

publicstaticvoidmain(String[]argv){

If you try to compile this code, you will get the following error message:
A variable is defined by an identifier, a type, and an optional initializer. The variables
also have a scope(visibility / lifetime).

count=100;//Cannotusecountbeforeitisdeclared!
intcount;
}
}

Compiling the code above generates the following error message:

//cisdynamicallyinitialized
doublec=Math.sqrt(2*2);

Assignment Operator

System.out.println("cis"+c);

The assignment operator is the single equal sign, =. It has this general form:

}
var=expression;

type of var must be compatible with the type of expression. The assignment
operator allows you to create a chain of assignments.

The output from the code above is

publicclassMain{

Java defines eight primitive types of


data: byte, short, int, long, char, float,double, and boolean.

publicstaticvoidmain(String[]argv){
intx,y,z;

Primitive Type

Reserved Word

Size

Min Value

Max Value

Boolean

boolean

N/A

N/A

N/A

Character

char

16-bit

Unicode 0

Unicode 216 - 1

Byte integer

byte

8-bit

-128

+127

Short integer

short

16-bit

-215

+215 - 1

Integer

int

32-bit

-231

+231 - 1

Dynamic Initialization

Long integer

long

64-bit

-263

+263 - 1

Java allows variables to be initialized dynamically. In the following code


the Math.sqrtreturns the square root of 2*2 and assigns the result to c directly.

Floating-point

float

32-bit

1.4e-045

3.4e+038

Double precision
floating-point

double

64-bit

4.9e-324

1.8e+308

x=y=z=100;//setx,y,andzto100
System.out.println("xis"+x);
System.out.println("yis"+y);
System.out.println("zis"+z);
}
}

The output:

publicclassMain{
publicstaticvoidmain(Stringargs[]){

10

byte, short, int, and long are for whole-valued signed


numbers. float anddouble are fractional precision numbers.

Name

Width in Bits

Approximate Range

char represents symbols in a character set, like letters and


numbers. booleanrepresents true/false values.

float

32

1.4e-045 to 3.4e+038

Java Integers

Java has a boolean type for logical values. This is the type returned by all relational
operators.

Java defines four integer types: byte, short, int, and long.
Integer types are signed and can have positive and negative values.

Value

The width and ranges of these integer types vary widely:

It can have only one of two possible values, true or false.

Name

Width

Range

long

64

-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Boolean literals are only two logical values: true and false. The values
of true andfalse do not convert into any numerical representation.

int

32

-2,147,483,648 to 2,147,483,647

The true literal in Java does not equal 1, nor does the false literal equal 0. In Java,
they can only be assigned to variables declared as boolean.

short

16

-32,768 to 32,767

Boolean class

byte

-128 to 127

Literals

The Boolean class wraps a primitive type boolean in an object. An object of type
Boolean contains a single field whose type is boolean.
Boolean class has the methods for converting a boolean to a String and a String to a
boolean.

Floating Point Types


There are two kinds of floating-point types: float and double. float type represents
single-precision numbers. double type stores double-precision numbers.

Example
Here is a program that demonstrates the boolean type:

Floating-Point Types width and ranges are shown here:


publicclassMain{

Name

Width in Bits

Approximate Range

double

64

4.9e-324 to 1.8e+308

publicstaticvoidmain(Stringargs[]){
booleanboolVariable;
boolVariable=false;

System.out.println("bis"+boolVariable);

11

12

Byte variables are declared by use of the byte keyword. The following declares two
byte variables called b and c:

boolVariable=true;

byteb,c;

System.out.println("bis"+boolVariable);

byte is a signed 8-bit type that has a range from -128 to 127.

The following code creates two byte type variables and assigns values.

publicclassMain{

publicstaticvoidmain(String[]args){
byteb1=100;

Output:

byteb2=20;
System.out.println("Valueofbytevariableb1is:"+b1);
System.out.println("Valueofbytevariableb1is:"+b2);
}
}

Example 2

The code above generates the following result.

The true literal in Java does not equal 1, nor does the false literal equal 0. In Java,
they can only be assigned to variables declared as boolean.
publicclassMain{

The Byte class wraps a value of primitive type byte in an object. Byte class provides
several methods for converting a byte to a String and a String to a byte.

publicstaticvoidmain(String[]argv){
booleanb=true;

inti=b;

Java short type

The size of Java short type is between byte and integer.

short is a signed 16-bit type. short type variable has a range from -32,768 to 32,767.

Here are some examples of short variable declarations:

If you try to compile the program, the following error message will be generated by
compiler.

shorts;
shortt;

Java byte type


The smallest integer type is byte. byte type variables are useful when working with
a stream of data from a network or file.

13

14

Java int type

longresult=(long)Integer.MAX_VALUE*(long)10;
System.out.println(result);//21474836470

When byte and short values are used in an expression they are promoted to int
when the expression is evaluated.
int is a signed 32-bit type that has a range from 2,147,483,648 to 2,147,483,647.

Java long type

}
}

The result could not have been held in an int variable.


The code above generates the following result.

Java long type is used when an int type is not large enough.
long is a signed 64-bit type and . The range of long type is 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
To specify a long literal, you need to tell the compiler that the literal value is of
typelong by appending an upper- or lowercase L to the literal. For
example,0x7ffffffffffffffL or 123123123123L.
The following code creates a long type literal and assigns the value to a long type
variable.

octal integer(base eight)


Octal values are denoted in Java by a leading zero. valid value 09 will produce an
error from the compiler, since 9 is outside of octal's 0 to 7 range.
publicclassMain{

publicclassMain{

publicstaticvoidmain(Stringargs[]){

publicstaticvoidmain(String[]args){

longl=0x7ffffffffffffffL;

inti=010;

System.out.println("lis"+l);

System.out.println(i);

The output generated by this program is shown here:

The output:

Example

Here is a program that use long type to store the result.


publicclassMain{
publicstaticvoidmain(Stringargs[]){

15

hexadecimal integer(base 16)


hexadecimal matches with modulo 8 word sizes, such as 8, 16, 32, and 64 bits. You
signify a hexadecimal constant with a leading zero-x, (0x or 0X).

16

The range of a hexadecimal digit is 0 to 15, so A through F (or a through f ) are


substituted for 10 through 15.

System.out.print(d);//3.14159
}

An integer literal can always be assigned to a long variable. An integer can also be
assigned to a char as long as it is within range.

The code above generates the following result.

publicclassMain{
publicstaticvoidmain(String[]argv){

intf=0XFFFFF;

Java double type

System.out.println(f);//1048575

Java double type represents double-precision numbers.

double is 64-bit width and its range is from 4.9e-324 to 1.8e+308 approximately.

Here is a program that uses double variables to compute the area of a circle:

The code above generates the following result.

publicclassMain{
publicstaticvoidmain(Stringargs[]){

doublepi,r,a;

float type

r=10.8888;//radiusofcircle

float type represents single-precision numbers.

a=pi*r*r;

float type variables are useful when you need a fractional component. Here are

some example float variable declarations:

System.out.println("Areaofcircleis"+a);

floathigh,low;

pi=3.1415926;//pi,approximately

Java float Value, size and Literals

The output:

float is 32-bit width and its range is from 1.4e045 to 3.4e+038 approximately.
Floating-point literals in Java default to double precision. To specify a float literal,
you must append an F or f to the constant.
The following code shows how to declare float literals.

Example
double type numbers have decimal values with a fractional component. They can be
expressed in either standard or scientific notation. Standard notation consists of a
whole number component followed by a decimal point followed by a fractional
component. For example, 2.0, 3.14159, and 0.6667.

publicclassMain{
publicstaticvoidmain(Stringargs[]){
floatd=3.14159F;

17

18

publicclassMain{

doubled2=314159E05;

publicstaticvoidmain(Stringargs[]){

doubled3=2e+100;

doubled=3.14159;

System.out.println("d1is"+d1);

System.out.print(d);//3.14159

System.out.println("d2is"+d2);

System.out.println("d3is"+d3);

The code above generates the following result.

The output generated by this program is shown here:

Example 2
You can explicitly specify a double literal by appending a D or d.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
doubled=3.14159D;
System.out.print(d);//3.14159
}

double value constant


Java's floating-point calculations are capable of returning +infinity,
infinity,+0.0, 0.0, and NaN
dividing a positive number by 0.0 returns +infinity. For
example,System.out.println(1.0/0.0); outputs Infinity.

The code above generates the following result.

publicclassMain{
publicstaticvoidmain(String[]args){
System.out.println(1.0/0.0);

Scientific notation

Scientific notation uses a standard-notation, floating-point number plus a suffix that


specifies a power of 10 by which the number is to be multiplied. The exponent is
indicated by an E or e followed by a decimal number, which can be positive or
negative. For example, 6.02E23, 314159E05, and 4e+100.

The code above generates the following result.

publicclassMain{
publicstaticvoidmain(String[]argv){
doubled1=6.022E23;

19

20

double Infinity

Dividing a negative number by 0.0 outputs infinity. For


example,System.out.println(1.0/0.0); outputs Infinity.

The code above generates the following result.

publicclassMain{
publicstaticvoidmain(String[]args){
System.out.println(1.0/0.0);
}

In Java, char stores characters. Java uses Unicode to represent characters.


Unicode can represent all of the characters found in all human languages.

Output:

Java char is a 16-bit type.


The range of a char is 0 to 65,536. There are no negative chars.

double NaN
Dividing 0.0 by 0.0 returns NaN. square root of a negative number is NaN. For
example, System.out.println(0.0/0.0) and System.out.println(Math.sqrt(
1.0))output NaN.

Char Literals
Characters in Java are indices into the Unicode character set. character is
represented inside a pair of single quotes. For example, 'a', 'z', and '@'.

Dividing a positive number by +infinity outputs +0.0. For


example,System.out.println(1.0/(1.0/0.0)); outputs +0.0.

Here is a program that demonstrates char variables:

Dividing a negative number by +infinity outputs 0.0. For


example,System.out.println(1.0/(1.0/0.0)); outputs 0.0.

publicclassMain{
publicstaticvoidmain(Stringargs[]){
charch1,ch2;

publicclassMain{

ch1=88;//codeforX

publicstaticvoidmain(String[]args){

Doubled1=newDouble(+0.0);

ch2='Y';

System.out.println(d1.doubleValue());

Doubled2=newDouble(0.0);

System.out.print("ch1andch2:");

System.out.println(d2.doubleValue());

System.out.println(ch1+""+ch2);//ch1andch2:XY

System.out.println(d1.equals(d2));

System.out.println(+0.0==0.0);

21

22

The code above generates the following result.

System.out.println("chis"+ch);//chisa
ch='@';

ch1 is assigned the value 88, which is the ASCII (and Unicode) value that
corresponds to the letter X.

System.out.println("chis"+ch);//chis@

Example

char type value can be used as an integer type and you can perform arithmetic

ch='$';

operations.

publicclassMain{

System.out.println("chis"+ch);//chis$

publicstaticvoidmain(Stringargs[]){

ch='%';

charch1;

System.out.println("chis"+ch);//chis%

ch1='X';

System.out.println("ch1contains"+ch1);//ch1containsX

The code above generates the following result.

ch='#';

System.out.println("chis"+ch);//chis#

ch1=(char)(ch1+1);//incrementch1
System.out.println("ch1isnow"+ch1);//ch1isnowY
}
}

The code above generates the following result.

Example 2
The following code shows that we can assign non-letter character to Java char type.

Example 3
The following code stores unicode value into a char variable. The unicode literal
uses\uxxxx format.
publicclassMain{

publicclassMain{

publicstaticvoidmain(String[]args){

publicstaticvoidmain(String[]argv){

intx=75;

charch='a';

chary=(char)x;

23

24

Escape value list

charhalf='\u00AB';
System.out.println("yis"+y+"andhalfis"+half);

The following table shows the character escape sequences.

Escape Sequence

Description

\ddd

Octal character (ddd)

\uxxxx

Hexadecimal Unicode character (xxxx)

\'

Single quote

\"

Double quote

\\

Backslash

\r

Carriage return

\n

New line

\f

Form feed

\t

Tab

\b

Backspace

The code above generates the following result.

Java char value escape


The escape sequences are used to enter impossible-to-enter-directly characters.
Syntax to escape char value:
'\'' is for the single-quote character. '\n' is for the newline character.

For octal notation, use the backslash followed by the three-digit number. For
example,'\141' is the letter 'a'.
For hexadecimal, you enter a backslash-u (\u), then exactly four hexadecimal digits.
For example, '\u0061' is the ISO-Latin-1 'a' because the top byte is zero. '\ua432' is a
Japanese Katakana character.
publicclassMain{
publicstaticvoidmain(String[]argv){
charch='\'';

System.out.println("chis"+ch);//chis'

}
}

Character is a simple wrapper around a char.

The String class represents character strings. A quoted string constant can be
assigned to a String variable.

The code above generates the following result.

25

26

Java String Literal

Example

String literals in Java are specified by enclosing a sequence of characters between a


pair of double quotes. In Java strings are actually object types.

The following code uses string concatenation to create a very long string.

The following code declares String type variable with Java String literal.

publicclassMain{
publicclassMain{

publicstaticvoidmain(Stringargs[]){

publicstaticvoidmain(String[]argv){

StringlongStr="Ajava.com"+

Stringstr="thisisatestfromjava2s.com";

"Bjava.com"+

System.out.println(str);

"Cjava.com"+

"Djava.com.";

System.out.println(longStr);

The output:

Java String Concatenation

You can use + operator to concatenate strings together.


For example, the following fragment concatenates three strings:

Example 2

You can concatenate strings with other types of data.

publicclassMain{
publicstaticvoidmain(String[]argv){
Stringage="9";
Strings="Heis"+age+"yearsold.";
System.out.println(s);
}

publicclassMain{
publicstaticvoidmain(String[]argv){
intage=1;
Strings="Heis"+age+"yearsold.";
System.out.println(s);

}
}

The output:

27

28

Example 3

Escape List

Be careful when you mix other types of operations with string concatenation.
Consider the following:

The following table summarizes the Java String escape sequence.


Escape Sequence

Description

\ddd

Octal character (ddd)

\uxxxx

Hexadecimal Unicode character (xxxx)

\'

Single quote

\"

Double quote

\\

Backslash

\r

Carriage return

\n

New line

Now s contains the string "four: 4".

\f

Form feed

Java String Escape

\t

Tab

\b

Backspace

publicclassMain{
publicstaticvoidmain(String[]argv){
Strings="four:"+2+2;
System.out.println(s);
}
}

This fragment displays

rather than the

To complete the integer addition first, you must use parentheses, like this:
Strings="four:"+(2+2);

The escape sequences are used to enter impossible-to-enter-directly strings.


For example, "\"" is for the double-quote character. "\n" for the newline string.
For octal notation, use the backslash followed by the three-digit number. For
example, "\141" is the letter "a".
For hexadecimal, you enter a backslash-u (\u), then exactly four hexadecimal digits.
For example, "\u0061" is the ISO-Latin-1 "a" because the top byte is zero. "\ua432"
is a Japanese Katakana character.

29

Examples of string literals with escape are


"HelloWorld"
"two\nlines"
"\"Thisisinquotes\""

30

The following example escapes the new line string and double quotation string.

If you try to compile this program, the compiler will generate the following error
message.

publicclassMain{
publicstaticvoidmain(String[]argv){
Strings="java.com";
System.out.println("sis"+s);
s="two\nlines";
System.out.println("sis"+s);

s="\"quotes\"";

System.out.println("sis"+s);

equals() vs ==

The output generated by this program is shown here:

equals() method and the == operator perform two different operations. equals(
)method compares the characters inside a String object. The == operator compares

two object references to see whether they refer to the same instance.

Example 4
Java String literials must be begin and end on the same line. If your string is across
several lines, the Java compiler will complain about it.

The following program shows the differences:

publicclassMain{
publicstaticvoidmain(Stringargs[]){

Strings1="demo.com";

publicclassMain{
publicstaticvoidmain(String[]argv){
Strings="line1
line2
";

Strings2=newString(s1);

System.out.println(s1+"equals"+s2+">"+s1.equals(s2));
System.out.println(s1+"=="+s2+">"+(s1==s2));
}
}

31

32

Here the square brackets appear after the variable name, rather than after the type
name.

This is exactly equivalent to the previous statement. int[] form is preferred since it
indicates more clearly that the type is an array of values of type int.

An array is a named set of variables of the same type.

The following two declarations are equivalent:

Each variable in the array is called an array element.

inta1[]=newint[3];
int[]a2=newint[3];

Java Array Variables


A Java array variable has two parts: array type and array object.

Array create

The array type is the type of the array variable. The array object is the memory
allocated for an array variable.

After you have declared an array variable, you can define an array that it references:

When defining an array we can first define the array type and allocate the memory
later.

myIntArray=newint[10];//Defineanarrayof10integers

This statement creates an array that stores 10 values of type int and stores a
reference to the array in the variable myIntArray.

Syntax

The reference is simply where the array is in memory.

You could declare the integer array variable myIntArray with the following statement:
int[]myIntArray;//Declareanintegerarrayvariable

You could also declare the array variable and define the array of type int to hold 10
integers with a single statement.

int[]myIntArray=newint[10];//Anarrayof10integers

The variable myIntArray is now a type for an integer array. No memory has been
allocated to hold an array itself.

The first part of the definition specifies the type of the array. The element type name,
int in this case, is followed by an empty pair of square brackets.

Later we will create the array by allocating memory and specify how many elements
it can contain.

The part of the statement that follows the equal sign defines the array.

The square brackets following the type indicates that the variable is for an array of
int values, and not for storing a single value of type int.

The keyword new indicates that you are allocating new memory for the array, and
int[10] specifies that the capacity is 10 variables of type int in the array.

The type of the array variable is int[].

Java Array Initial Values

Alternative Syntax

After we allocate memory for a Java array, Java assigns each element in an array to
its initial values

We can use an alternative notation for declaring an array variable:


intmyIntArray[];//Declareanintegerarrayvariable

The initial value is zero in the case of an array of numerical values, is false for
boolean arrays, is '\u0000' for arrays storing type char, and is null for an array of
objects of a class type.

The following table lists the default value for various array types.

33

34

Element Type

Initial Value

byte

int

float

0.0f

char

'\u0000'

object reference

null

short

long

0L

double

0.0d

boolean

false

inta2[]={1,2,3,4,5};
inta3[]={4,3,2,1};
System.out.println("lengthofa1is"+a1.length);
System.out.println("lengthofa2is"+a2.length);
System.out.println("lengthofa3is"+a3.length);
}
}

This program displays the following output:

Java Initialize Arrays


We can initialize the elements in an array with values when declaring it, and at the
same time determine how many elements it has.
To do this, we simply add an equal sign followed by the list of element values
enclosed between braces following the specification of the array variable.
For example, you can define and initialize an array with the following statement:
int[]primes={2,3,5,7,11,13,17};//Anarrayof7elements

Java Array Length


You can refer to the length of the array - the number of elements it contains - using
length, a data member of the array object.
Array size, arrayName.length, holds its length.
The following code outputs the length of each array by using its length property.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
inta1[]=newint[10];

35

The array size is determined by the number of initial values.


The values are assigned to the array elements in sequence, so in this example
primes[0] has the initial value 2, primes[1] has the initial value 3, primes[2] has the
initial value 5, and so on through the rest of the elements in the array.
When an array is initialized during the declaration there is no need to use new.
publicclassMain{
publicstaticvoidmain(Stringargs[]){

intdays[]={31,28,31,};

36

System.out.println("days[2]is"+days[2]);

System.out.println("days[2]is"+days[10]);

The output:

It generates the following error.

Java Array Index


To reference an element in an array, we use the array name combined with an
integer value, called index.
The index is placed between square brackets following the array name; for example,
data[9]

for loop
We usually use a for loop to access each element in an array. The following code
uses a one-dimensional array to find the average of a set of numbers.
publicclassMain{

refers to the element in the data array corresponding to the index value 9.

publicstaticvoidmain(Stringargs[]){

The index for an array element is the offset of the element from the beginning of the
array.

doublenums[]={10.1,11.2,12.3,13.4,14.5};

The first element has an index of 0, the second has an index of 1, the third an index
of 2, and so on.

intI;

We refer to the first element of the myIntArray array as myIntArray[0], and we


reference the fifth element in the array as myIntArray[4].

for(i=0;i<5;i++)

data[9] refers to the tenth element in the data array.


The maximum index value for an array is one less than the number of elements in
the array.
The index value does not need to be an integer literal, it can also be a variable.

doubleresult=0;

result=result+nums[i];

System.out.println("Averageis"+result/5);
}
}

The array index has to have a value equals to or greater than zero.
Array stores elements and we use index to reference a single value in an array. The
starting value of the index is 0. If you try to reference elements with negative
numbers or numbers greater than the array length, you will get a run-time error.
publicclassMain{
publicstaticvoidmain(Stringargs[]){

intdays[]={1,2,3,};

37

The output:

Java Array for each loop


We can use a collection-based for loop as an alternative to the numerical for loop
when processing the values of all the elements in an array.

38

The syntax of for each loop for an array is as follows.

[1][0][1][1][1][2][1][3][1][4]

for(arrayTypevariableName:array){

[2][0][2][1][2][2][2][3][2][4]

processeachvariableName

[3][0][3][1][3][2][3][3][3][4]

The wrong way to think about multi-dimension arrays is as follows.

Java array for each loop

++++

publicclassMain{

|1|2|3|

publicstaticvoidmain(Stringargs[]){

++++

intdays[]={1,2,3,};

|4|5|6|

for(inti:days){

++++

System.out.println(i);

|7|8|9|

++++

The right way to think about multi-dimension arrays

}
++++++

The code above generates the following result.

|||1|2|3|
++++++++++
|||4|5|6|
++++++++++
|||7|8|9|

Java Multidimensional Arrays

++++++

The following code use nested for loop to assign values to a two-dimensional array.

In Java, multidimensional arrays are actually arrays of arrays.


For example, the following declares a two-dimensional array variable called twoD.
inttwoD[][]=newint[4][5];

This allocates a 4-by-5 array and assigns it to twoD. This array will look like the one
shown in the following:

publicclassMain{
publicstaticvoidmain(Stringargs[]){
inttwoD[][]=newint[4][5];
for(inti=0;i<4;i++){
for(intj=0;j<5;j++){
twoD[i][j]=i*j;/*www.java2s.com*/

[leftIndex][rightIndex]

[0][0][0][1][0][2][0][3][0][4]

39

for(inti=0;i<4;i++){

40

for(intj=0;j<5;j++){

System.out.println();

System.out.print(twoD[i][j]+"");

System.out.println();

This program generates the following output:

}
}

This program generates the following output:

Example
The following program creates a 3 by 4 by 5, three-dimensional array.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
intthreeD[][][]=newint[3][4][5];
for(inti=0;i<3;i++)
for(intj=0;j<4;j++)
for(intk=0;k<5;k++)
threeD[i][j][k]=i*j*k;

Example 2
The following code shows how to iterate over Multidimensional Arrays with for-each.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
intsum=0;
intnums[][]=newint[3][5];

//givenumssomevalues

for(inti=0;i<3;i++){
for(intj=0;j<4;j++){
for(intk=0;k<5;k++)
System.out.print(threeD[i][j][k]+"");
System.out.println();

for(inti=0;i<3;i++)
for(intj=0;j<5;j++)
nums[i][j]=(i+1)*(j+1);

//useforeachfortodisplayandsumthevalues

41

42

for(intx[]:nums){

+++++++++++

for(inty:x){

|||7|8|9|10|

System.out.println("Valueis:"+y);

+++++++

sum+=y;
}

For example, the following code allocates the second dimension manually.

publicclassMain{

System.out.println("Summation:"+sum);

publicstaticvoidmain(String[]argv){

inttwoD[][]=newint[4][];

twoD[0]=newint[5];

The code above generates the following result.

twoD[1]=newint[5];
twoD[2]=newint[5];
twoD[3]=newint[5];
}
}

When allocating dimensions manually, you do not need to allocate the same number
of elements for each dimension.

Example 3
The following program creates a two-dimensional array in which the sizes of the
second dimension are unequal.
publicclassMain{

Jagged array

publicstaticvoidmain(Stringargs[]){

When you allocate memory for a multidimensional array, you can allocate the
remaining dimensions separately.

twoD[0]=newint[1];

An irregular multi-dimension array

twoD[2]=newint[3];

+++++

twoD[3]=newint[4];

|||1|2|

for(inti=0;i<4;i++){

+++++++++

for(intj=0;j<i+1;j++){

|||4|5|6|

twoD[i][j]=i+j;

inttwoD[][]=newint[4][];

twoD[1]=newint[2];

43

44

{0,1,2,3},

for(inti=0;i<4;i++){

{0,1,2,3}

for(intj=0;j<i+1;j++)

};

System.out.print(twoD[i][j]+"");

for(inti=0;i<4;i++){

System.out.println();

for(intj=0;j<4;j++){

System.out.print(m[i][j]+"");

System.out.println();

This program generates the following output:

}
}
}

When you run this program, you will get the following output:

The array created by this program looks like this:

Arithmetic operators are used in mathematical expressions.

All Arithmetic Operators


The following table lists the arithmetic operators:

Example 4
We can initialize multidimensional arrays during declaration by enclosing each
dimension's initializer within its own set of curly braces.

Operator

Result

Addition

Subtraction (unary minus)

Multiplication

publicclassMain{
publicstaticvoidmain(Stringargs[]){
doublem[][]={
{0,1,2,3},
{0,1,2,3},

45

46

Operator

Result

Division

Modulus

++

Increment

System.out.println("IntegerArithmetic");
inta=1+1;
intb=a*3;
intc=b/4;
intd=ca;
inte=d;
System.out.println("a="+a);
System.out.println("b="+b);

+=

Addition assignment

-=

Subtraction assignment

*=

Multiplication assignment

/=

Division assignment

%=

Modulus assignment

--

Decrement

System.out.println("c="+c);
System.out.println("d="+d);
System.out.println("e="+e);

intx=42;
System.out.println("xmod10="+x%10);
doubley=42.25;

System.out.println("ymod10="+y%10);
}
}

When you run this program, you will see the following output:
The operands of the arithmetic operators must be of a numeric type. You cannot use
arithmetic operators on boolean types, but you can use them on char types.
The basic arithmetic operations are addition, subtraction, multiplication, and division.
They behave as you would expect. The minus operator also has a unary form which
negates its single operand.
The quick demo below shows how to do a simple calculation in Java with basic
arithmetic operators.

publicclassMain{
publicstaticvoidmain(Stringargs[]){

47

48

The modulus operator, %, returns the remainder of a division operation. The modulus
operator can be applied to floating-point types as well as integer types.

System.out.println("b="+b);
System.out.println("c="+c);

Java Compound Assignment Operators

Statements like the following

a=a+4;

The output of this program is shown here:

can be rewritten as
a+=4;

Both statements perform the same action: they increase the value of a by 4.
Any statement of the form

Java Increment and Decrement Operator

var=varopexpression;

++ and are Java's increment and decrement operators. The increment


operator,++, increases its operand by one. The decrement operator, , decreases

can be rewritten as

its operand by one.


varop=expression;

Different between Increment and Decrement Operator:

Here is a sample program that shows several op= operator assignments:

For example, this statement:

x=x+1;

publicclassMain{

can be rewritten like this by use of the increment operator:

//fromwww.java2s.com
publicstaticvoidmain(Stringargs[]){

x++;

inta=1;

This statement:

intb=2;

x=x1;

intc=3;

is equivalent to

a+=1;
x;

b*=2;
c+=a*b;

The increment and decrement operators are unique in that they can appear both in
postfix form and prefix form. In the postfix form they follow the operand, for
example,i++. In the prefix form, they precede the operand, for example, i.

c%=3;
System.out.println("a="+a);

49

50

The difference between these two forms appears when the increment and/or
decrement operators are part of a larger expression. In the prefix form, the operand
is incremented or decremented before the value is used in the expression. In postfix
form, the value is used in the expression, and then the operand is modified.

In both cases x is set to 43. The line

The following table summarizes the difference between Pre-and Post- Increment
and Decrement Operations:
Initial Value of x

Expression

Final Value of y

Final Value of x

y = x++

y=x++;

is the equivalent of these two statements:


y=x;
x=x+1;

The following program demonstrates the increment operator.

y = ++x

y = x--

y = --x

publicclassMain{
/*www.java2s.com*/
publicstaticvoidmain(Stringargs[]){
inta=1;
intb=2;
intc=++b;
intd=a++;

For example:

x=42;

System.out.println("a="+a);

y=++x;

System.out.println("b="+b);
System.out.println("c="+c);

y is set to 43, because the increment occurs before x is assigned to y. Thus, the line

System.out.println("d="+d);

y=++x;

is the equivalent of these two statements:


x=x+1;

The output of this program follows:

y=x;

However, when written like this,


x=42;
y=x++;

the value of x is obtained before the increment operator is executed, so the value of
y is 42.

51

The Boolean logical operators operate on boolean operands.

52

Logical Operator List

True table

The following table lists all Java boolean logical operators.

The following table shows the effect of each logical operation:

Operator

Result

A|B

A&B

A^B

!A

&

Logical AND

False

False

False

False

False

True

Logical OR

True

False

True

False

True

False

Logical XOR (exclusive OR)

False

True

True

False

True

True

||

Short-circuit OR

True

True

True

True

False

False

&&

Short-circuit AND

The following program demonstrates the boolean logical operators.

Logical unary NOT

&=

AND assignment

|=

OR assignment

publicclassMain{
publicstaticvoidmain(Stringargs[]){
booleana=true;
booleanb=false;
booleanc=a|b;
booleand=a&b;

^=

XOR assignment

booleane=a^b;
booleanf=(!a&b)|(a&!b);
booleang=!a;

==

Equal to

!=

Not equal to

?:

Ternary if-then-else

System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("a|b="+c);
System.out.println("a&b="+d);
System.out.println("a^b="+e);
System.out.println("!a&b|a&!b="+f);
System.out.println("!a="+g);

53

54

System.out.println("a&b="+d);

System.out.println("a^b="+e);

]]>

System.out.println("~a&b|a&~b="+f);

The output:

System.out.println("~a="+g);

}
}

Here is the output from this program:

Java Logical Operators Shortcut

Example

The OR operator results in true when one operand is true, no matter what the
second operand is. The AND operator results in false when one operand is false, no
matter what the second operand is. If you use the || and &&, Java will not evaluate
the right-hand operand when the outcome can be determined by the left operand
alone.

The following program demonstrates the bitwise logical operators:

The following code shows how you can use short-circuit logical operator to ensure
that a division operation will be valid before evaluating it:

publicclassMain{

publicclassMain{

publicstaticvoidmain(Stringargs[]){

publicstaticvoidmain(String[]argv){

inta=1;

intdenom=0;

intb=2;

intnum=3;

intc=a|b;

if(denom!=0&&num/denom>10){

intd=a&b;

System.out.println("Here");

inte=a^b;

}else{

intf=(~a&b)|(a&~b);

System.out.println("There");

intg=~a&0x0f;

System.out.println("a="+a);

System.out.println("b="+b);
System.out.println("a|b="+c);

55

The output:

56

If we want to turn of the shortcut behaviour of logical operators we can use & and |.

Example 2
The following code uses a single & ensures that the increment operation will be
applied to e whether c is equal to 1 or not.

Operator

Result

==

Equal to

!=

Not equal to

>

Greater than

<

Less than

>=

Greater than or equal to

<=

Less than or equal to

publicclassMain{
publicstaticvoidmain(String[]argv){
intc=0;
inte=99;
intd=0;
if(c==1&e++<100)
d=100;

For example, the following code fragment is perfectly valid. It compares two int
values and assign the result to boolean value c.

System.out.println("eis"+e);
System.out.println("dis"+d);

publicclassMain{

publicstaticvoidmain(String[]argv){
inta=4;

The output:

intb=1;
booleanc=a<b;

Java relational operators determine the relationship between two operands.

System.out.println("cis"+c);
}
}

Relational Operators List

The result of a<b (which is false) is stored in c.

The relational operators in Java are:


Operator

57

Result

58

Example

publicstaticvoidmain(String[]argv){
intdenom=10;

The outcome of a relational operator is a boolean value. In the following code,


theSystem.out.println outputs the result of a relational operator.

intnum=4;
doubleratio;

publicclassMain{

publicstaticvoidmain(Stringargs[]){

ratio=denom==0?0:num/denom;

//outcomeofarelationaloperatorisabooleanvalue

System.out.println("ratio="+ratio);

System.out.println("10>9is"+(10>9));

The output:
The output generated by this program is shown here:

Example

The ? operator is a ternary (three-way) operator.


Java ternary operator is basically a short form of simple if statement.

Syntax
The ? has this general form:

Here is another program that demonstrates the ? operator. It uses it to obtain the
absolute value of a variable.

publicclassMain{
publicstaticvoidmain(Stringargs[]){
inti,k;

expression1?expression2:expression3

expression1 can be any expression that evaluates to a boolean value.


If expression1is true, then expression2 is evaluated. Otherwise, expression3 is

i=10;
k=i<0?i:i;
System.out.print("Absolutevalueof");

evaluated.

System.out.println(i+"is"+k);

The expression evaluated is the result of the ? operation.


Both expression2 andexpression3 are required to return the same type, which can't
be void.

Here is an example of ? operator:

i=10;
k=i<0?i:i;
System.out.print("Absolutevalueof");

System.out.println(i+"is"+k);

publicclassMain{

59

60

Example

The output generated by the program is shown here:


Java if statement is used to execute a block of code based on a condition.

If statement is often used to to compare two variables. The following code defines
two variables, x and y, the it uses the if statement to compare them and prints out
messages.

Java If Statement

publicclassMain{
publicstaticvoidmain(Stringargs[]){

The following the simplest form of Java if statement:

intx,y;

if(condition)

statement;

x=10;

condition is a boolean expression. If condition is true, then the statement is

executed.

y=20;

if(x<y){

If condition is false, then the statement is bypassed.


The following code outputs a message based on the value of an integer. It uses the
if statement to do the check.

System.out.println("xislessthany");
}

publicclassMain{

x=x*2;

publicstaticvoidmain(Stringargs[]){

if(x==y){

intnum=99;

System.out.println("xnowequaltoy");

if(num<100){

System.out.println("numislessthan100");

x=x*2;

if(x>y){

System.out.println("xnowgreaterthany");

The output generated by this program is shown here:

if(x==y){

System.out.println("===");
}
}
}

The output generated by this program is shown here:

61

62

if(condition)
statement1;
else

Example 2

statement2;

The else clause is optional. Each statement may be a single statement or a


compound statement enclosed in curly braces (a block). Only one statement can
appear directly after the if or the else. To include more statements, you'll need to
create a block, as in this fragment.

We can also use a boolean value to control the if statement. The value of
a booleanvariable is sufficient, by itself, to control the if statement.

The following example shows how to use Java ifelse statement.

publicclassMain{
publicstaticvoidmain(Stringargs[]){

booleanb;

publicclassMain{

b=false;

publicstaticvoidmain(String[]argv){

if(b){

inti=1;

System.out.println("Thisisexecuted.");

}else{

if(i>0){

System.out.println("ThisisNOTexecuted.");

System.out.println("Here");

i=1;

}else

System.out.println("There");
}

There is no need to write an if statement like this:

if(b==true)...

]]>

The output generated by this program is shown here:

The output:

Java if else Statement

It is good to include the curly braces when using the if statement, even when there
is only one statement in each clause.

The if statement is a conditional branch statement. We can add else statement to


the if statement.

Java if else ladder statement

Here is the general form of the ifelse statement:

The if else ladder statement is used to work on multiple conditions.

63

64

The if-else-if Ladder looks like this:


if(condition)

Here is the output produced by the program:

statement;
elseif(condition)
statement;
elseif(condition)

Java nested if statement

statement;

A nested if is an if statement inside another another if statement or else.

.
.

The following code uses a nested if statement to compare values.

else

statement;

publicclassMain{

Here is a program that uses an ifelseif ladder.

publicstaticvoidmain(String[]argv){
inti=10;

intj=4;

publicclassMain{
publicstaticvoidmain(Stringargs[]){
intmonth=4;
Stringvalue;
if(month==1)
value="A";
elseif(month==2)
value="B";
elseif(month==3)
value="C";
elseif(month==4)
value="D";
else

intk=200;
inta=3;
intb=5;
intc=0;
intd=0;
if(i==10){
if(j<20){
a=b;
}
if(k>100){
c=d;
}
else{

value="Error";

a=c;
}

System.out.println("value="+value);

}else{

a=d;

65

66

casevalueN:

System.out.println("a="+a);

statementsequence

System.out.println("b="+b);

break;

System.out.println("c="+c);

default:

System.out.println("d="+d);

defaultstatementsequence

The value1 to valueN are the possible case values for expression. Duplicate case
values are not allowed.

The output:

A break statement jumps out of switch statement to the first line that follows the
entireswitch statement.
Here is a simple example that uses a switch statement:

publicclassMain{
publicstaticvoidmain(Stringargs[]){

The switch statement is a multiway branch statement. It provides a better


alternative than a large series of ifelseif statements.

for(inti=0;i<6;i++)
switch(i){
case0:

Java switch Statement

System.out.println("iiszero.");
break;

Here is the general form of a switch statement:

switch(expression){

case1:

casevalue1:

System.out.println("iisone.");

statementsequence

break;

break;

casevalue2:

case2:

statementsequence

System.out.println("iistwo.");

break;

break;

case3:

System.out.println("iisthree.");
break;

67

68

System.out.println("iislessthan5");

default:

break;

System.out.println("iisgreaterthan3.");

case5:

case6:

case7:

case8:
case9:

The output produced by this program is shown here:

System.out.println("iislessthan10");

break;
default:
System.out.println("iis10ormore");
}
}
}

This program generates the following output:

Example
The break statement is optional. If you omit the break, execution will continue on into
the next case. For example, consider the following program:

publicclassMain{
publicstaticvoidmain(Stringargs[]){
for(inti=0;i<12;i++)
switch(i){

case0:
case1:

Example 2

case2:
case3:

Java supports the nested switch statements. For example, the following fragment is
a valid nested switch statement.

case4:
publicclassMain{

69

70

publicstaticvoidmain(Stringargs[]){

charp='a';

for(inti=0;i<6;i++)

switch(i){

Stringdetails="";

case0:

switch(i+1){//nestedswitch

switch(p){

case0:

case'E':

System.out.println("targetiszero");

case'e':

break;

details+="\tE...\n";

case1:

case'D':

System.out.println("targetisone");

case'd':

break;

details+="\tD...\n";

case'C':

break;

case'c':

case2://...

details+="\tC...\n";

case'B':

case'b':

details+="\tB...\n";

The output:

case'A':
case'a':
details+="\tA.\n";
break;
default:

Example 3

details="That's";

The following code shows how to switch with char value.

break;

System.out.println(details);
importjava.util.Scanner;

}
}

publicclassMain{
staticScannersc=newScanner(System.in);

The code above generates the following result.

publicstaticvoidmain(String[]args){

71

72

The simplest form of the for loop is shown here:

Example 4

for(initialization;condition;iteration)

The following code shows how to use string literals in switch statements.

statement;

publicclassMain{

Java for loop statement has three parts:

publicstaticvoidmain(String[]args){

String[]data=newString[]{"a","b","java2s.com"};
for(Stringargument:data){
switch(argument){

initialization sets a loop control variable to an initial value.


condition is a Boolean expression that tests the loop control variable. If condition is true,

the for loop continues to iterate. If condition is false, the loop terminates.
The iteration determines how the loop control variable is changed each time the loop
iterates.

case"a":
case"b":

System.out.println("java2s.com");

Here is a short program that illustrates the for loop. i is the loop control variable
and iis initialized to zero in the initialization. At the start of each iteration, the
conditional testx<10 is performed. If the outcome of this test is true,
the println() statement is executed, and then the iteration portion of the loop is
executed. This process continues until the conditional test is false.

break;

publicclassMain{

case"help":

publicstaticvoidmain(Stringargs[]){

System.out.println("displayHelp");

inti;

break;

default:

for(i=0;i<10;i=i+1)

System.out.println("Illegalcommandlineargument");

System.out.println("Thisisi:"+i);

System.out.println("aorb");
break;
case"java2s.com":

This program generates the following output:

}
}

The code above generates the following result.

Java for loop statement provides a powerful way of writing loop statement.

73

74

Example

Example 2

The following code writes the code logic from above again but loops reversively:

Here is a program that tests for prime numbers using for loop statement.

publicclassMain{

publicclassMain{

publicstaticvoidmain(Stringargs[]){

publicstaticvoidmain(Stringargs[]){

for(intn=10;n>0;n)

intnum;

System.out.println("n:"+n);

booleanisPrime=true;

num=50;

}]]>

for(inti=2;i<=num/2;i++){

The output:

if((num%i)==0){
isPrime=false;
break;
}
}
if(isPrime)
System.out.println("Prime");
else
System.out.println("NotPrime");

75

76

publicclassMain{
publicstaticvoidmain(Stringargs[]){

The output:

inti=0;

booleandone=false;
for(;!done;){

Example 3

System.out.println("iis"+i);
if(i==10)

Java allows two or more variables to control a for loop. And you can include
multiple statements in both the initialization and iteration portions of the for loop.
Each statement is separated from the next by a comma. Here is an example:

done=true;
i++;

publicclassMain{

publicstaticvoidmain(Stringargs[]){

for(inta=1,b=4;a<b;a++,b){

The output:

System.out.println("a="+a);
System.out.println("b="+b);

}
}
}

The program generates the following output:

Example 4
The three sections of the for can be used for any purpose and parts of the for loop
can be empty.

77

Example 5
for loop can be nested to produce powerful logic, for example, we can use
nestedfor loop to iterate a two-dimensional array. For example, here is a program
that nestsfor loops:

78

The following code shows how to use for each loop.

publicclassMain{

publicclassMain{

publicstaticvoidmain(Stringargs[]){

publicstaticvoidmain(Stringargs[]){

for(inti=0;i<10;i++){

String[]arr=newString[]{"java2s.com","a","b","c"};

for(intj=i;j<10;j++)

for(Strings:arr){

System.out.print(".");

System.out.println(s);

System.out.println();

The output:
The output produced by this program is shown here:

Example 6
The following code uses the foreach style loop to iterate a two-dimensional array.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
intsum=0;

Java for each loop

intnums[][]=newint[3][5];

The foreach loop iterates elements in a sequence without using the loop counter.

for(intj=0;j<5;j++){

The syntax of foreach loop is:

nums[i][j]=(i+1)*(j+1);

for(typevariable_name:array){

}
}

//useforeachfortodisplayandsumthevalues

for(intx[]:nums){

The type must be compatible with the array type.

79

for(inti=0;i<3;i++){

for(inty:x){

80

System.out.println("Valueis:"+y);

break;

sum+=y;

if(found)

System.out.println("Summation:"+sum);

System.out.println("Valuefound!");

The output from this program is shown here:

The code above generates the following result.

The while loop repeats a statement or block while its controlling condition is true.

Java while Loop


Here is its general form:
while(condition){
//bodyofloop
}

Example 7

The condition can be any Boolean expression.


The body of the loop will be executed as long as the conditional condition is true.
The curly braces are unnecessary if only a single statement is being repeated.

foreach style loop is useful when searching an element in an array.

Here is a while loop that counts down from 10, printing exactly ten lines of "tick":
publicclassMain{

publicstaticvoidmain(Stringargs[]){

publicclassMain{

intnums[]={6,8,3,7,5,6,1,4};

publicstaticvoidmain(Stringargs[]){

intval=5;

intn=10;

booleanfound=false;

while(n>0){

//useforeachstylefortosearchnumsforval

System.out.println("n:"+n);

for(intx:nums){

n;

if(x==val){

found=true;

81

82

}
}

When you run this program, you will get the following result:

Example 2
The body of the while loop will not execute if the condition is false. For example, in
the following fragment, the call to println() is never executed:

publicclassMain{
publicstaticvoidmain(String[]argv){
inta=10,b=20;
while(a>b){
System.out.println("Thiswillnotbedisplayed");

Example
The following code shows how to use the while loop to calculate sum.
publicclassMain{

}
System.out.println("Youarehere");
}
}

The output:

publicstaticvoidmain(String[]args){
intlimit=20;
intsum=0;
inti=1;

while(i<=limit){

Example 3
The body of the while can be empty. For example, consider the following program:

sum+=i++;

}
System.out.println("sum="+sum);

publicclassMain{
publicstaticvoidmain(Stringargs[]){

inti,j;

i=10;

The code above generates the following result.

83

j=20;

84

The output:

//findmidpointbetweeniandj
while(++i<j)
;
System.out.println("Midpointis"+i);
}
}

The while loop in the code above has no loop body and i and j are calculated in
the while loop condition statement. It generates the following output:

Java do while loop


To execute the body of a while loop at least once, you can use the do-while loop.
The syntax for Java do while loop is:

The loop in the preceding program can be written as follows:


publicclassMain{
publicstaticvoidmain(Stringargs[]){
intn=10;

do{

do{

//bodyofloop

System.out.println("n:"+n);

}while(condition);

}while(n>0);

Here is an example to show how to use a dowhile loop.

}
}

publicclassMain{

The output is identical the result above:

publicstaticvoidmain(Stringargs[]){
intn=10;
do{
System.out.println("n:"+n);
n;
}while(n>0);
}
}

85

86

System.out.println("A");
break;
case'2':
System.out.println("B");
break;
case'3':
System.out.println("C");
break;
case'4':
System.out.println("D");
break;

Example 4

case'5':

The following program implements a very simple help system with dowhile loop
andswitch statement.

break;

publicclassMain{

publicstaticvoidmain(Stringargs[])throwsjava.io.IOException{

System.out.println("E");

Here is a sample run produced by this program:

charchoice;
do{
System.out.println("Helpon:");
System.out.println("1.A");
System.out.println("2.B");
System.out.println("3.C");
System.out.println("4.D");
System.out.println("5.E");
System.out.println("Chooseone:");
choice=(char)System.in.read();
}while(choice<'1'||choice>'5');
System.out.println("\n");
switch(choice){

A class defines a new data type.


This new type can be used to create objects of that type.
A class is a template for an object, and an object is an instance of a class.

case'1':

87

88

Syntax

classBox{
intwidth;

The general form of a class definition is shown here:

intheight;

classclassname{

intdepth;

typeinstancevariable1;

typeinstancevariable2;
//...

Java Object

typeinstancevariableN;

When you create a class, you are creating a new data type. You can use this type to
declare objects of that type.

typemethodname1(parameterlist){

Creating objects of a class is a two-step process.

//bodyofmethod

}
typemethodname2(parameterlist){

Declare a variable of the class type.


Use the new operator to dynamically allocates memory for an object.

The following line is used to declare an object of type Box:

//bodyofmethod
Boxmybox=newBox();

}
//...
typemethodnameN(parameterlist){

This statement combines the two steps. It can be rewritten like this to show each
step more clearly:

//bodyofmethod
Boxmybox;//declarereferencetoobject

mybox=newBox();//allocateaBoxobject

A class is declared by using the class keyword.


The methods and variables defined within a class are called class members.
Variables defined within a class are called instance variables because each instance
of the class contains its own copy of these variables.
The data for one object is separate and unique from the data for another.

Example
Here is a class called Box that defines three member variables: width, height,
anddepth.

The first line declares mybox as a reference to an object of type Box. After this line
executes, mybox contains the value null. null indicates that mybox does not yet point
to an actual object.
Any attempt to use mybox at this point will result in an error.
The next line allocates an actual object and assigns a reference to mybox. After the
second line executes, you can use mybox as a Box object.
mybox holds the memory address of the actual Box object.

A class defines a new type of data. In this case, the new type is called Box. To
create aBox object, you will use a statement like the following:

classBox{

89

90

intwidth;

myBox.width=10;

intheight;

intdepth;

}
publicclassMain{

If you try to compile the code above, you will get the following error message from
the Java compiler.

publicstaticvoidmain(Stringargs[]){
BoxmyBox=newBox();

Java instanceof operator

myBox.width=10;

Java provides the run-time operator instanceof to check class type for an object.

System.out.println("myBox.width:"+myBox.width);

The instanceof operator has this general form:

objectinstanceoftype

The following program demonstrates instanceof:


The output:

classA{

myBox is an instance of Box. mybox contains its own copy of each instance
variable,width, height, and depth, defined by the class. To access these variables,
you will use the dot (.) operator.
mybox.width=10;

classB{
}

This statement assigns the width from mybox object to 10. Here is a complete
program that uses the Box class:

classCextendsA{
}

Any attempt to use a null mybox will result in a compile-time error.

classBox{

classDextendsA{

intwidth;

intheight;

intdepth;

publicclassMain{

publicstaticvoidmain(Stringargs[]){

Aa=newA();

publicclassMain{

Bb=newB();

publicstaticvoidmain(Stringargs[]){

Cc=newC();

BoxmyBox;

Dd=newD();

91

92

System.out.println("bmaybecasttoObject");

if(ainstanceofA)

if(cinstanceofObject)

System.out.println("aisinstanceofA");

System.out.println("cmaybecasttoObject");

if(binstanceofB)

if(dinstanceofObject)

System.out.println("bisinstanceofB");

System.out.println("dmaybecasttoObject");

if(cinstanceofC)

System.out.println("cisinstanceofC");

if(cinstanceofA)
System.out.println("ccanbecasttoA");

The output from this program is shown here:

if(ainstanceofC)
System.out.println("acanbecasttoC");

Aob;
ob=d;//Areferencetod
System.out.println("obnowreferstod");
if(obinstanceofD)
System.out.println("obisinstanceofD");

ob=c;//Areferencetoc
System.out.println("obnowreferstoc");
if(obinstanceofD)
System.out.println("obcanbecasttoD");

Classes usually consist of two things: instance variables and methods. Instance
variables are the data part of a class, while the methods defines the behaviours of a
class.

else
System.out.println("obcannotbecasttoD");

if(obinstanceofA)
System.out.println("obcanbecasttoA");
//allobjectscanbecasttoObject
if(ainstanceofObject)

Syntax
This is the general form of a method:
typename(parameterlist){
//bodyofmethod
}

System.out.println("amaybecasttoObject");
if(binstanceofObject)

93

94

type specifies the type of data returned by the method. If the method does not return
a value, its return type must be void. The name of the method is specified by name.
The parameter-list is a sequence of type and identifier pairs separated by commas.

Parameters receives the value of the arguments passed to the method.

Java Method Return

If the method has no parameters, then the parameter list will be empty.

A method in a class can return a value with the return statement.

Add a method to Box,as shown here:

Methods that have a return type other than void return a value to the calling routine
using the following form of the return statement:

classBox{
intwidth;
intheight;

returnvalue;

Here, value is the value returned.


We can use return statement to return a value to the callers.

intdepth;
voidcalculateVolume(){

System.out.print("Volumeis");

classRectangle{

System.out.println(width*height*depth);

intwidth;

intheight;

intgetArea(){

publicclassMain{

returnwidth*height;

publicstaticvoidmain(Stringargs[]){

Boxmybox1=newBox();

mybox1.width=10;

publicclassMain{

mybox1.height=20;

mybox1.depth=15;

publicstaticvoidmain(Stringargs[]){

Rectanglemybox1=newRectangle();

mybox1.calculateVolume();

intarea;

mybox1.width=10;

mybox1.height=20;

area=mybox1.getArea();

This program generates the following output:

System.out.println("Areais"+area);

95

96

publicstaticvoidmain(Stringargs[]){

MyClassob1=newMyClass();

The output:

ob1.myMemberValue=2;
MyClassob2;

ob2=ob1.doubleValue();

In this line the return statement returns value from the getArea()method. And the
returned value is assigned to area.

System.out.println("ob1.a:"+ob1.myMemberValue);
System.out.println("ob2.a:"+ob2.myMemberValue);

area=mybox1.getArea();

The actual returned data type must be compatible with the declared return type .
The variable receiving the returned value (area) must be compatible with the return
type.

ob2=ob2.doubleValue();
System.out.println("ob2.aaftersecondincrease:"+ob2.myMemberValue);
}

The following code uses the returned value directly in a println( ) statement:

System.out.println("Areais"+mybox1.getArea());

The output generated by this program is shown here:

Example
A method can return class types.

classMyClass{
intmyMemberValue=2;
MyClass(){
}

ava Method Parameters


Parameters allow a method to be generalized by operating on a variety of data
and/or be used in a number of slightly different situations.
This is the general form of a method:

MyClassdoubleValue(){
MyClasstemp=newMyClass();

typemethodName(parameterTypevariable,parameterType2variable2,...){

temp.myMemberValue=temp.myMemberValue*2;

//bodyofmethod

returntemp;

A parameterized method can operate on a variety of data.

The new Rectangle class has a new method which accepts the dimensions of a
rectangle and sets the dimensions with the passed-in value.

publicclassMain{

97

98

classRectangle{

Example 2

doublewidth;
doubleheight;

The following code passes objects to methods.

doublearea(){

classTest{

returnwidth*height;

inta;

Test(inti){

voidsetDim(doublew,doubleh){//Methodwithparameters

a=i;

width=w;

height=h;

booleanequals(Testo){

if(o.a==a)

returntrue;

else

publicclassMain{

returnfalse;

publicstaticvoidmain(Stringargs[]){

Rectanglemybox1=newRectangle();

doublevol;

publicclassMain{

mybox1.setDim(10,20);

publicstaticvoidmain(Stringargs[]){

Testob1=newTest(100);

vol=mybox1.area();

Testob2=newTest(100);

System.out.println("Areais"+vol);

System.out.println("ob1==ob2:"+ob1.equals(ob2));

The output:

This program generates the following output:

99

100

Java Method Overload

doubleresult=ob.test(123.25);
System.out.println("Resultofob.test(123.25):"+result);

Java allows to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different.
When this is the case, the methods are said to be overloaded, and the process is
referred to as method overloading.
Overloaded methods have the same name but different parameters. Overloaded
methods must differ in the type and/or number of their parameters. Overloaded
methods may have different return types. return type alone is insufficient to
distinguish two methods.

}
}

This program generates the following output:

The following example illustrates method overloading:

classOverloadDemo{
voidtest(){
System.out.println("Noparameters");
}
voidtest(inta){

Example 3
The following code demonstrates method overloading and data type promotion.

System.out.println("a:"+a);

}
voidtest(inta,intb){
System.out.println("aandb:"+a+""+b);

classOverloadDemo{
voidtest(){
System.out.println("Noparameters");

}
doubletest(doublea){
System.out.println("doublea:"+a);
returna*a;

}
voidtest(inta,intb){
System.out.println("aandb:"+a+""+b);
}

voidtest(doublea){

}
publicclassMain{
publicstaticvoidmain(Stringargs[]){
OverloadDemoob=newOverloadDemo();
ob.test();
ob.test(10);
ob.test(10,20);

101

System.out.println("Insidetest(double)a:"+a);
}
}

publicclassMain{
publicstaticvoidmain(Stringargs[]){

102

OverloadDemoob=newOverloadDemo();

inti=88;

ob.test();

publicclassMain{

ob.test(10,20);

publicstaticvoidmain(Stringargs[]){

Factorialf=newFactorial();

ob.test(i);//thiswillinvoketest(double)

ob.test(123.2);//thiswillinvoketest(double)

System.out.println("Factorialof5is"+f.fact(5));

This program generates the following output:

The output from this program is shown here:

Java main() Method


Java Method Recursion
Recursion allows a method to call itself.
The following code is an example of recursion. It calculates the factorial numbers.

The main() method is the entry point for standalone Java applications. To create an
application, you write a class definition that includes a main() method. To execute
an application, type java at the command line, followed by the name of the class
containing the main() method.

Syntax for main() method

classFactorial{
//thisisarecursivefunction

The signature for main() is:


publicstaticvoidmain(String[]args)

intfact(intn){
intresult;

The return type must be void. The main() method must be public. It is static so that
it can be executed without constructing an instance of the application class.

result=fact(n1)*n;

A command-line argument is the information that follows the program's name on the
command line. The command-line arguments are stored as string array passed to
main(). For example, the following program displays all of the command-line
arguments:

returnresult;

publicclassMain{

if(n==1)
return1;

103

104

publicstaticvoidmain(Stringargs[]){

}catch(NumberFormatExceptione){

for(inti=0;i<args.length;i++)

System.err.println("Number"+argv[0]+"invalid("+e.getMessage()+
").");

System.out.println("args["+i+"]:"+args[i]);

System.exit(1);

}else{

Try executing this program, as shown here:

System.err.println("usage:UseArgvnumber");
System.exit(1);
}

When you do, you will see the following output:

System.out.println("OK,numberis"+number);
}
}

The code above generates the following result.

Example 4

A constructor initializes an object during object creation when using new operator.

The following code shows how to use of argv to get an integer value from command
line.

Java allows objects to initialize themselves when they are created. This automatic
initialization is performed through the use of a constructor.

publicclassMain{

Syntax

publicstaticvoidmain(String[]argv){

It has the same name as the class. Constructors have no return type, not even void.

intnumber=0;

classClassName{

System.out.println("Thenumberofwordsinargvis"+argv.length);

ClassName(parameterlist){//constructor

if(argv.length==0){

...

number=1234;

}elseif(argv.length==1){

try{
number=Integer.parseInt(argv[0]);

105

106

In the following code the Rectangle class in the following uses a constructor to set
the dimensions:

Java Default Constructor

A default constructor is a constructor with no parameters.

classRectangle{
doublewidth;//

Syntax for Java Default Constructor

doubleheight;

Syntax for Java Default Constructor

classClassName{

Rectangle(){

width=10;

ClassName(){//defaultconstructor

height=10;

...

doublearea(){
returnwidth*height;

In the following code the constructor Rectangle() is the default constructor.

classRectangle{

doublewidth;//

publicclassMain{

doubleheight;

publicstaticvoidmain(Stringargs[]){

Rectanglemybox1=newRectangle();

Rectangle(){

doublearea;

width=10;

area=mybox1.area();

height=10;

System.out.println("Areais"+area);

doublearea(){

returnwidth*height;

When this program is run, it generates the following results:

}
}

publicclassMain{
publicstaticvoidmain(Stringargs[]){

107

108

Rectanglemybox1=newRectangle();

Rectanglemybox1=newRectangle();

doublearea;

doublearea;

area=mybox1.area();

area=mybox1.area();

System.out.println("Areais"+area);

System.out.println("Areais"+area);

If you don't declare a default constructor the Java compiler will add one for you.
When you call the default constructor added by Java compiler the class member
variables are initialized by default value. If you do provide a default constructor the
Java compiler would not insert one for you.

The output:

The code above generates the following result.

Java Constructor Parameters

Example

The constructors can also have parameters. Usually the parameters are used to set
the initial states of the object.

In the following code we removes the default constructor from class Rectangle.
When we compile the class Java compiler adds the default constructor for us so we
can still construct a Rectangle object by calling the default constructor. But the value
of widthand height would be initialized to 0.0.

Syntax for Java Constructor Parameters


Syntax for Java Constructor Parameters

classClassName{

classRectangle{

doublewidth;//

ClassName(parameterTypevariable,parameterType2variable2,...){//constructor

doubleheight;

...

doublearea(){

returnwidth*height;
}

In the the following demo code Rectangle class uses the parameters, w for width
andh for height, from the constructors to initialize its width and height.

publicclassMain{
publicstaticvoidmain(Stringargs[]){

109

classRectangle{
doublewidth;//

110

doubleheight;

classRectangle{

doublewidth;

Rectangle(doublew,doubleh){

doubleheight;

width=w;

height=h;

Rectangle(Rectangleob){//passobjecttoconstructor

width=ob.width;

height=ob.height;

doublearea(){

returnwidth*height;

Rectangle(doublew,doubleh){

width=w;

height=h;

publicclassMain{

publicstaticvoidmain(Stringargs[]){

Rectanglemybox1=newRectangle(10,20);

//constructorusedwhennodimensionsspecified

doublearea;

Rectangle(){

area=mybox1.area();

width=1;//use1toindicate

System.out.println("Areais"+area);

height=1;//anuninitialized

The output from this program is shown here:

//constructorusedwhencubeiscreated
Rectangle(doublelen){
width=height=len;
}

Example 2

doublearea(){

Just like methods in a class the constructors can not only accept primitive type
parameters it can also have the object parameters. Object parameters contains
more information and can help us initialize the class.
The following Rectangle class has a constructor whose parameter is
a Rectangleclass. In this way we can initialize a rectangle by the data from another
rectangle.

}
}

publicclassMain{
publicstaticvoidmain(Stringargs[]){

111

returnwidth*height;

112

Rectanglemybox1=newRectangle(10,20);

width=w;

Rectanglemyclone=newRectangle(mybox1);

height=h;

doublearea;

//getvolumeoffirstbox

area=mybox1.area();

//constructorusedwhennodimensionsspecified

System.out.println("Areaofmybox1is"+area);

Rectangle(){

//getvolumeofclone

width=1;//use1toindicate

area=myclone.area();

height=1;//anuninitialized

System.out.println("Areaofcloneis"+area);

Rectangle(doublelen){

The output:

width=height=len;
}

doublearea(){
returnwidth*height;

Java Constructors Overload

Method overloading is to declare two or more methods with the name but different
type or count of parameters.

In addition to overloading normal methods, you can also overload constructor


methods.

publicstaticvoidmain(Stringargs[]){

In the following code Rectangle defines three constructors to initialize the


dimensions of a rectangle in various ways.

Rectanglemybox2=newRectangle();

classRectangle{

doublewidth;/*

doublearea=mybox1.area();

doubleheight;

System.out.println(area);

//constructorusedwhenalldimensionsspecified

area=mybox2.area();

Rectangle(doublew,doubleh){

System.out.println(area);

113

publicclassMain{

Rectanglemybox1=newRectangle(10,20);

Rectanglemycube=newRectangle(7);

114

area=mycube.area();

//initializeaandbtothesamevalue

System.out.println(area);

MyClass(inti){

this(i,i);//invokesMyClass(i,i)

The output produced by this program is shown here:

//giveaandbdefaultvaluesof0
MyClass(){
this(0);//invokesMyClass(0)
}
}

this()

Three types of class variables

In Java this keyword can call the overloaded constructors. The general form is
shown here:

Java supports variables of three different lifetimes:

this(arglist)

When this() is executed, the overloaded constructor that matches the arg-list is
executed first.
The call to this() must be the first statement within a constructor.
The following code defines a class named MyClass. It has three constructors. The
first constructor accepts two int values. The second accepts one int type value. The
third one accepts no value.
classMyClass{
inta;
intb;

Member variable
Method local variables
Static variable

Class member variable


A member variable of a class is created when an instance is created, and it is
destroyed when the object is destroyed. All member variables that are not explicitly
assigned a value during declaration are automatically assigned an initial value. The
initialization value for member variables depends on the member variable's type.
The following table lists the initialization values for member variables:
Element Type

Initial Value

byte

short

//initializeaandbindividually
MyClass(inti,intj){
a=i;
b=j;
}

115

116

Element Type

Initial Value

int

long

0L

float

0.0f

Strings;

publicMyClass(){
System.out.println("i="+i);
System.out.println("b="+b);
System.out.println("f="+f);
System.out.println("d="+d);
System.out.println("s="+s);
}

double

0.0d

char

'\u0000'

boolean

false

object reference

null

publicclassMain{
publicstaticvoidmain(String[]argv){
newMyClass();

In the following example, the variable x is set to 20 when the variable is declared.

publicclassMain{

The output:

intx=20;
}

The following example shows the default value if you don't set them.
classMyClass{//
inti;

booleanb;

Example for method local variables

floatf;

An automatic variable of a method is created on entry to the method and exists only
during execution of the method. Automatic variable is accessible only during the
execution of that method. (An exception to this rule is inner classes).

doubled;

117

118

Automatic variable(method local variables) are not initialized by the system.


Automatic variable must be explicitly initialized before being used. For example, this
method will not compile:

publicclassMain{

Hidden instance variables and this

publicintwrong(){

Use this to reference the hidden instance variables.

inti;

Member variables and method parameters may have the same name. Under this
situation we can use this to reference the member variables.

returni+5;
}

Rectangle(doublewidth,doubleheight){

this.width=width;

this.height=height;

The output when compiling the code above:

Class variable (static variable)


There is only one copy of a class variable, and it exists regardless of the number of
instances of the class. Static variables are initialized at class load time; here y would
be set to 30 when the Main class is loaded.
publicclassMain{
staticinty=30;

The following example shows how to use this to reference instance variable.
classPerson{
privateStringname;

publicPerson(Stringname){
this.name=name;
}
publicStringgetName(){

returnname;

Java this Keyword

this refers to the current object.

this.name=name;

this can be used inside any method to refer to the current object.

The following code shows how to use this keyword.

publicvoidsetName(Stringname){

}
publicclassMain{

//Auseofthis.

publicstaticvoidmain(String[]args){

Rectangle(doublew,doubleh){

Personperson=newPerson("Java");

this.width=w;//thisisusedhere

System.out.println(person.getName());

this.height=h;

person.setName("newname");

119

120

System.out.println(person.getName());

voidsum(){

System.out.println("i+j+k:"+(i+j+k));

}
}

The code above generates the following result.

publicclassMain{

publicstaticvoidmain(Stringargs[]){
BasesuperOb=newBase();
ChildsubOb=newChild();

In Java the classes can inherit attributes and behavior from pre-existing classes.
The pre-existing classes are called base classes, superclasses, or parent classes.
The new classes are known as derived classes, subclasses, or child classes. The
relationships of classes through inheritance form a hierarchy.
Let's look at an example. Suppose we have a class called Employee. It defines first
name, last name. Then we want to create a class called Programmer. Programmer
would have first name and last name as well. Rather than defining the first name
and last name again for Programmer we can let Programmer inherit from Employee.
In this way the Programmer would have attributes and behavior from Employee.
To inherit a class, you can use the extends keyword.

superOb.i=10;
superOb.showBase();
System.out.println();

subOb.i=7;
subOb.showBase();
subOb.showChild();
System.out.println();

The following program creates a superclass called Base and a subclass


called Child.

classBase{

inti,j;
voidshowBase(){

subOb.sum();

The output from this program is shown here:

System.out.println("iandj:"+i+""+j);
}
}
classChildextendsBase{
intk;
voidshowChild(){
System.out.println("k:"+k);
}

121

122

The subclass Child includes all of the members of its superclass. The general form
of a class declaration that inherits a superclass is shown here:

depth=ob.depth;

classsubclassnameextendssuperclassname{

Box(doublew,doubleh,doubled){

//bodyofclass

width=w;

height=h;

You can only have one superclass for any subclass. Java does not support the
multiple inheritance. A class can be a superclass of itself.

depth=d;
}
doublevolume(){

Java super keyword

returnwidth*height*depth;
}

You can use super in a subclass to refer to its immediate superclass. super has two
general forms.

}
classBoxWeightextendsBox{

1. The first calls the superclass' constructor.


2. The second is used to access a member of the superclass.

doubleweight;//weightofbox
BoxWeight(Boxob){//passobjecttoconstructor

Call superclass constructors

super(ob);

To call a constructor from its superclass:

publicclassMain{
super(parameterlist);

parameterlist is defined by the constructor in the superclass.


super(parameterlist) must be the first statement executed inside a subclass' constructor.

publicstaticvoidmain(Stringargs[]){
Boxmybox1=newBox(10,20,15);
BoxWeightmyclone=newBoxWeight(mybox1);
doublevol;

Here is a demo for how to use super to call constructor from parent class.

vol=mybox1.volume();

classBox{

System.out.println("Volumeofmybox1is"+vol);

privatedoublewidth;

privatedoubleheight;

privatedoubledepth;

This program generates the following output:

Box(Boxob){//passobjecttoconstructor

width=ob.width;
height=ob.height;

123

124

Reference members from parent class

We can reference member variable from parent class with super keyword. Its
general form is:
super.member

member can be either a method or an instance variable.

Let's look at the following code.

Java Method Overriding


Method Overriding happens when a method in a subclass has the same name and
type signature as a method in its superclass.

When an overridden method is called within a subclass, it will refer to the method
defined in the subclass.

classBase{

The method defined by the superclass will be hidden. Consider the following:

inti;

classBase{

classSubClassextendsBase{
inti;//thisihidestheiinA
SubClass(inta,intb){
super.i=a;//iinA
i=b;//iinB
}

inti;
Base(inta){
i=a;
}
voidshow(){
System.out.println("i:"+i);

voidshow(){
System.out.println("iinsuperclass:"+super.i);
System.out.println("iinsubclass:"+i);
}

}
}
classSubClassextendsBase{
intk;

SubClass(inta,intc){

publicclassMain{
publicstaticvoidmain(Stringargs[]){
SubClasssubOb=newSubClass(1,2);
subOb.show();
}

super(a);
k=c;
}
voidshow(){
System.out.println("k:"+k);

This program displays the following:

}
publicclassMain{
publicstaticvoidmain(Stringargs[]){

125

126

SubClasssubOb=newSubClass(1,3);

subOb.show();

voidshow(){

super.show();//thiscallsA'sshow()

System.out.println("k:"+k);

The output produced by this program is shown here:

}
}

super and overridden method

publicclassMain{
publicstaticvoidmain(String[]argv){

To access the superclass version of an overridden function, you can do so by


usingsuper.

SubClasssub=newSubClass(1,2);

classBase{

inti;

sub.show();

The following output will be generated if you run the code above:

Base(inta){
i=a;
}

voidshow(){
System.out.println("i:"+i);
}
}

Method overriding vs method overload


Method overriding occurs when the names and the type signatures of the two
methods are identical. If not, the two methods are overloaded. For example,
consider this modified version of the preceding example:

classSubClassextendsBase{

classBase{

intk;

inti;

Base(inta){

SubClass(inta,intc){

i=a;

super(a);

k=c;

voidshow(){

System.out.println("i:"+i);

127

128

System.out.println("InsideA'sconstructor.");

classSubClassextendsBase{

intk;

SubClass(inta,intc){

//CreateasubclassbyextendingclassA.

super(a);

classBextendsA{

k=c;

B(){

System.out.println("InsideB'sconstructor.");

voidshow(Stringmsg){

System.out.println(msg+k);

//CreateanothersubclassbyextendingB.

publicclassMain{

classCextendsB{

publicstaticvoidmain(Stringargs[]){

C(){

SubClasssubOb=newSubClass(1,2);

System.out.println("InsideC'sconstructor.");

subOb.show("Thisisk:");

subOb.show();

publicclassMain{

The output produced by this program is shown here:

publicstaticvoidmain(Stringargs[]){
Cc=newC();
}
}

The output from this program is shown here:

Java Constructor in hierarchy


In a class hierarchy, constructors are called in order of derivation, from superclass to
subclass.
The following program illustrates when constructors are executed:

classA{
A(){

129

130

Polymorphism

r.callme();
r=b;

With polymorphism we can call methods from class hierarchy using a uniform
interface. The compiler will determine dynamically which implementation to use.

r.callme();
r=c;

Dynamic Method Dispatch

r.callme();

When an overridden method is called through a superclass reference, Java


determines which version of that method to execute.

Here is an example that illustrates dynamic method dispatch:

The output from the program is shown here:

classBase{
voidcallme(){
System.out.println("InsideA'scallmemethod");
}

Polymorphism Example

}
classSubClassextendsBase{
voidcallme(){
System.out.println("InsideB'scallmemethod");
}
}
classSubClass2extendsBase{

The following example uses the run-time polymorphism. It has three classes. The
parent class is Shape. Rectangle and Triangle are both extending
the Shape class.Shape defines a method called area() which returns the area of a
shape. Both Rectangle and Triangle override area() method and provide their own
version of implementation. When calling the area() method we can call it from the
same object reference and Java compiler can figure out which area() method to
use.

voidcallme(){

System.out.println("InsideC'scallmemethod");

classShape{

doubleheight;

doublewidth;

publicclassMain{

Shape(doublea,doubleb){

publicstaticvoidmain(Stringargs[]){

height=a;

Basea=newBase();

width=b;

SubClassb=newSubClass();

SubClass2c=newSubClass2();

doublearea(){

Baser;

System.out.println("AreaforFigureisundefined.");

r=a;

return0;

131

132

figref=t;

classRectangleextendsShape{

System.out.println("Areais"+figref.area());

Rectangle(doublea,doubleb){

super(a,b);

figref=f;

System.out.println("Areais"+figref.area());

//overrideareaforrectangle

doublearea(){

System.out.println("InsideAreaforRectangle.");
returnheight*width;

The output from the program is shown here:

}
}
classTriangleextendsShape{
Triangle(doublea,doubleb){
super(a,b);
}
//overrideareaforrighttriangle
doublearea(){
System.out.println("InsideAreaforTriangle.");
returnheight*width/2;
}
}
publicclassMain{

interface specifies what a class must do, but not how it does it.

An interface in Java is like a contract. It defines certain rules through Java


methods and the class which implements that interface must follow the rules by
implementing the methods.
To implement an interface, a class must create the complete set of methods
defined by the interface.

publicstaticvoidmain(Stringargs[]){
Shapef=newShape(10,10);
Rectangler=newRectangle(9,5);
Trianglet=newTriangle(10,8);

Syntax
An interface is defined much like a class. This is the general form of an interface:

accessinterfacename{

Shapefigref;

returntypemethodname1(parameterlist);

returntypemethodname2(parameterlist);

figref=r;

System.out.println("Areais"+figref.area());

typefinalvarname1=value;

133

134

typefinalvarname2=value;

//ImplementCallback'sinterface

publicvoidcallback(intp){

//...

returntypemethodnameN(parameterlist);

System.out.println("callbackcalledwith"+p);

typefinalvarnameN=value;

Variables can be declared inside of interface declarations. They are implicitly final
and static. Variables must also be initialized with a constant value. All methods and
variables are implicitly public if the interface, itself, is declared as public.

callback() is declared using the public access specifier. When you implement an
interface method, it must be declared as public.

Java Interface as data type

Here is an example of an interface definition.


interfaceMyInterface{
voidcallback(intparam);
}

Once we define an interface we can use it as a type for object instance we create
through its implementation class.
The following example calls the callback( ) method via an interface reference
variable:

Implementing Interfaces

interfaceMyInterface{
voidcallback(intparam);

To implement an interface, include the implements clause in a class definition, and


then create the methods defined by the interface.
The general form of a class that includes the implements clause looks like this:
accesslevelclassclassname[extendssuperclass][implementsinterface
[,interface...]]{
//classbody
}

classClientimplementsMyInterface{
//ImplementCallback'sinterface
publicvoidcallback(intp){
System.out.println("callbackcalledwith"+p);
}
}

Here is a small example class that implements the interface shown earlier.

publicclassMain{
publicstaticvoidmain(Stringargs[]){

interfaceMyInterface{
voidcallback(intparam);

MyInterfacec=newClient();
c.callback(42);

classClientimplementsMyInterface{

135

}//

136

The output of this program is shown here:

MyInterfacec=newClient();
AnotherClientob=newAnotherClient();

c.callback(42);

Polymorphism and interface

c=ob;//cnowreferstoAnotherClientobject

interface is designed for polymorphism. interface defines a list of methods acting

as the contract between the interface and its implementation. One interface can be
implements by more than once and each different implementation of the same
interface would follow the same list of methods. Therefore if we know several
classes implement the same interface we can use that interface to reference all of its
implementer classes. The compiler will determine dynamically which implementation
to use.

c.callback(42);

The output from this program is shown here:

interfaceMyInterface{
voidcallback(intparam);
}
classClientimplementsMyInterface{
//ImplementCallback'sinterface
publicvoidcallback(intp){

Java interface as build block


If a class implements an interface but does not fully implement its methods, then that
class must be declared as abstract. For example:

System.out.println("Client");
System.out.println("psquaredis"+(p*2));

interfaceMyInterface{

voidcallback(intparam);

}
classAnotherClientimplementsMyInterface{
//ImplementCallback'sinterface
publicvoidcallback(intp){
System.out.println("Anotherversionofcallback");
System.out.println("psquaredis"+(p*p));

voidshow();
}

abstractclassIncompleteimplementsMyInterface{
inta,b;

publicvoidshow(){

System.out.println(a+""+b);

classTestIface2{
publicstaticvoidmain(Stringargs[]){

137

138

Variables in Interfaces

The output:

We can use interface to organize constants.

Extend Interface

interfaceMyConstants{
intNO=0;//

One interface can inherit another interface with the keyword extends.

intYES=1;

interfaceIntefaceA{

voidmeth1();/*

classQuestionimplementsMyConstants{

voidmeth2();

intask(){

returnYES;

interfaceIntefaceBextendsIntefaceA{

voidmeth3();

classMyClassimplementsIntefaceB{

publicclassMainimplementsMyConstants{

publicvoidmeth1(){

staticvoidanswer(intresult){

System.out.println("Implementmeth1().");

switch(result){

caseNO:

publicvoidmeth2(){

System.out.println("No");

System.out.println("Implementmeth2().");

break;

caseYES:

publicvoidmeth3(){

System.out.println("Yes");

System.out.println("Implementmeth3().");

break;

publicclassMain{

publicstaticvoidmain(Stringargs[]){

publicstaticvoidmain(Stringarg[]){

Questionq=newQuestion();

MyClassob=newMyClass();

answer(q.ask());

ob.meth1();

ob.meth2();

139

140

ob.meth3();

packageMyPack;

publicclassMain{
publicstaticvoidmain(Stringargs[]){

The output:

System.out.println("hi");
}
}

Packages are containers for classes. Packages are used to keep the class name
space compartmentalized. In Java, package is mapped to a folder on your hard
drive.

Syntax
To define a package, include a package command as the first statement in a Java
source file. Any classes declared within that file will belong to the specified package.
If you omit the package statement, the class names are put into the default package,
which has no name.This is the general form of the package statement:
packagepackageName;

Then try executing the class, using the following command line:

Java Packages Import


In a Java source file, import statements occur immediately following the package
statement and before class definitions.
This is the general form of the import statement:
importpkg1[.pkg2].(classname|*);

* means including all classes under that package. For example,


importjava.lang.*;

Create a hierarchy of packages


To create a hierarchy of packages, separate each package name from the one
above it by use of a period. The general form of a multileveled package statement:
packagepkg1[.pkg2[.pkg3]];

Any place you use a class name, you can use its fully qualified name, which
includes its full package hierarchy.
For example, this fragment uses an import statement:
importjava.util.*;
classMyDateextendsDate{

A package hierarchy must be reflected in the file system of your Java development
system.

Java package maps to directory


Java package maps to physical directory on your hard drive. As what is defined in
the following example, you have to save the following file to a file named Main.java
and create a folder named MyPack to actually store Main.java file.

141

The same example without the import statement looks like this:
classMyDateextendsjava.util.Date{
}

142

static import

publicclassMain{

In order to access static members, it is necessary to qualify references. For


example, one must say:

publicstaticvoidmain(Stringargs[]){
System.out.println(newDate());

doubler=Math.cos(Math.PI*theta);

The static import construct allows unqualified access to static members.


importstaticjava.lang.Math.PI;

}
}

or:
importstaticjava.lang.Math.*;

Once the static members have been imported, they may be used without
qualification:
doubler=cos(PI*theta);

The static import declaration imports static members from classes, allowing them to
be used without class qualification.

Java Source File


All Java source files must end with the .java extension. A source file should contain,
at most, one top-level public class definition. If a public class is present, the class
name should match the unextended filename.
Three top-level elements known as compilation units may appear in a file. None of
these elements is required.
If they are present, then they must appear in the following order:
1. Package declaration
2. Import statements
3. Class, interface, and enum definitions
packageMyPack;
importjava.util.Date;

143

144

Вам также может понравиться