Está en la página 1de 146

Java Tutorial - Java Hello WorldLet's start by

compiling and running the following short sample program.


/* This is a simple Java program. Call this file "Main.java".
*/

public class Main {


// Your program begins with a call to main().
public static void main(String args[]) {
System.out.println("Java.");
}
}

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.
The code above generates the following result.

Compiling the Program


To compile the program, execute the compiler, javac, specifying the name of the
source file on the command line:
C:\>javac Main.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:\>java Main

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

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.
/*
This is a simple Java program. Call this file "Main.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:
public class Main {

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:
// Your program begins with a call to main().

A single-line comment begins with a // and ends at the end of the line. The next line
of code is shown here:
public static void main(String args[]) {

Java applications begin execution by calling main(String args[]). 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.
public class Main {
public static void main(String args[]) {
int num; // a variable called num
num = 100;
System.out.println("This is num: " + num);
num = num * 2;

System.out.print("The value of num * 2 is ");


System.out.println(num);
}
}

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

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

Following is the general form of a variable declaration:


type var-name;

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


3

num = 100; // this assigns num the value 100

Define more than one variable with comma


To declare more than one variable of the specified type, you may use a commaseparated list of variable names.
public class Main {
public static void main(String args[]) {
int num, num2;
num = 100; // assigns num the value 100
num2 = 200;
System.out.println("This is num: " + num);
System.out.println("This is num2: " + num2);

}
}

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

Using Blocks of Code


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:
public class Main {
public static void main(String args[]) {
int x, y;
x = 10;

y = 20;
if (x < y) { // begin a block
x = y;
y = 0;
System.out.println("x=" + x);
System.out.println("y=" + y);
} // end of block
}
}

Here is the output of the code above:

Example
A block of code as the target of a for loop.
public class Main {
public static void main(String args[]) {
int i, y;
y = 20;
for (i = 0; i < 10; i++) { // the target of this loop is a block
System.out.println("This is i: " + i);
System.out.println("This is y: " + y);
y = y - 1;

}
}
}

The output generated by this program is shown here:

Full list of keywords in Java


A keyword is a word whose meaning is defined by the programming language. Java
keywords and reserved Words:
abstract class

extends implements null

assert const

false import

strictfp

package super

true
try

boolean continue final instanceof private switch


break

default finally int

byte

do

case

double for

long

return

throw

catch

else

goto

native

short

throws

char

enum

if

protected synchronized volatile

float interface public

new

void

static

this

while

transient

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

3_a

// illegal: starts with a digit

!theValue

// illegal: bad 1st char

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

Using identifiers
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:
public class Main {
public static void main(String[] argv) {
int ATEST, count, i1, $Atest, this_is_a_test;
}

The following code shows invalid variable names include:


public class Main {
public static void main(String[] argv){
int 2count, h-l, a/b,

}
}

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).

Java variable type


In Java, all variables must be declared before they can be used. The basic form of a
variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;

There are three parts in variable definition:

type could be int or float.

Initialization includes an equal sign and a value.

identifier is the variable's name.

To declare more than one variable of the specified type, use a comma-separated list.
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f.

The following variables are defined and initialized in one expression.


public class Main {
public static void main(String[] argv) {
byte z = 2; // initializes z.
double pi = 3.14; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
}
}

Variable cannot be used prior to its declaration.


public class Main {
public static void main(String[] argv) {

count = 100; // Cannot use count before it is declared!

int count;
}
}

Compiling the code above generates the following error message:

Assignment Operator
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.

public class Main {


public static void main(String[] argv) {
int x, y, z;
x = y = z = 100; // set x, y, and z to 100
System.out.println("x is " + x);
System.out.println("y is " + y);
System.out.println("z is " + z);
}
}

The output:

Dynamic Initialization
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.
public class Main {
public static void main(String args[]) {

// c is dynamically initialized
double c = Math.sqrt(2 * 2);

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


}
}

The output from the code above is

Java defines eight primitive types of data: byte, short, int, long, char, float,double,
and boolean.
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

10

Primitive Type

Reserved Word

Size

Min Value

Max Value

Long integer

long

64-bit

-263

+263 - 1

Floating-point

float

32-bit

1.4e-045

3.4e+038

Double precision

double

64-bit

4.9e-324

1.8e+308

floating-point

byte, short, int, and long are for whole-valued signed numbers. float anddouble are

fractional precision numbers.


char represents symbols in a character set, like letters and

numbers. booleanrepresents true/false values.

Java Integers
Java defines four integer types: byte, short, int, and long.
Integer types are signed and can have positive and negative values.
The width and ranges of these integer types vary widely:
Name

Width

Range

long

64

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

int

32

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

short

16

-32,768 to 32,767

byte

-128 to 127

11

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.
Floating-Point Types width and ranges are shown here:
Name

Width in Bits

Approximate Range

double

64

4.9e-324 to 1.8e+308

float

32

1.4e-045 to 3.4e+038

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

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

Literals
Boolean literals are only two logical values: true and false. The values
of true andfalse do not convert into any numerical representation.
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.

Boolean class
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.
12

Example
Here is a program that demonstrates the boolean type:
public class Main {
public static void main(String args[]) {
boolean boolVariable;
boolVariable = false;

System.out.println("b is " + boolVariable);

boolVariable = true;

System.out.println("b is " + boolVariable);

}
}

Output:

Example 2
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.
public class Main {
public static void main(String[] argv) {
boolean b = true;

int i = b;

13

}
}

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

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.
Byte variables are declared by use of the byte keyword. The following declares two
byte variables called b and c:
byte b, c;

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.
public class Main {
public static void main(String[] args) {
byte b1 = 100;
byte b2 = 20;
System.out.println("Value of byte variable b1 is :" + b1);
System.out.println("Value of byte variable b1 is :" + b2);
}
}

The code above generates the following result.

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.
14

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:
short s;
short t;

Java int type


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


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.
public class Main {
public static void main(String args[]) {
long l = 0x7ffffffffffffffL;

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


}

15

The output generated by this program is shown here:

Example
Here is a program that use long type to store the result.
public class Main {
public static void main(String args[]) {
long result= (long)Integer.MAX_VALUE * (long)10;
System.out.println(result);//21474836470

}
}

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


The code above generates the following result.

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.
public class Main {

public static void main(String[] args) {


int i = 010;

System.out.println(i);
}

16

The output:

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).
The range of a hexadecimal digit is 0 to 15, so A through F (or a through f ) are
substituted for 10 through 15.
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.
public class Main{
public static void main(String[] argv){
int f = 0XFFFFF;

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

}
}

The code above generates the following result.

float type
float type represents single-precision numbers.
17

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

some example float variable declarations:


float high, low;

Java float Value, size and Literals


float is 32-bit width and its range is from 1.4e-045 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.
public class Main {
public static void main(String args[]) {
float d = 3.14159F;
System.out.print(d);//3.14159
}
}

The code above generates the following result.

Java double type


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:
public class Main {
public static void main(String args[]) {
double pi, r, a;
r = 10.8888; // radius of circle
pi = 3.1415926; // pi, approximately

18

a = pi * r * r;

System.out.println("Area of circle is " + a);


}
}

The output:

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.
public class Main {
public static void main(String args[]) {
double d = 3.14159;
System.out.print(d);//3.14159
}
}

The code above generates the following result.

Example 2
You can explicitly specify a double literal by appending a D or d.
public class Main {
public static void main(String args[]) {
double d = 3.14159D;

19

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

The code above generates the following result.

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, 314159E-05, and 4e+100.
public class Main {
public static void main(String[] argv) {
double d1 = 6.022E23;
double d2 = 314159E-05;
double d3 = 2e+100;
System.out.println("d1 is " + d1);
System.out.println("d2 is " + d2);
System.out.println("d3 is " + d3);
}

The output generated by this program is shown here:

20

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.
public class Main{
public static void main(String[] args) {
System.out.println(1.0/0.0);
}

The code above generates the following result.

double Infinity
Dividing a negative number by 0.0 outputs -infinity. For
example,System.out.println(-1.0/0.0); outputs -Infinity.
public class Main{
public static void main(String[] args) {
System.out.println(-1.0/0.0);
}

Output:

21

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.
Dividing a positive number by +infinity outputs +0.0. For
example,System.out.println(1.0/(1.0/0.0)); outputs +0.0.
Dividing a negative number by +infinity outputs -0.0. For
example,System.out.println(-1.0/(1.0/0.0)); outputs -0.0.
public class Main {
public static void main(String[] args) {
Double d1 = new Double(+0.0);
System.out.println(d1.doubleValue());
Double d2 = new Double(-0.0);
System.out.println(d2.doubleValue());
System.out.println(d1.equals(d2));
System.out.println(+0.0 == -0.0);

}
}

The code above generates the following result.

In Java, char stores characters. Java uses Unicode to represent characters. Unicode
can represent all of the characters found in all human languages.
Java char is a 16-bit type.
22

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

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 '@'.
Here is a program that demonstrates char variables:
public class Main {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X

ch2 = 'Y';

System.out.print("ch1 and ch2: ");


System.out.println(ch1 + " " + ch2);//ch1 and ch2: X Y
}
}

The code above generates the following result.

ch1 is assigned the value 88, which is the ASCII (and Unicode) value that

corresponds to the letter X.

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

operations.
public class Main {
public static void main(String args[]) {
char ch1;

23

ch1 = 'X';
System.out.println("ch1 contains " + ch1);//ch1 contains X

ch1 = (char)(ch1 + 1); // increment ch1


System.out.println("ch1 is now " + ch1);//ch1 is now Y
}
}

The code above generates the following result.

Example 2
The following code shows that we can assign non-letter character to Java char type.
public class Main {
public static void main(String[] argv) {
char ch = 'a';
System.out.println("ch is " + ch);//ch is a
ch = '@';

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


ch = '#';

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


ch = '$';

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


ch = '%';

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

24

}
}

The code above generates the following result.

Example 3
The following code stores unicode value into a char variable. The unicode literal
uses\uxxxx format.
public class Main {
public static void main(String[] args) {
int x = 75;
char y = (char) x;
char half = '\u00AB';
System.out.println("y is " + y + " and half is " + half);

}
}

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:
25

'\'' 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.
public class Main {
public static void main(String[] argv) {
char ch = '\'';

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

}
}

Character is a simple wrapper around a char.


The code above generates the following result.

Escape value list


The following table shows the character escape sequences.
Escape Sequence

Description

\ddd

Octal character (ddd)

\uxxxx

Hexadecimal Unicode character (xxxx)

\'

Single quote

26

Escape Sequence

Description

\"

Double quote

\\

Backslash

\r

Carriage return

\n

New line

\f

Form feed

\t

Tab

\b

Backspace

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

Java String Literal


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 declares String type variable with Java String literal.
public class Main{
public static void main(String[] argv){
String str = "this is a test from java2s.com";
System.out.println(str);
}

27

The output:

Java String Concatenation


You can use + operator to concatenate strings together.
For example, the following fragment concatenates three strings:

public class Main {


public static void main(String[] argv) {
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
}
}

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

public class Main {


public static void main(String args[]) {
String longStr = "A java .

com" +

"B j a v a . c o m
"C java
"D java.com .";

28

"+
.com" +

System.out.println(longStr);
}
}

Example 2
You can concatenate strings with other types of data.

public class Main {


public static void main(String[] argv) {
int age = 1;
String s = "He is " + age + " years old.";
System.out.println(s);
}
}

The output:

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

public class Main {


public static void main(String[] argv) {
String s = "four: " + 2 + 2;
System.out.println(s);
}

29

This fragment displays

rather than the

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

Now s contains the string "four: 4".

Java String Escape


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.

Escape List
The following table summarizes the Java String escape sequence.
Escape Sequence

Description

\ddd

Octal character (ddd)

\uxxxx

Hexadecimal Unicode character (xxxx)

30

Escape Sequence

Description

\'

Single quote

\"

Double quote

\\

Backslash

\r

Carriage return

\n

New line

\f

Form feed

\t

Tab

\b

Backspace

Examples of string literals with escape are


"Hello World"
"two\nlines"
"\"This is in quotes\""

The following example escapes the new line string and double quotation string.
public class Main {
public static void main(String[] argv) {
String s = "java.com";
System.out.println("s is " + s);

31

s = "two\nlines";
System.out.println("s is " + s);

s = "\"quotes\"";

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

}
}

The output generated by this program is shown here:

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.

public class Main {


public static void main(String[] argv){
String s = "line 1
line 2
";

}
}

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

32

equals() vs ==
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.
The following program shows the differences:

public class Main {


public static void main(String args[]) {
String s1 = "demo.com";
String s2 = new String(s1);

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


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

33

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


Each variable in the array is called an array element.

Java Array Variables


A Java array variable has two parts: array type and array object.
The array type is the type of the array variable. The array object is the memory
allocated for an array variable.
When defining an array we can first define the array type and allocate the memory
later.

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

// Declare an integer array variable

The variable myIntArray is now a type for an integer array. No memory has been
allocated to hold an array itself.
Later we will create the array by allocating memory and specify how many elements
it can contain.
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 type of the array variable is int[].

Alternative Syntax
We can use an alternative notation for declaring an array variable:
int myIntArray[];

34

// Declare an integer array variable

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.
The following two declarations are equivalent:
int a1[] = new int[3];
int[] a2 = new int[3];

Array create
After you have declared an array variable, you can define an array that it references:
myIntArray = new int[10];

// Define an array of 10 integers

This statement creates an array that stores 10 values of type int and stores a
reference to the array in the variable myIntArray.
The reference is simply where the array is in memory.
You could also declare the array variable and define the array of type int to hold 10
integers with a single statement.
int[] myIntArray = new int[10];

//An array of 10 integers

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.
The part of the statement that follows the equal sign defines the array.
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.

35

Java Array Initial Values


After we allocate memory for a Java array, Java assigns each element in an array to
its initial values
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.
Element Type

Initial Value

byte

int

float

0.0f

char

'\u0000'

object reference

null

short

long

0L

double

0.0d

boolean

false

36

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.
public class Main {
public static void main(String args[]) {
int a1[] = new int[10];
int a2[] = {1, 2, 3, 4, 5};
int a3[] = {4, 3, 2, 1};
System.out.println("length of a1 is " + a1.length);
System.out.println("length of a2 is " + a2.length);
System.out.println("length of a3 is " + 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};

37

// An array of 7 elements

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.
public class Main {
public static void main(String args[]) {

int days[] = {31, 28, 31,};


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

The output:

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]

refers to the element in the data array corresponding to the index value 9.
The index for an array element is the offset of the element from the beginning of the
array.
The first element has an index of 0, the second has an index of 1, the third an index
of 2, and so on.
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].
data[9] refers to the tenth element in the data array.
38

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.
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.
public class Main {
public static void main(String args[]) {

int days[] = {1, 2, 3,};


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

It generates the following error.

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.
public class Main {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int I;

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


result = result + nums[i];

39

System.out.println("Average is " + result / 5);


}
}

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.
The syntax of for each loop for an array is as follows.
for(arrayType variableName: array){
process each variableName
}

Java array for each loop


public class Main {
public static void main(String args[]) {
int days[] = {1, 2, 3,};
for(int i:days){
System.out.println(i);
}
}
}

The code above generates the following result.

40

Java Multidimensional Arrays


In Java, multidimensional arrays are actually arrays of arrays.
For example, the following declares a two-dimensional array variable called twoD.
int twoD[][] = new int[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:
[leftIndex][rightIndex]

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


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

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


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

The right way to think about multi-dimension arrays


+--+

+----+----+----+

| |--------| 1| 2| 3|
+--+

+----+----+----+

+----+----+----+

| |-----------------------------| 4| 5| 6|
+--+ +----+----+----+
| |---| 7| 8| 9|
+--+ +----+----+----+

41

+----+----+----+

The following code use nested for loop to assign values to a two-dimensional array.
public class Main {
public static void main(String args[]) {
int twoD[][] = new int[4][5];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
twoD[i][j] = i*j;/* w w w . j ava2 s . c om*/
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
}

This program generates the following output:

Example
The following program creates a 3 by 4 by 5, three-dimensional array.
public class Main {
public static void main(String args[]) {
int threeD[][][] = new int[3][4][5];
for (int i = 0; i < 3; i++)

42

for (int j = 0; j < 4; j++)


for (int k = 0; k < 5; k++)
threeD[i][j][k] = i * j * k;

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


for (int j = 0; j < 4; j++) {
for (int k = 0; k < 5; k++)
System.out.print(threeD[i][j][k] + " ");
System.out.println();
}
System.out.println();
}
}
}

This program generates the following output:

Example 2
The following code shows how to iterate over Multidimensional Arrays with for-each.
public class Main {
public static void main(String args[]) {

43

int sum = 0;
int nums[][] = new int[3][5];

// give nums some values


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

// use for-each for to display and sum the values


for (int x[] : nums) {
for (int y : x) {
System.out.println("Value is: " + y);
sum += y;
}
}
System.out.println("Summation: " + sum);
}
}

The code above generates the following result.

44

Jagged array
When you allocate memory for a multidimensional array, you can allocate the
remaining dimensions separately.
An irregular multi-dimension array
+--+

+----+----+

| |--------| 1| 2|
+--+

+----+----+

+----+----+----+

| |-----------------------------| 4| 5| 6|
+--+ +----+----+----+----+

+----+----+----+

| |---| 7| 8| 9| 10|
+--+ +----+----+----+----+

For example, the following code allocates the second dimension manually.
public class Main {
public static void main(String[] argv) {
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[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.
public class Main {

45

public static void main(String args[]) {


int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
for (int i = 0; i < 4; i++){
for (int j = 0; j < i + 1; j++) {
twoD[i][j] = i + j;
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < i + 1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}

This program generates the following output:

The array created by this program looks like this:

46

Example 4
We can initialize multidimensional arrays during declaration by enclosing each
dimension's initializer within its own set of curly braces.
public class Main{
public static void main(String args[]) {
double m[][] = {
{ 0, 1, 2, 3 },
{ 0, 1, 2, 3 },
{ 0, 1, 2, 3 },
{ 0, 1, 2, 3 }
};
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++){
System.out.print(m[i][j] + " ");
}
System.out.println();
}
}
}

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

Arithmetic operators are used in mathematical expressions.

All Arithmetic Operators


The following table lists the arithmetic operators:
47

Operator

Result

Addition

Subtraction (unary minus)

Multiplication

Division

Modulus

++

Increment

+=

Addition assignment

-=

Subtraction assignment

*=

Multiplication assignment

/=

Division assignment

%=

Modulus assignment

--

Decrement

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.

48

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.

public class Main {


public static void main(String args[]) {

System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);

int x = 42;
System.out.println("x mod 10 = " + x % 10);
double y = 42.25;

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


}
}

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

49

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.

Java Compound Assignment Operators


Statements like the following
a = a + 4;

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
var = var op expression;

can be rewritten as
var op= expression;

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

public class Main {

50

//from w ww .j a v a 2s .co m
public static void main(String args[]) {
int a = 1;
int b = 2;
int c = 3;

a += 1;
b *= 2;
c += a * b;
c %= 3;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);

}
}

The output of this program is shown here:

Java Increment and Decrement Operator


++ and -- are Java's increment and decrement operators. The increment operator, +
+, increases its operand by one. The decrement operator, --, decreases its operand

by one.
Different between Increment and Decrement Operator:
For example, this statement:
x = x + 1;

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


51

x++;

This statement:
x = x - 1;

is equivalent to
x--;

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.
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.
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

y = x--

y = --x

For example:
x = 42;
y = ++x;

52

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

is the equivalent of these two statements:


x = x + 1;
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.
In both cases x is set to 43. The line
y = x++;

is the equivalent of these two statements:


y = x;
x = x + 1;

The following program demonstrates the increment operator.

public class Main {


/* w ww.j a v a 2 s .c o m*/
public static void main(String args[]) {
int a = 1;
int b = 2;
int c = ++b;
int d = a++;

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


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

53

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


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

}
}

The output of this program follows:

The Boolean logical operators operate on boolean operands.

Logical Operator List


The following table lists all Java boolean logical operators.
Operator

Result

&

Logical AND

Logical OR

Logical XOR (exclusive OR)

||

Short-circuit OR

&&

Short-circuit AND

Logical unary NOT

54

Operator

Result

&=

AND assignment

|=

OR assignment

^=

XOR assignment

==

Equal to

!=

Not equal to

?:

Ternary if-then-else

True table
The following table shows the effect of each logical operation:
A

A|B

A&B

A^B

!A

False

False

False

False

False

True

True

False

True

False

True

False

False

True

True

False

True

True

True

True

True

True

False

False

The following program demonstrates the boolean logical operators.


55

public class Main {


public static void main(String args[]) {
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
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);
}
}
]]>

The output:

56

Example
The following program demonstrates the bitwise logical operators:

public class Main {


public static void main(String args[]) {
int a = 1;
int b = 2;
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;

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);

}
}

Here is the output from this program:

Java Logical Operators Shortcut


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
57

the right-hand operand when the outcome can be determined by the left operand
alone.
The following code shows how you can use short-circuit logical operator to ensure
that a division operation will be valid before evaluating it:

public class Main {


public static void main(String[] argv) {
int denom = 0;
int num = 3;
if (denom != 0 && num / denom > 10) {
System.out.println("Here");
} else {
System.out.println("There");
}
}
}

The output:

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.

public class Main {


public static void main(String[] argv) {
int c = 0;
int e = 99;
int d = 0;

58

if (c == 1 & e++ < 100)


d = 100;

System.out.println("e is " + e);


System.out.println("d is " + d);
}
}

The output:

Java relational operators determine the relationship between two operands.

Relational Operators List


The relational operators in Java are:
Operator

Result

==

Equal to

!=

Not equal to

>

Greater than

<

Less than

>=

Greater than or equal to

<=

Less than or equal to

59

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

public class Main {


public static void main(String[] argv) {
int a = 4;
int b = 1;
boolean c = a < b;

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


}
}

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

Example
The outcome of a relational operator is a boolean value. In the following code,
theSystem.out.println outputs the result of a relational operator.
public class Main {
public static void main(String args[]) {
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}

The output generated by this program is shown here:

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


60

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

Syntax
The ? has this general form:
expression1 ? expression2 : expression3

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

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


evaluated.
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:

public class Main {


public static void main(String[] argv) {
int denom = 10;
int num = 4;
double ratio;

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


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

The output:

61

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

public class Main {


public static void main(String args[]) {
int i, k;
i = 10;
k = i < 0 ? -i : i;
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);

i = -10;
k = i < 0 ? -i : i;
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);

}
}

The output generated by the program is shown here:


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

Java If Statement
The following the simplest form of Java if statement:
if(condition)
statement;

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

executed.
62

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.
public class Main {
public static void main(String args[]) {
int num = 99;
if (num < 100) {
System.out.println("num is less than 100");

}
}
}

The output generated by this program is shown here:

Example
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.
public class Main {
public static void main(String args[]) {
int x, y;

x = 10;
y = 20;

if (x < y){
System.out.println("x is less than y");
}

63

x = x * 2;
if (x == y){
System.out.println("x now equal to y");
}

x = x * 2;
if (x > y){
System.out.println("x now greater than y");
}

if (x == y){
System.out.println("===");
}
}
}

The output generated by this program is shown here:

Example 2
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.
public class Main {
public static void main(String args[]) {
boolean b;
b = false;
if (b) {
System.out.println("This is executed.");

64

} else {
System.out.println("This is NOT executed.");
}

}
}

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


if(b == true) ...

The output generated by this program is shown here:

Java if else Statement


The if statement is a conditional branch statement. We can add else statement to
the if statement.
Here is the general form of the if-else statement:
if (condition)
statement1;
else
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.
The following example shows how to use Java if else statement.

public class Main {


public static void main(String[] argv) {

65

int i = 1;

if (i > 0) {
System.out.println("Here");
i -= 1;

} else
System.out.println("There");
}
}
]]>

The output:

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

Java if else ladder statement


The if else ladder statement is used to work on multiple conditions.
The if-else-if Ladder looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
else
statement;

66

Here is a program that uses an if-else-if ladder.

public class Main {


public static void main(String args[]) {
int month = 4;
String value;
if (month == 1 )
value = "A";
else if (month == 2)
value = "B";
else if (month == 3)
value = "C";
else if (month == 4)
value = "D";
else
value = "Error";

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


}
}

Here is the output produced by the program:

Java nested if 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.

public class Main {


public static void main(String[] argv) {

67

int i = 10;
int j = 4;
int k = 200;
int a = 3;
int b = 5;
int c = 0;
int d =0;
if (i == 10) {
if (j < 20){
a = b;
}
if (k > 100){
c = d;
}
else{
a = c;
}
} else{
a = d;
}
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);

}
}

The output:

68

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


than a large series of if-else-if statements.

Java switch Statement


Here is the general form of a switch statement:
switch (expression) {
case value1:
statement sequence
break;
case value2:
statement sequence
break;
.
.
.
case valueN:
statement sequence
break;
default:
default statement sequence
}

The value1 to valueN are the possible case values for expression. Duplicate case
values are not allowed.
A break statement jumps out of switch statement to the first line that follows the
entireswitch statement.
69

Here is a simple example that uses a switch statement:

public class Main {


public static void main(String args[]) {
for (int i = 0; i < 6; i++)
switch (i) {
case 0:
System.out.println("i is zero.");
break;

case 1:
System.out.println("i is one.");
break;

case 2:
System.out.println("i is two.");
break;

case 3:
System.out.println("i is three.");
break;

default:
System.out.println("i is greater than 3.");
}
}
}

The output produced by this program is shown here:

70

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:

public class Main {


public static void main(String args[]) {
for (int i = 0; i < 12; i++)
switch (i) {
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println("i is less than 10");
break;
default:

71

System.out.println("i is 10 or more");
}
}
}

This program generates the following output:

Example 2
Java supports the nested switch statements. For example, the following fragment is
a valid nested switch statement.
public class Main {
public static void main(String args[]) {
for (int i = 0; i < 6; i++)
switch(i) {
case 0:
switch(i+1) { // nested switch
case 0:
System.out.println("target is zero");
break;
case 1:
System.out.println("target is one");

72

break;
}
break;
case 2: // ...
}
}
}

The output:

Example 3
The following code shows how to switch with char value.
import java.util.Scanner;

public class Main {


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

public static void main(String[] args) {


char p = 'a';

String details = "";

switch (p) {
case 'E':
case 'e':
details += "\tE...\n";
case 'D':
case 'd':
details += "\tD...\n";

73

case 'C':
case 'c':
details += "\tC...\n";
case 'B':
case 'b':
details += "\tB...\n";
case 'A':
case 'a':
details += "\tA.\n";
break;
default:
details = "That's";
break;
}
System.out.println(details);
}
}

The code above generates the following result.

Example 4
The following code shows how to use string literals in switch statements.
public class Main {
public static void main(String[] args) {
String[] data = new String[]{"a","b","java2s.com"};
for (String argument : data) {
switch (argument) {
case "a":
case "b":
System.out.println("a or b");

74

break;
case "java2s.com":
System.out.println("java2s.com");
break;
case "-help":
System.out.println("displayHelp");
break;
default:
System.out.println("Illegal command line argument");
}

}
}
}

The code above generates the following result.

Java for loop statement provides a powerful way of writing loop statement.
The simplest form of the for loop is shown here:
for(initialization; condition; iteration)
statement;

Java for loop statement has three parts:

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.

75

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.
public class Main {
public static void main(String args[]) {
int i;

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


System.out.println("This is i: " + i);
}
}

This program generates the following output:

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

public class Main {


public static void main(String args[]) {

76

for (int n = 10; n > 0; n--)


System.out.println("n:" + n);
}
} ]]>

The output:

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

public class Main {


public static void main(String args[]) {
int num;
boolean isPrime = true;
num = 50;
for (int i = 2; i <= num / 2; i++) {
if ((num % i) == 0) {
isPrime = false;
break;
}
}

77

if (isPrime)
System.out.println("Prime");
else
System.out.println("Not Prime");

}
}

The output:

Example 3
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:

public class Main {


public static void main(String args[]) {
for (int a = 1, b = 4; a < b; a++, b--) {
System.out.println("a = " + a);
System.out.println("b = " + b);

}
}
}

The program generates the following output:

78

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

public class Main {


public static void main(String args[]) {
int i = 0;
boolean done = false;
for (; !done;) {
System.out.println("i is " + i);
if (i == 10)
done = true;
i++;

}
}
}

The output:

79

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:

public class Main {


public static void main(String args[]) {
for (int i = 0; i < 10; i++) {
for (int j = i; j < 10; j++)
System.out.print(".");
System.out.println();
}
}
}

The output produced by this program is shown here:

80

Java for each loop


The for each loop iterates elements in a sequence without using the loop counter.
The syntax of for each loop is:
for (type variable_name:array){

The type must be compatible with the array type.


The following code shows how to use for each loop.
public class Main {
public static void main(String args[]) {
String[] arr = new String[]{"java2s.com","a","b","c"};
for(String s:arr){
System.out.println(s);
}
}
}

The output:
81

Example 6
The following code uses the for-each style loop to iterate a two-dimensional array.
public class Main {
public static void main(String args[]) {
int sum = 0;
int nums[][] = new int[3][5];
for (int i = 0; i < 3; i++){
for (int j = 0; j < 5; j++){
nums[i][j] = (i + 1) * (j + 1);
}
}
// use for-each for to display and sum the values
for (int x[] : nums) {
for (int y : x) {
System.out.println("Value is: " + y);
sum += y;
}
}
System.out.println("Summation: " + sum);
}
}

The output from this program is shown here:

82

Example 7
for-each style loop is useful when searching an element in an array.
public class Main {
public static void main(String args[]) {
int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 };
int val = 5;
boolean found = false;
// use for-each style for to search nums for val
for (int x : nums) {
if (x == val) {
found = true;
break;
}
}
if (found)
System.out.println("Value found!");
}
}

The code above generates the following result.


83

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

Java while Loop


Here is its general form:
while(condition) {
// body of loop
}

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.

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

public class Main {


public static void main(String args[]) {
int n = 10;
while (n > 0) {
System.out.println("n:" + n);
n--;
}
}
}

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

84

Example
The following code shows how to use the while loop to calculate sum.
public class Main {
public static void main(String[] args) {
int limit = 20;
int sum = 0;
int i = 1;

while (i <= limit) {


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

The code above generates the following result.

85

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:

public class Main {


public static void main(String[] argv) {
int a = 10, b = 20;
while (a > b) {
System.out.println("This will not be displayed");
}
System.out.println("You are here");
}
}

The output:

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

public class Main {


public static void main(String args[]) {
int i, j;
i = 10;
j = 20;

// find midpoint between i and j


while (++i < --j)

86

;
System.out.println("Midpoint is " + 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:
do {
// body of loop
} while (condition);

Here is an example to show how to use a do-while loop.

public class Main {


public static void main(String args[]) {
int n = 10;
do {
System.out.println("n:" + n);
n--;
} while (n > 0);
}
}

The output:

87

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


public class Main {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("n:" + n);
} while (--n > 0);
}
}

The output is identical the result above:

88

Example 4
The following program implements a very simple help system with do-while loop
andswitch statement.

public class Main {


public static void main(String args[]) throws java.io.IOException {
char choice;
do {
System.out.println("Help on:");
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("Choose one:");
choice = (char) System.in.read();
} while (choice < '1' || choice > '5');
System.out.println("\n");
switch (choice) {
case '1':
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;

89

case '5':
System.out.println("E");
break;
}
}
}

Here is a sample run produced by this program:

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.

Syntax
The general form of a class definition is shown here:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;

type methodname1(parameter-list) {

90

// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}

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.

class Box {
int width;
int height;
int depth;
}

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

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

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:


Box mybox = new Box();

This statement combines the two steps. It can be rewritten like this to show each
step more clearly:
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object

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:

class Box {
int width;
int height;
int depth;
}
public class Main {
public static void main(String args[]) {
Box myBox = new Box();
myBox.width = 10;

92

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

The output:

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;

This statement assigns the width from mybox object to 10. Here is a complete
program that uses the Box class:
Any attempt to use a null mybox will result in a compile-time error.
class Box {
int width;
int height;
int depth;
}

public class Main {


public static void main(String args[]) {
Box myBox;
myBox.width = 10;
}
}

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

93

Java instanceof operator


Java provides the run-time operator instanceof to check class type for an object.
The instanceof operator has this general form:
object instanceof type

The following program demonstrates instanceof:

class A {
}

class B {
}

class C extends A {
}

class D extends A {
}

public class Main{


public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new C();
D d = new D();

if (a instanceof A)
System.out.println("a is instance of A");
if (b instanceof B)
System.out.println("b is instance of B");
if (c instanceof C)

94

System.out.println("c is instance of C");


if (c instanceof A)
System.out.println("c can be cast to A");

if (a instanceof C)
System.out.println("a can be cast to C");

A ob;
ob = d; // A reference to d
System.out.println("ob now refers to d");
if (ob instanceof D)
System.out.println("ob is instance of D");

ob = c; // A reference to c
System.out.println("ob now refers to c");
if (ob instanceof D)
System.out.println("ob can be cast to D");
else
System.out.println("ob cannot be cast to D");

if (ob instanceof A)
System.out.println("ob can be cast to A");
// all objects can be cast to Object
if (a instanceof Object)
System.out.println("a may be cast to Object");
if (b instanceof Object)
System.out.println("b may be cast to Object");
if (c instanceof Object)
System.out.println("c may be cast to Object");
if (d instanceof Object)
System.out.println("d may be cast to Object");
}
}

95

The output from this program is shown here:

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.

Syntax
This is the general form of a method:
type name(parameter-list) {
// body of method
}

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.
If the method has no parameters, then the parameter list will be empty.
Add a method to Box,as shown here:

96

class Box {
int width;
int height;
int depth;
void calculateVolume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}

public class Main {

public static void main(String args[]) {


Box mybox1 = new Box();
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;

mybox1.calculateVolume();

}
}

This program generates the following output:

Java Method Return


A method in a class can return a value with the return statement.
Methods that have a return type other than void return a value to the calling routine
using the following form of the return statement:
return value;

97

Here, value is the value returned.


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

class Rectangle {
int width;
int height;

int getArea() {
return width * height;
}
}

public class Main {

public static void main(String args[]) {


Rectangle mybox1 = new Rectangle();
int area;
mybox1.width = 10;
mybox1.height = 20;

area = mybox1.getArea();
System.out.println("Area is " + area);

}
}

The output:

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

98

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.
The following code uses the returned value directly in a println( ) statement:
System.out.println("Area is " + mybox1.getArea());

Example
A method can return class types.

class MyClass {
int myMemberValue = 2;
MyClass() {
}
MyClass doubleValue() {
MyClass temp = new MyClass();
temp.myMemberValue = temp.myMemberValue*2;
return temp;
}
}

public class Main {


public static void main(String args[]) {
MyClass ob1 = new MyClass();
ob1.myMemberValue =2;
MyClass ob2;

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

ob2 = ob2.doubleValue();

99

System.out.println("ob2.a after second increase: " + ob2.myMemberValue);


}
}

The output generated by this program is shown here:

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:
type methodName(parameterType variable,parameterType2 variable2,...) {
// body of method
}

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.

class Rectangle {
double width;
double height;

double area() {
return width * height;
}

void setDim(double w, double h) { // Method with parameters

100

width = w;
height = h;
}
}

public class Main {

public static void main(String args[]) {


Rectangle mybox1 = new Rectangle();
double vol;
mybox1.setDim(10, 20);

vol = mybox1.area();
System.out.println("Area is " + vol);

}
}

The output:

Example 2
The following code passes objects to methods.

class Test {
int a;

Test(int i) {
a = i;
}
boolean equals(Test o) {

101

if (o.a == a )
return true;
else
return false;
}
}

public class Main {


public static void main(String args[]) {
Test ob1 = new Test(100);
Test ob2 = new Test(100);

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

}
}

This program generates the following output:

Java Method Overload


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.
The following example illustrates method overloading:
102

class OverloadDemo {
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a);
return a * a;
}
}
public class Main {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
ob.test();
ob.test(10);
ob.test(10, 20);
double result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);

}
}

This program generates the following output:

103

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

class OverloadDemo {
void test() {
System.out.println("No parameters");
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
void test(double a) {
System.out.println("Inside test(double) a: " + a);
}
}

public class Main {


public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
ob.test();
ob.test(10, 20);

ob.test(i); // this will invoke test(double)


ob.test(123.2); // this will invoke test(double)

104

}
}

This program generates the following output:

Java Method Recursion


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

class Factorial {
// this is a recursive function
int fact(int n) {
int result;

if (n == 1)
return 1;
result = fact(n - 1) * n;
return result;
}
}

public class Main {


public static void main(String args[]) {
Factorial f = new Factorial();

System.out.println("Factorial of 5 is " + f.fact(5));

105

}
}

The output from this program is shown here:

Java main() Method


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


The signature for main() is:
public static void main(String[] args)

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.
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:

public class Main {


public static void main(String args[]) {
for (int i = 0; i < args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}

106

Try executing this program, as shown here:

When you do, you will see the following output:

Example 4
The following code shows how to use of argv to get an integer value from command
line.
public class Main {
public static void main(String[] argv) {
int number = 0;

System.out.println("The number of words in argv is " + argv.length);

if (argv.length == 0) {
number = 1234;
} else if (argv.length == 1) {
try {
number = Integer.parseInt(argv[0]);
} catch(NumberFormatException e) {
System.err.println("Number " + argv[0] + " invalid (" + e.getMessage() + ").");
System.exit(1);
}
} else {
System.err.println("usage: UseArgv number");

107

System.exit(1);
}

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


}
}

The code above generates the following result.

A constructor initializes an object during object creation when using new operator.
Java allows objects to initialize themselves when they are created. This automatic
initialization is performed through the use of a constructor.

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

ClassName(parameter list){ // constructor


...
}
}

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

class Rectangle {
double width;//
double height;

108

Rectangle() {
width = 10;
height = 10;
}

double area() {
return width * height;
}
}

public class Main {


public static void main(String args[]) {
Rectangle mybox1 = new Rectangle();
double area;
area = mybox1.area();
System.out.println("Area is " + area);

}
}

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

Java Default Constructor


A default constructor is a constructor with no parameters.

Syntax for Java Default Constructor


Syntax for Java Default Constructor
class ClassName{

109

ClassName(){ // default constructor


...
}
}

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

class Rectangle {
double width;//
double height;

Rectangle() {
width = 10;
height = 10;
}

double area() {
return width * height;
}
}

public class Main {


public static void main(String args[]) {
Rectangle mybox1 = new Rectangle();
double area;
area = mybox1.area();
System.out.println("Area is " + 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
110

variables are initialized by default value. If you do provide a default constructor the
Java compiler would not insert one for you.
The code above generates the following result.

Example
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.

class Rectangle {
double width;//
double height;

double area() {
return width * height;
}
}

public class Main {


public static void main(String args[]) {
Rectangle mybox1 = new Rectangle();
double area;
area = mybox1.area();
System.out.println("Area is " + area);

}
}

The output:
111

Java Constructor Parameters


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

Syntax for Java Constructor Parameters


Syntax for Java Constructor Parameters
class ClassName{

ClassName(parameterType variable,parameterType2 variable2,...){ // constructor


...
}
}

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.

class Rectangle {
double width;//
double height;

Rectangle(double w, double h) {
width = w;
height = h;
}

double area() {
return width * height;

112

}
}

public class Main {


public static void main(String args[]) {
Rectangle mybox1 = new Rectangle(10, 20);
double area;
area = mybox1.area();
System.out.println("Area is " + area);
}
}

The output from this program is shown here:

Example 2
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.

class Rectangle {
double width;
double height;

Rectangle(Rectangle ob) { // pass object to constructor


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

113

Rectangle(double w, double h) {
width = w;
height = h;
}

// constructor used when no dimensions specified


Rectangle() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
}

// constructor used when cube is created


Rectangle(double len) {
width = height = len;
}

double area() {
return width * height;
}
}

public class Main {


public static void main(String args[]) {
Rectangle mybox1 = new Rectangle(10, 20);
Rectangle myclone = new Rectangle(mybox1);
double area;
// get volume of first box
area = mybox1.area();
System.out.println("Area of mybox1 is " + area);
// get volume of clone
area = myclone.area();
System.out.println("Area of clone is " + area);

114

}
}

The output:

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.
In the following code Rectangle defines three constructors to initialize the
dimensions of a rectangle in various ways.

class Rectangle {
double width;/*
double height;

// constructor used when all dimensions specified


Rectangle(double w, double h) {
width = w;
height = h;
}

// constructor used when no dimensions specified


Rectangle() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized

115

Rectangle(double len) {
width = height = len;
}

double area() {
return width * height;
}
}

public class Main {


public static void main(String args[]) {
Rectangle mybox1 = new Rectangle(10, 20);
Rectangle mybox2 = new Rectangle();
Rectangle mycube = new Rectangle(7);

double area = mybox1.area();


System.out.println(area);

area = mybox2.area();
System.out.println(area);

area = mycube.area();
System.out.println(area);

}
}

The output produced by this program is shown here:

116

this()
In Java this keyword can call the overloaded constructors. The general form is
shown here:
this(arg-list)

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.
class MyClass {
int a;
int b;

// initialize a and b individually


MyClass(int i, int j) {
a = i;
b = j;
}

// initialize a and b to the same value


MyClass(int i) {
this(i, i); // invokes MyClass(i, i)
}

// give a and b default values of 0

117

MyClass() {
this(0); // invokes MyClass(0)
}
}

Three types of class variables


Java supports variables of three different lifetimes:

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

int

long

0L

float

0.0f

118

Element Type

Initial Value

double

0.0d

char

'\u0000'

boolean

false

object reference

null

In the following example, the variable x is set to 20 when the variable is declared.
public class Main{
int x = 20;
}

The following example shows the default value if you don't set them.
class MyClass {//
int i;

boolean b;

float f;

double d;

String s;

public MyClass() {
System.out.println("i=" + i);

119

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

public class Main {


public static void main(String[] argv) {
new MyClass();

}
}

The output:

Example for method local variables


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).
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:
public class Main{

120

public int wrong() {


int i;
return i+5;
}

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.
public class Main{
static int y = 30;
}

Java this Keyword


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

The following code shows how to use this keyword.


// A use of this.
Rectangle(double w, double h) {
this.width = w; // this is used here
this.height = h;
}

121

Hidden instance variables and this


Use this to reference the hidden instance variables.
Member variables and method parameters may have the same name. Under this
situation we can use this to reference the member variables.
Rectangle(double width, double height) {
this.width = width;
this.height = height;
}

The following example shows how to use this to reference instance variable.
class Person{
private String name;

public Person(String name) {


this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Main{
public static void main(String[] args) {
Person person = new Person("Java");
System.out.println(person.getName());
person.setName("new name");
System.out.println(person.getName());
}

122

The code above generates the following result.

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.
The following program creates a superclass called Base and a subclass called Child.

class Base {
int i, j;
void showBase() {
System.out.println("i and j: " + i + " " + j);
}
}
class Child extends Base {
int k;
void showChild() {
System.out.println("k: " + k);
}
void sum() {

123

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


}
}

public class Main {


public static void main(String args[]) {
Base superOb = new Base();
Child subOb = new Child();

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

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

subOb.sum();
}
}

The output from this program is shown here:

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:

124

class subclass-name extends superclass-name {


// body of class
}

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

Java super keyword


You can use super in a subclass to refer to its immediate superclass. super has two
general forms.
1. The first calls the superclass' constructor.
2. The second is used to access a member of the superclass.

Call superclass constructors


To call a constructor from its superclass:
super(parameter-list);

parameter-list is defined by the constructor in the superclass.

super(parameter-list) must be the first statement executed inside a subclass' constructor.

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

class Box {
private double width;
private double height;
private double depth;

Box(Box ob) { // pass object to constructor


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

125

}
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}
}
class BoxWeight extends Box {
double weight; // weight of box
BoxWeight(Box ob) { // pass object to constructor
super(ob);
}
}
public class Main {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
BoxWeight myclone = new BoxWeight(mybox1);
double vol;

vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
}
}

This program generates the following output:

126

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.

class Base {
int i;
}
class SubClass extends Base {
int i; // this i hides the i in A
SubClass(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
public class Main {
public static void main(String args[]) {
SubClass subOb = new SubClass(1, 2);
subOb.show();
}
}

This program displays the following:

127

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.
The method defined by the superclass will be hidden. Consider the following:

class Base {
int i;
Base(int a) {
i = a;
}
void show() {
System.out.println("i:" + i);
}
}
class SubClass extends Base {
int k;
SubClass(int a, int c) {
super(a);
k = c;
}
void show() {
System.out.println("k: " + k);
}
}
public class Main {

128

public static void main(String args[]) {


SubClass subOb = new SubClass(1, 3);
subOb.show();
}
}

The output produced by this program is shown here:

super and overridden method


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

class Base {
int i;

Base(int a) {
i = a;
}

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

class SubClass extends Base {


int k;

SubClass(int a, int c) {
super(a);
k = c;

129

void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);

}
}

public class Main {


public static void main(String[] argv) {
SubClass sub = new SubClass(1, 2);
sub.show();
}
}

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

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:

class Base {
int i;
Base(int a) {
i = a;
}
void show() {

130

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


}
}
class SubClass extends Base {
int k;
SubClass(int a, int c) {
super(a);
k = c;
}
void show(String msg) {
System.out.println(msg + k);
}
}
public class Main {
public static void main(String args[]) {
SubClass subOb = new SubClass(1, 2);
subOb.show("This is k: ");
subOb.show();
}
}

The output produced by 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:

131

class A {
A() {
System.out.println("Inside A's constructor.");
}
}

// Create a subclass by extending class A.


class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}

// Create another subclass by extending B.


class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}

public class Main{


public static void main(String args[]) {
C c = new C();
}
}

The output from this program is shown here:

132

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

Dynamic Method Dispatch


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:

class Base {
void callme() {
System.out.println("Inside A's callme method");
}
}
class SubClass extends Base {
void callme() {
System.out.println("Inside B's callme method");
}
}
class SubClass2 extends Base {
void callme() {
System.out.println("Inside C's callme method");
}
}
public class Main {
public static void main(String args[]) {
Base a = new Base();
SubClass b = new SubClass();
SubClass2 c = new SubClass2();
Base r;

133

r = a;
r.callme();
r = b;
r.callme();
r = c;
r.callme();
}
}

The output from the program is shown here:

Polymorphism Example
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.

class Shape {
double height;
double width;
Shape(double a, double b) {
height = a;
width = b;
}
double area() {
System.out.println("Area for Figure is undefined.");

134

return 0;
}
}
class Rectangle extends Shape {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return height * width;
}
}
class Triangle extends Shape {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return height * width / 2;
}
}
public class Main {
public static void main(String args[]) {
Shape f = new Shape(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);

Shape figref;

figref = r;
System.out.println("Area is " + figref.area());

135

figref = t;
System.out.println("Area is " + figref.area());

figref = f;
System.out.println("Area is " + figref.area());
}
}

The output from the program is shown here:

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.

Syntax
An interface is defined much like a class. This is the general form of an interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);

136

type final-varname1 = value;


type final-varname2 = value;

// ...
return-type method-nameN(parameter-list);

type final-varnameN = 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.
Here is an example of an interface definition.
interface MyInterface{
void callback(int param);
}

Implementing Interfaces
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:
access-level class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}

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

interface MyInterface {
void callback(int param);
}

137

class Client implements MyInterface{


// Implement Callback's interface
public void callback(int p) {

System.out.println("callback called with " + p);


}
}

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


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:

interface MyInterface {
void callback(int param);
}//
class Client implements MyInterface{
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}
public class Main {
public static void main(String args[]) {
MyInterface c = new Client();
c.callback(42);

138

}
}

The output of this program is shown here:

Polymorphism and interface


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.

interface MyInterface {
void callback(int param);
}
class Client implements MyInterface{
// Implement Callback's interface
public void callback(int p) {
System.out.println("Client");
System.out.println("p squared is " + (p * 2));
}
}
class AnotherClient implements MyInterface{
// Implement Callback's interface
public void callback(int p) {
System.out.println("Another version of callback");
System.out.println("p squared is " + (p * p));
}

139

class TestIface2 {
public static void main(String args[]) {
MyInterface c = new Client();
AnotherClient ob = new AnotherClient();
c.callback(42);
c = ob; // c now refers to AnotherClient object
c.callback(42);
}
}

The output from this program is shown here:

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:

interface MyInterface {
void callback(int param);
void show();
}

abstract class Incomplete implements MyInterface {


int a, b;

140

public void show() {


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

Variables in Interfaces
We can use interface to organize constants.

interface MyConstants {
int NO = 0;//
int YES = 1;
}

class Question implements MyConstants {


int ask() {
return YES;
}
}

public class Main implements MyConstants {


static void answer(int result) {
switch (result) {
case NO:
System.out.println("No");
break;
case YES:
System.out.println("Yes");
break;
}
}

141

public static void main(String args[]) {


Question q = new Question();
answer(q.ask());
}
}

The output:

Extend Interface
One interface can inherit another interface with the keyword extends.

interface IntefaceA {
void meth1();/*
void meth2();
}
interface IntefaceB extends IntefaceA {
void meth3();
}
class MyClass implements IntefaceB {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
public class Main {

142

public static void main(String arg[]) {


MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}

The output:

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:
package packageName;

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:
package pkg1[.pkg2[.pkg3]];

143

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.
package MyPack;

public class Main {


public static void main(String args[]) {
System.out.println("hi");
}
}

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:
import pkg1[.pkg2].(classname|*);

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


import java.lang.*;

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:
144

import java.util.*;
class MyDate extends Date {
}

The same example without the import statement looks like this:
class MyDate extends java.util.Date {
}

static import
In order to access static members, it is necessary to qualify references. For
example, one must say:
double r = Math.cos(Math.PI * theta);

The static import construct allows unqualified access to static members.


import static java.lang.Math.PI;

or:
import static java.lang.Math.*;

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

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

145

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
package MyPack;
import java.util.Date;

public class Main {


public static void main(String args[]) {
System.out.println(new Date());
}
}

146

También podría gustarte