Intro Java - Ch. 2 - Variables
2.2.1 Two Types of numbers: integers and doubles
A2.3 - Converting Pounds to Kilograms
2. Variables
2.1 Math
2.1.1 Basic Math
- Basic math is an important part of programming. The usual arithmetic operations include:
Addition (+)
Subtraction (-)
Multiplication (*) - Note that this is an asterisk
Division (/)
2.1.2 Modulo
- There is another operation. It is the “remainder operator” also known as modulo (%). This returns the remainder after division is performed.
Ex: 17 % 4 = 1 (4 goes into 17 four times with 1 remaining)
20 % 3 = 2 (3 goes into 20 six times with 2 remaining)
10 % -5 = 0 (-5 goes into 10 with nothing remaining)
- Operator precedence - The computer follows the same rules as PEMDAS.
- Modulus is solved for at the same level as multiplication and division. Left to right.
2.2 Data Types
2.2.1 Two Types of numbers: integers and doubles
- There are two basic “types” of numbers that we are going to be dealing with in Java. Going back to basic math, we have:
- integers - Things that are not fractions. In Java this is known as: int
- decimals - Things that are fractions, or decimals. In Java, this is known as: double
- When Java deals with integers (int), it doesn’t see the decimals at all, which results in strange behavior. It doesn’t even round, it just cuts off the decimal completely:
- Example: 6 / 4 = 1 (not 1.5)
- Example: 100 / 9 = 11 (not 11.1111)
- Example: 5 / 6 = 0 (not 0.83334)
- When there is a double involved, even if only one, then Java keeps track of the decimals:
- Example: 6.0 / 4 = 1.5
- Example: 100 / 9.0 = 11.1111
- Example: 5.0 / 6.0 = 0.83334
2.2.2 Text: Strings
- As mentioned in 2.3, there is a variable type called String. This can hold letters, words and spaces. This is not like the other types in a lot of ways. For now, just notice that it is capitalized, while int, double and boolean are not.
- The same way we make an integer or other kind of variable, we can make a string (a chain of letters, numbers and spaces) into a variable.
int num1 = 7; // This makes a storage “box” in memory called
// num1 that holds the value of “7”.
String name = “Tom”; // This makes a storage “box” in memory called
// name that holds the value “Tom” (not including the quotes, just the stuff inside)
- Basic String example:
String firstName = "Jim";
String lastName = "Hendrix";
String fullName = firstName + lastName;
System.out.println(fullName); // Prints: JimHendrix
2.2.3 Booleans
- There is a type of variable called a boolean. These can only be true or false. Those are their actual values.
- The “ ! “ character can switch a boolean to the opposite value. When you see it, you can think of the word “not”:
!true is false (not true is false)
!false is true (not false is true)
- Basic boolean example:
boolean a = true;
System.out.println(a); // Prints true
System.out.println(!a); // Prints false
boolean b = false;
System.out.println(b); // Prints false
System.out.println(!b); // Prints true
2.3 Introduction to Variables
2.3.1 Naming Variables
- In Java, identifiers are names of things that you get to make up yourself.
- The only acceptable way to name things is a sequence of letters, digits and the underscore. They cannot begin with a digit. They are also case-sensitive, which means that “age” and “Age” are different.
- Acceptable identifier names: num1, Num1, block_A
- Not acceptable: 5row, bank book
- How you name things when writing programs is important. You want them to describe what they are representing, but not be very long. This takes practice.
- Every identifier in a Java program has a type associated with it. We learned about two types in the last exercise, int and double. We will mostly be dealing with those two and only two others throughout the course:
boolean - Just two possible values: True or False
String - Represents a word. This is the only one that is capitalized. They
are created using quotes.
2.3.2 Using Variables
- Most of the information in a program is represented by variables.
- A variable is a name for a location in memory used to hold a data value. You can think of it as a box. The label on the box is the variable name and what is in the box is the value of the variable.
- When you declare a variable (create it), you tell Java to make a box and what to label it.
- When you initialize a variable, you tell Java what the first value is that goes in the box.
EXAMPLE: Declaring and initializing an int variable
int kids; // DECLARES the variable
kids = 19; // INITIALIZE the variable
int rooms = 5; // Can DECLARE and INITIALIZE in one step!
System.out.println(“This class has “ + kids + “ kids and ” + rooms + “rooms.” );
OUTPUT: This class has 19 kids and 5 rooms.
- When the program gets to the variable “kids”, it prints what is currently stored in the “kids” box. It is converted to a string and printed.
EXAMPLE: We can change the value of a variable after we initialize it. We are just changing the value of what’s stored in the box.
// Prints the number of sides of several shapes
int sides = 7; // Declaration of “sides” with initialization
System.out.println (“A heptagon has “ + sides + “sides.”);
sides = 10; // Change the value stored in the variable
System.out.println (“A decagon has “ + sides + “sides.”);
sides = 12; // Change the value stored in the variable
System.out.println (“A dodecagon has “ + sides + “sides.”);
OUTPUT: A heptagon has 7 sides.
A decagon has 10 sides.
A dodecagon has 12 sides.
- The equal sign is not the same as in algebra. In Java, it is known as an “assignment statement” because it assigns a value to a variable. When this is executed, the expression on the right-hand side of the “ = ” is evaluated, and the result is stored in the variable on the left hand side.
- A variable can store only one value of its declared type. A new value overwrites the old one and the old one is gone.
- Reading the value of a variable, like what we do when we print it, doesn’t change it, but writing data to the same “box” replaces the old value with the new.
2.4 Concatenation
- Concatenation is the process of linking things together.
- Putting two strings together can be done with the plus sign. This may not seem useful right now, but we will be using it a lot very soon.
- Strings are a sequence of characters (letters, numbers or spaces)
- It gets tricky with numbers and strings.
EXAMPLE:
public class Concat
{
public static void main(String[] args)
{
System.out.println("I am " + 66 + " years old.");
System.out.println("I am " + 66 + 22 + " years old.");
System.out.println("I am " + (66 + 22) + " years old.");
System.out.println(66 + 22 + " years old.");
System.out.println(10 + 30 + " of us is " + 66 + 22);
}
}
OUTPUT:
I am 66 years old.
I am 6622 years old.
I am 88 years old.
88 years old.
40 of us is 6622
2.5 Introduction to Tracing
- Tracing is a technique used to keep track of the values of variables. This becomes important as the values of the variables change. Tracing involves making a heading for each variable and changing the value under that heading each time the value of the variable changes.
EXAMPLE: Use tracing to determine the output
public class Tracing
{
public static void main(String[] arg)
{
int num1 = 1, num2 = 4, num3 = 5;
String word1 = "desk", word2 = "table";
num2 = 6;
num3 = num2;
num1 = num1 + num2 + num3;
num2 = 3 * num1;
word1 = word1 + word2;
word2 = word2 + word1;
System.out.println("Value of word1: " + word1);
System.out.println("Value of word2: " + word2);
System.out.println("Value of num1: " + num1);
System.out.println("Value of num2: " + num2);
System.out.println("Value of num3: " + num3);
}
}
OUTPUT:
Value of word1: desktable
Value of word2: tabledesktable
Value of num1: 13
Value of num2: 39
Value of num3: 6
EXAMPLE: Use tracing to determine the output
public class MoreAndMoreTracing
{
public static void main(String[] arg)
{
int first_int = 5, second_int;
double first_double = 4.5;
String onlyWord = "Ba";
onlyWord = onlyWord + onlyWord + first_double;
second_int = first_int * 5;
first_double = first_double - first_int;
first_double = first_double - first_int;
System.out.println("Value of first_int: " + first_int);
System.out.println("Value of second_int: " + second_int);
System.out.println("Value of first_double: " + first_double);
System.out.println("Value of onlyWord: " + onlyWord);
}
}
OUTPUT:
Value of first_int: 5
Value of second_int: 25
Value of first_double: -5.5
Value of onlyWord: BaBa4.5
Chapter 2: Assignments
A2.1 - Practicing Modulo
First, try to solve each of the following on paper. Next, write ONE program that solves the following expressions and prints out the answers. Check your answers.
- 2 * 5 - ( 3 + 4)
- 5 % 2 * 100
- 1 % 2 + 3
- 7 + 5 * 4 - 2
- (8 % 5) % 2
- 14 - 5 % 5
- 4 * 3 % 7 % 3
- 0 % 4
- 1 % 4
OUTPUT:
a) (correct answer generated by the computer)
b) (correct answer generated by the computer)
c) (correct answer generated by the computer)
…...
A2.2 - Favorites Version #2
This assignment is similar to Favorites from the last chapter, but here, you are creating variables for each of your favorites that you will use when printing.
PROGRAM STRUCTURE:
public static void main(String[ ] args)
{
String name = // put your name here in quotes
String birthday = // put your birthday in quotes here
// continue creating variables using the names hobbies, book and movie
// create print statements using the variable names to print the result
}
SAMPLE RUN:
Name: Josh Finkel
Birthday: March 30, 1972
Hobbies: Spending time with annoying students
Favorite book: East of Eden
Favorite movie: Princess Bride
A2.3 - Converting Pounds to Kilograms
Write a program that converts pounds to kilograms using a conversion of 2.2 pounds for 1 kilogram. You should have one variable that represents the given pounds and another that is the resulting amount of kilograms after the conversion.
PROGRAM STRUCTURE:
public static void main(String[] args)
{
double pounds = 100; // Assign a variable to the number of pounds
double kg = pounds / 2.2; // Calculate equivalent kilograms using the
conversion
// Create a print statement using the variables pounds and kg.
}
SAMPLE OUTPUT:
100.0 pounds is equivalent to 45.45454545454545 kilograms.
A2.4 - Seconds in Years
Write a program that calculates how many seconds there are in a given number of years. Use variables for years, days, hours, and minutes.
PROGRAM STRUCTURE:
public static void main(String[] args)
{
int yrs = 7; // Calculating number of seconds in 7 years
int days = yrs * 365; // Figure out the number of days in that number of years
int hours = days * 24 // Keep going with the number of hours in those days
// Again with the number of minutes related to hours
// Once more with the number of seconds related to minutes
// Using the yrs and seconds variable, print the output
}
SAMPLE OUTPUT #1:
7 years has 220752000 seconds.
SAMPLE OUTPUT #2: (Changing the value of yrs to 2)
2 years has 63072000 seconds.
A2.5 - Area of a triangle
Write a program that calculates the area of a triangle (base * height * 0.5). You should create three variables with appropriate names for the base, height and area. Make all of the variables double and test your program to make sure it works for different dimensions of base and height.
PROGRAM STRUCTURE:
public static void main(String[] args)
{
// Declare and initialize the base variable with a made up value
// Declare and initialize the height variable with a made up value
// Declare and initialize the area variable using the formula for the area of a
// triangle to determine its value.
// Use a print statement using all of the variables to display the results
}
SAMPLE OUTPUT #1:
A triangle with a base of 4.0 and a height of 100.0 has an area of 200.0 units.
SAMPLE OUTPUT #2:
A triangle with a base of 4.5 and a height of 6.5 has an area of 14.625 units.
A2.6 - Find the Average
Write a program that creates three integer variables called num1, num2 and num3 with values that you make up. It should then calculate and store their average in a double variable called avg. It should then print the results to the screen. Be careful when calculating the average. Although you are using three integers, the average may be a decimal (double).
PROGRAM STRUCTURE:
public static void main(String[] args)
{
// Declare and initialize three integers called num1, num2, num3
// Declare a double called avg
// Initialize the avg by calculating the average of num1, num2, num3
// Use a print statement using all of the variables to display the results
}
SAMPLE OUTPUT #1:
The average of 4, 10, and 5 is 6.333333333333333
SAMPLE OUTPUT #2:
The average of 40, 152, and 5 is 65.66666666666667
A2.7 - Coins in a Jar
ASSIGNMENT:
Write a program that calculates the total amount of money in a jar of pennies, dimes, and nickels. Create three integer variables: pennies, dimes, and nickels. There will be a fourth variable, a double called total, that will represent the total amount of money made up of the coins.
PROGRAM STRUCTURE:
public static void main(String[] args)
{
// Declare and initialize the three integers
// Declare a double called total
// Determine total by using a formula similar to: value_of_nickels = 0.05 * nickels
// So if there are 7 nickels, value_of_nickels = 0.35
// Use a print statement using all of the variables to display the results
}
SAMPLE OUTPUT #1:
The jar has 7 pennies, 3 dimes and 2 nickels for a total of $0.47.
SAMPLE OUTPUT #2:
The jar has 1 pennies, 4 dimes and 5 nickels for a total of $0.66.
A2.8 - First and Last Name
Write a program that creates first and last name String variables and prints the following
PROGRAM STRUCTURE:
public static void main(String[] args)
{
// Declare and initialize two Strings called first and last
// Use a print statement using each variable twice to generate the desired output
}
SAMPLE OUTPUT:
My name is Josh Finkel, but on the class list, it would be Finkel, Josh.
A2.9 - Boolean Opposites
Set a boolean variable and print the value and the opposite of its value.
PROGRAM STRUCTURE:
public static void main(String[] args)
{
// Declare and initialize a boolean
// Create the print statement for the desired output
}
SAMPLE OUTPUT #1:
The opposite of true is false!!!
SAMPLE OUTPUT #2:
The opposite of false is true!!!