Академический Документы
Профессиональный Документы
Культура Документы
When Java source code is compiled, each individual class is put into its own file
namedclassname.class.
publicclassMain{
//Yourprogrambeginswithacalltomain().
/*
publicstaticvoidmain(Stringargs[]){
ThisisasimpleJavaprogram.Callthisfile"Main.java".
System.out.println("Java.");
*/
Comment is a remark for a program. The contents of a comment are ignored by the
compiler. The next line of code in the program is shown here:
In Java, a source file is called a compilation unit. It is a text file that contains one or
more class definitions. The Java compiler requires that a source file use the .java
filename extension.
In Java, all code must reside inside a class. By convention, the name of the public
class should match the its file name. And Java is case-sensitive.
publicclassMain{
The keyword class declares that a new class is being defined. Main is the name of
the class. The entire class definition is between the opening curly brace ({) and the
closing curly brace (}). The next line in the program is the single-line comment,
shown here:
The javac compiler creates a file called Main.class. Main.class contains the byte
code version of the program.
To run the program, use the Java interpreter, called java. Pass the class
name Mainas a command-line argument, as shown here:
C:\>javaMain
A single-line comment begins with a // and ends at the end of the line. The next line
of code is shown here:
publicstaticvoidmain(Stringargs[]){
Java applications begin execution by calling main(Stringargs[]). Java is casesensitive. Thus, Main is different from main.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
publicstaticvoidmain(Stringargs[]){
intnum,num2;
intnum;//avariablecallednum
num=100;//assignsnumthevalue100
num=100;
num2=200;
System.out.println("Thisisnum:"+num);
System.out.println("Thisisnum:"+num);
num=num*2;
System.out.println("Thisisnum2:"+num2);
System.out.print("Thevalueofnum*2is");
System.out.println(num);
When you run this program, you will see the following output:
Java can group two or more statements into blocks of code. Code block is enclosing
the statements between opening and closing curly braces({}).
For example, a block can be a target for Java's if and for statements. Consider
thisif statement:
publicclassMain{
publicstaticvoidmain(Stringargs[]){
intx,y;
x=10;
y=20;
if(x<y){//beginablock
x=y;
y=0;
To declare more than one variable of the specified type, you may use a commaseparated list of variable names.
System.out.println("y="+y);
System.out.println("x="+x);
}//endofblock
publicclassMain{
}
}
Example
A block of code as the target of a for loop.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
inti,y;
y=20;
for(i=0;i<10;i++){//thetargetofthisloopisablock
System.out.println("Thisisi:"+i);
System.out.println("Thisisy:"+y);
abstractclassextendsimplementsnullstrictfptrue
y=y1;
assertconstfalseimportpackagesupertry
booleancontinuefinalinstanceofprivateswitchvoid
breakdefaultfinallyintprotectedsynchronizedvolatile
bytedofloatinterfacepublicthiswhile
casedoubleforlongreturnthrow
catchelsegotonativeshortthrows
charenumifnewstatictransient
$a//legal
3_a//illegal:startswithadigit
!theValue//illegal:bad1stchar
In Java, all variables must be declared before they can be used. The basic form of a
variable declaration is shown here:
typeidentifier[=value][,identifier[=value]...];
Java Identifiers are case sensitive. For example, myValue and MyValue are distinct
identifiers.
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:
To declare more than one variable of the specified type, use a comma-separated
list.
publicclassMain{
intd=3,e,f=5;//declaresthreemoreints,initializingdandf.
publicstaticvoidmain(String[]argv){
inta,b,c;//declaresthreeints,a,b,andc.
intATEST,count,i1,$Atest,this_is_a_test;
}
publicclassMain{
publicstaticvoidmain(String[]argv){
bytez=2;//initializesz.
doublepi=3.14;//declaresanapproximationofpi.
charx='x';//thevariablexhasthevalue'x'.
publicclassMain{
publicstaticvoidmain(String[]argv){
int2count,hl,a/b,
publicclassMain{
publicstaticvoidmain(String[]argv){
If you try to compile this code, you will get the following error message:
A variable is defined by an identifier, a type, and an optional initializer. The variables
also have a scope(visibility / lifetime).
count=100;//Cannotusecountbeforeitisdeclared!
intcount;
}
}
//cisdynamicallyinitialized
doublec=Math.sqrt(2*2);
Assignment Operator
System.out.println("cis"+c);
The assignment operator is the single equal sign, =. It has this general form:
}
var=expression;
type of var must be compatible with the type of expression. The assignment
operator allows you to create a chain of assignments.
publicclassMain{
publicstaticvoidmain(String[]argv){
intx,y,z;
Primitive Type
Reserved Word
Size
Min Value
Max Value
Boolean
boolean
N/A
N/A
N/A
Character
char
16-bit
Unicode 0
Unicode 216 - 1
Byte integer
byte
8-bit
-128
+127
Short integer
short
16-bit
-215
+215 - 1
Integer
int
32-bit
-231
+231 - 1
Dynamic Initialization
Long integer
long
64-bit
-263
+263 - 1
Floating-point
float
32-bit
1.4e-045
3.4e+038
Double precision
floating-point
double
64-bit
4.9e-324
1.8e+308
x=y=z=100;//setx,y,andzto100
System.out.println("xis"+x);
System.out.println("yis"+y);
System.out.println("zis"+z);
}
}
The output:
publicclassMain{
publicstaticvoidmain(Stringargs[]){
10
Name
Width in Bits
Approximate Range
float
32
1.4e-045 to 3.4e+038
Java Integers
Java has a boolean type for logical values. This is the type returned by all relational
operators.
Java defines four integer types: byte, short, int, and long.
Integer types are signed and can have positive and negative values.
Value
Name
Width
Range
long
64
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Boolean literals are only two logical values: true and false. The values
of true andfalse do not convert into any numerical representation.
int
32
-2,147,483,648 to 2,147,483,647
The true literal in Java does not equal 1, nor does the false literal equal 0. In Java,
they can only be assigned to variables declared as boolean.
short
16
-32,768 to 32,767
Boolean class
byte
-128 to 127
Literals
The Boolean class wraps a primitive type boolean in an object. An object of type
Boolean contains a single field whose type is boolean.
Boolean class has the methods for converting a boolean to a String and a String to a
boolean.
Example
Here is a program that demonstrates the boolean type:
Name
Width in Bits
Approximate Range
double
64
4.9e-324 to 1.8e+308
publicstaticvoidmain(Stringargs[]){
booleanboolVariable;
boolVariable=false;
System.out.println("bis"+boolVariable);
11
12
Byte variables are declared by use of the byte keyword. The following declares two
byte variables called b and c:
boolVariable=true;
byteb,c;
System.out.println("bis"+boolVariable);
byte is a signed 8-bit type that has a range from -128 to 127.
The following code creates two byte type variables and assigns values.
publicclassMain{
publicstaticvoidmain(String[]args){
byteb1=100;
Output:
byteb2=20;
System.out.println("Valueofbytevariableb1is:"+b1);
System.out.println("Valueofbytevariableb1is:"+b2);
}
}
Example 2
The true literal in Java does not equal 1, nor does the false literal equal 0. In Java,
they can only be assigned to variables declared as boolean.
publicclassMain{
The Byte class wraps a value of primitive type byte in an object. Byte class provides
several methods for converting a byte to a String and a String to a byte.
publicstaticvoidmain(String[]argv){
booleanb=true;
inti=b;
short is a signed 16-bit type. short type variable has a range from -32,768 to 32,767.
If you try to compile the program, the following error message will be generated by
compiler.
shorts;
shortt;
13
14
longresult=(long)Integer.MAX_VALUE*(long)10;
System.out.println(result);//21474836470
When byte and short values are used in an expression they are promoted to int
when the expression is evaluated.
int is a signed 32-bit type that has a range from 2,147,483,648 to 2,147,483,647.
}
}
Java long type 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.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
publicstaticvoidmain(String[]args){
longl=0x7ffffffffffffffL;
inti=010;
System.out.println("lis"+l);
System.out.println(i);
The output:
Example
15
16
System.out.print(d);//3.14159
}
An integer literal can always be assigned to a long variable. An integer can also be
assigned to a char as long as it is within range.
publicclassMain{
publicstaticvoidmain(String[]argv){
intf=0XFFFFF;
System.out.println(f);//1048575
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:
publicclassMain{
publicstaticvoidmain(Stringargs[]){
doublepi,r,a;
float type
r=10.8888;//radiusofcircle
a=pi*r*r;
float type variables are useful when you need a fractional component. Here are
System.out.println("Areaofcircleis"+a);
floathigh,low;
pi=3.1415926;//pi,approximately
The output:
float is 32-bit width and its range is from 1.4e045 to 3.4e+038 approximately.
Floating-point literals in Java default to double precision. To specify a float literal,
you must append an F or f to the constant.
The following code shows how to declare float literals.
Example
double type numbers have decimal values with a fractional component. They can be
expressed in either standard or scientific notation. Standard notation consists of a
whole number component followed by a decimal point followed by a fractional
component. For example, 2.0, 3.14159, and 0.6667.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
floatd=3.14159F;
17
18
publicclassMain{
doubled2=314159E05;
publicstaticvoidmain(Stringargs[]){
doubled3=2e+100;
doubled=3.14159;
System.out.println("d1is"+d1);
System.out.print(d);//3.14159
System.out.println("d2is"+d2);
System.out.println("d3is"+d3);
Example 2
You can explicitly specify a double literal by appending a D or d.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
doubled=3.14159D;
System.out.print(d);//3.14159
}
publicclassMain{
publicstaticvoidmain(String[]args){
System.out.println(1.0/0.0);
Scientific notation
publicclassMain{
publicstaticvoidmain(String[]argv){
doubled1=6.022E23;
19
20
double Infinity
publicclassMain{
publicstaticvoidmain(String[]args){
System.out.println(1.0/0.0);
}
Output:
double NaN
Dividing 0.0 by 0.0 returns NaN. square root of a negative number is NaN. For
example, System.out.println(0.0/0.0) and System.out.println(Math.sqrt(
1.0))output NaN.
Char Literals
Characters in Java are indices into the Unicode character set. character is
represented inside a pair of single quotes. For example, 'a', 'z', and '@'.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
charch1,ch2;
publicclassMain{
ch1=88;//codeforX
publicstaticvoidmain(String[]args){
Doubled1=newDouble(+0.0);
ch2='Y';
System.out.println(d1.doubleValue());
Doubled2=newDouble(0.0);
System.out.print("ch1andch2:");
System.out.println(d2.doubleValue());
System.out.println(ch1+""+ch2);//ch1andch2:XY
System.out.println(d1.equals(d2));
System.out.println(+0.0==0.0);
21
22
System.out.println("chis"+ch);//chisa
ch='@';
ch1 is assigned the value 88, which is the ASCII (and Unicode) value that
corresponds to the letter X.
System.out.println("chis"+ch);//chis@
Example
char type value can be used as an integer type and you can perform arithmetic
ch='$';
operations.
publicclassMain{
System.out.println("chis"+ch);//chis$
publicstaticvoidmain(Stringargs[]){
ch='%';
charch1;
System.out.println("chis"+ch);//chis%
ch1='X';
System.out.println("ch1contains"+ch1);//ch1containsX
ch='#';
System.out.println("chis"+ch);//chis#
ch1=(char)(ch1+1);//incrementch1
System.out.println("ch1isnow"+ch1);//ch1isnowY
}
}
Example 2
The following code shows that we can assign non-letter character to Java char type.
Example 3
The following code stores unicode value into a char variable. The unicode literal
uses\uxxxx format.
publicclassMain{
publicclassMain{
publicstaticvoidmain(String[]args){
publicstaticvoidmain(String[]argv){
intx=75;
charch='a';
chary=(char)x;
23
24
charhalf='\u00AB';
System.out.println("yis"+y+"andhalfis"+half);
Escape Sequence
Description
\ddd
\uxxxx
\'
Single quote
\"
Double quote
\\
Backslash
\r
Carriage return
\n
New line
\f
Form feed
\t
Tab
\b
Backspace
For octal notation, use the backslash followed by the three-digit number. For
example,'\141' is the letter 'a'.
For hexadecimal, you enter a backslash-u (\u), then exactly four hexadecimal digits.
For example, '\u0061' is the ISO-Latin-1 'a' because the top byte is zero. '\ua432' is a
Japanese Katakana character.
publicclassMain{
publicstaticvoidmain(String[]argv){
charch='\'';
System.out.println("chis"+ch);//chis'
}
}
The String class represents character strings. A quoted string constant can be
assigned to a String variable.
25
26
Example
The following code uses string concatenation to create a very long string.
The following code declares String type variable with Java String literal.
publicclassMain{
publicclassMain{
publicstaticvoidmain(Stringargs[]){
publicstaticvoidmain(String[]argv){
StringlongStr="Ajava.com"+
Stringstr="thisisatestfromjava2s.com";
"Bjava.com"+
System.out.println(str);
"Cjava.com"+
"Djava.com.";
System.out.println(longStr);
The output:
Example 2
publicclassMain{
publicstaticvoidmain(String[]argv){
Stringage="9";
Strings="Heis"+age+"yearsold.";
System.out.println(s);
}
publicclassMain{
publicstaticvoidmain(String[]argv){
intage=1;
Strings="Heis"+age+"yearsold.";
System.out.println(s);
}
}
The output:
27
28
Example 3
Escape List
Be careful when you mix other types of operations with string concatenation.
Consider the following:
Description
\ddd
\uxxxx
\'
Single quote
\"
Double quote
\\
Backslash
\r
Carriage return
\n
New line
\f
Form feed
\t
Tab
\b
Backspace
publicclassMain{
publicstaticvoidmain(String[]argv){
Strings="four:"+2+2;
System.out.println(s);
}
}
To complete the integer addition first, you must use parentheses, like this:
Strings="four:"+(2+2);
29
30
The following example escapes the new line string and double quotation string.
If you try to compile this program, the compiler will generate the following error
message.
publicclassMain{
publicstaticvoidmain(String[]argv){
Strings="java.com";
System.out.println("sis"+s);
s="two\nlines";
System.out.println("sis"+s);
s="\"quotes\"";
System.out.println("sis"+s);
equals() vs ==
equals() method and the == operator perform two different operations. equals(
)method compares the characters inside a String object. The == operator compares
two object references to see whether they refer to the same instance.
Example 4
Java String literials must be begin and end on the same line. If your string is across
several lines, the Java compiler will complain about it.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
Strings1="demo.com";
publicclassMain{
publicstaticvoidmain(String[]argv){
Strings="line1
line2
";
Strings2=newString(s1);
System.out.println(s1+"equals"+s2+">"+s1.equals(s2));
System.out.println(s1+"=="+s2+">"+(s1==s2));
}
}
31
32
Here the square brackets appear after the variable name, rather than after the type
name.
This is exactly equivalent to the previous statement. int[] form is preferred since it
indicates more clearly that the type is an array of values of type int.
inta1[]=newint[3];
int[]a2=newint[3];
Array create
The array type is the type of the array variable. The array object is the memory
allocated for an array variable.
After you have declared an array variable, you can define an array that it references:
When defining an array we can first define the array type and allocate the memory
later.
myIntArray=newint[10];//Defineanarrayof10integers
This statement creates an array that stores 10 values of type int and stores a
reference to the array in the variable myIntArray.
Syntax
You could declare the integer array variable myIntArray with the following statement:
int[]myIntArray;//Declareanintegerarrayvariable
You could also declare the array variable and define the array of type int to hold 10
integers with a single statement.
int[]myIntArray=newint[10];//Anarrayof10integers
The variable myIntArray is now a type for an integer array. No memory has been
allocated to hold an array itself.
The first part of the definition specifies the type of the array. The element type name,
int in this case, is followed by an empty pair of square brackets.
Later we will create the array by allocating memory and specify how many elements
it can contain.
The part of the statement that follows the equal sign defines the array.
The square brackets following the type indicates that the variable is for an array of
int values, and not for storing a single value of type int.
The keyword new indicates that you are allocating new memory for the array, and
int[10] specifies that the capacity is 10 variables of type int in the array.
Alternative Syntax
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.
33
34
Element Type
Initial Value
byte
int
float
0.0f
char
'\u0000'
object reference
null
short
long
0L
double
0.0d
boolean
false
inta2[]={1,2,3,4,5};
inta3[]={4,3,2,1};
System.out.println("lengthofa1is"+a1.length);
System.out.println("lengthofa2is"+a2.length);
System.out.println("lengthofa3is"+a3.length);
}
}
35
intdays[]={31,28,31,};
36
System.out.println("days[2]is"+days[2]);
System.out.println("days[2]is"+days[10]);
The output:
for loop
We usually use a for loop to access each element in an array. The following code
uses a one-dimensional array to find the average of a set of numbers.
publicclassMain{
refers to the element in the data array corresponding to the index value 9.
publicstaticvoidmain(Stringargs[]){
The index for an array element is the offset of the element from the beginning of the
array.
doublenums[]={10.1,11.2,12.3,13.4,14.5};
The first element has an index of 0, the second has an index of 1, the third an index
of 2, and so on.
intI;
for(i=0;i<5;i++)
doubleresult=0;
result=result+nums[i];
System.out.println("Averageis"+result/5);
}
}
The array index has to have a value equals to or greater than zero.
Array stores elements and we use index to reference a single value in an array. The
starting value of the index is 0. If you try to reference elements with negative
numbers or numbers greater than the array length, you will get a run-time error.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
intdays[]={1,2,3,};
37
The output:
38
[1][0][1][1][1][2][1][3][1][4]
for(arrayTypevariableName:array){
[2][0][2][1][2][2][2][3][2][4]
processeachvariableName
[3][0][3][1][3][2][3][3][3][4]
++++
publicclassMain{
|1|2|3|
publicstaticvoidmain(Stringargs[]){
++++
intdays[]={1,2,3,};
|4|5|6|
for(inti:days){
++++
System.out.println(i);
|7|8|9|
++++
}
++++++
|||1|2|3|
++++++++++
|||4|5|6|
++++++++++
|||7|8|9|
++++++
The following code use nested for loop to assign values to a two-dimensional array.
This allocates a 4-by-5 array and assigns it to twoD. This array will look like the one
shown in the following:
publicclassMain{
publicstaticvoidmain(Stringargs[]){
inttwoD[][]=newint[4][5];
for(inti=0;i<4;i++){
for(intj=0;j<5;j++){
twoD[i][j]=i*j;/*www.java2s.com*/
[leftIndex][rightIndex]
[0][0][0][1][0][2][0][3][0][4]
39
for(inti=0;i<4;i++){
40
for(intj=0;j<5;j++){
System.out.println();
System.out.print(twoD[i][j]+"");
System.out.println();
}
}
Example
The following program creates a 3 by 4 by 5, three-dimensional array.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
intthreeD[][][]=newint[3][4][5];
for(inti=0;i<3;i++)
for(intj=0;j<4;j++)
for(intk=0;k<5;k++)
threeD[i][j][k]=i*j*k;
Example 2
The following code shows how to iterate over Multidimensional Arrays with for-each.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
intsum=0;
intnums[][]=newint[3][5];
//givenumssomevalues
for(inti=0;i<3;i++){
for(intj=0;j<4;j++){
for(intk=0;k<5;k++)
System.out.print(threeD[i][j][k]+"");
System.out.println();
for(inti=0;i<3;i++)
for(intj=0;j<5;j++)
nums[i][j]=(i+1)*(j+1);
//useforeachfortodisplayandsumthevalues
41
42
for(intx[]:nums){
+++++++++++
for(inty:x){
|||7|8|9|10|
System.out.println("Valueis:"+y);
+++++++
sum+=y;
}
For example, the following code allocates the second dimension manually.
publicclassMain{
System.out.println("Summation:"+sum);
publicstaticvoidmain(String[]argv){
inttwoD[][]=newint[4][];
twoD[0]=newint[5];
twoD[1]=newint[5];
twoD[2]=newint[5];
twoD[3]=newint[5];
}
}
When allocating dimensions manually, you do not need to allocate the same number
of elements for each dimension.
Example 3
The following program creates a two-dimensional array in which the sizes of the
second dimension are unequal.
publicclassMain{
Jagged array
publicstaticvoidmain(Stringargs[]){
When you allocate memory for a multidimensional array, you can allocate the
remaining dimensions separately.
twoD[0]=newint[1];
twoD[2]=newint[3];
+++++
twoD[3]=newint[4];
|||1|2|
for(inti=0;i<4;i++){
+++++++++
for(intj=0;j<i+1;j++){
|||4|5|6|
twoD[i][j]=i+j;
inttwoD[][]=newint[4][];
twoD[1]=newint[2];
43
44
{0,1,2,3},
for(inti=0;i<4;i++){
{0,1,2,3}
for(intj=0;j<i+1;j++)
};
System.out.print(twoD[i][j]+"");
for(inti=0;i<4;i++){
System.out.println();
for(intj=0;j<4;j++){
System.out.print(m[i][j]+"");
System.out.println();
}
}
}
When you run this program, you will get the following output:
Example 4
We can initialize multidimensional arrays during declaration by enclosing each
dimension's initializer within its own set of curly braces.
Operator
Result
Addition
Multiplication
publicclassMain{
publicstaticvoidmain(Stringargs[]){
doublem[][]={
{0,1,2,3},
{0,1,2,3},
45
46
Operator
Result
Division
Modulus
++
Increment
System.out.println("IntegerArithmetic");
inta=1+1;
intb=a*3;
intc=b/4;
intd=ca;
inte=d;
System.out.println("a="+a);
System.out.println("b="+b);
+=
Addition assignment
-=
Subtraction assignment
*=
Multiplication assignment
/=
Division assignment
%=
Modulus assignment
--
Decrement
System.out.println("c="+c);
System.out.println("d="+d);
System.out.println("e="+e);
intx=42;
System.out.println("xmod10="+x%10);
doubley=42.25;
System.out.println("ymod10="+y%10);
}
}
When you run this program, you will see the following output:
The operands of the arithmetic operators must be of a numeric type. You cannot use
arithmetic operators on boolean types, but you can use them on char types.
The basic arithmetic operations are addition, subtraction, multiplication, and division.
They behave as you would expect. The minus operator also has a unary form which
negates its single operand.
The quick demo below shows how to do a simple calculation in Java with basic
arithmetic operators.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
47
48
The modulus operator, %, returns the remainder of a division operation. The modulus
operator can be applied to floating-point types as well as integer types.
System.out.println("b="+b);
System.out.println("c="+c);
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=varopexpression;
can be rewritten as
x=x+1;
publicclassMain{
//fromwww.java2s.com
publicstaticvoidmain(Stringargs[]){
x++;
inta=1;
This statement:
intb=2;
x=x1;
intc=3;
is equivalent to
a+=1;
x;
b*=2;
c+=a*b;
The increment and decrement operators are unique in that they can appear both in
postfix form and prefix form. In the postfix form they follow the operand, for
example,i++. In the prefix form, they precede the operand, for example, i.
c%=3;
System.out.println("a="+a);
49
50
The difference between these two forms appears when the increment and/or
decrement operators are part of a larger expression. In the prefix form, the operand
is incremented or decremented before the value is used in the expression. In postfix
form, the value is used in the expression, and then the operand is modified.
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--
y = --x
publicclassMain{
/*www.java2s.com*/
publicstaticvoidmain(Stringargs[]){
inta=1;
intb=2;
intc=++b;
intd=a++;
For example:
x=42;
System.out.println("a="+a);
y=++x;
System.out.println("b="+b);
System.out.println("c="+c);
y is set to 43, because the increment occurs before x is assigned to y. Thus, the line
System.out.println("d="+d);
y=++x;
y=x;
the value of x is obtained before the increment operator is executed, so the value of
y is 42.
51
52
True table
Operator
Result
A|B
A&B
A^B
!A
&
Logical AND
False
False
False
False
False
True
Logical OR
True
False
True
False
True
False
False
True
True
False
True
True
||
Short-circuit OR
True
True
True
True
False
False
&&
Short-circuit AND
&=
AND assignment
|=
OR assignment
publicclassMain{
publicstaticvoidmain(Stringargs[]){
booleana=true;
booleanb=false;
booleanc=a|b;
booleand=a&b;
^=
XOR assignment
booleane=a^b;
booleanf=(!a&b)|(a&!b);
booleang=!a;
==
Equal to
!=
Not equal to
?:
Ternary if-then-else
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("a|b="+c);
System.out.println("a&b="+d);
System.out.println("a^b="+e);
System.out.println("!a&b|a&!b="+f);
System.out.println("!a="+g);
53
54
System.out.println("a&b="+d);
System.out.println("a^b="+e);
]]>
System.out.println("~a&b|a&~b="+f);
The output:
System.out.println("~a="+g);
}
}
Example
The OR operator results in true when one operand is true, no matter what the
second operand is. The AND operator results in false when one operand is false, no
matter what the second operand is. If you use the || and &&, Java will not evaluate
the right-hand operand when the outcome can be determined by the left operand
alone.
The following code shows how you can use short-circuit logical operator to ensure
that a division operation will be valid before evaluating it:
publicclassMain{
publicclassMain{
publicstaticvoidmain(Stringargs[]){
publicstaticvoidmain(String[]argv){
inta=1;
intdenom=0;
intb=2;
intnum=3;
intc=a|b;
if(denom!=0&&num/denom>10){
intd=a&b;
System.out.println("Here");
inte=a^b;
}else{
intf=(~a&b)|(a&~b);
System.out.println("There");
intg=~a&0x0f;
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("a|b="+c);
55
The output:
56
If we want to turn of the shortcut behaviour of logical operators we can use & and |.
Example 2
The following code uses a single & ensures that the increment operation will be
applied to e whether c is equal to 1 or not.
Operator
Result
==
Equal to
!=
Not equal to
>
Greater than
<
Less than
>=
<=
publicclassMain{
publicstaticvoidmain(String[]argv){
intc=0;
inte=99;
intd=0;
if(c==1&e++<100)
d=100;
For example, the following code fragment is perfectly valid. It compares two int
values and assign the result to boolean value c.
System.out.println("eis"+e);
System.out.println("dis"+d);
publicclassMain{
publicstaticvoidmain(String[]argv){
inta=4;
The output:
intb=1;
booleanc=a<b;
System.out.println("cis"+c);
}
}
57
Result
58
Example
publicstaticvoidmain(String[]argv){
intdenom=10;
intnum=4;
doubleratio;
publicclassMain{
publicstaticvoidmain(Stringargs[]){
ratio=denom==0?0:num/denom;
//outcomeofarelationaloperatorisabooleanvalue
System.out.println("ratio="+ratio);
System.out.println("10>9is"+(10>9));
The output:
The output generated by this program is shown here:
Example
Syntax
The ? has this general form:
Here is another program that demonstrates the ? operator. It uses it to obtain the
absolute value of a variable.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
inti,k;
expression1?expression2:expression3
i=10;
k=i<0?i:i;
System.out.print("Absolutevalueof");
evaluated.
System.out.println(i+"is"+k);
i=10;
k=i<0?i:i;
System.out.print("Absolutevalueof");
System.out.println(i+"is"+k);
publicclassMain{
59
60
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.
Java If Statement
publicclassMain{
publicstaticvoidmain(Stringargs[]){
intx,y;
if(condition)
statement;
x=10;
executed.
y=20;
if(x<y){
System.out.println("xislessthany");
}
publicclassMain{
x=x*2;
publicstaticvoidmain(Stringargs[]){
if(x==y){
intnum=99;
System.out.println("xnowequaltoy");
if(num<100){
System.out.println("numislessthan100");
x=x*2;
if(x>y){
System.out.println("xnowgreaterthany");
if(x==y){
System.out.println("===");
}
}
}
61
62
if(condition)
statement1;
else
Example 2
statement2;
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.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
booleanb;
publicclassMain{
b=false;
publicstaticvoidmain(String[]argv){
if(b){
inti=1;
System.out.println("Thisisexecuted.");
}else{
if(i>0){
System.out.println("ThisisNOTexecuted.");
System.out.println("Here");
i=1;
}else
System.out.println("There");
}
if(b==true)...
]]>
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.
63
64
statement;
elseif(condition)
statement;
elseif(condition)
statement;
.
.
else
statement;
publicclassMain{
publicstaticvoidmain(String[]argv){
inti=10;
intj=4;
publicclassMain{
publicstaticvoidmain(Stringargs[]){
intmonth=4;
Stringvalue;
if(month==1)
value="A";
elseif(month==2)
value="B";
elseif(month==3)
value="C";
elseif(month==4)
value="D";
else
intk=200;
inta=3;
intb=5;
intc=0;
intd=0;
if(i==10){
if(j<20){
a=b;
}
if(k>100){
c=d;
}
else{
value="Error";
a=c;
}
System.out.println("value="+value);
}else{
a=d;
65
66
casevalueN:
System.out.println("a="+a);
statementsequence
System.out.println("b="+b);
break;
System.out.println("c="+c);
default:
System.out.println("d="+d);
defaultstatementsequence
The value1 to valueN are the possible case values for expression. Duplicate case
values are not allowed.
The output:
A break statement jumps out of switch statement to the first line that follows the
entireswitch statement.
Here is a simple example that uses a switch statement:
publicclassMain{
publicstaticvoidmain(Stringargs[]){
for(inti=0;i<6;i++)
switch(i){
case0:
System.out.println("iiszero.");
break;
switch(expression){
case1:
casevalue1:
System.out.println("iisone.");
statementsequence
break;
break;
casevalue2:
case2:
statementsequence
System.out.println("iistwo.");
break;
break;
case3:
System.out.println("iisthree.");
break;
67
68
System.out.println("iislessthan5");
default:
break;
System.out.println("iisgreaterthan3.");
case5:
case6:
case7:
case8:
case9:
System.out.println("iislessthan10");
break;
default:
System.out.println("iis10ormore");
}
}
}
Example
The break statement is optional. If you omit the break, execution will continue on into
the next case. For example, consider the following program:
publicclassMain{
publicstaticvoidmain(Stringargs[]){
for(inti=0;i<12;i++)
switch(i){
case0:
case1:
Example 2
case2:
case3:
Java supports the nested switch statements. For example, the following fragment is
a valid nested switch statement.
case4:
publicclassMain{
69
70
publicstaticvoidmain(Stringargs[]){
charp='a';
for(inti=0;i<6;i++)
switch(i){
Stringdetails="";
case0:
switch(i+1){//nestedswitch
switch(p){
case0:
case'E':
System.out.println("targetiszero");
case'e':
break;
details+="\tE...\n";
case1:
case'D':
System.out.println("targetisone");
case'd':
break;
details+="\tD...\n";
case'C':
break;
case'c':
case2://...
details+="\tC...\n";
case'B':
case'b':
details+="\tB...\n";
The output:
case'A':
case'a':
details+="\tA.\n";
break;
default:
Example 3
details="That's";
break;
System.out.println(details);
importjava.util.Scanner;
}
}
publicclassMain{
staticScannersc=newScanner(System.in);
publicstaticvoidmain(String[]args){
71
72
Example 4
for(initialization;condition;iteration)
The following code shows how to use string literals in switch statements.
statement;
publicclassMain{
publicstaticvoidmain(String[]args){
String[]data=newString[]{"a","b","java2s.com"};
for(Stringargument:data){
switch(argument){
the for loop continues to iterate. If condition is false, the loop terminates.
The iteration determines how the loop control variable is changed each time the loop
iterates.
case"a":
case"b":
System.out.println("java2s.com");
Here is a short program that illustrates the for loop. i is the loop control variable
and iis initialized to zero in the initialization. At the start of each iteration, the
conditional testx<10 is performed. If the outcome of this test is true,
the println() statement is executed, and then the iteration portion of the loop is
executed. This process continues until the conditional test is false.
break;
publicclassMain{
case"help":
publicstaticvoidmain(Stringargs[]){
System.out.println("displayHelp");
inti;
break;
default:
for(i=0;i<10;i=i+1)
System.out.println("Illegalcommandlineargument");
System.out.println("Thisisi:"+i);
System.out.println("aorb");
break;
case"java2s.com":
}
}
Java for loop statement provides a powerful way of writing loop statement.
73
74
Example
Example 2
The following code writes the code logic from above again but loops reversively:
Here is a program that tests for prime numbers using for loop statement.
publicclassMain{
publicclassMain{
publicstaticvoidmain(Stringargs[]){
publicstaticvoidmain(Stringargs[]){
for(intn=10;n>0;n)
intnum;
System.out.println("n:"+n);
booleanisPrime=true;
num=50;
}]]>
for(inti=2;i<=num/2;i++){
The output:
if((num%i)==0){
isPrime=false;
break;
}
}
if(isPrime)
System.out.println("Prime");
else
System.out.println("NotPrime");
75
76
publicclassMain{
publicstaticvoidmain(Stringargs[]){
The output:
inti=0;
booleandone=false;
for(;!done;){
Example 3
System.out.println("iis"+i);
if(i==10)
Java allows two or more variables to control a for loop. And you can include
multiple statements in both the initialization and iteration portions of the for loop.
Each statement is separated from the next by a comma. Here is an example:
done=true;
i++;
publicclassMain{
publicstaticvoidmain(Stringargs[]){
for(inta=1,b=4;a<b;a++,b){
The output:
System.out.println("a="+a);
System.out.println("b="+b);
}
}
}
Example 4
The three sections of the for can be used for any purpose and parts of the for loop
can be empty.
77
Example 5
for loop can be nested to produce powerful logic, for example, we can use
nestedfor loop to iterate a two-dimensional array. For example, here is a program
that nestsfor loops:
78
publicclassMain{
publicclassMain{
publicstaticvoidmain(Stringargs[]){
publicstaticvoidmain(Stringargs[]){
for(inti=0;i<10;i++){
String[]arr=newString[]{"java2s.com","a","b","c"};
for(intj=i;j<10;j++)
for(Strings:arr){
System.out.print(".");
System.out.println(s);
System.out.println();
The output:
The output produced by this program is shown here:
Example 6
The following code uses the foreach style loop to iterate a two-dimensional array.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
intsum=0;
intnums[][]=newint[3][5];
The foreach loop iterates elements in a sequence without using the loop counter.
for(intj=0;j<5;j++){
nums[i][j]=(i+1)*(j+1);
for(typevariable_name:array){
}
}
//useforeachfortodisplayandsumthevalues
for(intx[]:nums){
79
for(inti=0;i<3;i++){
for(inty:x){
80
System.out.println("Valueis:"+y);
break;
sum+=y;
if(found)
System.out.println("Summation:"+sum);
System.out.println("Valuefound!");
The while loop repeats a statement or block while its controlling condition is true.
Example 7
Here is a while loop that counts down from 10, printing exactly ten lines of "tick":
publicclassMain{
publicstaticvoidmain(Stringargs[]){
publicclassMain{
intnums[]={6,8,3,7,5,6,1,4};
publicstaticvoidmain(Stringargs[]){
intval=5;
intn=10;
booleanfound=false;
while(n>0){
//useforeachstylefortosearchnumsforval
System.out.println("n:"+n);
for(intx:nums){
n;
if(x==val){
found=true;
81
82
}
}
When you run this program, you will get the following result:
Example 2
The body of the while loop will not execute if the condition is false. For example, in
the following fragment, the call to println() is never executed:
publicclassMain{
publicstaticvoidmain(String[]argv){
inta=10,b=20;
while(a>b){
System.out.println("Thiswillnotbedisplayed");
Example
The following code shows how to use the while loop to calculate sum.
publicclassMain{
}
System.out.println("Youarehere");
}
}
The output:
publicstaticvoidmain(String[]args){
intlimit=20;
intsum=0;
inti=1;
while(i<=limit){
Example 3
The body of the while can be empty. For example, consider the following program:
sum+=i++;
}
System.out.println("sum="+sum);
publicclassMain{
publicstaticvoidmain(Stringargs[]){
inti,j;
i=10;
83
j=20;
84
The output:
//findmidpointbetweeniandj
while(++i<j)
;
System.out.println("Midpointis"+i);
}
}
The while loop in the code above has no loop body and i and j are calculated in
the while loop condition statement. It generates the following output:
do{
do{
//bodyofloop
System.out.println("n:"+n);
}while(condition);
}while(n>0);
}
}
publicclassMain{
publicstaticvoidmain(Stringargs[]){
intn=10;
do{
System.out.println("n:"+n);
n;
}while(n>0);
}
}
85
86
System.out.println("A");
break;
case'2':
System.out.println("B");
break;
case'3':
System.out.println("C");
break;
case'4':
System.out.println("D");
break;
Example 4
case'5':
The following program implements a very simple help system with dowhile loop
andswitch statement.
break;
publicclassMain{
publicstaticvoidmain(Stringargs[])throwsjava.io.IOException{
System.out.println("E");
charchoice;
do{
System.out.println("Helpon:");
System.out.println("1.A");
System.out.println("2.B");
System.out.println("3.C");
System.out.println("4.D");
System.out.println("5.E");
System.out.println("Chooseone:");
choice=(char)System.in.read();
}while(choice<'1'||choice>'5');
System.out.println("\n");
switch(choice){
case'1':
87
88
Syntax
classBox{
intwidth;
intheight;
classclassname{
intdepth;
typeinstancevariable1;
typeinstancevariable2;
//...
Java Object
typeinstancevariableN;
When you create a class, you are creating a new data type. You can use this type to
declare objects of that type.
typemethodname1(parameterlist){
//bodyofmethod
}
typemethodname2(parameterlist){
//bodyofmethod
Boxmybox=newBox();
}
//...
typemethodnameN(parameterlist){
This statement combines the two steps. It can be rewritten like this to show each
step more clearly:
//bodyofmethod
Boxmybox;//declarereferencetoobject
mybox=newBox();//allocateaBoxobject
Example
Here is a class called Box that defines three member variables: width, height,
anddepth.
The first line declares mybox as a reference to an object of type Box. After this line
executes, mybox contains the value null. null indicates that mybox does not yet point
to an actual object.
Any attempt to use mybox at this point will result in an error.
The next line allocates an actual object and assigns a reference to mybox. After the
second line executes, you can use mybox as a Box object.
mybox holds the memory address of the actual Box object.
A class defines a new type of data. In this case, the new type is called Box. To
create aBox object, you will use a statement like the following:
classBox{
89
90
intwidth;
myBox.width=10;
intheight;
intdepth;
}
publicclassMain{
If you try to compile the code above, you will get the following error message from
the Java compiler.
publicstaticvoidmain(Stringargs[]){
BoxmyBox=newBox();
myBox.width=10;
Java provides the run-time operator instanceof to check class type for an object.
System.out.println("myBox.width:"+myBox.width);
objectinstanceoftype
classA{
myBox is an instance of Box. mybox contains its own copy of each instance
variable,width, height, and depth, defined by the class. To access these variables,
you will use the dot (.) operator.
mybox.width=10;
classB{
}
This statement assigns the width from mybox object to 10. Here is a complete
program that uses the Box class:
classCextendsA{
}
classBox{
classDextendsA{
intwidth;
intheight;
intdepth;
publicclassMain{
publicstaticvoidmain(Stringargs[]){
Aa=newA();
publicclassMain{
Bb=newB();
publicstaticvoidmain(Stringargs[]){
Cc=newC();
BoxmyBox;
Dd=newD();
91
92
System.out.println("bmaybecasttoObject");
if(ainstanceofA)
if(cinstanceofObject)
System.out.println("aisinstanceofA");
System.out.println("cmaybecasttoObject");
if(binstanceofB)
if(dinstanceofObject)
System.out.println("bisinstanceofB");
System.out.println("dmaybecasttoObject");
if(cinstanceofC)
System.out.println("cisinstanceofC");
if(cinstanceofA)
System.out.println("ccanbecasttoA");
if(ainstanceofC)
System.out.println("acanbecasttoC");
Aob;
ob=d;//Areferencetod
System.out.println("obnowreferstod");
if(obinstanceofD)
System.out.println("obisinstanceofD");
ob=c;//Areferencetoc
System.out.println("obnowreferstoc");
if(obinstanceofD)
System.out.println("obcanbecasttoD");
Classes usually consist of two things: instance variables and methods. Instance
variables are the data part of a class, while the methods defines the behaviours of a
class.
else
System.out.println("obcannotbecasttoD");
if(obinstanceofA)
System.out.println("obcanbecasttoA");
//allobjectscanbecasttoObject
if(ainstanceofObject)
Syntax
This is the general form of a method:
typename(parameterlist){
//bodyofmethod
}
System.out.println("amaybecasttoObject");
if(binstanceofObject)
93
94
type specifies the type of data returned by the method. If the method does not return
a value, its return type must be void. The name of the method is specified by name.
The parameter-list is a sequence of type and identifier pairs separated by commas.
If the method has no parameters, then the parameter list will be empty.
Methods that have a return type other than void return a value to the calling routine
using the following form of the return statement:
classBox{
intwidth;
intheight;
returnvalue;
intdepth;
voidcalculateVolume(){
System.out.print("Volumeis");
classRectangle{
System.out.println(width*height*depth);
intwidth;
intheight;
intgetArea(){
publicclassMain{
returnwidth*height;
publicstaticvoidmain(Stringargs[]){
Boxmybox1=newBox();
mybox1.width=10;
publicclassMain{
mybox1.height=20;
mybox1.depth=15;
publicstaticvoidmain(Stringargs[]){
Rectanglemybox1=newRectangle();
mybox1.calculateVolume();
intarea;
mybox1.width=10;
mybox1.height=20;
area=mybox1.getArea();
System.out.println("Areais"+area);
95
96
publicstaticvoidmain(Stringargs[]){
MyClassob1=newMyClass();
The output:
ob1.myMemberValue=2;
MyClassob2;
ob2=ob1.doubleValue();
In this line the return statement returns value from the getArea()method. And the
returned value is assigned to area.
System.out.println("ob1.a:"+ob1.myMemberValue);
System.out.println("ob2.a:"+ob2.myMemberValue);
area=mybox1.getArea();
The actual returned data type must be compatible with the declared return type .
The variable receiving the returned value (area) must be compatible with the return
type.
ob2=ob2.doubleValue();
System.out.println("ob2.aaftersecondincrease:"+ob2.myMemberValue);
}
The following code uses the returned value directly in a println( ) statement:
System.out.println("Areais"+mybox1.getArea());
Example
A method can return class types.
classMyClass{
intmyMemberValue=2;
MyClass(){
}
MyClassdoubleValue(){
MyClasstemp=newMyClass();
typemethodName(parameterTypevariable,parameterType2variable2,...){
temp.myMemberValue=temp.myMemberValue*2;
//bodyofmethod
returntemp;
The new Rectangle class has a new method which accepts the dimensions of a
rectangle and sets the dimensions with the passed-in value.
publicclassMain{
97
98
classRectangle{
Example 2
doublewidth;
doubleheight;
doublearea(){
classTest{
returnwidth*height;
inta;
Test(inti){
voidsetDim(doublew,doubleh){//Methodwithparameters
a=i;
width=w;
height=h;
booleanequals(Testo){
if(o.a==a)
returntrue;
else
publicclassMain{
returnfalse;
publicstaticvoidmain(Stringargs[]){
Rectanglemybox1=newRectangle();
doublevol;
publicclassMain{
mybox1.setDim(10,20);
publicstaticvoidmain(Stringargs[]){
Testob1=newTest(100);
vol=mybox1.area();
Testob2=newTest(100);
System.out.println("Areais"+vol);
System.out.println("ob1==ob2:"+ob1.equals(ob2));
The output:
99
100
doubleresult=ob.test(123.25);
System.out.println("Resultofob.test(123.25):"+result);
Java allows to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different.
When this is the case, the methods are said to be overloaded, and the process is
referred to as method overloading.
Overloaded methods have the same name but different parameters. Overloaded
methods must differ in the type and/or number of their parameters. Overloaded
methods may have different return types. return type alone is insufficient to
distinguish two methods.
}
}
classOverloadDemo{
voidtest(){
System.out.println("Noparameters");
}
voidtest(inta){
Example 3
The following code demonstrates method overloading and data type promotion.
System.out.println("a:"+a);
}
voidtest(inta,intb){
System.out.println("aandb:"+a+""+b);
classOverloadDemo{
voidtest(){
System.out.println("Noparameters");
}
doubletest(doublea){
System.out.println("doublea:"+a);
returna*a;
}
voidtest(inta,intb){
System.out.println("aandb:"+a+""+b);
}
voidtest(doublea){
}
publicclassMain{
publicstaticvoidmain(Stringargs[]){
OverloadDemoob=newOverloadDemo();
ob.test();
ob.test(10);
ob.test(10,20);
101
System.out.println("Insidetest(double)a:"+a);
}
}
publicclassMain{
publicstaticvoidmain(Stringargs[]){
102
OverloadDemoob=newOverloadDemo();
inti=88;
ob.test();
publicclassMain{
ob.test(10,20);
publicstaticvoidmain(Stringargs[]){
Factorialf=newFactorial();
ob.test(i);//thiswillinvoketest(double)
ob.test(123.2);//thiswillinvoketest(double)
System.out.println("Factorialof5is"+f.fact(5));
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.
classFactorial{
//thisisarecursivefunction
intfact(intn){
intresult;
The return type must be void. The main() method must be public. It is static so that
it can be executed without constructing an instance of the application class.
result=fact(n1)*n;
A command-line argument is the information that follows the program's name on the
command line. The command-line arguments are stored as string array passed to
main(). For example, the following program displays all of the command-line
arguments:
returnresult;
publicclassMain{
if(n==1)
return1;
103
104
publicstaticvoidmain(Stringargs[]){
}catch(NumberFormatExceptione){
for(inti=0;i<args.length;i++)
System.err.println("Number"+argv[0]+"invalid("+e.getMessage()+
").");
System.out.println("args["+i+"]:"+args[i]);
System.exit(1);
}else{
System.err.println("usage:UseArgvnumber");
System.exit(1);
}
System.out.println("OK,numberis"+number);
}
}
Example 4
A constructor initializes an object during object creation when using new operator.
The following code shows how to use of argv to get an integer value from command
line.
Java allows objects to initialize themselves when they are created. This automatic
initialization is performed through the use of a constructor.
publicclassMain{
Syntax
publicstaticvoidmain(String[]argv){
It has the same name as the class. Constructors have no return type, not even void.
intnumber=0;
classClassName{
System.out.println("Thenumberofwordsinargvis"+argv.length);
ClassName(parameterlist){//constructor
if(argv.length==0){
...
number=1234;
}elseif(argv.length==1){
try{
number=Integer.parseInt(argv[0]);
105
106
In the following code the Rectangle class in the following uses a constructor to set
the dimensions:
classRectangle{
doublewidth;//
doubleheight;
classClassName{
Rectangle(){
width=10;
ClassName(){//defaultconstructor
height=10;
...
doublearea(){
returnwidth*height;
classRectangle{
doublewidth;//
publicclassMain{
doubleheight;
publicstaticvoidmain(Stringargs[]){
Rectanglemybox1=newRectangle();
Rectangle(){
doublearea;
width=10;
area=mybox1.area();
height=10;
System.out.println("Areais"+area);
doublearea(){
returnwidth*height;
}
}
publicclassMain{
publicstaticvoidmain(Stringargs[]){
107
108
Rectanglemybox1=newRectangle();
Rectanglemybox1=newRectangle();
doublearea;
doublearea;
area=mybox1.area();
area=mybox1.area();
System.out.println("Areais"+area);
System.out.println("Areais"+area);
If you don't declare a default constructor the Java compiler will add one for you.
When you call the default constructor added by Java compiler the class member
variables are initialized by default value. If you do provide a default constructor the
Java compiler would not insert one for you.
The output:
Example
The constructors can also have parameters. Usually the parameters are used to set
the initial states of the object.
In the following code we removes the default constructor from class Rectangle.
When we compile the class Java compiler adds the default constructor for us so we
can still construct a Rectangle object by calling the default constructor. But the value
of widthand height would be initialized to 0.0.
classClassName{
classRectangle{
doublewidth;//
ClassName(parameterTypevariable,parameterType2variable2,...){//constructor
doubleheight;
...
doublearea(){
returnwidth*height;
}
In the the following demo code Rectangle class uses the parameters, w for width
andh for height, from the constructors to initialize its width and height.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
109
classRectangle{
doublewidth;//
110
doubleheight;
classRectangle{
doublewidth;
Rectangle(doublew,doubleh){
doubleheight;
width=w;
height=h;
Rectangle(Rectangleob){//passobjecttoconstructor
width=ob.width;
height=ob.height;
doublearea(){
returnwidth*height;
Rectangle(doublew,doubleh){
width=w;
height=h;
publicclassMain{
publicstaticvoidmain(Stringargs[]){
Rectanglemybox1=newRectangle(10,20);
//constructorusedwhennodimensionsspecified
doublearea;
Rectangle(){
area=mybox1.area();
width=1;//use1toindicate
System.out.println("Areais"+area);
height=1;//anuninitialized
//constructorusedwhencubeiscreated
Rectangle(doublelen){
width=height=len;
}
Example 2
doublearea(){
Just like methods in a class the constructors can not only accept primitive type
parameters it can also have the object parameters. Object parameters contains
more information and can help us initialize the class.
The following Rectangle class has a constructor whose parameter is
a Rectangleclass. In this way we can initialize a rectangle by the data from another
rectangle.
}
}
publicclassMain{
publicstaticvoidmain(Stringargs[]){
111
returnwidth*height;
112
Rectanglemybox1=newRectangle(10,20);
width=w;
Rectanglemyclone=newRectangle(mybox1);
height=h;
doublearea;
//getvolumeoffirstbox
area=mybox1.area();
//constructorusedwhennodimensionsspecified
System.out.println("Areaofmybox1is"+area);
Rectangle(){
//getvolumeofclone
width=1;//use1toindicate
area=myclone.area();
height=1;//anuninitialized
System.out.println("Areaofcloneis"+area);
Rectangle(doublelen){
The output:
width=height=len;
}
doublearea(){
returnwidth*height;
Method overloading is to declare two or more methods with the name but different
type or count of parameters.
publicstaticvoidmain(Stringargs[]){
Rectanglemybox2=newRectangle();
classRectangle{
doublewidth;/*
doublearea=mybox1.area();
doubleheight;
System.out.println(area);
//constructorusedwhenalldimensionsspecified
area=mybox2.area();
Rectangle(doublew,doubleh){
System.out.println(area);
113
publicclassMain{
Rectanglemybox1=newRectangle(10,20);
Rectanglemycube=newRectangle(7);
114
area=mycube.area();
//initializeaandbtothesamevalue
System.out.println(area);
MyClass(inti){
this(i,i);//invokesMyClass(i,i)
//giveaandbdefaultvaluesof0
MyClass(){
this(0);//invokesMyClass(0)
}
}
this()
In Java this keyword can call the overloaded constructors. The general form is
shown here:
this(arglist)
When this() is executed, the overloaded constructor that matches the arg-list is
executed first.
The call to this() must be the first statement within a constructor.
The following code defines a class named MyClass. It has three constructors. The
first constructor accepts two int values. The second accepts one int type value. The
third one accepts no value.
classMyClass{
inta;
intb;
Member variable
Method local variables
Static variable
Initial Value
byte
short
//initializeaandbindividually
MyClass(inti,intj){
a=i;
b=j;
}
115
116
Element Type
Initial Value
int
long
0L
float
0.0f
Strings;
publicMyClass(){
System.out.println("i="+i);
System.out.println("b="+b);
System.out.println("f="+f);
System.out.println("d="+d);
System.out.println("s="+s);
}
double
0.0d
char
'\u0000'
boolean
false
object reference
null
publicclassMain{
publicstaticvoidmain(String[]argv){
newMyClass();
In the following example, the variable x is set to 20 when the variable is declared.
publicclassMain{
The output:
intx=20;
}
The following example shows the default value if you don't set them.
classMyClass{//
inti;
booleanb;
floatf;
An automatic variable of a method is created on entry to the method and exists only
during execution of the method. Automatic variable is accessible only during the
execution of that method. (An exception to this rule is inner classes).
doubled;
117
118
publicclassMain{
publicintwrong(){
inti;
Member variables and method parameters may have the same name. Under this
situation we can use this to reference the member variables.
returni+5;
}
Rectangle(doublewidth,doubleheight){
this.width=width;
this.height=height;
The following example shows how to use this to reference instance variable.
classPerson{
privateStringname;
publicPerson(Stringname){
this.name=name;
}
publicStringgetName(){
returnname;
this.name=name;
this can be used inside any method to refer to the current object.
publicvoidsetName(Stringname){
}
publicclassMain{
//Auseofthis.
publicstaticvoidmain(String[]args){
Rectangle(doublew,doubleh){
Personperson=newPerson("Java");
this.width=w;//thisisusedhere
System.out.println(person.getName());
this.height=h;
person.setName("newname");
119
120
System.out.println(person.getName());
voidsum(){
System.out.println("i+j+k:"+(i+j+k));
}
}
publicclassMain{
publicstaticvoidmain(Stringargs[]){
BasesuperOb=newBase();
ChildsubOb=newChild();
In Java the classes can inherit attributes and behavior from pre-existing classes.
The pre-existing classes are called base classes, superclasses, or parent classes.
The new classes are known as derived classes, subclasses, or child classes. The
relationships of classes through inheritance form a hierarchy.
Let's look at an example. Suppose we have a class called Employee. It defines first
name, last name. Then we want to create a class called Programmer. Programmer
would have first name and last name as well. Rather than defining the first name
and last name again for Programmer we can let Programmer inherit from Employee.
In this way the Programmer would have attributes and behavior from Employee.
To inherit a class, you can use the extends keyword.
superOb.i=10;
superOb.showBase();
System.out.println();
subOb.i=7;
subOb.showBase();
subOb.showChild();
System.out.println();
classBase{
inti,j;
voidshowBase(){
subOb.sum();
System.out.println("iandj:"+i+""+j);
}
}
classChildextendsBase{
intk;
voidshowChild(){
System.out.println("k:"+k);
}
121
122
The subclass Child includes all of the members of its superclass. The general form
of a class declaration that inherits a superclass is shown here:
depth=ob.depth;
classsubclassnameextendssuperclassname{
Box(doublew,doubleh,doubled){
//bodyofclass
width=w;
height=h;
You can only have one superclass for any subclass. Java does not support the
multiple inheritance. A class can be a superclass of itself.
depth=d;
}
doublevolume(){
returnwidth*height*depth;
}
You can use super in a subclass to refer to its immediate superclass. super has two
general forms.
}
classBoxWeightextendsBox{
doubleweight;//weightofbox
BoxWeight(Boxob){//passobjecttoconstructor
super(ob);
publicclassMain{
super(parameterlist);
publicstaticvoidmain(Stringargs[]){
Boxmybox1=newBox(10,20,15);
BoxWeightmyclone=newBoxWeight(mybox1);
doublevol;
Here is a demo for how to use super to call constructor from parent class.
vol=mybox1.volume();
classBox{
System.out.println("Volumeofmybox1is"+vol);
privatedoublewidth;
privatedoubleheight;
privatedoubledepth;
Box(Boxob){//passobjecttoconstructor
width=ob.width;
height=ob.height;
123
124
We can reference member variable from parent class with super keyword. Its
general form is:
super.member
When an overridden method is called within a subclass, it will refer to the method
defined in the subclass.
classBase{
The method defined by the superclass will be hidden. Consider the following:
inti;
classBase{
classSubClassextendsBase{
inti;//thisihidestheiinA
SubClass(inta,intb){
super.i=a;//iinA
i=b;//iinB
}
inti;
Base(inta){
i=a;
}
voidshow(){
System.out.println("i:"+i);
voidshow(){
System.out.println("iinsuperclass:"+super.i);
System.out.println("iinsubclass:"+i);
}
}
}
classSubClassextendsBase{
intk;
SubClass(inta,intc){
publicclassMain{
publicstaticvoidmain(Stringargs[]){
SubClasssubOb=newSubClass(1,2);
subOb.show();
}
super(a);
k=c;
}
voidshow(){
System.out.println("k:"+k);
}
publicclassMain{
publicstaticvoidmain(Stringargs[]){
125
126
SubClasssubOb=newSubClass(1,3);
subOb.show();
voidshow(){
super.show();//thiscallsA'sshow()
System.out.println("k:"+k);
}
}
publicclassMain{
publicstaticvoidmain(String[]argv){
SubClasssub=newSubClass(1,2);
classBase{
inti;
sub.show();
The following output will be generated if you run the code above:
Base(inta){
i=a;
}
voidshow(){
System.out.println("i:"+i);
}
}
classSubClassextendsBase{
classBase{
intk;
inti;
Base(inta){
SubClass(inta,intc){
i=a;
super(a);
k=c;
voidshow(){
System.out.println("i:"+i);
127
128
System.out.println("InsideA'sconstructor.");
classSubClassextendsBase{
intk;
SubClass(inta,intc){
//CreateasubclassbyextendingclassA.
super(a);
classBextendsA{
k=c;
B(){
System.out.println("InsideB'sconstructor.");
voidshow(Stringmsg){
System.out.println(msg+k);
//CreateanothersubclassbyextendingB.
publicclassMain{
classCextendsB{
publicstaticvoidmain(Stringargs[]){
C(){
SubClasssubOb=newSubClass(1,2);
System.out.println("InsideC'sconstructor.");
subOb.show("Thisisk:");
subOb.show();
publicclassMain{
publicstaticvoidmain(Stringargs[]){
Cc=newC();
}
}
classA{
A(){
129
130
Polymorphism
r.callme();
r=b;
With polymorphism we can call methods from class hierarchy using a uniform
interface. The compiler will determine dynamically which implementation to use.
r.callme();
r=c;
r.callme();
classBase{
voidcallme(){
System.out.println("InsideA'scallmemethod");
}
Polymorphism Example
}
classSubClassextendsBase{
voidcallme(){
System.out.println("InsideB'scallmemethod");
}
}
classSubClass2extendsBase{
The following example uses the run-time polymorphism. It has three classes. The
parent class is Shape. Rectangle and Triangle are both extending
the Shape class.Shape defines a method called area() which returns the area of a
shape. Both Rectangle and Triangle override area() method and provide their own
version of implementation. When calling the area() method we can call it from the
same object reference and Java compiler can figure out which area() method to
use.
voidcallme(){
System.out.println("InsideC'scallmemethod");
classShape{
doubleheight;
doublewidth;
publicclassMain{
Shape(doublea,doubleb){
publicstaticvoidmain(Stringargs[]){
height=a;
Basea=newBase();
width=b;
SubClassb=newSubClass();
SubClass2c=newSubClass2();
doublearea(){
Baser;
System.out.println("AreaforFigureisundefined.");
r=a;
return0;
131
132
figref=t;
classRectangleextendsShape{
System.out.println("Areais"+figref.area());
Rectangle(doublea,doubleb){
super(a,b);
figref=f;
System.out.println("Areais"+figref.area());
//overrideareaforrectangle
doublearea(){
System.out.println("InsideAreaforRectangle.");
returnheight*width;
}
}
classTriangleextendsShape{
Triangle(doublea,doubleb){
super(a,b);
}
//overrideareaforrighttriangle
doublearea(){
System.out.println("InsideAreaforTriangle.");
returnheight*width/2;
}
}
publicclassMain{
interface specifies what a class must do, but not how it does it.
publicstaticvoidmain(Stringargs[]){
Shapef=newShape(10,10);
Rectangler=newRectangle(9,5);
Trianglet=newTriangle(10,8);
Syntax
An interface is defined much like a class. This is the general form of an interface:
accessinterfacename{
Shapefigref;
returntypemethodname1(parameterlist);
returntypemethodname2(parameterlist);
figref=r;
System.out.println("Areais"+figref.area());
typefinalvarname1=value;
133
134
typefinalvarname2=value;
//ImplementCallback'sinterface
publicvoidcallback(intp){
//...
returntypemethodnameN(parameterlist);
System.out.println("callbackcalledwith"+p);
typefinalvarnameN=value;
Variables can be declared inside of interface declarations. They are implicitly final
and static. Variables must also be initialized with a constant value. All methods and
variables are implicitly public if the interface, itself, is declared as public.
callback() is declared using the public access specifier. When you implement an
interface method, it must be declared as public.
Once we define an interface we can use it as a type for object instance we create
through its implementation class.
The following example calls the callback( ) method via an interface reference
variable:
Implementing Interfaces
interfaceMyInterface{
voidcallback(intparam);
classClientimplementsMyInterface{
//ImplementCallback'sinterface
publicvoidcallback(intp){
System.out.println("callbackcalledwith"+p);
}
}
Here is a small example class that implements the interface shown earlier.
publicclassMain{
publicstaticvoidmain(Stringargs[]){
interfaceMyInterface{
voidcallback(intparam);
MyInterfacec=newClient();
c.callback(42);
classClientimplementsMyInterface{
135
}//
136
MyInterfacec=newClient();
AnotherClientob=newAnotherClient();
c.callback(42);
c=ob;//cnowreferstoAnotherClientobject
as the contract between the interface and its implementation. One interface can be
implements by more than once and each different implementation of the same
interface would follow the same list of methods. Therefore if we know several
classes implement the same interface we can use that interface to reference all of its
implementer classes. The compiler will determine dynamically which implementation
to use.
c.callback(42);
interfaceMyInterface{
voidcallback(intparam);
}
classClientimplementsMyInterface{
//ImplementCallback'sinterface
publicvoidcallback(intp){
System.out.println("Client");
System.out.println("psquaredis"+(p*2));
interfaceMyInterface{
voidcallback(intparam);
}
classAnotherClientimplementsMyInterface{
//ImplementCallback'sinterface
publicvoidcallback(intp){
System.out.println("Anotherversionofcallback");
System.out.println("psquaredis"+(p*p));
voidshow();
}
abstractclassIncompleteimplementsMyInterface{
inta,b;
publicvoidshow(){
System.out.println(a+""+b);
classTestIface2{
publicstaticvoidmain(Stringargs[]){
137
138
Variables in Interfaces
The output:
Extend Interface
interfaceMyConstants{
intNO=0;//
One interface can inherit another interface with the keyword extends.
intYES=1;
interfaceIntefaceA{
voidmeth1();/*
classQuestionimplementsMyConstants{
voidmeth2();
intask(){
returnYES;
interfaceIntefaceBextendsIntefaceA{
voidmeth3();
classMyClassimplementsIntefaceB{
publicclassMainimplementsMyConstants{
publicvoidmeth1(){
staticvoidanswer(intresult){
System.out.println("Implementmeth1().");
switch(result){
caseNO:
publicvoidmeth2(){
System.out.println("No");
System.out.println("Implementmeth2().");
break;
caseYES:
publicvoidmeth3(){
System.out.println("Yes");
System.out.println("Implementmeth3().");
break;
publicclassMain{
publicstaticvoidmain(Stringargs[]){
publicstaticvoidmain(Stringarg[]){
Questionq=newQuestion();
MyClassob=newMyClass();
answer(q.ask());
ob.meth1();
ob.meth2();
139
140
ob.meth3();
packageMyPack;
publicclassMain{
publicstaticvoidmain(Stringargs[]){
The output:
System.out.println("hi");
}
}
Packages are containers for classes. Packages are used to keep the class name
space compartmentalized. In Java, package is mapped to a folder on your hard
drive.
Syntax
To define a package, include a package command as the first statement in a Java
source file. Any classes declared within that file will belong to the specified package.
If you omit the package statement, the class names are put into the default package,
which has no name.This is the general form of the package statement:
packagepackageName;
Then try executing the class, using the following command line:
Any place you use a class name, you can use its fully qualified name, which
includes its full package hierarchy.
For example, this fragment uses an import statement:
importjava.util.*;
classMyDateextendsDate{
A package hierarchy must be reflected in the file system of your Java development
system.
141
The same example without the import statement looks like this:
classMyDateextendsjava.util.Date{
}
142
static import
publicclassMain{
publicstaticvoidmain(Stringargs[]){
System.out.println(newDate());
doubler=Math.cos(Math.PI*theta);
}
}
or:
importstaticjava.lang.Math.*;
Once the static members have been imported, they may be used without
qualification:
doubler=cos(PI*theta);
The static import declaration imports static members from classes, allowing them to
be used without class qualification.
143
144