Java Tutorial
Java Tutorial
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.
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 Java source code is compiled, each individual class is put into its own file
namedclassname.class.
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.
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
}
}
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
}
}
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;
}
}
}
assert const
false import
strictfp
package super
true
try
byte
do
case
double for
long
return
throw
catch
else
goto
native
short
throws
char
enum
if
new
void
static
this
while
transient
// legal
Myclass
// legal
$a
// legal
3_a
!theValue
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;
}
}
}
If you try to compile this code, you will get the following error message:
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.
int count;
}
}
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.
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);
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
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
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;
boolVariable = true;
}
}
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.
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 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
15
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
}
}
System.out.println(i);
}
16
The output:
System.out.println(f);//1048575
}
}
float type
float type represents single-precision numbers.
17
float type variables are useful when you need a fractional component. Here are
18
a = pi * r * r;
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
}
}
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
}
}
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);
}
20
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);
}
}
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
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';
ch1 is assigned the value 88, which is the ASCII (and Unicode) value that
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
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 = '@';
24
}
}
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);
}
}
'\'' 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 = '\'';
}
}
Description
\ddd
\uxxxx
\'
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.
27
The output:
Example
The following code uses string concatenation to create a very long string.
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.
The output:
Example 3
Be careful when you mix other types of operations with string concatenation.
Consider the following:
29
To complete the integer addition first, you must use parentheses, like this:
String s = "four: " + (2 + 2);
Escape List
The following table summarizes the Java String escape sequence.
Escape Sequence
Description
\ddd
\uxxxx
30
Escape Sequence
Description
\'
Single quote
\"
Double quote
\\
Backslash
\r
Carriage return
\n
New line
\f
Form feed
\t
Tab
\b
Backspace
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\"";
}
}
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.
}
}
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:
33
Syntax
You could declare the integer array variable myIntArray with the following statement:
int[] myIntArray;
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
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];
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];
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
Initial Value
byte
int
float
0.0f
char
'\u0000'
object reference
null
short
long
0L
double
0.0d
boolean
false
36
37
// An array of 7 elements
The output:
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[]) {
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;
39
The output:
40
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]
+----+----+----+
| |--------| 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();
}
}
}
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
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];
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
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:
Operator
Result
Addition
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.
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;
When you run this program, you will see the following output:
49
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;
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);
}
}
by one.
Different between Increment and Decrement Operator:
For example, this statement:
x = x + 1;
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;
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++;
53
}
}
Result
&
Logical AND
Logical OR
||
Short-circuit OR
&&
Short-circuit AND
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 output:
56
Example
The following program demonstrates the bitwise logical operators:
}
}
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:
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.
58
The output:
Result
==
Equal to
!=
Not equal to
>
Greater than
<
Less than
>=
<=
59
For example, the following code fragment is perfectly valid. It compares two int
values and assign the result to boolean value 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));
}
}
Syntax
The ? has this general form:
expression1 ? expression2 : expression3
The output:
61
Example
Here is another program that demonstrates the ? operator. It uses it to obtain the
absolute value of a variable.
i = -10;
k = i < 0 ? -i : i;
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
Java If Statement
The following the simplest form of Java if statement:
if(condition)
statement;
executed.
62
}
}
}
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("===");
}
}
}
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.");
}
}
}
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.
66
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 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
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.");
}
}
}
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:
71
System.out.println("i is 10 or more");
}
}
}
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;
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);
}
}
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");
}
}
}
}
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;
condition is a Boolean expression that tests the loop control variable. If condition is true, the
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;
Example
The following code writes the code logic from above again but loops reversively:
76
The output:
Example 2
Here is a program that tests for prime numbers using for loop statement.
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:
}
}
}
78
Example 4
The three sections of the for can be used for any purpose and parts of the for loop
can be empty.
}
}
}
The output:
79
Example 5
for loop can be nested to produce powerful logic, for example, we can use
80
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);
}
}
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 while loop repeats a statement or block while its controlling 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":
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;
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:
The output:
Example 3
The body of the while can be empty. For example, consider the following program:
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:
The output:
87
88
Example 4
The following program implements a very simple help system with do-while loop
andswitch statement.
89
case '5':
System.out.println("E");
break;
}
}
}
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
}
}
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
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;
}
If you try to compile the code above, you will get the following error message from
the Java compiler.
93
class A {
}
class B {
}
class C extends A {
}
class D extends A {
}
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
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
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);
}
}
mybox1.calculateVolume();
}
}
97
class Rectangle {
int width;
int height;
int getArea() {
return width * height;
}
}
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;
}
}
ob2 = ob1.doubleValue();
System.out.println("ob1.a: " + ob1.myMemberValue);
System.out.println("ob2.a: " + ob2.myMemberValue);
ob2 = ob2.doubleValue();
99
class Rectangle {
double width;
double height;
double area() {
return width * height;
}
100
width = w;
height = h;
}
}
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;
}
}
}
}
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);
}
}
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);
}
}
104
}
}
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;
}
}
105
}
}
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:
106
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;
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);
}
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{
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;
}
}
}
}
109
class Rectangle {
double width;//
double height;
Rectangle() {
width = 10;
height = 10;
}
double area() {
return width * height;
}
}
}
}
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;
}
}
}
}
The output:
111
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
}
}
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;
113
Rectangle(double w, double h) {
width = w;
height = h;
}
double area() {
return width * height;
}
}
114
}
}
The output:
class Rectangle {
double width;/*
double height;
115
Rectangle(double len) {
width = height = len;
}
double area() {
return width * height;
}
}
area = mybox2.area();
System.out.println(area);
area = mycube.area();
System.out.println(area);
}
}
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;
117
MyClass() {
this(0); // invokes MyClass(0)
}
}
Member variable
Method local variables
Static variable
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);
}
}
}
The output:
120
121
The following example shows how to use this to reference instance variable.
class Person{
private String name;
122
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
superOb.i = 10;
superOb.showBase();
System.out.println();
subOb.i = 7;
subOb.showBase();
subOb.showChild();
System.out.println();
subOb.sum();
}
}
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
You can only have one superclass for any subclass. Java does not support the
multiple inheritance. A class can be a superclass of itself.
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;
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);
}
}
126
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();
}
}
127
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
class Base {
int i;
Base(int a) {
i = a;
}
void show() {
System.out.println("i: " + i);
}
}
SubClass(int a, int c) {
super(a);
k = c;
129
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}
The following output will be generated if you run the code above:
class Base {
int i;
Base(int a) {
i = a;
}
void show() {
130
131
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
132
Polymorphism
With polymorphism we can call methods from class hierarchy using a uniform
interface. The compiler will determine dynamically which implementation to use.
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();
}
}
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());
}
}
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
// ...
return-type method-nameN(parameter-list);
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
callback() is declared using the public access specifier. When you implement an
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 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);
}
}
interface MyInterface {
void callback(int param);
void show();
}
140
Variables in Interfaces
We can use interface to organize constants.
interface MyConstants {
int NO = 0;//
int YES = 1;
}
141
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
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;
143
A package hierarchy must be reflected in the file system of your Java development
system.
Then try executing the class, using the following command line:
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);
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
146