1.2 Builtin Types of Data
A data type is a set of values and a set of operations defined on them. For example, we are familiar with numbers and with operations defined on them such as addition and multiplication (in mathematics, we are accustomed to thinking of the set of numbers as being infinite; in computer programs we have to work with a finite number of possibilities).
There are eight different builtin types of data in Java, mostly different kinds of numbers. Other types are available in system libraries, and programming in Java is actually centered around building our own data types, as we shall see later. We use the system type for strings of characters so frequently that we also consider it here.
Basic definitions. We use the following four statement Java program fragment to introduce some terminology that we'll be using:
int a, b, c; a = 1234; b = 99; c = a + b;
The first statement declares three variables with the identifiers a, b, and c to be of type int. The next two assignment statements change the values of the variables, using the literals 1234 and 99. The final statement assigns c to have the value 1333 by evaluating the expression a + b.
Characters and Strings. A char is an alphanumeric character or symbol, like the ones that you type. We usually do not perform any operations on characters other than assigning values to variables. A String is a sequence of characters. The most common operation that we perform on strings is known as concatenation: given two strings, chain them together to make a new string. For example, consider the following Java program fragment:
String a, b, c; a = "Hello,"; b = " Bob"; c = a + b;
The first statement declares three variables to be of type String. The next three statements assign values to them, with the end result that c has the value "Hello, Bob". Using string concatenation, Program Ruler.java prints the relative lengths of the subdivisions on a ruler.
Integers. An int is an integer (whole number) between 2^{31} and 2^{31}  1 (2,147,483,648 to 2,147,483,647). We use ints frequently not just because they occur frequently in the real world, but also they naturally arise when expressing algorithms. Standard arithmetic operators for addition, multiplication, and division, for ints are built in to Java, as illustrated in IntOps.java.
The type long is similar to int except it can represent integers in a much larger ranger, between 2^{63} an 2^{63}  1. We occasionally use long when we need to work with huge integers.
Real numbers. The double type is for representing floatingpoint numbers, e.g., for use in scientific applications. The internal representation is like scientific notation, so that we can compute with real numbers in a huge range. We can specify a floating point number using either a string of digits with a decimal point, e.g., 3.14159 for a 6 six digit approximation to the mathematical constant pi, or with a notation like scientific notation, e.g., 6.022E23 for Avogadro's constant 6.022 × 10^{23}. Standard arithmetic operators for addition, multiplication, and division, for doubles are built in to Java, as illustrated in DoubleOps.java. Program Quadratic.java shows the use of doubles in computing the two roots of a quadratic equation using the quadratic formula. The Java Math library defines trigonometric functions, logarithm/exponential, and other common functions for doubles. Trig.java illustrates a number of trigonometric functions including Math.sin(), Math.cos(), and Math.toRadians().
Booleans. The boolean type has just two values: true or false. The apparent simplicity is deceiving  booleans lie at the foundation of computer science. The most important operators defined for booleans are for and, or, and not.
 and: a && b is true if both a and b are true, and false otherwise.
 or: a  b is true if either a or b is true (or both are true), and false otherwise
 not: !a is true if a is false, and false otherwise.
Although these definitions are intuitive and easy to understand, it is worthwhile to fully specify each possibility for each operation in a truth table.
a  b  a && b  a  b 

false  false  false  false 
false  true  false  true 
true  false  false  true 
true  true  true  true 
Comparisons. The comparison operators are mixedtype operations that take operands of one type (e.g., int or double) and produce a result of type boolean. These operations play a critical role in the process of developing more sophisticated programs.
op  meaning  a op b  true  false 

==  equal to  a is equal to b  2 == 2  3 == 2 
!=  not equal to  a is not equal to b  3 != 2  2 != 2 
<  less than  a is less than b  2 < 13  2 < 2 
<=  less than or equal to  a is less than or equal to b  2 <= 2  3 <= 2 
>  greater than  a is greater than b  13 > 2  2 > 13 
>=  greater than or equal to  a is greater than or equal to b  3 >= 2  2 >= 3 
LeapYear.java tests whether an integer corresponds to a leap year in the Gregorian calendar. Here's is Stanley Rabinowitz's entertaining response to a question as to why OpenVMS assumes that 2000 is a leap year.
Type conversion.
We often find ourselves converting data from one type to another using one of the following approaches. Explicit type conversion. Call methods such as Math.round(), Integer.parseInt(), and Double.parseDouble().
 Automatic type conversion. For primitive numeric types, the system automatically performs type conversion when we use a value whose type has a larger range of values than expected.
 Explicit casts. Java also has some builtin type conversion methods for primitive types that you can use when you are aware that you might lose information, but you have to make your intention using something called a cast. Program RandomInt.java reads in a commandline argument N and prints out a "random" integer between 0 and N1.
 Automatic conversions for strings. The builtin type String obeys special rules. One of these special rules is that you can easily convert any type of data to a String by using the + operator.
Q + A
Q. How do I get the  symbol on my keyboard?
A. It's there. Often it's above the \ symbol.
Q. Java prints out a ton of digits when I System.out.println() a double. How can I format it so it displays only 3 digits after the decimal place?
A. Use the method System.out.printf() described in Section 1.5.
Q. Why does the integer quotient 0/3 yield 0, but the double quotient 0.0/3.0 yields 0.0?
A. Java represent integers using something called two's complement notation, and there is only one representation of 0. (You'll learn about this in Section 5.1.) Java represents doubles using IEEE specifications, and there are two distinct representations of the number zero, 0 and 0. (You'll learn about this in Section 9.1.)
Q. What happens when I use / and % with a negative numerator?
A. Try it and see. 47 / 5 = 9 and 47 % 5 = 2. The quotient is always rounded toward zero. To ensure the Euclidean property b * (a / b) + (a % b) = a, the result of the remainder operator can be negative. This convention was inherited from ancestral languages like FORTRAN and C. Some languages (but not Java) include both remainder and modulo operators because it is often convenient to have a version that returns only nonnegative integers.
Q. Can I use % with real numbers?
A. Yes. If angle is nonnegative, then angle % (2 * Math.PI) converts the angle to be between 0 and 2 π.
Q. How do I print a "?
A. Since " is a special character when dealing with strings, you must escape the convention rules by using \". For example, System.out.println("The pig said \"Oink Oink\" afterwards");.
Q. OK, so then how do I print a \?
A. Use "\\".
Q. Are there any restrictions on the variable names I can use?
A. Yes. A Java identifier is a Java letter, followed by an unlimited sequence of Java letters and Java digits. Java letters and digits can be drawn from the entire Unicode character set, although we only use English language characters in this book. By convention, variables usually begin with a lowercase letter. An identifier cannot be named any of the following reserved words.
Q. What are the precedence rules for operators in Java?
abstract default goto package this assert do if private throw boolean double implement protected throws break else import public transient byte enum instanceof return true case extends int short try catch false interface static void char final long strictfp volatile class finally native super while const float new switch continue for null synchronized
A. This table provides the precedence order of operators in Java.
Q. Is there any difference between a += b and a = a + b, where a and b are primitive types?
A. Possibly, if a and b are of different types. The assignment statement a += b is equivalent to a = (int) (a + b) if a is of type int. Thus, if b is of type double, a += b is legal, but a = a + b is a compiletime error.
Q. Why do I need to declare the type of a variable in Java?
A. By specifying the type, the compiler can alert you of potential errors, say if you try to multiply an integer with a string. For the same reason, when doing physics calculations, it is always a good idea to keep track of the units and make sure they "type check." For small programs, this may not seem important; for large programs it is crucial. The Ariane 5 rocket exploded 40 seconds after takeoff because of a bug in its software that incorrectly converted a 64 bit real number into a 16 bit integer.
Q. Why is the type for real numbers called double?
A. Historically, the type for floating point numbers was float, but they had limited accuracy. The type double was introduced as a floating point type with twice as much accuracy.
Exercises

Suppose that a and b are int values. What does
the following sequence of statements do?
int t = a; b = t; a = b;
Answer: sets a, b, and t equal to the original value of a.
 Write a program that uses Math.sin() and Math.cos() to check that the value of sin^{2}θ + cos^{2}θ is approximately 1 for any θ entered as a commandline argument. Just print the value. Why are the values not always exactly 1?
 Suppose that a and b are boolean values. Show that the expression (!(a && b) && (a  b))  ((a && b)  !(a  b)) is equivalent to true.

Suppose that a and b are int values.
Simplify the following expression: (!(a < b) && !(a > b))
Solution: (a == b)
 The exclusive or operator ^ for boolean operands is defined to be true if they are different, false if they are the same. Give a truth table for this function.

Why does 10/3 give 3 and not 3.33333333?
Solution. Since both 10 and 3 are integer literals, Java sees no need for type conversion and uses integer division. You should write 10.0/3.0 if you mean the numbers to be double literals. If you write 10/3.0 or 10.0/3, Java does implicit conversion to get the same result.

What do each of the following print?
 System.out.println(2 + "bc"); prints: 2bc
 System.out.println(2 + 3 + "bc"); prints: 5bc
 System.out.println((2+3) + "bc"); prints: 5bc
 System.out.println("bc" + (2+3)); prints: bc5
 System.out.println("bc" + 2 + 3); prints: bc23
Explain each outcome.

Explain how to use Quadratic.java
to find the square root of a number.
Answer: to find the square root of c, find the roots of x^2 + 0x  c.

What do each of the following print?
 System.out.println('b');
 System.out.println('b' + 'c');
 System.out.println((char) ('a' + 4));
Explain each outcome.

Suppose that a variable a is declared as int a = 2147483647
(or equivalently, Integer.MAX_VALUE).
What do each of the following print?
 System.out.println(a);
 System.out.println(a + 1);
 System.out.println(2  a);
 System.out.println(2  a);
 System.out.println(2 * a);
 System.out.println(4 * a);
Explain each outcome.

Suppose that a variable a is declared as double a = 3.14159.
What do each of the following print?
 System.out.println(a);
 System.out.println(a + 1);
 System.out.println(8 / (int) a);
 System.out.println(8 / a);
 System.out.println((int) (8 / a));
Explain each outcome.
 Describe what happens if you write sqrt instead of Math.sqrt() in Quadratic.java.
 What is the value of (Math.sqrt(2) * Math.sqrt(2) == 2)?
 Write a program that takes two positive integers as commandline arguments and prints true if either evenly divides the other.
 Write a program that takes three positive integers as commandline arguments and prints true if any one of them is strictly greater than the sum of the other two and false otherwise. (Note : This computation tests whether the three numbers could be the lengths of the sides of some nondegenerate triangle.)

A physics student gets unexpected results when using the code
F = G * mass1 * mass2 / r * r;
to compute values according to the formula F = G m1 m2 / r^2. Explain the problem and correct the code.Solution. It divides by r, then multiplies by r (instead of dividing by r *r). Use parentheses:
F = G * mass1 * mass2 / (r * r);

Give the value of a after the execution of each of the following sequences:
int a = 1; boolean a = true; int a = 2; a = a + a; a = !a; a = a * a; a = a + a; a = !a; a = a * a; a = a + a; a = !a; a = a * a;

Suppose that x and y are double values that represent
the Cartesian coordinates of a point (x, y) in the plane. Give an expression whose
value is the distance of the point from the origin.
Solution. Math.sqrt(x*x + y*y)
 Write a program that takes two int values a and b from the command line and prints a random integer between a and b.
 Write a program SumOfTwoDice.java that prints the sum of two random integers between 1 and 6 (such as you might get when rolling dice).
 Write a program that takes a double value t from the command line and prints the value of sin(2t) + sin(3t).
 Write a program that takes three double values x0, v0, and t from the command line and prints the value of x0 + v0*t + 1/2 gt^2, where g is the constant 9.800722 m/s^2. (Note : This value the displacement in meters after t seconds when an object is thrown straight up from initial position x0 at velocity v0 meters per second.)
 Write a program SpringSeason.java that takes two int values m and d from the command line and prints true if day d of month m is between March 20 (m = 3, d =20) and June 20 (m = 6, d = 20), false otherwise.
Creative Exercises
 Loan payments. Write a program that calculates the monthly payments you would have to make over a given number of years to pay off a loan at a given interest rate compounded continuously, taking the number of years t, the principal P, and the annual interest rate r as commandline arguments. The desired value is given by the formula Pe^(rt). Use Math.exp().

Wind chill.
Given the temperature t (in Fahrenheit) and the wind speed v (in
miles per hour), the National Weather Service defines the effective
temperature (the
wind chill) to be:
w = 35.74 + 0.6215 t + (0.4275 t  35.75) v^{0.16}
Write a program WindChill.java that takes two double commandline arguments t and v and prints out the wind chill. Use Math.pow(a, b) to compute a^{b}. Note: the formula is not valid if t is larger than 50 in absolute value or if v is larger than 120 or less than 3 (you may assume that the values you get are in that range).  Polar coordinates. Write a program CartesianToPolar.java that converts from Cartesian to polar coordinates. Your program should take two real numbers x and y on the command line and print the polar coordinates r and θ. Use the Java method Math.atan2(y, x), which computes the arctangent value of y/x that is in the range from π to π.
 Gaussian random numbers.
One way to generate a random number taken from the Gaussian distribution is
to use the BoxMuller formula
Z = sin(2 π v) (2 ln u)^{1/2}
where u and v and real numbers between 0 and 1 generated by the Math.random() method. Write a program StdGaussian.java that prints out a standard Gaussian random variable.  Order check. Write a program that takes three double values x, y, and z as commandline arguments and prints true if the values are strictly ascending or descending (x < y < z or x > y > z), and false otherwise.

Day of the week.
Write a program DayOfWeek.java
that takes a date as input and prints the day of the week that date falls on.
Your program should take three commandline arguments:
m (month), d (day), and y (year).
For m use 1 for January, 2 for February, and so forth. For output print
0 for Sunday, 1 for Monday, 2 for Tuesday, and so forth.
Use the following
formulas, for the Gregorian calendar:
y0 = y  (14  m) / 12 x = y0 + y0/4  y0/100 + y0/400 m0 = m + 12 * ((14  m) / 12)  2 d0 = (d + x + (31*m0)/ 12) mod 7
y = 1953  0 = 1953 x = 1953 + 1953/4  1953/100 + 1953/400 = 2426 m = 8 + 12*0  2 = 6 d = (2 + 2426 + (31*6) / 12) mod 7 = 2443 mod 7 = 0 (Sunday)
 Uniform random numbers. Write a program Stats5.java that prints five uniform random values between 0 and 1, their average value, and their minimum and maximum value. Use Math.random(), Math.min(), and Math.max().
 Mercator projection.
The Mercator
projection is a conformal (angle preserving) projection
that maps latitude φ and longitude λ to rectangular
coordinates (x, y). It is widely used  for example, in nautical charts and in the maps
that you print from the web.
The project is defined by the equations
x = λ  λ_{0} y = 1/2 ln((1 + sin φ) / (1  sin φ))
 Color conversion.
Several different formats are used to represent color. For
example, the primary format for LCD displays, digital cameras, and web pages,
known as the RGB format, specifies the level of red (R), green (G), and blue (B)
on an integer scale from 0 to 255. The primary format for publishing books and
magazines, known as the CMYK format, specifies the level of cyan (C), magenta
(M), yellow (Y), and black (K) on a real scale from 0.0 to 1.0. Write a program RG
BtoCMYK that converts RGB to CMYK. Take three integers  red,
green, and blue  from
the command line and print the equivalent CMYK values. If the RGB values are all 0,
then the CMY values are all 0 and the K value is 1; otherwise, use these formulas:
% java RGBtoCMYK 75 0 130 // indigo cyan = 0.4230769230769229 magenta = 1.0 yellow = 0.0 black = 0.4901960784313726

Great circle.
Write a program GreatCircle.java
that takes four commandline arguments  x1, y1, x2, and y2  (the latitude and
longitude, in degrees, of two points on the earth) and prints out the
greatcircle distance between them. The greatcircle distance d (in nautical miles)
is given by the formula derived from the law of cosines:
Note: the shape of the earth is more like a flattened spheroid than a sphere, so the formula above is only an approximation (up to around 0.5% error). Also, this formula is unreliable for small distances because the inverse cosine function is illconditioned.
Here is the Haversine formula:
a = sin^2(L2L1)/2) + cos(L1) * cos(L2) * sin^2((G2G1)/2) c = 2 * arcsin(min(1, sqrt(a))) // distance in radians distance = 60 * c // nautical miles
The Haversine formula is accurate for most distances, but it suffers from rounding errors when the points are (nearly) antipodal. The following formula is accurate for all distances.
double delta = G1  G2; double p1 = cos(L2) * sin(delta); double p2 = cos(L1) * sin(L2)  sin(L1) * cos(L2) * cos(delta); double p3 = sin(L1) * sin(L2) + cos(L1) * cos(L2) * cos(delta); distance = 60 * Math.atan2(Math.sqrt(p1*p1 + p2*p2), p3);

Threesort.
Write a program ThreeSort.java
that takes three
int values from the command line and prints them in ascending order. Use Math.min() and Math.max().  Dragon curve. Write a program Dragon.java to print the instructions for drawing the dragon curves of order 0 through 5. The instructions are strings of the characters F, L, and R, where F means "draw line while moving 1 unit forward", L means "turn left", and R means turn right. A dragon curve of order N is formed when you fold a strip of paper in half N times, then unfold to right angles. The key to solving this problem is to note that a curve of order N is a curve of order N1 followed by an L followed by a curve of order n1 traversed in reverse order, and then to figure out a similar description of the reverse curve.
Web Exercises
 Write a program Distance.java that takes two integer commandline arguments x and y and outputs the Euclidan distance from the point (x, y) to the origin (0, 0).
 Write a program Swap.java that takes two integer commandline arguments a and b and swaps their values using the swapping idiom described on p. 17. After each assignment statement, use System.out.println() to print out a trace of the variables.

What does the following statement do where grade is
a variable of type int?
boolean isA = (90 <= grade <= 100);
Solution. Syntax error since <= is a binary operator. You can rewrite the expression as (90 <= grade && grade <= 100).
 RGB to YIQ color converter. Write a program RGBtoYIQ.javathat takes an RGB color (three integers between 0 and 255) and transforms it to an YIQ color (three different integers between 0 and 255). Write a program YIQtoRGB.java that applies the inverse transformation.
 CMYK to RGB color matching. Write a program CMYKtoRGB that reads in four command line inputs C, M, Y, and K between 0 and 1, and prints out the corresponding RGB parameters. Devise the appropriate formula by "inverting" the RGB to CMYK conversion formula.

What does the following code fragment print out?
double x = (double) (3/5); System.out.println(x);
Solution. It prints 0.0 since the integer division is done before the cast.

Why doesn't the following program print out 4294967296 = 2^32?
int x = 65536; long y = x * x; System.out.println(y);
 What is the value of (Math.sqrt(2) * Math.sqrt(2) == 2)?

Write a program DivideByZero.java
to see what happens when you divide an int or double
by zero.
Solution.
 (17 / 0) and (17 % 0) result in a division by zero exception;
 (17.0 / 0.0) results in a value Infinity;
 (17.0 % 0.0) results in a value NaN that stands for "not a number."
 Guess the biggest number. Consider the following game. Alice writes down two integers between 0 and 100 on two cards. Bob gets to select one of the two cards and see its value. After looking at the value, Bob commits to one of the two cards. If he chooses a card with the largest value, he wins; otherwise he loses. Devise a strategy (and corresponding computer program) for Bob so that he guarantees to win strictly more than half the time.
 Fibonacci word. Write a program FibonacciWord.java that prints the Fibonacci word of order 0 through 10. f(0) = "a", f(1) = "b", f(2) = "ba", f(3) = "bab", f(4) = "babba", and in general f(n) = f(n1) followed by f(n2). Use string concatenation.
 Standard deviation. Modify Exercise 1.2.30 so that it prints out the sample standard deviation in addition to the average.
 Write a program that reads in three parameters and prints true if all three are equal, and false otherwise.

What happens if you compile LeapYear.java and execute it with
 java LeapYear
 java LeapYear 1975.5
 java LeapYear 1975
 java LeapYear 1975 1976 1977

What does the compiler do if you try to write the following expression:
int a = 27 * "three";

What does the compiler do if you try to write the following expression:
double x; System.out.println(x);
Solution. The compiler complains that the variable x might not have been initialized. Variables within main are not automatically initialized.

What does the following code fragment print.
int threeInt = 3; int fourInt = 4; double threeDouble = 3.0; double fourDouble = 4.0; System.out.println(threeInt / fourInt); System.out.println(threeInt / fourDouble); System.out.println(threeDouble / fourInt); System.out.println(threeDouble / fourDouble);
 Write a program that takes four realvalued command line parameters x1, y1, x2, and y2 and prints the Euclidean distance between the points (x1, y1) and (x2, y2). Use Math.sqrt().
 Write a program Ordered.java that reads in three integer command line arguments, x, y, and z. Create a boolean variable b that is true if the three values are either in ascending or in descending order, and false otherwise. Print out the variable b.
 Write a program Divisibility.java that reads in two command line inputs and prints true if both are divisible by 7, and false otherwise.
 Area of a triangle. Write a program TriangleArea.java that takes three command line inputs a, b, and c, representing the side lengths of a triangle, and prints out the area of the triangle using Heron's formula: area = sqrt(s(sa)(sb)(sc)), where s = (a + b + c) / 2.
 Equatorial to horizontal coordinates.
The equatorial coordinate system is widely used by
astronomers to indicate the position of a star on the celestial
sphere. The position is specified by its declination δ,
its hour angle H, and its latitude φ.
The horizontal coordinate system (a.k.a. Alt/Az coordinate
system) is useful for determining the setting/rising time of
celestial objects. The position is specified by its altitude
(vertical angle from the horizon) and and its azimuth
(horizontal angle). Given a star's position using
equatorial coordinates, find its position in horizontal coordinates
using the formulas below.
Altitude = asin (sin φ sin δ + cos φ cos δ cos H) Azimuth = acos ((cos φ sin δ  sin φ cos δ cos H) / cos (Altitude) )
 Body mass index. The body mass index (BMI) is the ratio of the weight of a person (in kilograms) to the square of the height (in meters). Write a program BMI.java that takes two commandline arguments, weight and height, and prints out the BMI.
 Temperature conversion.
What is wrong with the following code fragment to convert from Fahrenheit (F)
to Celsius (C)?
double C = (F  32) * (5 / 9);
 Exponentiation.
What is wrong with the following code fragment to compute a^{2},
where a is of type double?
double b = a^2;
Solution. In Java, ^ does not mean exponentiation (it's the exclusive or function from logic). Use a*a instead. To compute a^{x}, use Math.pow(a, x). Note that Math.pow() returns a double so that you would need an explicit cast if a and b in the above example were integers.

What of the following statements is legal?
boolean b = 1; boolean b = true; boolean b = "true"; boolean b = True;
Solution. Only the second one.

Barring overflow, give a code fragment to compute the maximum
of two integers a and b without using
Math.max() or if.
int max = (a + b + Math.abs(a  b)) / 2;
 Discriminant of cubic polynomial. Given the coefficients b, c, and d of the cubic polynomial x^3 + bx^2 + cx + d, write an expression to compute the discriminant b^2c^2  4c^3  4b^3d  27d^2 + 18bcd.
 Barycenter.
In a twobody system, the
barycenter
is the center
of gravity about which the two celestial bodies orbit each other.
Given the masses m_{1} and m_{2}
of two bodies, and the
shortest distance a between the two bodies, write a program to compute
the distance from the center of the first (more massive)
body to the barycenter:
r_{1} = a m_{2} / (m_{1} + m_{2}).
Here are a few examples. Masses are in earthmass units, distances are in kilometers.
Earthmoon: m_{1} = 1, m_{2} = .0123, a = 384,000, r_{1} = 4,670, R_{1} = 6,380.
PlutoCharon: m_{1} = .0021, m_{2} = .000254, a = 19,600, r_{1} = 2,110, R_{1} = 1,150.
SunEarth: m_{1} = 333,000, m_{2} = 1, a = 150,000,000, r_{1} = 449, R_{1} = 696,000.
Note that if r_{1} is less than the radius of the first body R_{1}, then the barycenter lies within the first body.
 Poision parentheses.
Find a legal Java expression that leads to a compiletime error
when you add parentheses around a subexpression to
to document the order of evaluation that would take place in their absence.
Solution. The literal value 2147483648 (2^31) is permitted only as an operand of the unary minus operator, i.e., 2147483648. Enclosing it in parentheses, i.e., (2147483648), leads to a compiletime error. Similar ideas with the literal value 9223372036854775808L (2^63).

Car loan payments.
Write a program CarLoan.java
that reads in three commandline arguments P, Y, and R and
calculates the monthly payments you would have to make over Y
years to pay off a P dollar loan at R per cent interest compounded monthly. The formula is
The formula is
P r payment = , where n = 12 * Y, r = R / (12 * 100) 1  (1 + r)^(n)