Tutorial Week 2
Tutorial Week 2
T323
Tutorial – Week 2
// user input
scanner.close();
}
Output:
Exercise 2:
Rectangle.java Write a program that asks the length and width of a rectangle from the argument
input, and then prints:
if (args.length != 2) {
return;
Part B
1) There are three stages in developing Java programs. First, the program is written in
human- readable form
a. What should the file name be for a public class named HelloWorld?
Ans: For a public class named HelloWorld, the file name should be HelloWorld.java
2) What is the difference between variable declaration and variable assignment? What is
variable initialization?
Variable Declaration:
Variable Assignment:
Variable Initialization:
Difference:
Declaration: It announces the existence and data type of a variable.
Assignment: It assigns a value to a variable that has already been declared.
Initialization: It is a specific form of assignment that takes place during declaration.
3.
b. There's an error in x+1 = y+1; because the left side of the expression is not a variable.
c. There are errors in z = x+y; because z is not declared, and x is not initialized.
e. There's an error in String 9tails="cat"; because variable names cannot start with a digit.
f. There's an error in int this=4, that=5; because this is a keyword and cannot be used as an
identifier.
4. Trace through the following code. Make sure to write down the values of variables when
you have carried out each line.
int a = 5 + 4; // a = 9
int b = a * 2; // b = 18
int c = b / 4; // c = 4
int d = b - c; // d = 14
int f = e % 4; // f = -2
Solve:
1. num1 != 5:
o This is false because num1 is indeed equal to 5.
2. num2 == 10:
o This is true because num2 is equal to 10.
3. (false || true):
o The result is true because it's an OR (||) operation,
and only one side needs
to be true for the overall expression to be true.
4. !(num1 == 5):
o This is true because num1 == 5 is false, and the ! (NOT) operator negates
it.
5. (true && true):
o The result is true because it's an AND (&&) operation, and both sides are true.
Result:
7) Trace the following code segments, giving the value of all variables after the segment is
executed.
a.
java
int x = 0;
int y = 1;
x = y; // x = 1
y = x; // y = 1
java
int x = 10;
x = x + 10; // x = 20
c.
java
String title;
String s = "Get ";
String t = "Shorty";
title = s + t; // title = "Get Shorty"
After this segment, the variable title has the value "Get Shorty".
d.
java
int a = 5 + 4; // a = 9
int b = a * 2; // b = 18
int c = b / 4; // c = 4
int d = b - c; // d = 14
int e = -d; // e = -14
int f = e % 4; // f = -2
double g = 18.4; // g = 18.4
double h = g % 4; // h = 2.4
int i = 3; // i = 3
int j = i++; // j = 3, i = 4 (post-increment)
int k = ++i; // k = 5, i = 5 (pre-increment)
a = 9
b = 18
c = 4
d = 14
e = -14
f = -2
g = 18.4
h = 2.4
i = 5
j = 3
k = 5