Start of Tutorial > Start of Trail > Start of Lesson | Search |
- Question: Identify all of the variables in the
Sort
program.
Answer: Here's the sort program again with the variable declarations shown in red:public class Sort { public static void main(String[] args) { int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; for (int i = arrayOfInts.length; --i >= 0; ) { for (int j = 0; j < i; j++) { if (arrayOfInts[j] > arrayOfInts[j+1]) { int temp = arrayOfInts[j]; arrayOfInts[j] = arrayOfInts[j+1]; arrayOfInts[j+1] = temp; } } } for (int i = 0; i < arrayOfInts.length; i++) { System.out.print(arrayOfInts[i] + " "); } System.out.println(); } }
- Question: What is the name of each variable?
Answer:args
,arrayOfInts
,i
,j
,temp
, andi
a second time. This program can usei
twice because the two variables have different scope.
- Question: What is the data type for each variable?
Answer:args
is an array ofString
objects.arrayOfInts
is an array of integers. All of the other variables are integers.
- Question: What is the scope for each variable?
Answer: The following diagram shows the scope of each variable declared within theSort
program.
- Exercise: Rewrite the
MaxVariables
program to display the minimum value of each integer data type.
- Exercise: Use a different method to discover if
aChar
is an upper case letter.
- Exercise: Give
aBoolean
a different value.
Answers: Here's our solution to all three exercises, calledMinVariables
, with the differences shown in red:public class MinVariables { public static void main(String args[]) { // integers byte smallestByte = Byte.MIN_VALUE; short smallestShort = Short.MIN_VALUE; int smallestInteger = Integer.MIN_VALUE; long smallestLong = Long.MIN_VALUE; // real numbers float smallestFloat = Float.MIN_VALUE; double smallestDouble = Double.MIN_VALUE; // other primitive types char aChar = 'S'; boolean aBoolean = false; // display them all System.out.println("The smallest byte value is " + smallestByte); System.out.println("The smallest short value is " + smallestShort); System.out.println("The smallest integer value is " + smallestInteger); System.out.println("The smallest long value is " + smallestLong); System.out.println("The smallest float value is " + smallestFloat); System.out.println("The smallest double value is " + smallestDouble); if (Character.isLowerCase(aChar)) { System.out.println("The character " + aChar + " is lower case."); } else { System.out.println("The character " + aChar + " is upper case."); } System.out.println("The value of aBoolean is " + aBoolean); } }
Start of Tutorial > Start of Trail > Start of Lesson | Search |