Upload
roddy
View
45
Download
1
Tags:
Embed Size (px)
DESCRIPTION
Java Fundamentals Expanded. In Java, there are two basic categories of datatypes – primitives and classes. Let's review primitive datatypes and cover them in more detail: byte , short , int , long float , double char boolean. 1. The Integer Types . - PowerPoint PPT Presentation
Citation preview
Java Fundamentals Expanded
SE1021Dr. Mark L. Hornick
1
2
In Java, there are two basic categories of datatypes – primitives and classesLet's review primitive datatypes and cover
them in more detail: byte, short, int, long float, double char boolean
1
3
The Integer Types
To access a data type's minimum and maximum values, use the MIN_VALUE and MAX_VALUE named constants that come with the datatype's wrapper class.
For example:System.out.println("Largest int = " + Integer.MAX_VALUE);
TypeStorage Req’d
Wrapper Class's
MIN_VALUE
Wrapper Class's
MAX_VALUE
byte 8 bits -128 127short 16 bits -32768 32767int 32 bits -2 billion 2 billionlong 64 bits -9*1018 9*1018
4
The default integer literal constant datatype is int
That is, a literal value like 123 is an int
To explicitly force an integer constant to be a long, use an l or L suffix Thus, 123L is a long
Examples:long ageOfPlanet = 4540000000; // compiler error!
long ageOfPlanet = 4540000000L; // OK
5
The Floating-Point datatypes – float and double
For doubles, the number of significant digits is approximately 15. For floats, the number of significant digits is approximately 6.
Normally, the double type is preferred over the float type because the double type provides more accuracy as well as greater range
TypeStorag
ePrecisio
n
Wrapper Class's
MIN_NORMAL
Wrapper Class's
MAX_VALUE
float 32 bits6-9
digits 1.2 * 10-38 3.4*1038
double 64 bits15-17 digits 2.2 * 10-308 1.8*10308
6
A floating-point data type's minimum and maximum values are defined via the MIN_NORMAL and MAX_VALUE named constants
Note that a floating-point MIN_NORMAL is qualitatively different from an integer MIN_VALUE. Instead of being the largest-magnitude negative value, it's the smallest-magnitude positive value.
For floating-point numbers, if you want the largest-magnitude negative value, use the negation operator (-) with the MAX_VALUE named constant. For example, here's how to print the largest-magnitude negative float value:System.out.println( "Largest-magnitude negative float = " + -Float.MAX_VALUE);
7
The default floating-point literal constant datatype is double
That is, a literal value like 123.0 is a double
If you declare a variable to be a float, you must append an f or F suffix to all floating-point constants that go into it, like this:float gpa1 = 3.22f; // OKfloat gpa2 = 2.75F; // OKfloat gpa3 = 4.0; // error!!
8
The char datatypeFor most languages (including Java), character
values have an underlying numeric value. For example, the letter 'A' has the underlying
value of 65.
For most languages, the ASCII table specifies the underlying numeric values for characters.
9
The ASCII Tablenumeric
value characternumeric
valuechar-acter
numeric value
char-acter
numeric value
char-acter
0 null 32 space 64 @ 96 `1 start of heading 33 ! 65 A 97 a2 start of text 34 " 66 B 98 b3 end of text 35 # 67 C 99 c4 end of transmission 36 $ 68 D 100 d5 enquiry 37 % 69 E 101 e6 acknowledge 38 & 70 F 102 f7 audible bell 39 ' 71 G 103 g8 backspace 40 ( 72 H 104 h9 horizontal tab 41 ) 73 I 105 i10 line feed 42 * 74 J 106 j11 vertical tab 43 + 75 K 107 k12 form feed 44 , 76 L 108 l13 carriage return 45 - 77 M 109 m14 shift out 46 . 78 N 110 n15 shift in 47 / 79 O 111 o16 data link escape 48 0 80 P 112 p17 device control 1 49 1 81 Q 113 q18 device control 2 50 2 82 R 114 r19 device control 3 51 3 83 S 115 s20 device control 4 52 4 84 T 116 t21 negative acknowledge 53 5 85 U 117 u22 synchronous idle 54 6 86 V 118 v23 end transmission block 55 7 87 W 119 w24 cancel 56 8 88 X 120 x25 end of medium 57 9 89 Y 121 y26 substitute 58 : 90 Z 122 z27 escape 59 ; 91 [ 123 {28 file separator 60 < 92 \ 124 |29 group separator 61 = 93 ] 125 }30 record separator 62 > 94 ^ 126 ~31 unit separator 63 ? 95 _ 127 delete
10
What's the point of having an underlying numeric value?
A: So characters can be ordered (e.g., 'A' comes before 'B' because A's 65 is less than B's 66). Character ordering is necessary so characters
(and strings) can be sorted.
11
You can concatenate a char value to a String using the + operator
Example:char first = ‘J';char last = 'D';System.out.println("Hello, " + first + last + '!');
When the JVM sees a String next to a + sign, it converts the operand on the other side of the + sign to a String, and then concatenates the Strings. Q: What mechanism does the JVM use to
convert the non-String operand to a String?
12
Be wary of applying the + operator to two chars
The + operator does not perform concatenation; instead, it performs mathematical addition using the characters' underlying ASCII valueschar first = 'J';char last = 'D';System.out.println(first + last + ", What's up?");// result is: 142, What's up?
The intended output is: JD, What's up? Q: How can you fix the code?
13
Java is a strongly-typed language
Each variable and each value within a Java program must be defined to have a particular datatypes, but statements within a program can often mix datatypes.
Example:
int x = 3; // intdouble y = 4.0 + x; // mixing double and int
How? Through datatype conversions. Conversions are only allowed for numeric types, not booleans.
14
Primitive datatype Conversions
The ordering scheme for primitive datatype conversions:narrower wider
byte short int long float double
char
This diagram illustrates what datatypes “fit inside” other datatypes:A “narrower” datatype can “fit inside” a “wider” datatype.
15
There are two types of conversion: Promotion and Type casting
Promotion: A promotion = an implicit conversion
it's when an operand's type is automatically converted without having to use a typecast operator.
It occurs when there's an attempt to use a narrower type in a place that expects a wider type it occurs when you’re going with the flow of the arrows in the previous
diagram.
16
Examples of PromotionsFor each statement, what happens in terms
of promotion? long x = 44;float y = x;
double z = 3 + 4.5;int num = 'f' + 5;
With a mixed expression, the narrower operand(s) is promoted to match the type of the wider operand.
These are mixed expressions. Mixed expressions contain operands of different data types.
17
Promotions typically occur as part of assignment statements, mixed expressions, and method calls.
Here's a method call example.public class MethodPromotion{ public static void main(String[] args) { float x = 4.5f; printSquare(x); // x is a float! printSquare(3); // 3 is an int! }
private static void printSquare(double num) { System.out.println(num * num); }} // end class MethodPromotion
18
Type casting = an explicit type conversion.It's when an expression's type is (forcibly)
converted by using a cast operator.
It's legal to use a cast operator to convert any numeric type to any other numeric type the conversion can go in either direction in the
previous "ordering scheme" diagram.Syntax:(<type>) <expression>
double x = 12345.6;int y = (int) x; // result in y??
19
Example from p 444import java.util.*;
public class PrintCharFromAscii{ public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); int asciiValue; // user entered ASCII value char ch; // the asciiValue's associated character char nextCh; // the character after ch in the ASCII table
System.out.print("Enter an integer between 0 and 127: "); asciiValue = stdIn.nextInt(); ch = (char) asciiValue; nextCh = (char) (asciiValue + 1); System.out.println("Entered number: " + asciiValue); System.out.println("Associated character: " + ch); System.out.println("Next character: " + nextCh); } // end main} // end class PrintCharFromAscii
20
There are two different modes for the ++ increment operator – prefix and postfix.Prefix mode:
++x increment x before x's value is used
Example:y = ++x; x = x + 1;
y = x;Postfix mode:
x++ increment x after x's value is used Example:y = x++; y = x;
x = x + 1;
21
Trace this code fragment
int x, y;x = 4;y = ++x;System.out.println(x + " " + y);x = 4;y = x++;System.out.println(x + " " + y);
22
Decrement operators work the same as increment operators
…except that subtraction is performed instead of addition.
Trace this code fragment:int a, b, c;a = 8;b = --a;c = b-- + --a;System.out.println(a + " " + b + " " + c);
23
Assignment expressions are sometimes embedded inside larger expressions
int a, b = 8, c = 5;a = b = c;System.out.println(a + " " + b + " " + c);
When that happens, remember that: An assignment expression evaluates to the assigned value. The assignment operator exhibits right-to-left associativity.
In the interest of compactness, it's fairly common to embed an assignment expression inside a loop condition. For example:while ((score = stdIn.nextDouble()) != -1)
24
Conditional operator expressions implement if else logic using a more compact form
Syntax:<condition> ? <expression1> : <expression2>
Semantics: If the condition is true, then the conditional operator
expression evaluates to the value of expression1. If the condition is false, then the conditional
operator expression evaluates to the value of expression2.
Assume x = 2 and y = 5. What does this expression evaluate to?(x>y) ? x+1 : y-1
25
A conditional operator expression cannot appear on a line by itself
…because it is not considered to be a statement. Instead, it must be embedded inside of a statement. For example:int score = 88;boolean extraCredit = true;score += (extraCredit ? 2 : 0);
Is the same as:
int score = 88;boolean extraCredit = true;if( extraCredit )
score += 2;else score += 0;
26
Short-Circuit Evaluation
What happens when the code runs with null input values?String input =
JOptionPane.showInputDialog(“Enter a pos value”);
int value;if( (input!=null) && value=Integer.parseInt(input)>0 ){
// do something with positive value}else{ // print an error message}
27
The empty statement is a statement that does nothing.
It consists of a semicolon by itself. Use the empty statement in places where
the compiler requires a statement, but there is no need to do anything.
Example: The below for loop can be used as a "quick
and dirty" way to add a delay to your program:<print monster>for (long i=0; i<1000000000L; i++) ;<erase monster>
Style requirement:Put the empty statement on a line by itself and indent it.
28
Empty Statements can also cause errors!
Be aware that you can sometimes accidentally introduce the empty statement into a program Such statements are usually the source of
runtime errors. For example:System.out.print("Do you want to play a game (y/n)? ");while (stdIn.next().equals("y"));{
// The code to play the game goes here ... System.out.print("Play another game (y/n)? ");}
empty statement