Download Com Sci Chapter 4 Lecture Notes

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Computer Science Notes
Chapter 4
Page 1 of 8
Chapter 4: Fundamental Data Types
Big Skills:
1. To understand integer and floating point numbers.
2. To recognize limitations of the numeric types.
3. To become aware of causes of overflow and roundoff errors.
4. To understand the proper uses of constants.
5. To write arithmetic expressions in Java.
6. To use the String type to define and manipulate character stings.
7. To learn how to read program input and produce formatted output.
Section 4.1: Number types
Type
int
byte
short
long
double
float
char
boolean
Primitive Types
Description
-2,147,483,648  integer  2,147,483,647
These range limits are stored in
java.lang.Integer.MIN_VALUE
and java.lang.Integer.MAX_VALUE
-128  integer byte  127
These range limits are stored in
java.lang.Byte.MIN_VALUE
and java.lang.Byte.MAX_VALUE
-32768  short integer  32767
These range limits are stored in
java.lang.Short.MIN_VALUE
and java.lang.Short.MAX_VALUE
-9,223,372,036,854,775,808  long integer
 9,223,372,036,854,775,807
These range limits are stored in
java.lang.Long.MIN_VALUE
and java.lang.Long.MAX_VALUE
Double-precision floating point: 10308 and about 15
significant figures
These range limits are stored in
java.lang.Double.MIN_VALUE
and java.lang.Double.MAX_VALUE
Single-precision floating point: 1038 and about 7
significant figures
These range limits are stored in
java.lang.Float.MIN_VALUE
and java.lang.Float.MAX_VALUE
Character type, using Unicode
The type with 2 truth values: true and false
Size
4 bytes
1 byte
2 bytes
8 bytes
8 bytes
4 bytes
2 bytes
1 bit
Computer Science Notes
Chapter 4
Page 2 of 8
Casting: converting a value from one type to another by preceding it with a type name in parentheses
Overflow: when a computation falls outside the range of a number type
Example: short i = 100*100;
//should be an overflow for variable i
Example:
float x = (float) 1.0E20;
float y = (float) 1.0E-20;
float z = 0;
z = x / y;
System.out.print("z = ");
System.out.println(z);
// output is: z = Infinity
Rounding error: when an exact conversion between a number and its binary representation is not possible.
Information loss: data lost in converting data types; use Math.round (in the java.lang package) to minimize this
kind of error
Big Number objects: the classes BigDecimal and BigInteger (in the java.math package)…
BigInteger a = new BigInteger(“1234567890”);
BigInteger b = new BigInteger(“9876543210”);
System.out.println(a.multiply(b));
Converting numbers to binary and vice-versa:
To convert binary to base-10, just add up the correct powers of 2.
To convert base 10 integers to binary, repeatedly divide by 2; when you get to 0, the list of the remainders are
the binary digits.
To convert base 10 decimals to binary, repeatedly multiply by 2; when you get to 0.0 or a repeating pattern, the
list of the whole number occurrences are the binary digits.
To have your Java program convert an integer n to binary, call Integer.toString(n, 2).
To have your Java program convert an binary digit string digitString to an integer, call
Integer.parseInt(digitString, 2).
Computer Science Notes
Chapter 4
Page 3 of 8
Section 4.2: Constants
Constant: values that do not change in a program

use the key word final

convention is to use all caps for a constant

also use the keyword static if the constant is in a class

usually make constants public, and access them with the “.” operator, just like for methods

examples: Math.PI, Math.E

good practice: always use constants instead of numbers

good practice: always use descriptive variable names

Example:
final int DAYS_PER_YEAR = 365
Syntax 4.2: Constant Definition
In a method: final typeName variableName = expression;
Example in a method: final double NICKEL_VALUE = 0.05;
In a class: accessSpecifier static final typeName variableName = expression;
Example in a class: public static final double METERS_PER_FOOT = 0.3048;
Computer Science Notes
Chapter 4
Section 4.3: Assignment, Increment, and Decrement
Assignment: setting a variable equal to a value; use the assignment operator “=”
Increment: adds the value 1 to a variable; use the increment operator “++”
Decrement: subtracts the value 1 from a variable; use the decrement operator “--”
Section 4.4: Arithmetic Operations and Mathematical Functions
Arithmetic operators:

Addition: +

Subtraction: 
Multiplication: *

Division (integer versus floating point): /

Remainder (modulus): %
Grouping symbols:
()
Combined arithmetic and assignment operators:
+=
-=
*/=
%=
Additional methods are in the Math class (in the java.lang package):
Math.sqrt(x)
Math.pow(x, y)
Math.sin(x)
// the angle x must be in radians
Math.cos(x)
Math.tan(x)
Math.asin(x)
Math.acos(x)
Math.atan(x)
Math.atan2(y, x)
//arctangent of (y/x) with a range from - to 
Math.toRadians(x)
Math.toDegrees(x)
Math.exp(x) // e^x
Math.log(x) //natural logarithm of x
Math.round(x)
Math.ceil(x)
Math.floor(x)
Math.abs(x)
Math.max(x, y)
// the larger of x and y
Math.min(x, y)
…
Note: integer division results in just the quotient for an answer (no rounding, no remainder)
Page 4 of 8
Computer Science Notes
Chapter 4
Page 5 of 8
Section 4.5: Calling Static Methods
Static methods are methods that do not operate on an object.
Example: Math.sqrt(x) takes a double precision input and produces a double precision output, but does not do
anything on any “number class” because primitive number types are not objects.
 when looking for methods to manipulate numbers, check the API for static methods… the Integer class is
full of static methods that do neat tricks with integers.
Syntax 4.3: Static Method Call
ClassName.methodName(parameters)
Example: Math.sqrt(5)
Section 4.6: Strings
String: a sequence of characters; strings are objects of the String class
Sting concatenation operator: +
Example: “Hello” + “ dude” is equivalent to “Hello dude”
Some string methods:

public String concat(String str)
Concatenates the specified string to the end of this string.
Examples:
"cares".concat("s") returns "caress"
"to".concat("get").concat("her") returns "together"

public String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with
newChar.
Example:
"mesquite in your cellar".replace('e', 'o') returns "mosquito in your collar"

public String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified
literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for
example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".

public String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.

public String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.

public String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.

public static String valueOf(int i)
Returns the string representation of the int argument.

public static String valueOf(double d)
Computer Science Notes
Chapter 4
Page 6 of 8
Returns the string representation of the double argument.

public int length()
Returns the length of this string. The length is equal to the number of 16-bit Unicode characters
in the string.

public String substring(int beginIndex)
Returns a new string that is a substring of this string. The substring begins with the character at
the specified index and extends to the end of this string.
Example:
"unhappy".substring(2) returns "happy"

public String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified
beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is
endIndex-beginIndex.
Examples:
"hamburger".substring(4, 8) returns "urge"
"smiles".substring(1, 5) returns "mile"

public char charAt(int index)
Returns the char value at the specified index. An index ranges from 0 to length() - 1. The
first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
Conversion of strings into numbers:
 can use the static parseInt method of the java.lang.Integer class:
String input = “19”;
int count = Integer.parseInt(input);
 can use the static parseDouble method of the java.lang.Double class:
String input = “3.95”;
double price = Double.parseDouble(input);
Escape sequences: special codes for special characters

\"
generates a double quotes within a string

\\
generates the backslash character

\n
generates a newline character (a linefeed)

\t
generates a tab character

\u… generates the Unicode character specified by … (in base 16)
e.g. \u00E9 is the symbol é
Computer Science Notes
Chapter 4
Page 7 of 8
Section 4.7: Reading Input
To read keyboard input: use the Scanner class (in the java.util package). To construct a Scanner object, pass
the System.in object to the Scanner constructor. Then use the appropriate method to get the desired input.
Example:
import java.util.Scanner;
…
Scanner user_input = new Scanner(System.in)
System.out.print("Enter an integer: ");
int user_integer = user_input.nextInt();
System.out.print("Enter a decimal number: ");
double user_double = user_input.nextDouble();
System.out.print("Enter a string: ");
String user_string = user_input.nextLine(); //returns all characters until the return key is entered
System.out.print("Enter a word: ");
String user_word = user_input.next();
//returns all characters until any whitespace is entered
To read input from a Dialog box:
1. Import the JOptionPane class from the javax.swing package
2. Read the input into a string variable using something like:
String input = JOptionPane.showInputDialog(“Enter a number:”);
3. Add the statement System.exit(0); to the end of your main method
To format numeric output: use the printf() method of the PrintStream class (in the java.io package)
The printf() method expects to find format specifiers which tell it how many spaces, decimal places, etc. to use
when printing out numbers. A format specifier is a code that starts with the % character and ends with a letter
for the type of format to be applied. Format specifiers may include flags that give additional format info.
Example:
//the following line produces an output where the format specifier %6.2f will be replaced with the
//floating point number 1.5 written using 6 spaces and 2 digits after the decimal point (and followed by a
//newline)
System.out.printf("Price is: $%6.2f\n", 1.5);
//sample output: Price is: $ 1.50
Format Types
Code
dd
Type
Decimal integer
x
Hexadecimal integer
o
Octal integer
f
Fixed floating point
e
Exponential floating point
g
General floating point (method decides whether to
Example
System.out.printf("%5d", 123);
//output: 123
System.out.printf("%5x", 123);
//output: 7B
System.out.printf("%5o", 123);
//output: 173
System.out.printf("%6.2f", 123);
//output:123.00
System.out.printf("%10.2e", 123);
//output: 1.23e+1
System.out.printf("%6.2g", 123);
Computer Science Notes
Chapter 4
s
use f or e)
String
n
Platform-independent line end
Page 8 of 8
//output:123.00
System.out.printf("%6s", “123”);
//output: 123
Format Flags
Flag
-
Meaning
Left justifiation
0
Show leading zeros
+
Show a + sign for positive numbers
(
Enclose negative numbers in parentheses
,
Show decimal separators
^
Convert letters to uppercase
s
String
Example
System.out.printf("%-5dhello", 123);
//output:123 hello
System.out.printf("%06d", 123);
//output:000123
System.out.printf("%+6d", 123);
//output: +123
System.out.printf("%(6d", -123);
//output: (123)
System.out.printf("%10d", 123000);
//output: 123,000
System.out.printf("%^6s", "hello");
//output:HELLO
System.out.printf("%^10.2e", 123);
//output: 1.23E+1
Note: to access this functionality in Eclipse, make sure that you are using a version compliance of 5.0 or higher.