Upload
lenhi
View
221
Download
0
Embed Size (px)
Citation preview
Java Programs
A Java program contains at least one class definition.
public class Hello {public static void main(String[] args) {
System.out.println("Hello, world!") ;}
}
This code defines a class named Hello. The definition ofHello must be in a file Hello.java. The method mainis the code that runs when you call ‘java Hello’.
Identifiers
When we give an element in a program a name, we callthat name an identifier. In the previous example, Hellowas an identifier. In Java, identifiers:
• Always start with a letter.
• Can include letters, digits, underscore (‘ ’) and thedollar sign symbol ($).
• Must be different from any Java reserved words (orkeywords).
Keywords that we’ve seen so far include: public,static, class and void.
Case Sensitivity
Identifiers and keywords in Java are case sensitive. Inother words, capitalization matters. Keywords are alwaysin lowercase. The following identifers are all different:
• foobar
• Foobar
• FooBar
• FOOBAR
Even so, it would probably be a bad idea to use more thanone of them in the same program.
Whitespace
We use the word whitespace to describe blanks, tabs andnewline characters. The Java compiler ignores whitespaceexcept when it is used to separate words. E.g.:
y=m*x+b;total=total+y;
Is the same as:
y = m*x + b ;total = total + y ;
But which is easier to read?
Comments
To make our code understandable to those who comeafter us, we comment sections whose purpose is notimmediately obvious.
// this comment ends at a newline
/* this comment goes until itis explicitly ended with a: */
The Java compiler treats comments as if they werewhitespace—it ignores them unless they separate words.I.e., “foo/*hi, mom!*/bar” becomes “foo bar”, not“foobar”.
Variables
A variable is a location in memory where data is stored.Every variable is associated with an identifier.
We can assign a value to a variable using the assignmentoperator ‘=’.
x = 12 ;
The assignment operator means “take the value on theright-hand side and store it in the memory location on theleft-hand side.”
Types
The values a variable can take on and the operations thatcan be performed on it are determined by its type. Javahas five categories of types:
• Booleans
• Characters
• Integers
• Floating-point numbers
• References to objects
Booleans
Boolean variables can only take on the values “true” or“false”. They are often used to test for conditions in aprogram.
boolean t = true ;boolean f = false ;
Characters
Character variables can store one character. A charactervalue is a character surrounded by single quotes:
char q = ’Q’ ;
Some special characters are:
\n newline
\t tab
\’ single quote
\" double quote
\\ backslash
Integers
The integers are the infinite set: Z = {. . . ,−1, 0, 1, . . . }.
Obviously, we can’t represent all of the integers in onevariable. We have to choose an n-bit encoding that canrepresent 2
n integers.
The Java integer types represent both positive andnegative integers. An n-bit integer x can represent therange:
−2n−1 ≤ x < 2
n−1
Integers Types
The Java integer types are:
byte 8 bits
short 16 bits
int 32 bits
long 64 bits
E.g.:
byte b = 127 ;short s = -32768 ;int i = 2 ;
Integer Literals
An integer value, or literal, can be written in decimal, hexor octal (base-8):
• A hex literal starts with ‘0x’, e.g.: 0x1F (= 3110)
• An octal literal starts with just ‘0’, e.g.: 072 (= 5810)
• A decimal literal is just a regular number that doesn’tstart with ‘0’, e.g.: 123
Integer literals are by default of type int.A long literal ends with ‘L’.
Integer Conversions
If an int literal is small enough to fit into a byte or ashort, it will be automatically converted. The same istrue for long literals and int, byte and short.
byte b = 0x7F ; /* 7 bits, OK */short s = 0x7FFF ; /* 15 bits, OK */int i = 0x12345678L /* 29 bits, OK */
byte b2 = 0xFF ; /* Error: 255 > 127 */int i2 = 0x123456789ABCDEFL
/* Error: way too big, 57 bits */
Integer Conversions: 2
If a literal is too big for its target variable, you mustexplicitly convert it using a type cast. The number isconverted by truncating the extra bits, which is probablynot what you want.
/* 0x100 = 256 */byte b = (byte) 0x100 ;/* b now equals 0! */
An int literal can always be assigned to a longvariable—its value will be the same as if it was assignedto an int variable.
Floating-Point Numbers
Floating-point numbers are used to represent the reals(R), i.e., numbers that may have fractional parts. Thefloating-point representation uses a form of scientificnotation:
0.123 = 1.23 × 10−1
1.23 = 1.23 × 100
12.3 = 1.23 × 101
123.0 = 1.23 × 102
Floating-Point Types
A floating-point variable uses some of its bits to store theexponent and some of them to store the fractional part (orsignificand). Thus, floating-point numbers are constrainedby both magnitude and precision.
The Java floating-point types are:
float 32 bits
double 64 bits
Floating-Point Literals
Floating-point literals are decimal numbers with anoptional decimal point.
123.4 0.99 55. .2
You may also include an exponent n, which multiplies theliteral by 10
n:
1.234e2 9.9e-1 55e0 .02e1
A floating-point literal is by default of type double.A float literal ends with ‘F’.
Floating-Point Conversions
The only automatic conversion between floating-pointtypes is the assignment of a float value to a double.
double d = 1.23F ; /* OK */float f = 5.99 ;
/* Error: cannot assign double to float */
When an integer literal is assigned to a floating-point type,it is automatically “promoted” to floating-point, even if thatmeans a loss of precision.
float f = 2 ; /* OK, f = 2.0 */float f2 = 1234512345L ;
/* OK, but f2 = 1234512384 */
Objects
You may have heard that Java is an object-orientedprogramming language. What does that mean?
An object is a collection of data and operations thatmanipulate that data.
public class Circle {int x ;int y ;double radius ;...
}
Object-Oriented Programming
In object-oriented programming (or OOP), we try to defineall of our data as objects, and we define the program asinteraction between those objects.
public class HappyFace {Circle head ;SemiCircle smile ;
void draw() {head.draw() ;smile.draw() ;
}...
}
Object-Oriented Programming: 2
OOP encourages us to think of objects asmodules—reusable components. If we have Circle, wecan use it to make HappyFace. If we have HappyFace, wecan use it to make StickMan.
public class StickMan {HappyFace head ;Line body ;Line arm1, arm2 ;Line leg1, leg2 ;...
}
Defining Object Types
An object is usually a noun, a thing. To define an object,we first need to define what kind of a thing it is. In Java,we use the keyword class:
public class Car {String make ;int model_year ;Color color ;int max_occupants ;...
}
Defining Object Types: 2
Now that we’ve defined a class, we can create instancesof the class (i.e., objects). In order to create an instance,we need to tell Java how to initialize the object. We do thisusing a constructor.
public class Car {...public Car(String mk, int yr, Color c,
int max) {make = mk ;model_year = yr ;color = c ;max_occupants = max ;
}}
Defining Objects
Now we can use the keyword new to invoke theconstructor and create an instance of the class. We cancreate any kind of a car we need by changing theparameters to the constructor.
Car suv = new Car("Ford Explorer", 1999,Color.BLUE, 5) ;
Car mini = new Car("Cooper Mini", 2002,Color.RED, 4) ;
The Type of an Object
An object’s type is its class. A Car variable can only takethe value of a Car object, or an object that is compatiblewith Car. (We’ll talk about what it means for an object tobe compatible next week.)
Car suv = new Car("Ford Explorer", 1999,Color.BLUE, 5) ;
Car c = suv ; /* OK: suv is a Car */
StickMan s = suv ;/* Error: suv is not a StickMan */
References
We said earlier that one of the categories of Java types is“references to objects”. What is a reference?
We said that a variable is a location in memory. When wedeclare an integer variable x and assign it a value 123,the location in memory set aside for x contains the binaryrepresentation of 123.
n + 1
n
n− 1
true
6.02e23
123x
References: 2
A variable of an object type is a reference variable. Whenwe declare a Car variable suv, the location in memory setaside for suv contains a reference to the location of thedata members of suv.
n + 1
n
n− 1
6.02e23
’X’
suv ref
"Ford Explorer"
1999
Color.BLUE
5
Reference Assignment
Assignment means “copy the value on the right-hand sideinto the memory location on the left-hand side”. If youassign one variable to another, the value is copied andthat is that.
int x = 0 ;int y = x ;
/* x and y both equal 0 */
x = 2 ;/* x now equals 2,
y still equals 0 */
Reference Assignment: 2
When you assign the value of one reference variable toanother, it’s the reference that’s copied, not the object.This can lead to surprising results.
Point p = new Point(0,0) ;Point q = p ;
/* p and q now refer to the same object */
p.x = 2 ;/* p.x now equals 2
q.x now equals 2, as well */
Reference Assignment: 2
When you copy the reference value, you still have only onecopy of the object data. You just have two references to it.
0xFFFFFFFF
false
p
q
ref
ref
x: 2
y: 0
This may seem confusing at first, but there’s a simplereason for it: copying data is slow. We avoid it when wecan.
Strings
String is a class that has special support in Java. Astring literal is surrounded by double quotes.
String hamlet = "To be or not to be" ;
String is a reference type, but you don’t have to use thenew operator to create an instance. You can assign astring literal to a String variable directly, as above.
Strings: 2
Character and string values may seem confusingly similar.• A char value is a single character, surrounded by
single quotes:char c1 = ’C’ ;char c2 = ’\n’ ;
• A String value is a sequence of characterssurrounded by double quotes. A String may beempty.String s1 = "C" ;String s2 = "" ;String s3 = "LastName\tFirstName\tGrade\n" ;/* Words separated by tabs, closed with a
newline. */
Arithmetic
Java provides five basic arithmetic operators:
+ addition
- subtraction
* multiplication
/ division
% remainder
There are also unary + and - operators.
The operators can be applied to any of the integer orfloating-point types.
Operator Precedence
Multiplication, division and remainder have higherprecedence than addition and subtraction. Allhigher-precedence operators are evaluated before anylower-precedence operators. Operators at the sameprecedence are evaluated left-to-right. Parentheses canbe used to override operator precedence.
x+y*z = x+(y*z)
a*b+c%d = (a*b)+(c%d)
Assignment is the lowest-precedence operator of all.Unary + and - are higher-precedence than multiplication.
Integer Arithmetic
Integer division is “grade-school” division: fractionalresults round toward zero.
9/2 = 4
-9/2 = -4
Integer division and remainder obey the rule:
(x/y)*y + x%y = x
9%2 = 1
-9%2 = -1
Overflow and Underflow
If the result of an operation is greater than the maximumvalue (overflow) or less than the minimum value(underflow) of its type, the result “wraps around”.
Integer.MAX VALUE + 1 = Integer.MIN VALUE
Integer.MIN VALUE - 1 = Integer.MAX VALUE
All arithmetic is performed with int and long values.byte and short values are automatically promoted.
Typecasting
The result of an integer arithmetic operation is always anint or long. This means you have to cast back to asmaller type when you assign a result.
byte b = 1 ;byte b2 = b + 1 ;
/* Error: can’t assign int to byte */
byte b3 = (byte)( b + 1 ) ;/* OK: b3 now equals 2 */
byte b4 = (byte)( Byte.MAX_VALUE + 1 ) ;/* OK: b4 now equals Byte.MIN_VALUE */
Floating-point Arithmetic
Floating-point arithmetic works pretty much how youwould expect, except you have to be careful aboutprecision.
float f = 1.0e8F, g = 1.0e-8F ;float x = f + g ;
/* x now equals 1.0e8 */
float y = (f - f) + g ;/* y now equals 1.0e-8 */
float z = f - (f + g) ;/* z now equals 0 */
Special Floating-point Values
Floating-point arithmetic has several special values thatbehave in interesting ways.
+Inf Infinity
-Inf Negative Infinity
+0.0 Zero
-0.0 Negative Zero
NaN Not a Number
Special Floating-point Values: 2
Here’s how to get and what you get from, these specialvalues:
1/0.0 = Inf 1/-0.0 = -Inf
1/Inf = 0.0 1/-Inf = -0.0
Inf/Inf = NaN Inf*0.0 = NaN
1+Inf = Inf 1-Inf = -Inf
1%Inf = 1 Inf%1 = NaN
Increment and Decrement
Adding or subtracting one from a number is a commonoperation. Java provides a short-hand in the increment(++) and decrement (--) operators.
Increment and decrement can be used as prefix or postfixoperators. In prefix form, increment means “add one tothis variable and use the incremented value in thisexpression.” In postfix form, increment means “add one tothis variable, and use the previous value in thisexpression.”
Aside: C also has increment and decrement. Thedevelopers of C++ wanted to indicate it was anincremental improvement on C.
Increment and Decrement:Examples
int i = 0, j ;
i++ ; /* i = 1 */i-- ; /* i = 0 */
j = i++ ; /* i=1, j=0 */j = ++i ; /* i=2, j=2 */j = --i ; /* i=1, j=1 */j = i-- ; /* i=0, j=1 */
Increment and Decrement:Precedence
Increment and decrement are higher-precedence thanany operator we’ve seen so far. Postfix ishigher-precedence than prefix.
Highest ++, -- (postfix)
++, -- (prefix), +, - (unary)
*, /, %
+, -
Lowest =
Comparison Operators
Java provides the following operators for comparingnumbers:
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to
‘==’ and ‘!=’ can be applied to boolean values, but ‘>’, ‘<’,‘>=’ and ‘<=’ cannot.
The result of a comparison operation is a boolean value.
Reference Comparison
‘==’ and ‘!=’ can be applied to reference variables. Theytest whether the references are equal, not the datamembers.
Point x = new Point(0,0) ;Point y = new Point(0,0) ;Point z = x ;
boolean b = x==y ;/* false, x and y are references
to different objects */
boolean b2 = x==z ;/* true, x and z are references
to the same object */
The instanceof Operator
Occasionally we want to investigate the type of an object.The instanceof operator tells us if a reference variableis an instance of a class.
Point x = new Point(0,0) ;
boolean a = x instanceof Point ;/* true, x is a Point */
boolean b = x instanceof Car ;/* false, x is not a Car */
Comparison Operators: Precedence
The relational operators have higher precedence than theequality operators. All of the comparison operators havelower precedence than the arithmetic operators.
Highest ++, -- (postfix)
++, -- (prefix), +, - (unary)
*, /, %
+, -
<, >, <=, >=, instanceof
==, !=
Lowest =
Logical Operators
Java provides the following logical operators:
& AND
| OR
ˆ XOR
! NOT
&& short-circuit AND
|| short-circuit OR
The operands of a logical operator are boolean valuesand the result is also a boolean.
AND
AND is true if and only if both of its operands are true.
a b a&b
false false false
false true false
true false false
true true true
OR
OR is true if one of its operands are true.
a b a|b
false false false
false true true
true false true
true true true
XOR
XOR is true if and only if exactly one of its operands istrue.
a b aˆb
false false false
false true true
true false true
true true false
Short-circuit AND and OR
The logical AND and OR operators (‘&’ and ‘|’) alwaysevaluate both of their operands. In some cases, this canbe wasteful.
If the first operand of AND is false, then AND must befalse. Short-circuit AND (‘&&’) doesn’t evaluate the secondoperand if the first is false.
If the first operand of OR is true, then OR must be true.Short-circuit OR (‘||’) doesn’t evaluate the secondoperand if the first is true.
Short-circuit Operators: Example
boolean a = true, b = false ;int i = 0, j = 1, k = 2 ;
boolean c = a || (i=j) < k ;/* c = true, i = 0 */
boolean d = a && (i=j) < k ;/* d = true, i = 1 */
boolean e = a && (i=k) < j ;/* e = false, i = 2 */
Logical Operators: Precedence
AND has higher precedence than OR. The short-circuitoperators have lower precedence than their ordinaryequivalents. All of the logical operators have lowerprecedence than arithmetic and comparison.
Highest Arithmetic, etc.
<, >, <=, >=, instanceof
==, !=
&
ˆ
|
&&
||
Lowest =
Bitwise Operators
Java provides the following operators for manipulating bitpatterns:
& Bitwise AND
| Bitwise OR
ˆ Bitwise XOR
<< Shift left
>> Shift right signed
>>> Shift right unsigned
‘&’, ‘|’ and ‘ˆ’ are overloaded operators. They are logicaloperators when applied to boolean values, and bitwiseoperators when applied to integers.
Bitwise AND
Bitwise AND applies the AND operation to every pair ofbits in the operands. A 0 is treated as false and a 1 istreated as true.
0xF6 & 0x93 =
1111 0110
AND 1001 0011
= 1001 0010
Bitwise OR
Bitwise OR applies the OR operation to every pair of bitsin the operands.
0xF6 | 0x93 =
1111 0110
OR 1001 0011
= 1111 0111
Bitwise XOR
Bitwise XOR applies the XOR operation to every pair ofbits in the operands.
0xF6 ˆ 0x93 =
1111 0110
XOR 1001 0011
= 0110 0101
Shift left
The shift left operator shifts the bits in its first operand asindicated by its second operand.
0xF6 << 2 =
1111 0110 << 2
11 0110 00
Shift right signed
The way integers are represented in Java, thehighest-order bit is the sign of the number. If we shift rightthe same way we shift left (bringing in zeroes), the signmight changed. The shift right signed operator brings inbits that match the sign.
0xF6 >> 2 =
1111 0110 >> 2
11 1111 01
Shift right unsigned
The shift right unsigned operator ignores the sign bit andbrings in zeroes.
0xF6 >>> 2 =
1111 0110 >>> 2
00 1111 01
Using Bitwise Operators
Bitwise AND is good for turning bits off:
int i = 0xC7 & 0xFE ;/* i = 0xC6 */
Bitwise OR is good for turning bits on:
int i = 0xC7 | 0x08 ;/* i = 0xCF */
Bitwise XOR is good for flipping bits:
int i = 0xC7 | 0x09 ;/* i = 0xCE */
Bitwise Operators: Precedence
The precedence of bitwise AND, OR and XOR match theirlogical equivalents. The precendence of the shift operatorsis between the arithmetic and comparison operators.
Highest Unary operators
*, /, %
+, -
<<, >>, >>>
<, >, <=, >=, instanceof
==, !=
Lowest Logical operators, assignment
String Concatenation
The + is also overloaded. When applied to two strings, itconcatenates them. I.e., it appends the second to the first.
String a = "Flower" ;String b = "Power" ;String c = a + b ;
/* c = "FlowerPower" */
String Concatenation: 2
All of the basic types are automatically converted toString under the concatenation operator.
int i = 2 ;double x = 5.2 ;
String s = "i = " + i + " and x = " + x ;/* s = "i = 2 and x = 5.2" */