Java Reference
In-Depth Information
if
(x
>
3)
{
a=5;
}
else
{
a=7;
}
9. Consider the following code.
if
(
true
)
{
int
i=3;
System. out . println ( i ) ;
What is the scope of the variable
i
? Why will the program not compile? How can the
program be changed to compile.
10. Consider the following code.
int
i=6;
if
(
false
)
i=3;
System. out . println ( i ) ;
What will the program do? Why is the
println
line not part of the
if
statement?
11. Suppose
x=3
and
y=4
. Which of the following conditions are true.
(a)
(x==3 && y >2)
(b)
(x< 5 || y > 7)
(c)
!(x>3) || (y > 4)
(d)
!(x > 3 || y < 7)
12. Write a program that reads two strings from the keyboard and prints the largest
(relative to lexicographical order). Use the
compareTo
method to compare the strings.
2.12 Lab
Write a program that prints the following diamond.
1
234
12574
235
4
The printed numbers are random digits between 0 and 9. In Java,
Math.random()
returns
a random
double
that is greater than or equal to 0 and smaller than 1. The method is
defined in the library
java.math.*
(use
import java.math.*
) . Multiply this number by
something to get a digit between 0 and 9. Use
int i = (int) d;
to convert a
double
to
an
int
.