Title: A Little More Java Syntax
1A Little More JavaSyntax
- Based on lectures by Walter Makovoz, Ph.D.
2Data Types
Primitive type Size Minimum Maximum Wrapper
type boolean 1-bit
Boolean char 16-bit Unicode
0 Unicode 216- 1 Character byte
8-bit -128 127 Byte short 16-bit -215 215
1 Short int 32-bit -231 231
1 Integer long 64-bit -263 263
1 Long float 32-bit IEEE754
IEEE754 Float double 64-bit IEEE754
IEEE754 Double void Void
3Java Types
- High-Precision numbers
- Java 1.1 has added two classes for performing
high-precision arithmetic BigInteger and
BigDecimal. - Although these approximately fit into the same
category as the above wrapper classes, neither
one has a primitive analogue. - Both classes have methods that provide analogues
for the operations that you perform on primitive
types. - That is, you can do anything with a BigInteger or
BigDecimal that you can with an int or float, its
just that you must use method calls instead of
operators. - Also, since theres more involved the operations
will be slower youre exchanging speed for
accuracy.
4Data Types
- BigInteger supports arbitrary-precision integers.
- This means you can accurately represent integral
values of any size without losing any information
during operations. - BigDecimal is for arbitrary-precision fixed-point
numbers you can use these for accurate monetary
calculations, for example.
5Default Values
- Primitive type Default
- boolean false
- char \u0000 (null)
- byte (byte)0
- short (short)0
- int 0
- long 0L
- float 0.0f
- double 0.0d
6Java Operators
- An operator takes one or more arguments and
produces a new value. - The arguments are in a different form than
ordinary method calls, but the effect is the
same. - Addition (), subtraction and unary minus (-),
multiplication (), division (/) and assignment
() all work much the same in any programming
language. - All operators produce a value from their
operands. - Additionally, an operator can change the value of
an operand this is called a side effect. - The most common use for operators that modify
their operands is to generate the side effect,
but you should keep in mind that the value
produced is available for your use just as in
operators without side effects. - Almost all operators work only with primitives.
- The exceptions are , and !, which work
with all objects (and are a point of confusion
for objects). - In addition, the String class supports and
.
7Precedence
- Operator precedence defines how an expression
evaluates when several operators are present. - Java has specific rules that determine the order
of evaluation. - The easiest to remember is that multiplication
and division happen before addition and
subtraction. - The other precedence rules are often forgotten by
programmers, so you should use parentheses to
make the order of evaluation explicit. - For example
- A X Y - 2/2 Z
- has a very different meaning from the same
statement with a particular grouping of
parentheses - A X (Y - 2)/(2 Z)
8Assignments
- Assignment is performed with the operator .
- It means take the value of the right-hand side
(often called the rvalue) and copy it into the
left-hand side (often called the lvalue). - An rvalue is any constant, variable, or
expression that can produce a value, but an
lvalue must be a distinct, named variable (that
is, there must be a physical space to store a
value). - For instance, you can assign a constant value to
a variable (A 4), but you cannot assign
anything to constant value it cannot be an
lvalue (you cant say 4 A). - Assignment of primitives is quite
straightforward. - Since the primitive holds the actual value and
not a handle to an object, when you assign
primitives you copy the contents from one place
to another. - That is, if you say A B for primitives then the
contents of B is copied into A. - If you then go on to modify A, B is naturally
unaffected by this modification. - This is what youve come to expect as a
programmer for most situations.
9Assignments
- Whenever you manipulate an object what youre
manipulating is the handle, so when you assign
from one object to another youre actually
copying a handle from one place to another. - This means if you say C D for objects, what you
end up with is both C and D pointing to the
object that, originally, only D was pointing to.
10Assignments
- Example
- // Assignment.java
- // Assignment with objects is a bit tricky
- class Number
- int i
-
- public class Assignment
- public static void main(String args)
- Number n1 new Number()
- Number n2 new Number()
- n1.i 9
- n2.i 47
- System.out.println("1 n1.i " n1.i
- ", n2.i " n2.i)
- n1 n2
- System.out.println("2 n1.i " n1.i
- ", n2.i " n2.i)
11Assignments
- The Number class is very simple, and two
instances of it (n1 and n2) are created within
main( ). - The i value within each Number is given a
different value, and then n2 is assigned to n1,
and n1 is changed. In many programming languages
you would expect n1 and n2 to be independent at
all times, but because youve actually assigned a
handle heres the output youll see - 1 n1.i 9, n2.i 47
- 2 n1.i 47, n2.i 47
- 3 n1.i 27, n2.i 27
12Mathematical Operators
- The basic mathematical operators are the same as
the ones available in most programming languages
addition (), subtraction (-), division (/),
multiplication () and modulus (,produces the
remainder from integer division). - Integer division truncates, rather than rounds,
the result. - Java also uses a shorthand notation to perform an
operation and an assignment at the same time. - This is denoted by an operator followed by an
equal sign, and is consistent with all the
operators in the language (whenever it makes
sense). - For example, to add 4 to the variable x and
assign the result to x, you say x 4.
13Statements Constructs
- COMMENTS
- / C type comment /
- // C type comment
- / Java documentation comment /
- "Documentation comments" are processed
- by the "javadoc" program
14An old C / C problem with bit shifts is solved
in Java
- ltlt shift left, fill with zero on the right
- gtgt shift right, fill with sign bit on the left
- gtgtgt shift right, fill with zero on the left
15Java (C / C )Example
- public class Try1
-
- public static void main(String args)
-
- int a, b, c
- a 5
- b 4
- c (a b) (a 6 - b)
- System.out.println(c)
-
- result (63)
16Basic Rules
- "... the order of evaluation of expressions is
- undefined. In particular the compiler considers
- itself free to compute subexpressions in the
- order it believes most efficient, even if the
- subexpressions involve side effects. The order
- in which side effects take place is unspecified.
- Expressions involving a commutative and
- associative operator such as addition or
- multiplication may be rearranged arbitrarily,
- even in the presence of parentheses..."
17CONDITIONAL STATEMENTS
- A) if statement
- if (ch gt 'a' ch lt 'z')
- System.out.println("Lower case
letter") - if (a b)
- w a 5
- else
- w b 3
- B) if expression
- w (a b) ? a 5 b 3
- ternary operator ?
18Case
- a b c 0
- switch (n)
- case 0
- case 1 a 5
- case 2 b 3
- case 3 c 2
- break
- case 4 a 5
- break
- case 5 b 3
- break
- default a b c 42
- break
-
- "case" values must be integer or character
- constants
19LOOPING STATEMENTS
- A) while statement
- fac 1
- k 1
- while (k lt n)
-
- fac fac k
- k
-
- B) for statement
- fac 1
- for (k 1 k lt n k)
- fac fac k
- _______________________________
- for (fac k 1 k lt n fac k)
20LOOPING STATEMENTS
- do statement
- fac 1
- k 1
- do
- fac fac k
- while (k lt n)
- D) labelled break and continue
- tmp 1
- out while (tmp lt p)
-
- for (k 1 k lt tmp k)
-
- if (k gt n) break out // break out of
the while - total k tmp
-
- tmp
-
- Useful when exiting a nested loop construct
21METHODS
- Because of the object-oriented nature of Java,
- functions are referred to as "methods". But their
- syntax is almost identical to ANSI C / C
- All Java programs consist of objects with method
- interfaces
- Translation
- All programs consist of grouped functions
22Methods
- All methods consist of two parts
- METHOD HEADER
- COMPOUND STATEMENT (BODY)
- All receiving parameters must be data typed in
the - header
- All parameter values are sent by value (objects
send their reference by value)
23REFERENCES
- Java does not have pointers like those found in C
/ C - Instead, Java has "references"
- References are an old idea (borrowed in part from
the - Simula programming language)
- References are similar to pointers but you cannot
- perform arbitrary arithmetic operations on them
24Pointers
- Java references must point to objects but the
compiler - handles the context of the usage
- Integer x, y // x and y are reference variables
- x new Integer(23)
- y x
- System.out.println("The value is " y)
25ARRAYS
- In Java, an array is an object consisting of an
"ordered - collection of elements". A special declaration
syntax is - used to type a reference variable to hold an
array. - public class Try2
-
- static final int LENGTH 42 // def a const
- public static void main(String args)
-
- int w new intLENGTH // w can hold an array
of type int - int k
- for (k 0 k lt LENGTH k)
- wk k k
-
26Arrays
- Multidimensional arrays are supported through the
- creation of arrays of arrays
- int a2 new int1020
- is equivalent to
- int a2 new int10
- for (int k 0 k lt a2.length k)
- a2k new int20
27Arrays
- It is also possible to create a sparse matrix
- int s new int10
- for (int k 0 k lt s.length k)
- sk new ints.length - k
28Arrays
- The following declarations are equivalent
- Java only Java and C/C
- int a3, a4 int a2,
a3 - char a char a,
b - char b
- Note that the last example allocates one
reference - variable of type char array and one non-reference
- variable of type char
- In Java a "char " declaration represents a
binding of - the " " (array reference) declaration with the
"char" - type instead of the old C approach of binding the
" " - with the variable named
29STRINGS
- Strings in Java look and behave like objects but
have - special "privileges" since they are an integral
part of - the formal definition of the language
- Allocation
- String str
- String operators
- str "The answer is "
- str str 42
- The addition operator represents string
concatenation
30But be aware of pitfalls similar to those in C /
C
- public class Str1
-
- public static void main(String args)
-
- String x, y
- x "Hello"
- y "world"
- x x ", " y
- if (x.equals("Hello, world"))
- System.out.println("String values
are equivalent") - if (x "Hello, world")
- System.out.println("Reference values
are identical") -
-
- Only the first "println" gets executed!
31It is possible to map between Strings and char
arrays
- public class Str2
-
- public static void main(String args)
-
- char str 'H', 'e', 'l', 'l', 'o'
- String x, y "world"
- x new String(str, 0, 5) // convert char to a
string, - // starting with subscript 0 and with a length of
5 - x x ", " y
- str x.toCharArray() // convert the String's
value to - // an array
- for (int k 0 k lt str.length k)
- System.out.print(strk)
- System.out.println()
-
32Strings
- Command line arguments can be received as an
array - of Strings by the "main"
- public class Str3
-
- public static void main(String args)
-
- for (int k 0 k lt args.length
k) - System.out.println(argsk)
-
-
- Java does not follow the UNIX command line
convention - of sending the name of the program as an argument!
33MORE ON DATA TYPES
- Non-reference data types start with a lower case
- character
- int a // a holds an int
- char b // b holds a char
- Reference data types either start with an upper
case - character
- Integer c // c holds a reference to an Integer
- String d // d holds a reference to a String
- or are array references
- int e // e holds a reference to an array of
int - String f // f holds a reference to an array of
String references
34Execution Control
- Java uses all Cs execution control statements,
so if youve programmed with C or C then most
of what you see will be familiar. - Most procedural programming languages have some
kind of control statements, and there is often
overlap among languages. - In Java, the keywords include if-else, while,
do-while, for, and a selection statement called
switch. - Java does not, however, support the much-maligned
goto (which can still be the most expedient way
to solve certain types of problems). - You can still do a goto-like jump but it is much
more constrained than a typical goto.
35Execution Control
- true and false
- All conditional statements use the truth or
falsehood of a conditional expression to
determine the execution path. - An example of a conditional expression is A B.
This uses the conditional operator to see if
the value of A is equivalent to the value of B. - The expression returns true or false.
- Any of the relational operators youve seen
earlier in this chapter can be used to produce a
conditional statement. - Note that Java doesnt allow you to use a number
as a boolean, even though its allowed in C and
C (where truth is nonzero and falsehood is
zero). - If you want to use a non-boolean in a boolean
test, such as if(a), you must first convert it to
a boolean value using a conditional expression,
such as if(a ! 0).
36Execution Control
- if-else
- The if-else statement is probably the most basic
way to control program flow. - The else is optional, so you can use if in two
forms - if(Boolean-expression) statement
- or
- if(Boolean-expression) statementelse
statement - The conditional must produce a Boolean result.
- The statement means either a simple statement
terminated by a semicolon or a compound
statement, which is a group of simple statements
enclosed in braces. - Anytime the word statement is used, it always
implies that the statement can be simple or
compound.
37Iteration
- while, do-while and for control looping, and are
sometimes classified as iteration statements. - A statement repeats until the controlling
Boolean-expression evaluates to false.
38While Statement
- The form for a while loop is
- while(Boolean-expression) statement
- The Boolean-expression is evaluated once at the
beginning of the loop, and again before each
further iteration of the statement. - The statement can be a compound statement
surrounded by curly braces, which is true with
any statement.
39While Statement
- Heres a simple example that generates random
numbers until a particular condition is met - // WhileTest.java
- // Demonstrates the while loop
- public class WhileTest
- public static void main(String args)
- double r 0
- while(r lt 0.99d)
- r Math.random()
- System.out.println(r)
-
-
- ///
- This uses the static method random( ) in the Math
library, which generates a double value between 0
and 1 (it includes 0, but not 1). The conditional
expression for the while says keep doing this
loop until the number is greater than 0.99. Each
time you run this program youll get a
different-sized list of numbers.
40Do-while
- The form for do-while is
- do statementwhile(Boolean-expression)
- The only difference between while and do-while is
that the statement of the do-while always
executes at least once, even if the expression
evaluates to false the first time. - In a while, if the conditional is false the first
time the statement never executes. In practice,
do-while is less common than while.
41For Statement
- The for allows you to select the path of
execution and is thus called a selection
statement. - A for loop performs initialization before the
first iteration. - Then it performs conditional testing and, at the
end of each iteration, some form of stepping.
The form of the for loop is - for(initialization Boolean-expression step)
statement - Any of the expressions initialization,
Boolean-expression, or step may be empty. - The expression is tested before each iteration,
and as soon as it evaluates to false execution
will continue at the line following the for
statement. - At the end of each loop, the step executes.
42For Statement
- for loops are usually used for counting tasks
- // ListCharacters.java
- // Demonstrates "for" loop by listing
- // all the ASCII characters.
- public class ListCharacters
- public static void main(String args)
- for( char c 0 c lt 128 c)
- if (c ! 26 ) // ANSI Clear screen
- System.out.println(
- "value " (int)c
- " character " c)
-
- ///
- Notice that the variable c is defined at the
point where it is used, inside the control
expression of the for loop, rather than the
beginning of the block denoted by the open curly
brace. - The scope of c is the expression controlled by
the for.
43break and continue
- Inside the body of any of the iteration
statements you can control the flow of the loop
using break and continue. - break quits the loop without executing the rest
of the statements in the loop. - continue stops the execution of the current
iteration and goes back to the beginning of the
loop to begin a new iteration.
44Java Arrays
- Arrays are first-class objects.
- Arrays are always bound-checked.
- Array index starts from 0.
- int ia new int3
- int ia new int3
- int ia 1, 2, 3
- float mat new float44
- for (int y 0 y lt mat.length y)
- for (int x 0 x lt maty.length x)
- matxy 0.0
-
45Java Strings
- Strings are first-class objects.
- Strings are not arrays of char's.
- String index starts from 0.
- String concatenation
- s1 s2 and s1 s2
- s.length()
- the length of a string s.
- s.charAt(i)
- character at position i.
- for (int i 0 i lt str.length() i)
- countsstr.charAt(i)
46Java Program Organization
- Java provides mechanisms to organize large-scale
programs in a logical and maintainable fashion. - Class --- highly cohesive functionalities
- File --- one class or more closely related
classes - Package --- a collection of related classes or
packages - The Java class library is organized into a number
of packages - java.awt --- GUI
- java.io --- IO
- java.util --- utilities
- java.applet --- applet
- java.net --- network