Download Chapter 3 - Computer Sciences User Pages

Document related concepts
no text concepts found
Transcript
Chapter 4 – Fundamental
Data Types
Goals



Gain a firm understanding of the fundamental
data types and their properties and limitations
Understanding strings
Dealing with user input, and program output
Number Types

All values are either references to objects or one of
8 primitives

A numeric computation overflows if the result
falls outside the range for the number type
int n = 1000000;
System.out.println(n * n);
// prints -727379968
Primitives



So far we’ve seen 6 number types

byte, short, int, long for whole numbers

float, double for reals
Numbers can have overflow (value too large)
Reals can also have underflow (rounding errors)
double f = 4.35;
System.out.println(100 * f);
// prints 434.99999999999994
Conversion

2 types of conversion – increase in precision, decrease
in precision

Increase in precision(int to long, byte to float)



More memory being used
Allowed in Java – Java does this automatically
Ex.
int dollars = 100;
double balance = dollars; //OK
Conversoin

Decrease in precision
Representing a number with less memory
 Error in Java – the compiler will yell at you
 Example:

double balance = 13.75;
int dollars = balance; //ERROR!
Type Casting

Error is because compiler wants us to know that
we are going to possibly lose information
4.0 to 4, not a big deal
 .99 to 0, is a big deal


To override this (i.e. tell the compiler to convert
anyways) we must use the type cast operator
Type Casting: Syntax
(<type>) expression
Example
double balance = 12.45;
int dollar = (int) balance; //stores 12

Truncates (removes fractional part) when going
from real (ie double) to whole number (ie int)

Can cast to any type you want (including objects)
Rounding

What if you want to round instead of truncate?

2 solutions:
Hack: add 0.5 to number then truncate
 Real solution: Use Math.round()

long rounded = Math.round(balance);
Constants

In math, equations have variables and constants

In programming, the same
Already learned about variables
 Numbers that do change but have specific meanings
are important


Randomly placed numbers in a program can be
confusing, so we give them symbolic names
Constants

Use a constant to hold the value


Use reserved word final to modify declaration


Can’t change after assigned when declared
final double PI = 3.14159;
Naming Convention for constants

USE_ALL_CAPS_WITH_UNDERSCORES
Constants

Constants often used for important numbers

Make meaning of code easier to understand

Make changes to code a lot easier
Constants: Example
public double getPay ()
{
double pay = numHours * 6.70;
return pay;
}
What is 6.70 doing?
Why is it there?
Constants: Example
public double getPay ()
{
final int PAY_RATE = 6.70;
double pay = numHours * PAY_RATE;
return pay;
}


Much easier to understand now when reading the code
Much easier to change now as well
Class Constants

Often, we want to use the same constant across
several methods in a class

To do this, make a constant instance field
Class Constants

Differences in the declaration


Make it public since we don’t have to worry about the value
being changed
Add static modifier to make it part of the class, so all objects
of that class share it (more on this later)
public class Math {
…
public static final double E = 2.71828
public static final double PI = 3.14159
…
}
Class Constants

One copy of the variable (static)

Available to all classes (public)

Example: You have a class where you want to
calculate circumference
double circumference = Math.PI * diameter
Constant Definition

In a method (local constant)
final <type> <name> = <value>;
final int PAY_RATE = 6.70;

In a class (class constant)
<accessSpecifier> static final <type>
<name> = <value>;
public static final int HOURS_IN_DAY =
24;
Constants

So when should I use a constant?

In general if the number has significance, give it
a symbolic name (make it a constant identifier)
Example

time = duration * 60;
Is this converting minutes to seconds or hours
to minutes?
Assignment, Increment, and
Decrement

= is the assignment operator
On the left, place the variable
 On the right, place the expression/value


Not an equality sign!!!

Action is to copy the right side to the variable
on the left side
Interesting twists on =
items = items + 1;

Expression to right is always computed first


Add items
+ 1;
The value of the expression is assigned to the
variable afterwards
Example
Example
int items = 1;
items = items + 1;
Do right side first  2
Assign to items  items
= 2
Increment Operator

Net result is to increment items by 1

Increment is so common, Java uses a shorthand
for it

++ operator increases the value of a variable by
one
Increment Operator
items = items + 1;
Postincrement:
items++;
Preincrement:
++items;
Decrement Operator
items = items - 1;
Postdecrement:
items--;
Predecrement:
--items;
Other Shortcuts

Arithmetic modifications to a variable can use
shorthand operations
items = items +5;  items += 5;
items = items*2;  items *= 2;
items = items – 2*5;  items -= 2*5;
Arithmetic
Already seen some symbols, here are all
Operators – mathematical operations
+
addition
Subtraction
*
Multiplication
/
Division
%Modulo (Remainder)
Operands – the values to which the operator is
applied

Examples
int x = 3 + 5;
// 8
x = 10/2;
// 5
x = 10 * 3 – 4;
// 26
x = 12 % 5;
// 2
Division


Returns quotient
When both operands are integers, an integer is
returned
x = 10/2 … x = ?
 y = 6/3 … y = ?


When either or both operands are real, a real is
returned

z = 2.5/0.5 … z = ?
Integer Division


When dividing two integers, only the whole
number is returned
Examples:
6/4 = ?
1/5 = ?
-3/4 = ?
6/3 = ?
Integer Division

Why does Java do this?
Easier for the computer
 Has it’s advantages:

int
int
int
int
totalTime = 503;
MINUTES_PER_HOUR = 60;
hours = totalTime / MINUTES_PER_HOUR;
minutes = totalTime % MINUTES_PER_HOUR;
Modulo Operator

Returns remainder
23 % 5 = 3
 4%2=?


Mainly used for integers (possible for reals also,
but not as useful)
Precedence
High
subexpressions
unary operators
multiplicative operators
additive operators
Low
()
-, +
*, /, %
+, -
Precedence

Parenthesis take precedence
(a + b) / 2 different than a + b /2
Math Class

Provided automatically (it’s in the java.lang package)

Exponentiation
Math.pow(x,n)  xn

Square Roots
Math.sqrt(x)
 x0.5
Math Class

Translating expressions from mathematics to
Java is a little different

Java has no exponents, symbols, or fraction bars
so we can’t write
6^3
 √5



Quadratic Equation
(-b + Math.sqrt(b * b -4 * a * c)) / (2 * a)
Math Class

In mathematical notation:

In Java:
(-b + Math.sqrt(b*b - 4*a*c))/(2*a)

In Java
(-b + Math.sqrt(b *b -4
*a * c)) / (2 * a)
Precedence
Math Class
Questions

What is the value of
1729 / 100?
 1729 % 100?


Computing Average: Is this correct?
double average = s1 + s2 + s3 / 3;

What if
s1, s2, s3
are integers?
Style

White space inside equations can go a far way –
placing spaces before and after arithmetic
symbols is very helpful

White space can also be helpful to group code

i.e. have 5 lines for calculating some information,
then a blank line followed by a series of output
Style

Important property for good programming –
never have two lines of code doing the exact
same thing
Won’t be heavily enforced, but good to get practice
 Inefficient – making computer do work twice
 Error prone – when there is a bug, you may only fix
it one place

Example – Quadratic Eqn
x1 =
(2
x2 =
(2
(-b + Math.sqrt(b * b – 4 * a * c)) /
* a);
(-b - Math.sqrt(b * b – 4 * a * c)) /
* a);
double root = Math.sqrt(b * b – 4 * a * c);
x1 = (-b + root) / (2 * a);
x2 = (-b - root) / (2 * a);
Static Methods

So far we have been discussing classes as
templates and objects as the entities

All the methods and instance fields for the Path
class belonged to an individual object
Each had its own xDistance, yDistance
 A method call was on the object itself


p.getX() different then q.getX()
Static Methods

Has everything we’ve used been an object?



System
Math
Both of these are classes, yet we made calls on
them to either fields (System.out) or methods
(Math.sqrt())

We never created an instance Math of the class or
System class
Static Methods

The calls on the Math class were unique


They were static – belonging to the class, not an
individual object
In other words, these methods did not depend
on an object

Math.sqrt() will ALWAYS do the same thing, so
why create an object whenever we use it?
Static Methods

Static methods are defined in the classes like
normal methods

They do not operate on object, though

Don’t have any internal data to deal with
Static Methods: Syntax
ClassName.methodName(parameters)
Example:
Math.sqrt(4)
Purpose:
To invoke a static method (a method that does
not operate on an object) and supply its
parameters
Static Methods

How can we tell if methods are static?
Java follows conventions: for example, Math is
capitalized, so we know it’s a class
 Look at javadocs - static methods will be listed with
the static modifier

Strings

Along with numbers, the most commonly used
data type in programming


Unlike numbers, Strings are objects
Already learned about length() method

String str = “four”;

System.out.println(str.length())  4

“” is the empty string
Strings




Strings are sequences of characters
Each character is stored at an index of the
string
Indexing begins at 0!
The charAt method returns the character at the
specified index
0
1
2
D
o
n
3
n
4
a
Concatenation

Putting strings together
If either left or right side is a String, the result is String (no
matter what the other side is)
 Works left to right


How does Java interpret:
A + B + C
"A" + "B" + "C"
1 + 2 + 3
"1" + 2 + 3
"(1+2+3)"
1 + 2 + "3"
Concatenation

Concatenation is useful for outputting results
System.out.print(“My age is ”);
System.out.println(age);
vs.
System.out.println(“My age is ” + age);
Number to String Conversion

Converting from a number to String is easy
int number = 15;
String string = "" + number;

How about the reverse?
int result = Integer.parseInt(someString);
double result = Double.parseDouble(someString);
Similar for all other number types
Parsing

Only works if entire string is a number
"19" // Works for parseInt() & parseDouble()
"15.23"
// Works for parseDouble() only
"123a"
// Error for both
Strings

String substring()
method
String greeting = "Hello, World!";
String sub = greeting.subString(0,5);
// sub is "Hello“
Note that the first parameter is the first letter you
want (zero based indexing) and the second
parameter is the first letter you DON’T want
Reading Input

All examples so far have been pretty basic


Do not vary, we code in all values when testing
Most useful programs interact with a user to get
data input and perform operations on that data
Reading Input

Output uses the System.out object

You would think input should then use
System.in
Exists, but not very powerful
 Takes in only one byte of information at a time,
when all characters on the keyboard are 2 bytes!

Reading Input

Input used to be a pain in Java (relatively
speaking)
BufferedReader buf = new BufferedReader(
new InputStreamReader(System.in));
int a = Integer.parseInt(buf.readLine());

Java 5.0 now includes a Scanner class

Easily connect to keyboard to get input
Scanner stdin = new Scanner(System.in);
int a = stdin.nextInt();
Reading Input

Scanner can be associated with files, but for now
we will learn about keyboard input

A Scanner object must be created, associated
with System.in as follows:
Scanner stdin = new Scanner(System.in);
Reading Input

To read numbers from user, use the methods
nextInt(), nextDouble()

When called, these methods wait for the user to
type input and then hit the enter key. The
number inputted is returned

Usually, the program will prompt the user for
information – give instructions via System.out
Reading Input

To get a String, use nextLine()

Allows user to type as much as they want.
When they hit enter, all characters typed are
returned as a String object

To read just one word (not entire line), use
next()
Example
Scanner stdin = new Scanner(System.in);
System.out.print("Enter name: ");
String name = stdin.nextLine();
System.out.print("Enter age:
int age = stdin.nextInt();
");
Characters




char stores one character (one letter or one
digit or one symbol)
Computer thinks of everything as numbers
including characters
‘0’ (48) + ‘A’ (65) is equal to ‘q’ (113)
How do we know what numbers different
characters correspond to?
Characters

Encodings: specify what number a character is

ASCII – basic 128 characters


Stores only English letters, digits, and a few symbols
Unicode – every symbol used on computers

Stores accented characters, Chinese characters, Greek
letters, etc
ASCII is a subset of Unicode
 Java uses Unicode, but we’re really only concerned
with ASCII in this course

Escape Sequences


Backslashs signal escape sequences
Suppose you wanted to print
He said, “We need more cows”

What’s the problem with
System.out.println(
“He said, “We need more cows””);
Escape Sequences

Solution:
System.out.println(
“He said, \“We need more cows\””);

Other useful escape sequences:
\n
 \t
 \’

new line
tab
single quote
Formatting Numbers


will print out all available digits for a
real number
To change, new method printf() is available in
the PrintStream class (System.out)
println()
System.out.printf(“Total:%5.2f”, total);

Used in other programming languages
Productivity Hint

Those error messages you get for runtime errors
can actually be your friend!

Provide two pieces of information
The error (interpreting will be easier later in the
semester)
 More importantly: The line of the error!
