Java Concepts - Early Objects.pdf

(101905 KB) Pobierz
Class Declaration
public class CashRegister
{
private int itemCount;
private double totalPrice;
Variable and Constant Declarations
Type
Instance variables
Name
Initial value
int cansPerPack = 6;
final double CAN_VOLUME = 0.335;
public void addItem(double price)
{
itemCount++;
totalPrice = totalPrice + price;
}
. . .
}
Method
Method Declaration
Modifiers
Return type
Parameter
type and name
Selected Operators and Their Precedence
(See Appendix B for the complete list.)
[]
++ -- !
* / %
public static double cubeVolume(double sideLength)
{
double volume = sideLength * sideLength * sideLength;
return volume;
Exits method and
}
Array element access
returns result.
Increment, decrement, Boolean
not
Multiplication, division, remainder
+ -
Addition, subtraction
< <= > >=
Comparisons
== !=
Equal, not equal
&&
Boolean
and
||
Boolean
or
=
Assignment
Mathematical Operations
Math.pow(x, y)
Math.sqrt(x)
Math.log10(x)
Math.abs(x)
Math.sin(x)
Math.cos(x)
Raising to a power
x
y
Square root
x
Decimal log log
10
(x)
Absolute value |x|
Sine, cosine, tangent of
x
(x in radians)
Conditional Statement
Condition
if (floor >= 13)
{
Executed when condition is true
actualFloor = floor - 1;
}
else if (floor >= 0)
Second condition (optional)
{
actualFloor = floor;
}
else
{
Executed when
System.out.println("Floor negative");
all conditions are
}
Math.tan(x)
String Operations
String s = "Hello";
int n = s.length(); // 5
char ch = s.charAt(1); // 'e'
String t = s.substring(1, 4); // "ell"
String u = s.toUpperCase(); // "HELLO"
if (u.equals("HELLO")) ... //
Use
equals
, not
==
for (int i = 0; i < s.length(); i++)
{
char ch = s.charAt(i);
Process
ch
}
false (optional)
Loop Statements
Condition
while (balance < TARGET)
{
year++;
balance = balance * (1 + rate / 100);
}
do
{
Loop body executed
at least once
System.out.print("Enter a positive integer: ");
input = in.nextInt();
Executed while
condition is true
}
while (input <= 0);
Initialization Condition Update
for (int i = 0; i < 10; i++)
{
System.out.println(i);
}
Set to a new element in each iteration
An array or collection
for each element
for (double value : values)
{
Executed
sum = sum + value;
}
Java
ConCepts
early objects
seventh edition
Java
ConCepts
San Jose State University
early objects
seventh edition
© FLPA/John Holmes/Age Fotostock America, Inc.
© Frans Lemmens/SuperStock
Cay Horstmann
© S Sailer/A Sailer/Age Fotostock America, Inc.
Zgłoś jeśli naruszono regulamin