Quick reference
Java cheat sheet
1. Store a value in a variable
A variable has a type, a name, and a value: int count = 5;. The type tells Java what kind of value it can hold. End declarations and assignments with a semicolon.
The five types used in this lab
| Type | Stores | Example |
int | Whole numbers, including zero and negatives | int count = 5; |
double | Numbers that can have a fractional part; decimal results may be approximate | double price = 2.50; |
char | One character, in single quotes | char initial = 'J'; |
String | Text, in double quotes; use a capital S | String name = "Jordan"; |
boolean | true or false, without quotes | boolean ready = true; |
Java is case-sensitive: score and Score are different names. Declare a variable once in the same block; leave off its type when changing its value.
int count = 5; // Declare and initialize.
count = 8; // Replace the old value.
count = count + 1; // Read the old value, then store 9.
System.out.println("Count: " + count); // Prints Count: 9
= stores the value on its right in the variable on its left. Copying a number into another variable does not keep the two variables linked.
2. Calculate and print
Arithmetic and text operations
| Operation | Meaning | Example result |
+ | Add numbers | 7 + 2 is 9 |
- | Subtract | 7 - 2 is 5 |
* | Multiply | 7 * 2 is 14 |
/ | Divide; two integers give an integer result, discarding the fractional part | 7 / 2 is 3; 7 / 2.0 is 3.5 |
% | Find the remainder after division | 7 % 2 is 1; 8 % 2 is 0 |
+ with text | Join text and values | "Score: " + 8 is "Score: 8" |
Use parentheses to group calculations: (6 + 4) / 2.0 is 5.0. Multiplication, division, and remainder happen before addition and subtraction. Do not divide by zero.
System.out.println("Hello!"); // Print text, then start a new line.
System.out.println("Total: " + (4 + 2)); // Prints Total: 6
Common trap: double result = 7 / 2; stores 3.0, because integer division happens first. Use 7 / 2.0 to keep the fraction. To square a number, multiply it by itself; ^ is not Java's exponent operator.
3. Compare values
A comparison produces a boolean result: true or false.
Comparisons and boolean operations
| Operator | Meaning | Example |
== / != | Equal / not equal (numbers, characters, booleans) | 5 == 5 is true |
< / <= | Less than / less than or equal | 5 < 5 is false |
> / >= | Greater than / greater than or equal | 5 >= 5 is true |
&& | AND: both conditions must be true | (5 > 0) && (5 < 10) is true |
|| | OR: at least one condition must be true | (5 < 0) || (5 == 5) is true |
! | NOT: reverse a boolean | !true is false |
.equals(...) | Compare String contents; capitalization matters | "rock".equals("paper") is false |
Remember: = assigns; == compares. Use choice.equals("rock") to compare text, rather than choice == "rock".
4. Make a decision with if
An if runs its block only when the condition in parentheses is true. An else runs when that condition is false. Put the statements for each branch inside braces.
boolean ready = true;
if (ready) {
System.out.println("Let's begin!");
} else {
System.out.println("Take a moment to get ready.");
}
For more than two possibilities, use else if. Java checks this chain from top to bottom and runs only the first matching branch, or the final else if none match.
int books = 2;
if (books == 0) {
System.out.println("No books yet.");
} else if (books == 1) {
System.out.println("One book.");
} else {
System.out.println("More than one book.");
}
An else is optional when nothing needs to happen for a false condition. Do not put a semicolon immediately after if (...).
The 10 problems
Use the starting values first, then try the checks. Your answers must come from the variables and calculations, not from typing the expected answers directly into print statements.
1. Say hello
Print Hello world!!!. Then declare String studentName = "Jordan"; and char section = 'A';. Use those variables to print the second line below.
Hello world!!!
Student: Jordan, section: A
Check: Change the name and section to your own. Both should change in the output. Use + to join text and values.
2. Swap two values, step by step
Declare int a = 10; and int b = 20;. A swap means that a ends with the original value of b, and b ends with the original value of a.
Why a third variable? If you write a = b; first, the original value in a is overwritten. Writing b = a; afterward would copy 20 again. A temporary variable holds the original value so it is not lost.
- Print the starting values as shown below.
- Create the temporary storage with
int temp = a;. Now temp holds a copy of 10.
- Write an assignment that copies the value of
b into a.
- Write an assignment that copies the saved value in
temp into b.
- Print both variables again. Do not swap by typing
a = 20; and b = 10;; the same code should work for other starting numbers.
Before: a = 10, b = 20
After: a = 20, b = 10
Check: With starting values a = -3 and b = 7, the final values should be a = 7 and b = -3. Trace the values of a, b, and temp on paper after each assignment.
3. Square a number
Declare int numberToSquare = 3;. Multiply the variable by itself, store the result in an int named squared, and print the result.
Square: 9
Check: Try -4 (expect 16) and 0 (expect 0). Use * for multiplication.
4. Find the larger number
Declare int firstNumber = 4; and int secondNumber = -5;. Use if, else if, and else to print the larger value. If the values are equal, print The numbers are equal. Leave both variables unchanged.
Larger: 4
Check: Try 2, 9 (print Larger: 9) and 6, 6 (print the equality message). Check whether the first number is greater, then whether the second is greater.
5. Put the larger value first
Declare int firstValue = 10; and int secondValue = 21;. If firstValue is less than secondValue, swap their values using the temporary-variable technique from #2. Otherwise, leave them alone. Print both values after the if, so they print whether or not a swap happens.
firstValue = 21, secondValue = 10
Hint: The three swap statements belong inside the if braces. Use a new temporary-variable name, such as savedValue.
Check: Starting values 30, 5 should stay 30, 5; 8, 8 should stay 8, 8.
6. Is the number negative?
Declare int numberToCheck = -6;. Use an if / else to print Negative when the value is less than zero, or Not negative otherwise.
Negative
Check: Both 4 and 0 should print Not negative. Zero is not negative; it is not positive either.
7. Even or odd?
Declare int wholeNumber = 8;. Print Even if it divides by 2 with no remainder; otherwise print Odd. Use % to find the remainder and compare it with zero.
Even
Check: 7 is odd, 0 is even, -4 is even, and -3 is odd. Checking for remainder zero works for negative numbers too.
8. Calculate an average, then a letter grade
Declare three double variables with these starting values: gradeOne = 94.0, gradeTwo = 87.0, and gradeThree = 75.0. Assume each grade is between 0 and 100, inclusive.
- Add all three grades in parentheses and divide their sum by
3.0. Store the answer in double average and print it.
- Use an
if / else if / else chain to print a letter grade using the table below. Check the highest cutoff first.
Grading scale for this exercise
| Average | Letter |
| 90 through 100 | A |
| At least 80 but less than 90 | B |
| At least 70 but less than 80 | C |
| At least 60 but less than 70 | D |
| Less than 60 | F |
Average: 85.33333333333333
Letter grade: B
No rounding or special decimal formatting is required. Choose the letter from the unrounded average: 89.9 is a B.
Check: Set all three grades to 90.0 (A), then 80.0 (B), 70.0 (C), 60.0 (D), and 59.0 (F). Also check all zeros (F) and all hundreds (A).
9. Let a boolean choose the message
Declare boolean isReady = true;. Use if (isReady) and else to print Ready to begin! when it is true, or Not ready yet. when it is false.
Ready to begin!
Check: Change only the starting value to false and run again. You should see only Not ready yet. A boolean can be used directly as the condition; it does not need quotes or a comparison with true.
Challenge
10. Rock, paper, scissors
Declare String playerOne = "rock"; and String playerTwo = "paper";. Each value will be exactly "rock", "paper", or "scissors", all lowercase. Simulate one round; no keyboard input, random choices, or invalid-input handling is required.
Rules: Rock beats scissors, scissors beats paper, and paper beats rock. Matching choices are a tie. Print exactly one result: Player 1 wins!, Player 2 wins!, or Tie!.
- Check for a tie first with
playerOne.equals(playerTwo).
- Next, check the three ways Player 1 can win. For one winning pair, both choices must match:
playerOne.equals("rock") && playerTwo.equals("scissors"). Add the other two winning pairs with separate else if branches, or join the pairs with ||.
- If it is not a tie and none of Player 1's winning pairs match, Player 2 wins.
Player 2 wins!
Test all nine pairs; each cell is the expected result
| Player 1 choice | Player 2: rock | Player 2: paper | Player 2: scissors |
| rock | Tie! | Player 2 wins! | Player 1 wins! |
| paper | Player 1 wins! | Tie! | Player 2 wins! |
| scissors | Player 2 wins! | Player 1 wins! | Tie! |