CS 111A Lecture Notes - Calculations - Chapter 2 part 2
Primitive Datatypes
- Floating Point - a term referring to real number approximations stored in computers.
- float - floating point number, uses 4 bytes in the range of
+/-3.4e-38 to +/-3.4e38
- double - floating point number, uses 8 bytes in the range of +/-1.7e-308 to +/-1.7.4e308
- byte - integer number, uses 1 byte (range -128 to 127)
- short - integer number, uses 2 bytes
- int - integer number, uses 4 bytes (range approx. -2.1 billion to 2.1 billion)
- long - integer number, uses 8 bytes
- char - stores one character (one keyboard key) using 2 bytes (unicode character set).
Character literals are enclosed with apostrophes, e.g. 'w'
- boolean - stores a Boolean value, e.g. true or false
- The Scanner class has methods to input directly into an int: scan.nextInt(), and also to input directly
into a double: scan.nextDouble()
Calculations, Assignments
- Arithmetic operators:
*
for multiplication
+
for addition
-
for subtraction
/
for division (beware of integer division, as explained below)
%
for modulus (the remainder from integer division)
=
for assignment (stroring the result of operation at right in
variable at left; think of it like an arrow to the left)
- Integer division produces an integer result. To get a floating point (real number) result, one or
both operands must be a floating point value.
- Semi-colons terminate most lines of code.
- The order of operations is just like in mathematics: multiplication (*), division (/), and modulus(%) are processed first, followed by addition (+) and subtraction (-). After all of that, the assignment operator (=) is processed. Parentheses may be used to specify a different of order of operations.
Shortcut Operators
+=
adds a value to a variable. Similarly, to subtract from or multiply or divide
by a value, or take the modulus of a value, use: -=
or *=
or /=
or
%=
++
increments a variable. So x++;
is equivalent to x += 1;
and x = x + 1;
--
decrements a variable
Formatting Output using printf
- printf is a function that is used in the C language to format output, and its popularity has led
it to be used in Java and other languages. With printf, you specify a string to output, with special codes
in the string.
- Those codes are called format specifiers. They are placeholders for variables which are to be
output, and also specify how those variables should be formatted when they are output. Format specifiers
begin with the percent-sign (%) and end with the format type.
- Here is a list of the most common format types:
- d - decimal integer - as distinguished from binary, octal, or hexidecimal integers.
- f - fixed floating point - displayed without scientific notation
- s - string
- Between the percent-sign and format type, you can insert many optional items, such as width, optionally
followed by a decimal point and the number of digits to display after that decimal point. For example,
%10.2f would show a floating point number right-aligned in a field of 10 characters, with 2 digits after the
decimal point.
- Between the percent-sign and the width, you can also insert a comma to indicate that groups of 3 digits
(thousands) are to be separated by commas, and/or a minus-sign to make output left-aligned instead of the
default right-alignment. For example, %-,15d would show an integer number left-aligned in a field of 15
characters, with commas separating groups of 3 digits.
- Because printf uses string codes to denote formatting, these codes are not checked at compile time.
Make sure to test your output thoroughly.
- After your output string is complete, you close the quote for it, and have a comma-seprated list of the
variables or exressions you want to insert into the string: one for each format specifier.
- Example: CalcFormatDemo.java
In-class exercise 1: Write a program that has the user enter 3 numeric homework grades, and outputs their
average.
Make sure to use a floating point data type for the grades. Use "printf" to show the average rounded to the nearest
tenth (showing just 1 digit after the decimal point)
GradeAverage.java: Solution to above in-class exercise averaging grades
Mathematical Functions (Methods)
- method or function - like in algebra, a function can take input (arguments) and produce
output (return value). It performs a calculation or executes other code. We'll write our own functions
later, but for now we are going to use pre-defined functions. A "method" is a function that's defined
inside a class. Since all functions are defined inside classes in Java, the words "method" and "function"
are interchangeable in Java.
- function call - a line of code that executes a function
- arguments - the data passed into a function when it is called. Also called actual
parameters
- return value - the "answer" produced by the function, returned from it to the function call.
- The class Math is defined for you, with methods for common mathematical operations.
- Math.pow function - pre-defined mathematical function to calculate an exponent. For example, to
store in the variable x the result of 2 to the 3rd power:
x = Math.pow(2, 3);
- Another useful mathematical function is sqrt, which returns the square root of a number.
- You can find
full documentation on the Math class in the Java API Reference
Type Casting
- Type Cast - an expression to make a value look like it has a different datatype. Type
casting never changes the datatype of a variable -- that's impossible. Instead, a type cast is like a
function that returns the same value in a different datatype.
- The notation for type casts uses the type name only. E.g. to cast the
variable x to type double, you write:
(double)x
- Example use of casting: avoiding truncation in integer division. Remember that the result of a
division operation will be truncated to an integer if both the operands were integers. So to get an
accurate floating point result, cast one of the operands to a floating-point type.
- Example finding the average word length in a document.
Constants
- A constant is a named location in memory that has a datatype (just like a variable) except that its
value cannot be changed after it is initialized. Use the keyword final before the datatype to
declare a constant.
In-class exercise 2: You're planning a wedding, and you need to transport all your wedding guests from the
ceremony to the reception. A bus can carry 40 passengers. Your program should ask the user how many
guests are expected, and it should output how many busses are needed, and the number of extra people
you could carry with those busses. You may find it helpful to use the
Math.ceil
method (which rounds a double up to the next higher integer)
Busses.java: Solution to above in-class exercise
Reference Variables, Memory Allocation, and Variable Scope
- A reference variable stores the memory address of an object or array. It's similar to the C++
concept of a pointer. (It's the closest thing Java has to pointers.) Unlike C++ pointers, reference
variables do not need to be de-referenced.
- new - a keyword used to dynamically allocate memory for an object. Returns a reference to
that object. Used with all constructor calls in Java, except it's optional with the String class.
- null - keyword indicating an empty reference. I.e. a reference variable whose value is null
is one that doesn't refer to an object.
- A null reference is often returned to indicate no value can be returned. E.g. when we click "Cancel"
on an InputDialog, the showInputDialog method returns null.
- In Java, strings are stored in the standard String class, so strings are stored as objects, and we
use reference variables to refer to them.
String methods
- charAt(i) - returns the character at position "i" in the string (starting from 0)
- length() - returns the integer length of the string (number of characters in it)
- toLowerCase() - returns the same string with all letters in lower case.
- toUpperCase() - returns the same string with all letters in upper case.
- To make it easier to work with Strings and get the expected behavior, the String class is designed
so it is immutable, meaning strings are never modified after they're created.
- For example, the String method toUpperCase does not modify the string it is called upon; it returns
a reference to a new String object which is the upper case version of the original.
- indexOf(s) - returns the 0-based index where the string or character "s" is found in the
string. (Location of first occurrence of s.)
- substring(i) - returns the string from character at position "i" to the end.
- substring(i, j) - returns the string from character at position "i" to character at position
"j" (not including the character at "j").
- equals(s) - returns true if the string is equal to the string "s" or false if they are not the
same (case in-sensitive version is equalsIgnoreCase) Do not use == to compare strings!
- Example: StringDemo.java: Shows various ways to manipulate strings.
Return to CS 111A page