Date post: | 21-Jan-2016 |
Category: |
Documents |
Upload: | roger-dalton |
View: | 220 times |
Download: | 0 times |
Computer Numbers
• Integers (byte, short, int, long)– whole numbers– exact– Relatively limited in magnitude (~1019)
• Floating Point (float, double)– fractional– often approximations (0.33333)– larger magnitude (~10308)– Actually hold signed mantissa & exponent
• 6.023 x 1023
List of Data TypesPrimitive Type Default Value
boolean falsechar '\u0000' (null)byte (byte) 0short (short) 0int 0long 0Lfloat 0fdouble 0dvoid N/A
Note: At times, the Java Language Specification refers to void as a primitive, though other parts (e.g., s. 14.7) say ‘void’ is not a primitive as in C/C++. One cannot cast to a void type in Java.
Data Type Ranges
Type Size Min Default
boolean false
Max
1 false* true*
char '\u0000' (null)16
byte (byte) 08 -128 127
short (short) 016 -32,768 32,767
int 032 -2,147,483,648 2,147,483,647
long 0L64 -9,223,372,036,854,775,808 9,223,372,036,854,775,807
float 0.0F32 Approx ±3.4E+38 with 7 significant digits
double 0.0D64 Approx ±1.7E+308 with 15 significant digits
void
* Not truly min and max.
OK!OK!CompilesCompiles
Understanding CastingLast class, we covered some basics of casting.Sometimes an explicit cast is required, sometimes it’s not.
int x = 10;float f1 = x;
float f2 = 11.234f;int y = f2;
Which one requires a cast to compile? Why?
ERRORERRORExplicit cast neededExplicit cast needed
Understanding Casting
To understand when we need casting, let’s look closely at an example.
Let’s work with these two types and identifiers:
int x;
char c;
The real question is, How BIG are these data types in memory?
RecallWe already discussed the sizes of various data types in Java. You are guaranteed to have four bytes in each and every int. We can think of an int as a container--much like a box.
java intjava int
Nutritional FactsServ. Size 1 int
Amount per Serving
Calories 0
% Daily Value
Total Bytes 4 100%
Cereal(tahıl) box
And recall...
java charjava char
Nutritional FactsServ. Size 1 char
Amount per Serving
Calories 0
% Daily Value
Total Bytes 2 50%
A char on the other hand is only 2 bytes.It’s smaller than an int. We might imagine it as a smaller container.
tuna(ton balığı or orkinos) can
So...A char is 2 bytes, and an int is 4 bytes. So when we code the following:
int x; char c;
We get:
x
c
Symbol Picture of Memory Symbol Picture of Memory
Each block isone byte
0000 0000
0000 0000 0000 0000 0000 0000
0100 0001
0101 0110
Reality Check
java charjava char
java intjava int
Will a can of tuna fit into a box of cereal? Yes, the can is smaller.
Will a box of cereal fit into a can of tuna? Not neatly, the box is larger.
In a similar vein...
Will a char fit into an int?
Will an int fit into a char?
x
c
Symbol Picture of Memory Symbol Picture of Memory
Reality Check
java charjava char
java intjava int
What if you wanted to fit HALF the box into the can. That would fit!
For example, if we know thetop half of the box is empty,we can throw it away!
Explicit Casting: Intentional Loss of Precision
x
c
Symbol Picture of Memory Symbol Picture of Memory
int x = 45;char c = ‘A’;c = (char) x; // cast needed
cast needed!
Testing Yourself
What happens when we do this:
int someInt = 2000; long longNumber; longNumber = (long) someInt;
Is that cast legal?Is that cast required?
Fill in the blank.
Another Example
float f;int i, j;i = 9;j = 2;f = i / j;
f = (float) i / j;
Returns 4 becauseof integer truncation!
f = (float) i / (float) j;
If that is not what was intended,Three possible solutions
f = i / (float)j;
Another example
Signbit 31 bits
for data
We also have to consider how Java preserves the sign of a value through casting. Consider the eight bytes used for an int. The highest bit is used for a sign (plus or minus, through a 0 or 1).
intint
Casting and Sign
Preservessignbit
intint
bytebyte
Casting is not merely chopping one data type into another. The VM doesn’t merely throw away half of the information. The sign is preserved.
Another ExampleSuppose we had some very, very old data, where the date was expressed in a “int” (four byte) format, such as:
19291031
1929 10(October)
31
This is very crude, but some old data source (e.g., tape archives) might have this format.
Explicit Cast needed
public class CutData { public static void main(String[] args) {
int iDate = 20001225; // this is how it was read in
byte byDay = (byte) (iDate % 100);
System.out.println ("The day was " + byDay);
iDate = iDate / 100;
byte byMonth = (byte) (iDate % 100);
System.out.println ("The month was " + byMonth);
iDate = iDate / 100;
short sYear = (short) iDate;
System.out.print ("The year was = " + sYear); }} // CutData
public class PackDate {
public static void main(String[] args) {
byte month = 12;byte day = 25;short year = 2000;
int date = year * 10000 + month * 100 + day;
System.out.println ("The date = " + date); } } // PackDate
When working in the opposite direction (accumulating bytes and shorts into an int), no casting is needed, because we do not lose precision or information.
• Given: int start = 10; float temp = 5.5f; temp = (int) temp * start;
• What does temp now hold?
Casting: Test Your Knowledge
• Given: char c = ‘A’;
int x;
c = x;
• Legal?Quick Review
Test Your Knowledge• Here’s the problem:
int iVar = 10;float fVar = 23.26f;
// gives compile-time erroriVar = iVar * fVar
• Which solution works best?
iVar = (int) iVar * fVar
iVar = (int) (iVar * fVar)
iVar = iVar * (int) fVar
1
2
3
iVar = (int) ((float) iVar * fVar)
4
232
Same Compile Error
232
230
Quick Review
Shorthand Operators• counter = counter + 1; OR counter++;• counter = counter - 1; OR counter--;• counter = counter + 2; OR counter+=2;
• counter = counter * 5; OR counter*=5;
Last two examples: perform operation first (eg. counter+2) then performs the assignment.
Quick Review
Understand this, but please avoid these types of expressions.
The Short End of ShorthandBe careful to avoid ‘clever’ expressions with shorthand notations.
For example, we can declare a variable called “_”. (Yes, and underline character alone is a valid name.)
int _ = 1;int _ = 1;We can then use a combination of operators to make Morse code:
_ -= --_ - _--;_ -= --_ - _--;Yes, this is valid; however, it’s completely unreadable.(Your replacement will not appreciate this style!)
Documentation & Comments
• Three ways to do it:// comments out everything until the end of the line
/* comments out everything until the */(There are no nested comments as in C++.)
/*** This is syntax for Javadoc comments (similar to second style* of commenting, but allows for HTML formatting features.*/
• For CS1302, use Javadoc comments
Quick Review
Let’s work a javadoc example
Javadoc: Simple Exampleimport java.util.*;/** * HelloComments.java * * * Created: Wed Jan 12 18:17:29 2000 * * @author David Dagon * @version 98 beta */public class HelloComments { /** * A <b> VERY </b> simple variable. */ public int x = 10;
Javadoc commentsmust appear above
the item they modify.
In the case of class comments, place them BELOW the
import statements.
Recall:HTML is OK!
Short, one-liner,followed by period
Simple Example (cont’d)
Just give the variablename; no dashes, etc.
/** * This comment is reproduced twice, because * of the comma delimited declaration of ints. * The solution would be to use separate lines * for each declaration. */ public int y = 4, z = 11;
/** * The Main method. This method is the starting * point of this program, when this class is run. * * @param args The arguments from the command line. */ public static void main(String[] args) {
} } // HelloComments
@author @param@return @exception @deprecated // jdk 1.1 @since // jdk 1.1@serial // jdk 1.2
@see <class name> @see <full-class name> @see <full-class
name#method.name>@version
• You may include HTML tags (but avoid structuring tags, like <H1>, etc.)
• Javadoc comments should immediately preceed the declaration of the class, field or method. The first sentence should be a summary. Use the special javadoc tags--@. When '@' tags are used, the parsing
continues until the doc compiler encounters the next '@' tag.
Javadoc (Cont’d)
You mightrefer backto these
notes onceyou start
writing yourown javadoccomments.
Questions?
Constants
• Java:– public final static <type> <IDer> = <value>;
– public final static int MIN_PASSING = 60;– public final static float PI = 3.14159f;
• Details on “why this syntax” to come soon...
Quick Review
Printing to Screen• Java:
– System.out.println(<argument>);– System.out.println( ); // prints blank line– System.out.println(5); // prints 5– System.out.println(“Hello World”); // prints Hello
World– “println” vs. “print” in Java:
• println includes “carriage return” at end, hence the next print or println starts new line
• print – not carriage return included.causes next print or println to begin on same line
Quick Review
MethodMadness
Caution
Before we can talk about methods in Java, we need to look at programming languages in general, from a very high level.
Don’t be alarmed by some of the syntax on the following slides. The big picture is what’s important, not the coding details....
Programming Paradigms
Procedural Programming
‘Imperative’ assignment used to create state, and procedures manipulate state. E.g., C, Assembly, Pascal int y; int x = 3; y = manipulateData(x);
Functional Programming
Functions (procedures that do not depend on outside data) are used to provided data. E.g., Lisp.
(defun check-member (input-item input-list) (cond ((null input-list) nil) ((equal input-item (first input-list)) T) (T (check-member input-item (rest input-list)))))
Object-Oriented Programming
All data exists in objects; interaction occurs only between objects. Even numbers are objects that know how to add themselves. E.g., SmallTalk:
| array |array := Array new: 5.rect := 0@0 corner: [email protected] to: array size do: [ :item | rect origin: item@item. array at: item put: rect copy ].
Where does Java fit? Object-oriented, but not 100% OO, since it contains primitives, and tolerates some (hopefully small) degree of procedural programming.
Programming Paradigms
There are other paradigms, but these three help explain where Java comes from
Java MethodsJava MethodsThere exists in Java a single construct, the method, for both procedures and functions:
• when a procedure is called for, specify the return type “void” before method name
public void printHelloWorld( ) {
System.out.println(“Hello World!”);
} // printHelloWorld
• Note: All methods must have parentheses for parameters . . . even if no parameters!
Note the comment
Single construct (method) for both procedures and functions:
• when a function is called for, specify the appropriate return type before method name
public float average (float num1, float num2, float num3) { float answer; answer = (num1 + num2 + num3)/ 3; return (answer); } // of average
Java MethodsJava Methods
Writing Methods: A Larger LookWriting Methods: A Larger LookA Java requirement:
--Each method belongs to an object (or class).--It must be unambiguous which object or class that is when a method called.--To run an application program, there must be a class whose name is that of the program and that class must have a method called main:
a class method,
not aninstancemethod
visible to all
nothingreturned
Method name
for command line parameters
public static void main (String[ ] argv)
class A{
public static void main(...}
class B{
public static void main(...}
class C{
public static void main(...}
Thus, each classmay have it’s ownmain method. Youpick the one youwish to run wheninvoking the JVM.
This fact becomescritical when we
learn to writedebug test mains.
Method Signatures“The signature of a method consists of the name of the method and the number and types of formal parameters to the method. A class may not declare two methods with the same signature, or a compile time error occurs.”
--Java Language Specification s.8.4.2
Method overloading occurs where identically named methods have subtle variations in the method parameters.
public int getCube(int num){return num*num*num;
}
public int getCube(float num){return (int)(num*num*num);
}
public int getCube(double num){return (int) (num*num*num);
}
Java lets youoverloadinstead.
Methods: Common Mistakes
public float average (float num1, float num2, float num3); { float answer; answer = (num1 + num2 + num3)/ 3; return (answer); } // average
Note ending semicolon-- could be viewed as ‘abstract’ method
(more on abstract methods later)-- results in unhelpful error message about
abstract methods (more on this later) -- EASY mistake to make!
Where do Methods Go?
Just like the main method we saw last time, any method we create must appear in classes, as either “class” or “instance” members. More on creating classes and objects shortly . . .
For now, just know that methods belong in a class. i.e. They are defined inside a class.
OO Programming NoteAlready, we’ve covered one of the most important aspects of Object Oriented (OO) programming:
Data and methods belong together in a class.
Right now, it’s sufficient that you merely know that variables and methods belong in classes.
Later, we’ll see how this enables us to encapsulate state (the variables) with behavior (the methods).
So, remember this day. You’ve started to learn THE cornerstone of OO programming.
Questions?
Conditionals
Decision Statements• Java:
if (condition) single statement;else single statement;
• or:
if (condition){ statements;}else{ statements;}
Examples• Java: What happens here?
int testGrade = 65;
boolean passing = true;
if (testGrade < 60)
passing = false;
System.out.println(“Is “ + testGrade + “passing? “ +passing);
Boolean and Relational Operators
• Boolean: Java: AND &&
OR ||
NOT !
• Relational: equal to ==
not equal to !=
less than <
less than or equal to <=
greater than >
greater than or equal to >=
• Note:Assignment =
Example
if (enrolled && passing) {// etc.
}
Java also supports short-circuiting, where only part of a boolean will be evaluated, as necessary:
if (enrolled(studentNum) || getPassing(studentNum)) {
// etc. }If fir
st condition is true,
it stops evaluation
A bit o’ codepublic static void main(String args[]) {
int quiz1 = 42;
int quiz2 = 99;
if(isPassing(quiz1) && isPassing(quiz2))
System.out.println(“Passed both quizzes”);
}
public static boolean isPassing(int testGrade) {
boolean passing = true;
if (testGrade < 60)
passing = false;
System.out.println(“Is “ + testGrade +
“ passing? “ + passing);
return passing;
}
Final Answer?
Is 42 passing? false
Is 42 passing? false
Is 99 passing? true
ab
Multiple Selections via Multiple Selections via switchswitch
Use if construct for one selection.
Use if/else construct for double selection.
Use switch construct for multiple selection. (e.g., situations appropriate for if-elseif-elseif-else)
Note:
• Useful when making a selection among multiple values of the same variable.
• Not useful when selecting among values of different variables.
Switch
switch (<variable>)
{
case <value>:
// whatever code you want
break; // optional
case <value>:
// whatever code you want
break; // optional
default:
// whatever code you want
break; // optional
}
Multiple Selections via switch
Note the “optional” default case at the end of the switch statement. It is optional It is optional onlyonly in terms of syntax. in terms of syntax.
switch (iNumber) { case 1:
System.out.println (“One”);break;
case 2:System.out.println (“Two”);break;
case 3:System.out.println (“Three”);break;
default: System.out.println(“Not 1, 2, or 3”); break; // Needed???
} // switch
In practice you should always include a ‘default’ case statement.
This wouldwork withoutthe default, but would
be poortechnique
How many days?
if(month == 4 || month == 6 ||
month == 9 || month == 11)
numdays = 30;
else if(month == 2)
{
numdays = 28;
if(leap)
numdays = 29;
}
else
numdays = 31;
Switchswitch (month)
{
case 4:
case 6:
case 9:
case 11:
numdays = 30;
break;
case 2:
numdays = 28;
if(leap)
numdays = 29;
break;
default: /* Good idea? */
numdays = 31;
}
• The switch statement can only be used with the following types:
int, char, short & byte
(You can cast floats, doubles, etc.)
• The case values must all be of the same type.
• The case values must all be FINAL constants.
Multiple Selections via Multiple Selections via switch--Notesswitch--Notes
Multiple Selections via Multiple Selections via switchswitch
switch (grade) { case ‘A’: case ‘a’: countOfAGrades++; break; case ‘B’: case ‘b’: countOfBGrades++; break; case ‘C’: case ‘c’: countOfCGrades++; break; case ‘D’: case ‘d’: countOfDGrades++; break; case ‘F’: case ‘f’: countOfFGrades++; break; default: System.out.println(“Invalid grade”); break;}
(assume these variables exist and have value)
if (grade==‘A’ || grade==‘a’)countOfAGrades++;
else if (grade==‘B’ || grade==‘b’)countOfBGrades++;
else if (grade==‘C’ || grade==‘c’)countOfCGrades++;
else if (grade==‘D’ || grade==‘d’) countOfDGrades++;
else if (grade==‘F’ || grade==‘f’) countOfFGrades++;
elseSystem.out.println (“Invalid grade”);
same
Before we go too far...
• We often take liberties with good coding practice just to fit material onto a slide.
• Your coding style should reflect clearly and unambiguously what the code is supposed to do.
• Keep in mind your two audiences– The machine– Other programmers
IfStyle 1
if(<boolean expression>)
{
// code if true
}
else
{
// code if false
}
IfStyle 2
if(<boolean expression>) {
// code if true
} // comment
else {
// code if false
} // comment
Conditional AssignmentConditional Assignment
boolean b; int count;
b = checkCompletion();count = (b) ? 3 : 1;
Must resolve to boolean
If true . . .
. . . if false
<boolean> ? <true condition>: <false condition>
Note: This is not any faster.
It’s less readable.
It exists only for ‘recovering C hackers’
A Semi Partial Conditional Summary
• Control structures
–Two kinds of conditional (summary)
• if { ... } else { ... }– branch on boolean expression
• switch (...) { case ...; break; default: ... }– branch on constant value– don’t forget to break !!
Questions?