Uploaded by Katie Wickham

variables-and-primitives (1)

advertisement
Variables and Primitive
Types
D Barnette
https://canvas.vt.edu/
“Variables” store state in objects
and methods
 A variable is a name for a location in memory
 A field (also called a data member or an attribute or an
instance variable) is one sort of variable
 Fields store values through the life of an object
 They are accessible throughout the class
 Methods can include shorter-lived variables called local
variables
 They exist only as long as the method is being executed
 They are only accessible from within the method
A variable’s declaration gives its
type
 A variable must be declared by specifying the variable's
name and the type of information that it will hold
data type
variable name
initial value
int count = 15;
 It is best to always provide an initial value, except for
fields initialized in a constructor
 A variable’s value can be changed over time
 When a variable is referenced anywhere in your program,
its current value is used
Assignment gives a variable a new
value
 The assignment operator is the = sign
int total = 55;
 The expression on the right is evaluated and the result is
stored in the variable on the left
 The value that was in total is overwritten
 You can assign only a value that is consistent with the
receiving variable's declared type
Besides objects, we also use
primitive data
 There are exactly eight primitive data types in Java
 One represents true or false values:
 boolean
 One of them represents single character values:
 char
 Four of them represent integers of different sizes:
 byte, short, int, long
 Two of them represent floating point numbers:
 float, double
Boolean values represent true or
false
 The reserved words true and false are the only valid
values for a boolean type:
boolean done = false;
 A boolean also can be used to represent any two states,
such as a light bulb being on or off
 You can save the value returned by a predicate for use later
Characters can also be stored in
variables
 A char variable stores a single character from the Unicode
character set
 A character set is an ordered list of characters, and each
character corresponds to a unique number
 The Unicode character set uses 16 bits per character, allowing for
65,536 unique characters
 It is an international character set, containing symbols and
characters from many world languages
 ASCII (an older US character set) is a subset of Unicode
 Character literals are delimited by single quotes:
'a'
'X'
'7'
'$'
','
'\n'
Primitive numeric types differ in
their ranges
 The difference between the various numeric primitive types
is their size, and therefore the range of values they can
store:
Type
Storage
Min Value
Max Value
byte
short
int
long
8 bits
16 bits
32 bits
64 bits
-128
-32,768
-2,147,483,648
< -9 x 1018
127
32,767
2,147,483,647
> 9 x 1018
float
double
32 bits
64 bits
+/- 3.4 x 1038 with 7 significant digits
+/- 1.7 x 10308 with 15 significant digits
Data can sometimes be converted
to another type
 Sometimes it is convenient to convert data from one type to
another, and there are several ways this can happen
 For now, we’ll only mention the first one, which is also the most
powerful
 A cast is an explicit data conversion requested by the programmer
 To cast, the type is put in parentheses in front of the value
being converted
 If not used with care, it can cause loss of data
 For example:
int nextChar = ...;
if (Character.isWhitespace((char)nextChar)) ...
Strings represent sequences of
text characters
 Every character string is an object in Java, defined by the
String class
String beatleSinger = "Paul McCartney";
 Every string literal is delimited by double quotation marks, and
represents a String object
 A string literal cannot be broken across two lines in a program
Strings represent sequences of
text characters
 The plus operator (+) is used to concatenate, or append, one
string to the end of another (producing a new string as a result)
String name = "Paul " + "McCartney";
 It can also be used to append a number (or any other data value)
to a string
String bandSize = 3 + " members";
 A string literal cannot be broken across two lines in a program
String long = ”This is a really
long line.";
String long = "This is a really ”
+ "long line.";
The String class provides many
useful methods
 Many of the methods return a value, such as an integer or a
new String object
 Here are some commonly used methods:
int
boolean
boolean
boolean
String
int
String
length()
equals(String another)
startsWith(String prefix)
endsWith(String suffix)
substring(int start, int end)
indexOf(int ch)
toLowerCase()
 See more in the Java API documentation for the String
class
Strings are immutable
 Immutable: an object with a fixed state (fixed value) that can
never be changed
 A string object is a read-only piece of text that can never be
changed
 Functions like toLowerCase(), substring(), etc.
produce new String values, and leave the original
unchanged
When should a variable be a field?
 Deciding where to place a variable’s declaration is
important for code readability
 Work on developing skill at making such decisions
 General rule: make each declaration as limited in scope as
possible (that is, visible in the smallest amount of your code
as is reasonable)
 For now: if it is only used in one method, it should be a
local variable
 If it is used by more than one method and it seems like a
natural attribute of the class you are defining, make it a
field
Arithmetic
 Operators
Symbol
Meaning
Example
Value
+
addition
43 + 8
51
-
subtraction
43.0 - 8.0
35.0
*
multiplication
43 * 8
344
/
division
43.0 / 8.0
43
/ 8
5.375
5
%
remainder
43 % 8
3
-
unary minus
-43
-43
The operands can be of any type for which the operation makes sense.
Parentheses may be used to group terms in more complex expressions:
32 - (3 + 2)*5 ---> 32 - 5*5 ---> 32 - 25 ---> 7
There is no operator in Java for exponentiation (xy).
Increment/Decrement
 Increment/Decrement operators
 Adding or subtracting 1 is so common that Java provides a shorthand
notation.
int x = 0,
y = 7;
x++;
y--;
// same effect as x = x + 1;
// same effect as y = y - 1;
The notation x++ is referred to as postfix increment since the operator ++ comes after the
variable being incremented. The operator may also be used as a prefix: ++x.
These two statements have exactly the same effect:
int x = 0;
x++;
++x;
But it's more complex when the increment/decrement operators are used in a larger
expression::
int x = 0, y = 7, z, w;
z = y * x++;
// z <- 7 * 0, x <- 1
w = y * ++x;
// w <- 7 * 2, x <- 2
Console Output
 Java standard/default output device
 Java provides a default window, for text output only, on the system
default output monitor
 System.out – name of default output text window/console
 Output class provides print() & println() methods
 Parameter can be text or text concatenated expression
// Instance/static variables ......
private int numHops = 0 ;
// . . .
System.out.println( “Hops made = 0”);
// . . .
numHops++;
System.out.println(“Hops made = ” + numHops );
Primitive Java notation
 Primitive type
 Java determines the type of primitive numeric literals in a couple of
ways.
 If it does not have a decimal point it is an int. If it has a decimal point it
is double.
 To explicitly type a numeric literal a 1 letter suffix which is the first
uppercase letter of the type name:
float delta = 0.00001F;
double epsilon = 0.00000000000001D; //D is optional
long quadrillion = 1000000000000000L;
int billion = 1000000000; //no ‘I’ default is int
Real Arithmetic
 Mixed-mode expressions
 When operands are of different types Java will up-convert the
smaller range type to the larger. Java will convert ints to doubles
yielding a double value.
 Mixed-mode expressions consisting of bytes, char, and short will
be promoted to int.
 Scientific Notation
 When large or small doubles are output Java uses scientific
notation:
double billion = 1.0E9;
System.out.println( “1 Billion = ” + 1000000000.0);
//displays
1 Billion = 1.0E9
Java.lang.Math
 Java math library
 Code library for standard mathematical functions:
Math.sqrt(x)
Math.abs(x)
Math.pow(a, b)
Math.max(a, b)
Math.min(a, b)
Math.round(x)
–
–
–
–
-
square root
absolute value
exponentiation ab
maximum
minimum
returns closest int
 also contains trigonometric & logarithmetic functions
Real Equality
 Comparing real values for equality
 Due to representational errors, (and conversion errors), real values
should never be directly compared for equality.
if ( dbl1 == dbl22 ) // WRONG !!!
if (Math.abs ( dbl1 – dbl22 ) < DELTA )
 where DELTA = 0.00000000000001 ;
 an appropriate value near the precision limit of the CPU.
 Supported by the Testing Assert Class API
 static void assertEquals(double expected, double actual, double delta)
Asserts that two doubles are equal concerning a delta.
 static void assertEquals(float expected, float actual, float delta)
Asserts that two floats are equal concerning a delta.
Binary ⇔ Decimal
 Binary, Base 2
 Processor arithmetic is in binary
 Integers
 Within the finite range of the int type computer arithmetic is exact
and the operation of division is closed.
 Reals
 Computer real arithmetic is not exact.
 Decimal
 321 == 3·102 + 2·101 + 1·100 (positional notation)
 0.123 == 1·10-1 + 2·10-2 + 3·10-3 (positional notation)
 Binary
 10112 == 1·23 + 0·22 + 1·21 + 1·20 == 1110
 0.1012 = 1·2-1 + 0·2-2 + 1·2-3 == 0.510 + 010 + 0.12510 = 0.62510
 0.110 cannot be represented exactly in binary.
Download