arches national park fiery furnace

Chunk 1, Module 3: Java Variables, Operators, and If-Controlled Blocks

Essential building blocks of every Java Program

With Modules 1 and 2 under our belt, we're ready to dig into the essential process of creating variables that store data and using operators to manipulate their values. Don't forget to consult your textbook (Java: A Beginner's Guide) when referenced in the teal boxes to supplement this bare-bones tutorial.

Jump to a section

check_boxLearning Objectives
check_boxGet your work environment setup
extensionCore Concepts
motorcycleExercise 0: Familiarizing ourselves with essential operators in Java
motorcycleExercise 1: Developing a Road Trip to Southern Utah simulator

Get your work environment setup

We need a logical place to put the code you'll write in this module. Follow these steps:

  1. Inside netbeans, create a project of type "Java Application" called "cit111OnlineCourse"
  2. Right click "Source Packages" >> new >> Java Package and call it "week3"
  3. Right Click your new package >> new >> Java Class and call it "Variables" (don't forget the capital V)
Refer to our module on running code in NetBeans if you need a refresher. Your setup should look like this:

java variable type sequecnce


Learning Objectives


Confidently discuss the concept of variables in programming: They are storage containers for any data of a declared type


Initialize and reference primitive-type and String-type variables


Show command of the assignment operator = and other basic operators such as + - % * /



External Resources

  1. Oracle online tutorial on primitive data types
  2. Oracle online tutorial on Operators (entire subsection)
  3. Oracle online tutorial on If-then statements
  4. Java: A Beginner's Guide: Chapter 2 on Data Types and Operators (6th edition pages 31-61). If you have other editions, check the Table of Contents for "Data types and Operators"
  5. Java: A Beginner's Guide: Sub-chunks of Chapter 3 on the If-Then statement (6th edition pages 63-69 only).



Module Core Concepts

Primitive types

At the most basic level, Java programs create variables that store data values and then do stuff with those values with operators (adding, subtracting, assigning values to other variables, etc.).

Java's variables come in two flavors: primitive types and Object types. We'll work with mostly primitive types for the next two weeks (with String types as the exception). Primitive types get their name because they only store one piece of data and that's all they do. Object types are fancy because they store values and also store mechanisms for "doing things" to and with those values.

A few of Java's primitive types which we'll work with are displayed in the following table:

Primitive type name Java keyword Example literal value Size in memory
Integer int 23 8 bits
Boolean (On/off or 1/0) boolean true 1 bit
Floating point value (has a decimal point) float 34.3323 64 bits

bookStudy data types in Java: A Beginner's Guide (6th edition). Java includes more than these four primitive types--but we won't use them routinely in this class. Study the first part of chapter 2 for a full discussion of these types. (6th ed pages 32-42.) You're encouraged to tinker with these other types.

Using primitive type values

The following flow chart shows how we can use primitive types to store data and manipulate that data.

java variable type sequecnce

To become a proficient Java programmer, you should develop a sense for what is going on inside the computer when variables are created and manipulated. A common notation for representing variables which we'll use in this class depicts a variable as a box, with its type on its bottom and its name on the top, with the value it stores in the middle. We can depict the sequence of the diagram above with more detail. Study this carefully:

java variable type sequecnce

Now we're ready to see this in complete Java code, with the final value of totalYears printed to the console with a literal text inserted before it inside our call to println():

warningType this code into NetBeans! Code as much as you can: type EACH and EVERY example you see in these tutorials into your own NetBeans and tinker with it. Reading is not the same as doing.


And the output of this program reveals that our addition operators + and our assignment operator = worked as expected.


The code above separates out the declaration and initialization steps, but more commonly, these steps are combined as follows:


Error messages are our friend!

Remember, when you're coding, you'll probably see a number of pre-compiler errors that clue you into code errors that would prohibit the compiler from completing its work and running the program. Remember, unlike markup languages like HTML (that this page is written in) that will just skip over errors, the Java compiler demands completely compilable code on each and every line.

Let's see what the error is if you type a variable name incorrectly:


The message in the tip box that appears when we hover over the red-highlighted code reads: "cannot find symbol" which means the compiler doesn't know what to do with yearsEleSchool because we didn't ever declare a variable with that name (we abbreviated "school" as "schl" in our variable). So when you see this error, don't panic--think about what the pre-compiler is telling you: "I can only add known values. You must tell me what type every variable is before you try to add it to something else."

Interestingly, let's look back at this error capture and see that when we mistyped the variable name, the variable we DID declare called yearsEleSchl is changed to gray font which gives us this warning when we hover over it:


This makes sense because with a mistyped variable name in our assignment statement, we didn't actually do anything with yearsEleSchl. (Inappropriate political note: Java is a lot like the NSA--it reads everything we type and can give us warnings about what it notices before we get a compiler error. Luckily, Java's pre-compiler isn't run by politicians.)

We can try to compile any code we'd like, and we can also get messages about what went wrong directly from the compiler itself, instead of NetBeans handy little pre-compiler that reads the code as we write it. The red text seems awful and scary, but it's actually very informative:


Notice what this error is called: RuntimeException which means there was an exception in the normal flow when the compiler tried to turn our source code into bytecode. Also, note that the error gives us a location of the error! How Nice! See the magenta box: means that the error is located in the file and on its line number 35. Wow--super handy! We can even click that link to jump right to that line in our code, and we'll see that there is indeed a mis-typed variable.

You should also note that there are elements of this error that involve Java-speak that you probably don't understand yet, but reading it and getting comfortable with the way code is digested is critical to your learning. Please practice reading and trying to comprehend text and code that you don't fully understand yet. There's only one way to get there: wrestle with it!

highlightRead all error messages carefully! Microsoft Corporation's approach to software development has created an expectation by most computer users most any error message we get from a computer will be mostly useless and unlikely to help us figure out what went wrong (or, in some cases, deliberately misleading). Thankfully, Java was NOT written by the Microsoft Corporation and is embedded with error messages designed to HELP users! Imagine that--what a concept!



Exercise 0: Familiarizing ourselves with essential operators in Java

Exercise type: Code Along

This basic exercise will expose us to how the basic operators in Java act on variables to produce new values. You can code along with the instructor using this screen cast video. The code created in the video is also posted below and on our GitHub account here.

The raw material for this exercise is the Oracle Corporation's Java tutorials on operators. You should work through the first two sections: 1) "Assignment, Arithmetic, and Unary Operators" and 2) "Equality, Relational, and Conditional Operators". (You can certainly try "Bitwise and Bit Shift Operators" but we will not be using these operators in CIT111.) The following screen screen shot links into the first of these two.


Follow these steps when working through these exercises:

  1. Review the entire page before coding anything.
  2. In your week3 package, create a class for each of the classes that the Oracle tutorial works through.
  3. Split your window with half the screen on Oracle's page and the other half with NetBeans and type the code in the Oracle tutorial into your NetBeans, running the program and studying the results as you go. TINKER along the way--adjust the variable names and how they are operated upon. Remember, this is practice, not an exercises to "complete" for the sake of getting the assignment done.

Your turn: Coding Exercise

Now that you have worked through the Oracle tutorial that gave you exposure to the operators, follow these steps to create your own operator practice program. Remember, follow this sequence as you code this exercise:


What this means is you should create comments in your code as your English plan, and then write the Java. You must develop a connection between the English version of what a Java program does and the Java code so that your brain can think through stuff and then spit out correct java.

Your code should do the following:

  1. Create a class called OperatorsChallenge inside your week3 package.
  2. Create a main() method inside this class.
  3. Create an int type variable called a and initialize it to 100
  4. Create an int type variable called b and initialize it to 2000
  5. Create a double type variable called d and initialize it to 10.5
  6. Create a String type variable called line1 and store in it "Go Ask Alice"

Check your work so far

Once you think you have these variables setup correctly from steps 1-5 above, check your work against this key to make sure you're setup correctly for the rest of the steps

  1. Create a String type variable called line2 and store in it "I think she'll know"
  2. Create int type variable called r and store in it the result of dividing b by a
  3. Print out the value of r with a label of what is displayed
  4. Create an int type variable called mod and store in it b modulus a;
  5. Print out b % a is: followed by the value of mod

Checkpoint: Verify against the key up to this point if you want

  1. Create a double variable called rd and store in it the value of mod multiplied by the variable d
  2. Print out the value of this operation that's stored in rd
  3. Add 5 to a and store it in a
  4. Print out that you're about to compute the value of "b mod a"
  5. Compute b modulus a and store it in rd
  6. Print out the value of rd with a label
  7. Concatenate line2 followed by line1 with a space in between
  8. Concatenate line1 followed by line2 with a space in between
  9. Run your program and see how close you can get the output of your program to match the key output here:
  10. code
  11. Only check your answer against the code by clicking the button below once you have worked hard at the task:

You can view this solution code in GitHub here.



Exercise 1: Comparison operators practice

Exercise type: Coding exercises with solutions

Now that you've got the essential operators like + and / under your belt, let's practice the comparison operators and logical operators you learned as you worked through the Oracle tutorial at the beginning of exercise 0.

Let's setup our workspace. We need a class to work in and let's call it Comparisons. It should be placed inside your package called week3.

Carefully code the following into your class. READ the comments as you go--they're how you'll learn in this exercise. We're going to learn the behavior of the if()-controlled block to use in our exploration of comparison operators.


Let's review this code: we create two variables of type int and intialize their values. We can then use the <= operator which compares the values on either side and returns either a value of true or false. We can use this operator to then control which code the compiler executes using the if() statement. We'll study if() more in the next module.

Execute this program we just created and see the output shows us how the comparison operators work:


Passcode Comparisons

Since you've already had some exposure to the comparison operators in the Oracle tutorial, see if you can try coding the following steps in the same class you just worked in. Feel free to delete the code you wrote and replace it with your new code:

  1. Create an int type variable called correctPasscode and initialize it to 5934
  2. Create an int type variable called attemptedPasscode and initialize it to 1234
  3. Build an if() statement block that tests if correctPasscode is equal to attemptedPasscode. You'll use the == operator to test equality.
  4. If the pass codes match, display: Codes Match! You're in!
  5. In the else{ } block, display: Codes don't match--No soup for you!
  6. Test your code with a few different values of attemptedPasscode to see that your logic works as expected
  7. Comment the key lines of code to remind your brain what the code does

Your output should look like this--since the passcodes are not equal


Note on the difference between == and =

We used the == operator to check for equality, not the assignment operator = which we've seen a bunch already. Try changing the == to a single = and see the error the pre-compiler gives:


The message says incompatible types: int cannot be converted to boolean which means that when the compiler evaluates the expression inside ( ) of the if statement and sees an assignment, it is left with an integer value. But the if() only can operate with an expression that evaluates to true or false. Remember: reading error codes and tips helps us understand Java better.



Challenge Exercise: Simulating a road trip to Southern Utah!

Exercise type: Code Along

NOTE: The following exercise is a somewhat more complex set of steps for students who are feeling confident with variables and following steps for coding up logic with instructions. For most folks who are just starting at out at Java, this is a great exercise to try--but don't be too hard on yourself if you have to reference the key to get the desired code correct. If it's a struggle, you're not "behind"--just keep learning!

Code-Along screen cast for beginning of this RoadTrip simulator

Let's write some code to demonstrate the other primitive types built into Java. This code is written during the screen cast in the video above.


Now that we have variables setup and printed to the console, we're ready to create a coding plan. In coding terms, we call this coding specification: what do we want the code to do--stated in plain English so it's clear. Then we can convert that plan into Java and test it against our specification. We can visualize this simple process as follows:


I made a thermos of coffee, did some thinking, and here's our plan written in English


With the English plan in place, I can code up my Java as follows: (You can access the completed code in GitHub here since it's hard to read in the screen shot.)

The code written in the above screen cast is shown in the image below--for reference or if you're not the video watching type.


The output of this program is as follows:


Your turn! Keep Building our RoadTrip Class

Now that you've seen this project developed some with screen casts, you're probably ready to code some more yourself. Follow these steps to flesh out the rest of our RoadTrip class and arrive in scenic Southern Utah:

warningDevise a plan for each of these steps in English FIRST just as your instructor did for the first leg. Write what you'll do with each variable in comments. Don't take shortcuts here, even if you think you can hack your way through. We must practice good form to develop good form.

  1. We've made it a quarter of the way. Keep coding after our print lines showing the updated variables after leg 1 by calculating a leg distance of 500 miles. This means we will hard code the value of "500.0" as our leg distance and do calculations with that.
  2. Simulate finding a pair of hitchhikers to pick up and add to the car. Use our if(){...} controlled block to decide if they can be picked up.
  3. Calculate our fuel price of our 500 mile leg and update our budget, assuming we purchased our fuel :)
  4. Print out all of our stats after leg 2 is complete
  5. Finish the trip with leg 3 that is the remaining distance to MoabUtah. Use operators to get us there by manipulating the variables as needed.
  6. You see another hitch hiking couple and you stop to see if you can pick them up. You should find that you cannot fit two more folks, and they decide they don't want to split up, so you pass them by. Use your if() logic to test this.
  7. Pay for gas through the end of the trip and adjust your cash on hand
  8. Arrive at your destination, toggling our boolean variable to represent arriving at that destination
  9. Print out final stats! Then go look at some photos online of the "Fiery Furnace" in Arches national park and celebrate your efforts.

You can view the solution code in GitHub here.


Page created on 11 Feb 2018 and last updated on 15 Feb 2018 and can be freely reproduced according to the site's content use agreement.