Exercise (Solutions)
E1
What is wrong with the following variable declarations?
int x = “24”;
boolean isFun = “true”;
String myname = jayshree;
int my number;
int 24_number = 24;
E2
In the below program, you want all the additions to be evaluated first before multiplication and division can happen. How do you fix the code to make that happen?
class MyClass {
public static void main(String[]args) {
double d = 5 * 6 + 4 + 5 / 3;
System.out.println(d);
}
}
E3
What is wrong with the below code?
class MyClass {
public static void main(String[]args) {
b = 10;
System.out.println(b);
}
}
E4
Write a program that prints out the name, street name, city, phone number all on different lines by taking all the inputs from Scanner one at a time.
E5
The program below is supposed to calculate and show the time it takes for light to travel from the sun to the earth. When you run the program it prints 0 min and -1 sec as the time, which makes no sense. Fix the program so that it will show the correct value of 8 minutes and 20 secs:
public class SunLightTimer {
public static void main(String[] args) {
int earthDistanceFromSunInKm = 150000000;
int speedOfLightInMetersPerSec = 299792458;
//Convert distance to meters:
int earthDistanceFromSunInMeters = earthDistanceFromSunInKm * 1000;
int timeTakenByLightInSecs = earthDistanceFromSunInMeters / speedOfLightInMetersPerSec;
System.out.println(timeTakenByLightInSecs + " secs");
int timeInMins = timeTakenByLightInSecs / 60;
timeTakenByLightInSecs = timeTakenByLightInSecs - (timeInMins * 60);
System.out.println("Light will take.. ");
System.out.println(timeInMins + " minute(s) and " + timeTakenByLightInSecs + " second(s)");
System.out.println("to reach earth from sun ");
}
}
E6
Write a console program to define and initialize a variable of type byte to 1 and then successively multiply it by 2 and display its value 8 times. Observe the output and explain the reason for the displayed value in the last output.
Here is the partial code given:
byte a = 1;
a *= 2;
System.out.println(a);
Repeat the second and third line 8 times and explain the value that you see in the last output statement.