Download Java Basics - PUC-SP

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java Basics
Java syntax is very similar to that of C.
In this section we will examine the elements of Java programs which appear
inside class and method definitions.
1. Statements.
2. Variables and data types.
3. Comments.
4. Literals.
5. Named Constants
6. Arithmetic in Java (Expressions &
Operators).
7. Comparisons
8. Logical & Bitwise Operators
9. Control statements
Statements
A Java class body is built up from
statements.
Simple statements:
int i = 1;
i = (a + 27) / 2;
System.out.println("Hello");
Compound statements: (Blocks).
Groups of statements enclosed within
braces “{...}”.
Control statements: (for, while, do, if,
switch).
This is all very similar to C. Java, like C,
is free-format. Note, however, that variable declarations are statements in Java.
Variables
Variable: A symbolic name for a memory location in which a value may be
stored.
Every variable has:
1. A name (unique symbolic name for a storage location),
2. A data type (telling us what sort of thing
we are allowed to store),
3. A value.
Three types of variable in Java:
1. Local (local to a method or block),
2. Instance (unique to a specific object),
3. Class (shared by all objects in that class).
There are no Global Variables in Java.
Data Types
Java has a small number of primitive
data types which map directly onto
hardware (for efficiency).
Integer types:
byte
short
int
long
8 bits −128...127
16 bits −32768...32767
32 bits −231...(231−1)
64 bits −263...(263−1)
Floating-point types:
float
32 bits IEEE 754 SP
double 64 bits IEEE 754 DP
Character type:
char
16 bits
16-bit Unicode
Logical type:
boolean logical value
false/true
Declarations
public class Declarations {
static int sharedByAllObjectsInClass;
double localToEachObjectOfClass, numberTwo;
public static void main(String[] args)
{
int count = 0;
while ( count < 100 ) {
int countDown = 100 - count;
System.out.println(count + " " +
countDown);
count++;
}
System.out.println(count);
}
}
Note:
Initialisations allowed in declarations (like C).
Declarations are statements (unlike C), so can
appear wherever statements are legal.
Syntax of Variable Names
Variable names may comprise any Unicode letter or digit character, the dollar sign (“$”) or
underscore character (“_”), but must start with
either an upper or lowercase letter, “$” or “_”.
There is no length restriction.
Java is case sensitive.
Realistic variable names restrict themselves to
a single language.
By convention, variables start with a lowercase
letter. If the variable name consists of several
words, all the others words in the name are
capitalised.
int count3OfThem;
String title;
String johnsAddress;
double distanceToProximaCentauri;
boolean isAsleep;
Class definitions start with an uppercase letter
(convention).
Comments
/**
There are three types of comment in
Java. This is a multiline JavaDoc comment.
It is used by the javadoc program to help
generate documentation for a source file
in HTML.
*/
public class Declarations {
/* This is a C-style multiline comment.
JavaDoc comments and C-style comments
are ignored by the javac compiler
*/
static int sharedByAllObjectsInClass;
double localToEachObjectOfClass;
public
{
//
//
//
//
//
//
static void main(String[] args)
This is the third style of Java
comment, extending from the double
slashes to the end of the current
line. If you want more than a single
line in your comment, you have to
delimit each one separately.
int count = 0;
.
.
.
Literals
A Literal is a constant value typed
directly into the program source. Numbers, characters and string constants are
all literals.
Integer Number Literals:
4, 7, −32, 4589 all literals of type int.
4294967296L a literal of type long (too
big to fit in an int). The L modifier tells the
java compiler that this number needs more than
32 bits.
4L a literal which would otherwise fit in
an int explictly forced to type
using the L modifier.
0377 an octal int literal.
0x3fa2 a hexadecimal int literal.
Floating-Point Number Literals
2.0, −27e−4, 3.14159 These are all
double literals (64-bit). All floatingpoint literals are double by default.
To force a floating-point literal to be a
float (32-bit) value, attach an “F” (or
“f”) to the end of the literal.
2.0F, −27e−4f, 3.14159F, 3.0E8f
This can be important when trying to
assign to (or initialise) a float variable
with a literal.
float c = 3.0e8;
// wrong!
float c = 3.0e8f;
// right!
// Alternatively, use a C-style cast
float c = (float) 3.0e8;
Boolean Literals:
Two keywords: false & true.
Character Literals:
'a', '#', '3' single characters sur-
rounded by single quote marks. Nonprintable characters are represented
using “escape sequences”.
\n
\t
\b
\r
\\
\'
\"
\ddd
\xdd
\udddd
newline
tab
backspace
carriage return
backslash
single quote
double quote
octal charcode
hexadecimal charcode
hex 16-bit (Unicode)
charcode
String Literals:
String literals consist of sequences of
characters enclosed within double quotation marks:
"Hi, I’m a string literal"
"" // this is an empty string
Strings can contain character escape
sequences such as newline, tab, etc.
" This text\n spans 2 lines.”
"Here is how to include \"quotes\""
"This is Java\u2122"
The Unicode escape sequence \u2122 generates the  symbol (if your system supports it).
The Java compiler automatically constructs a String object for every string
literal encountered in your program.
Named Constants
Unlike C, Java has no preprocessor.
Hence, you can’t use “#define” to generate named constants, as in C.
Instead, named constants are formed
using the “final” modifier, applied to
class variables. “final” tells the Java
compiler that it is illegal to change the
value of the “variable”.
public class ConstantExample {
final static float C = 3.0e8F;
final static char
TRADEMARK = '\u2122';
.
.
Why class variables? Because if you use
instance variables, you get a new copy of the
variable in every object, a waste of space since
all the copies of a constant must be identical.
Arithmetic in Java (Expressions & Operators)
Expressions in Java are pieces of code
which return values. They are built up
from variables, literals, method calls,
and operators.
Basic Arithmetic Operators:
Java has 5 basic arithmetic operators:
+
*
/
%
addition
subtraction
multiplication
division
modulus
These may be applied to all types of
integer and floating-point values. They
yield a result of the same type as the
highest-rank type they are applied to.
{
h
t
a
M
c
i
s
a
B
s
s
a
l
c
c
i
l
b
u
p
{
)
s
g
r
a
]
[
g
n
i
r
t
S
(
n
i
a
m
d
i
o
v
c
i
t
a
t
s
c
i
l
b
u
p
;
9
9
=
2
i
,
6
5
4
3
2
=
1
i
t
n
i
;
F
0
.
9
9
=
2
f
,
F
0
.
6
5
4
3
2
=
1
f
t
a
o
l
f
;
)
)
2
i
+
1
i
(
+
"
=
"
+
2
i
+
"
+
"
+
1
i
(
n
l
t
n
i
r
p
.
t
u
o
.
m
e
t
s
y
S
;
)
)
2
i
1
i
(
+
"
=
"
+
2
i
+
"
"
+
1
i
(
n
l
t
n
i
r
p
.
t
u
o
.
m
e
t
s
y
S
;
)
)
2
i
*
1
i
(
+
"
=
"
+
2
i
+
"
*
"
+
1
i
(
n
l
t
n
i
r
p
.
t
u
o
.
m
e
t
s
y
S
;
)
)
2
i
/
1
i
(
+
"
=
"
+
2
i
+
"
/
"
+
1
i
(
n
l
t
n
i
r
p
.
t
u
o
.
m
e
t
s
y
S
;
)
)
2
i
%
1
i
(
+
"
=
"
+
2
i
+
"
%
"
+
1
i
(
n
l
t
n
i
r
p
.
t
u
o
.
m
e
t
s
y
S
;
)
)
2
f
+
1
f
(
+
"
=
"
+
2
f
+
"
+
"
+
1
f
(
n
l
t
n
i
r
p
.
t
u
o
.
m
e
t
s
y
S
;
)
)
2
f
1
f
(
+
"
=
"
+
2
f
+
"
"
+
1
f
(
n
l
t
n
i
r
p
.
t
u
o
.
m
e
t
s
y
S
;
)
)
2
f
*
1
f
(
+
"
=
"
+
2
f
+
"
*
"
+
1
f
(
n
l
t
n
i
r
p
.
t
u
o
.
m
e
t
s
y
S
;
)
)
2
f
/
1
f
(
+
"
=
"
+
2
f
+
"
/
"
+
1
f
(
n
l
t
n
i
r
p
.
t
u
o
.
m
e
t
s
y
S
;
)
)
2
f
%
1
f
(
+
"
=
"
+
2
f
+
"
%
"
+
1
f
(
n
l
t
n
i
r
p
.
t
u
o
.
m
e
t
s
y
S
;
)
)
2
f
+
1
i
(
+
"
=
"
+
2
f
+
"
+
"
+
1
i
(
n
l
t
n
i
r
p
.
t
u
o
.
m
e
t
s
y
S
;
)
)
2
f
/
1
i
(
+
"
=
"
+
2
f
+
"
/
"
+
1
i
(
n
l
t
n
i
r
p
.
t
u
o
.
m
e
t
s
y
S
}
}
C:\...\> java BasicMath
23456 + 99 = 23555
23456 - 99 = 23357
23456 * 99 = 2322144
23456 / 99 = 236
23456 % 99 = 92
23456.0
23456.0
23456.0
23456.0
23456.0
+
*
/
%
99.0
99.0
99.0
99.0
99.0
=
=
=
=
=
int addition
int subtraction
int multiplication
int divison (note rounding)
int modulus
23555.0
23357.0
2322144.0
236.92929
92.0
float +
float float *
float /
float %
23456 + 99.0 = 23555.0
23456 / 99.0 = 236.92929
ints promoted
to floats
The Assignment Operator:
Variable assignment is a form of expression in
Java, hence it produces a result which can be
used in another expression.
a = b = c = d = 5;
a = (b = 6) * 3;
// b = 6
// a = 18
Arithmetic Assignments (C-like):
a
a
a
a
+=
-=
*=
/=
b
b
b
b
a
a
a
a
=
=
=
=
a
a
a
a
+
*
/
b
b
b
b
Incrementing & Decrementing:
a
a
a
a
=
=
=
=
b++;
++b;
b--;
--b;
a
b
a
b
=
=
=
=
b; b =
b + 1;
b; b =
b - 1;
b
a
b
a
+
=
=
1;
b;
1;
b;
Operator Precedence & Parentheses:
Java operators have precedence. The usual
conventions apply in common cases. Use
parentheses to help to clarify complex expressions:
a = b * c + d * f
a = b * c + d * f
Comparisons
Java comparisons are very similar to C
comparisons, except that they return a
boolean value (instead of 0 or non-0.).
==
!=
<
<=
>
>=
Equal
Not equal
Less than
Less or equal
Greater
Greater or Equal
a
a
a
a
a
a
==
!=
<
<=
>
>=
8
8
8
8
8
8
Logical & Bitwise Operators
The logical operators combine boolean values
using the connectives “and”, “or”, “not” and
“exclusive or”.
The bitwise operators combine integer values
(using similar connectives, but working with
the individual bits of their arguments.)
Logical Operators:
&
logical and
&& logical and
(short-circuting)
| logical or
|| logical or
(short-circuiting)
! logical not
^ exclusive-or
(b ==
(c !=
(b ==
(c !=
(b ==
(c !=
(b ==
(c !=
!(c >
bool1
3) &
7)
3) &&
7)
3) |
7)
3) ||
7)
7)
^ bool2
The short-circuiting operators abandon
evaluation of a multi-part expression
once they know what the result must be:
boolean test1, test2;
int a = 3, b = 7;
test1 = (a == 4) && (b == 7);
test2 = (a != 4) || (b == 7);
Bitwise Operators:
bitwise and
bitwise or
bitwise exclusive-or
bitwise complement
left shift
arithmetic right shift
logical (zero-fill) right shift
left shift assignment
arithmetic right shift
assignment
>>>= logical (zero-fill) right shift
assignment
&=
bitwise and assignment
|=
bitwise or assignment
^=
bitwise exclusive-or
assignment
&
|
^
~
<<
>>
>>>
<<=
>>=
LSB
MSB
A:
1 0 1 0 1 0 1
1 0 1 0 1 0
B:
1 1 1 1 0 0 0
0 0 1 1 1 1
A & B:
1 0 1 0 0 0 0
0 0 1 0 1 0
A | B:
1 1 1 1 1 0 1
1 0 1 1 1 1
A ^ B:
0 1 0 1 1 0 1
1 0 0 1 0 1
~A:
0 1 0 1 0 1 0
0 1 0 1 0 1
0 0 1 1 1 1 0
B << 1:
1 1 1 0 0 0
B << 2:
1 1 0 0 0
B >> 1:
1 1 1 1 1 0 0 0
B >> 2:
1 1 1 1 1 1 0 0 0
0 0 1 1 1 1 0 0
B >>> 1:
0 1 1 1 1 0 0 0
B >>> 2:
0 0 1 1 1 1 0 0 0
0 0 1 1 1
0 0 1 1
0 0 1 1 1
0 0 1 1
Note that arithmetic right shifts (“>>”) copy
the original MSB, whereas logical right shifts
(“>>>”) shift a zero into the new MSB.
Control Statements
Java’s control statements are very similar to those of C:
•
•
•
•
•
if-then-else
switch
while
do-while
for
(conditional)
(multi-way conditional)
(loop construct)
(loop with test at bottom)
(loop with initialisation,
test & increment)
if-then-else conditional: Same as in C:
if ( diameter < 4 ) {
bigEnough = false;
System.out.println("too small");
}
else
bigEnough = true;
The else part is optional.
The conditional operator: Same as in C:
The conditional operator is used to construct an
expression which returns one of two values
depending on the state of a boolean test. It provides an alternative to the if-then-else conditional in simple cases:
<boolean> ? <if true return this>
: <if false return this> ;
int smaller = x < y ? x : y ;
Nested if-then-else: Same as in C:
if ( operator == '+' )
result = addArgs(arg1, arg2);
else if ( operator == '-' )
result = subArgs(arg1, arg2);
else if ( operator == '*' )
result = mulArgs(arg1, arg2);
else if ( operator == '/' )
result = divArgs(arg1, arg2);
else
error("Unknown operator");
switch conditional: Same as in C:
switch (character) {
case 'a' :
case 'b' :
case 'c' :
System.out.println(
"Got a, b or c");
break;
case '1' :
case '2' :
case '3' :
System.out.println(
"Got 1, 2 or 3");
break;
default :
System.out.println(
"That’s no good");
break;
}
Execution starts with the first matching case
expression and continues until a break is
encountered. The default body of code is executed if no match occurs. The default section
is optional, but it is a good idea to include it.
Nested if-then-else or switch?
A switch statement is less flexible than a
nested if-then-else.
•
The values of the cases must be simple
“int-like” types, (e.g., int, short, byte
or char.) You may not use float, double,
long, boolean or any non-primitive type.
•
The only comparison between the expression being tested and the argument of a
case is equality.
•
Every case expression must be both
constant and unique. Duplicate case labels
are not allowed, nor are ones whose values
cannot be evaluated at compile time.
A nested if-then-else does not have these
limitations, but is harder to read, and can
result in slower code.
while loop: Same as in C:
int x = 0;
while ( x < 10 ) {
System.out.println(x++);
}
do-while loop: Same as in C:
int x = 0;
do {
System.out.println(x++);
} while ( x < 10 );
The body of a do-while loop is always executed
at least once because the test is at the end of
the loop.
for loop: Similar to C:
for (int x = 0; x < 10; x++) {
System.out.println(x);
}
The for loop combines the three parts of a typical looping structure, initialisation, termination
test and increment, into one structure.
In Java we can declare, as well as initialise,
looping variables in the initialisation section.
We are not limited to a single variable. Consider the following:
for (int n = 0, f = 1; n < 10; n++) {
if ( n > 1 ) f *= n;
System.out.println("Factorial "
+ n + " is " + f);
}
Here we declare and initialise two integer variables (“n” and “f”) in the head of the for loop
(this loop calculates factorials between 0 and
9).
The scope of the looping variables declared in
the head of the loop is the body of the loop.
They cannot be used outside the loop body.
factorial method:
This method calculates the factorial of its argument. We use a long for the return value
because factorials grow in size very rapidly.
public static long factorial(int n) {
long f = 1;
for (int i = 2; i <= n; i++)
f *= i;
}
return f;
Notes:
•
This is a class method (like main).
•
It returns a long result (public static long).
•
The result is accumulated in f. This variable
cannot be declared in the head of the loop
because its value is needed outside the
body of the loop (in the return statement).
•
The return statement is used to pass the
value of f, where the factorial has been
accumulated, back to the caller of factorial.
printBinary method:
This method prints a binary representation of
its integer argument to the standard output
stream. It uses various bitwise operators.
public static void printBinary(int v) {
char ch;
for (int bitMask = 0x80000000;
bitMask != 0;
bitMask >>>= 1) {
if ( (v & bitMask) == 0 )
ch = '0';
else
ch = '1';
System.out.print(ch);
}
}
Notes:
•
This method does not return a result (public
static void).
•
0x80000000 is a 1 in bit 31 (the MSB of a
32-bit integer), 0’s everywhere else.
•
bitMask >>>= 1 shifts the 1 in bitMask
one position to the right on each iteration.
printOctal method:
This method prints an octal (base-8) representation of its integer argument to the standard
output stream. It uses bitwise operators to get
at each octal digit and a switch statement to
select the character to output based on that
digit.
public static void printOctal(int v) {
System.out.print('0');
for (int i = 30; i >= 0; i -= 3) {
char ch;
int octalDigit = (v >>> i) & 07;
switch (octalDigit) {
case 0 : ch = '0'; break;
case 1 : ch = '1'; break;
case 2 : ch = '2'; break;
case 3 : ch = '3'; break;
case 4 : ch = '4'; break;
case 5 : ch = '5'; break;
case 6 : ch = '6'; break;
default : ch = '7'; break;
}
System.out.print(ch);
}
}
Notes:
•
This method does not return a result (public
static void).
•
Each octal digit represents 3 bits. The
method works by examining 3-bit blocks of
the integer at a time. Each block represents
an octal digit.
•
The most significant octal digit corresponds to bits 31 and 30 (only 2 bits for the
MS octal digit because only 32 bits in an
integer).
•
Each block is shifted down to bits 2..0 and
any high order bits masked off using a bitwise and with binary 111 (octal 07)
(int octalDigit = (v >>> i) & 07; ).
•
The amount to shift (“i”) is reduced by the
block size on each iteration (i -= 3).
•
This method prints a leading 0 to indicate
an octal number. It always prints a fixed
number of digits (12) regardless of the
magnitude of its argument.
Breaking out of loops:
break: Exit immediately from enclosing
switch or loop
for (int i = LOWER; i <= UPPER; i++) {
current = factorial(i);
if ( last >= current ) {
System.out.println("Limit is " +
(i-1));
}
}
break;
labeled break: immediately exit from outermost loop, switch or if governed by the label.
In the example, the label “out:” governs the
outer for loop. When i + j exceeds 15, both
inner (j) and outer (i) loops are terminated.
out:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if ( i + j > 15 ) break out;
System.out.println((i+j));
}
}
continue: skip the remainder of the code in the
body of the current loop and start a new iteration of the loop.
for (int i = SAMP1; i <= SAMP50; i++) {
if ( rejectBatch(i) ) continue;
.
. // processing if batch good
.
}
}
labeled continue: immediately jump to the
start of the outermost loop governed by the
label and start a new iteration of that loop. In
the example, the label “out:” governs the outer
for loop. When i + j exceeds 15, the outer (i)
loop immediately starts a new iteration.
out:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if ( i + j > 15 ) continue out;
System.out.println((i+j));
}
}