Convert each of the folowing mathematical formulas to a Java expression:
3x
3x+y
x+y
----
7
3x + y
------
x + 2
1. What is the value of number after the following is executed?
number = (1/3) * 3;
2. What is the value of quotient and remainder after the following is executed?
int quotient, remainder;
quotient = 7/3;
remainder = 7%3;
3. What is the value of result after the following is executed?
int result = 11;
result /=2;
4. double celsius = 20;
double fahrenheit;
fahrenheit = (9/5) * celsius + 32.0;
What is the value of fahrenheit? Explain why this is happening? Rewrite the code to produce the desired result.
5. What is the value of n after the following is executed?
int n = (int) 3.9;
6. What is the output produced by the following lines of code?
int n = 3;
n++;
System.out.println("n = " + n);
n--;
System.out.println("n= " + n);
7. What is the output produced by the following?
String verbPhrase = "is money";
System.out.println("Time" + verbPhrase);
8. What is the output produced by the following?
System.out.println("abc\ndef");
9. What is the output produced by the following?
System.out.println("abc\\ndef");
10. What is the output of the following two lines of Java code?
System.out.println("2 + 2 = " + (2 + 2));
System.out.println("2 + 2 = " + 2 + 2);
11. Suppose sam is an object of a class named Person and suppose increaseAge is a method for the class Person that takes one argument that is an integer. How do you write an invocation of the method increaseAge using sam as the calling object and using the argument 10? The method increaseAge will change the data in sam so that it simulates sam aging by 10 years.
12. Identify and correct the errors in each of the following pieces of code. [Note: There may be more than one error in each piece of code.]
a) if ( age >= 65);
System.out.println( "Age greater than or equal to 65" );
else
System.out.println( "Age is less than 65 )";
b) int x = 1, total;
while ( x <= 10 )
{
total += x;
++x;
}
c) while (x <= 100 )
total += x;
++x;
d) while ( y > 0)
{
System.out.println ( y );
++y;
13. Determine the value of the variables in the following statement after the calculation is performed. Assume that when the statement begins executing, all variables have the type int and have the value 5.
product *= x++;
Revised: September 11, 2008. Exercises from Savitch text. Comments to bill@billpegram.com