Welcome to Lesson 4!

Learning Objectives

By the end of today's lesson, you should know...
  • What kinds of data the computer can store in its memory
  • The four most common data types in Java and what kind of data they represent:
    • int - whole number or integer data
    • boolean - true or false values
    • double - numbers with a decimal point
    • char - character data
  • How computers store data in memory.
  • What is a variable.
  • How to name variables.
  • How to declare variables.
  • How to assign values to variables.


Announcements

  • Don't forget Quiz 2 due tomorrow at midnight
  • Don't forget Lab 2 due tomorrow at midnight!
    • Did you get registered for CodeLab?
  • How did it go installing Eclipse?
    • If you had any problems, please feel free to see my in office hours. Please bring your computer, if possible.
  • See me at break if you are still hoping to add

Review Activity
  • With a partner, write a complete program to print out the message Greetings! to the console window.
    • Assume you are writing it in a file named Greeting.java
    • Also, make sure that you have a correct comment up top with your name and section information
    • How much of the code can you and your partner remember together?
  • Add an inline (single line) comment to your program that states This program prints the message Greetings!
    • Place this comment above public static void main

Introducing Data Types


What is a data type?
  • What is data?
    • Information produced or stored by the computer.
  • What is a type?
    • The kind of data.
    • For example, numbers vs letters.
  • Data types are important because the compiler treats different types of data differently:
    • What kind of operations can be performed. Ex: We can't add and subtract letters.
    • How much storage to allot. Numbers and letters are stored differently in memory.
  • There are four basic categories into which each data type falls:


 Category Explanation Example
 Integer
 A whole number. No decimal point.
 106
 Floating Point Number
 A number with a decimal point.
 3.14
 Character Individual letters, digits and symbols
'A', '%', '9'
 Boolean True/False, 0/1, On/Off
 true, false



Java Has a Variety of Data Types:

TypeBytesUse
boolean1true or false value.

char2
All Unicode characters, which may require more than 1 byte of storage

short2Short integers from -32,768 to 32,767.
int4Integers from -2,147,483,647 to 2,147,483,647.
long8
Integers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (quintillion).



float4Single-precision, floating-point numbers from about E-45 to E38 with 6 or 7 significant digits.
double8Double-precision, floating-point numbers from E-308 to E308 with from 14 to 15 significant digits.
  • Note that the number of bytes used for storage depends on the system and compiler

Group Activity: Name That Data Type!

Which of the 4 most common data types are the values below. Select int, double, boolean or char.
  • 'A' is a(n) _____________________
  • -213.555 is a(n) ________________
  • 14 is a(n) _____________________
  • 14.0 is a(n) ____________________
  • false is a ______________________
  • '$' is a ________________________
  • -2147483647 is a ______________
  • true is a _______________________


Most Common Data Types:

Type            Memory Used            Example        Size Range            
    int                4 bytes                        10                    -2,147,483,648 to 2,147,483,647
    double        8 bytes                        10.5                  10e-38 to 10e38
    char            2 bytes                           'c'                     not applicable
    boolean      1 byte                           true                  not applicable


Storing Data In the Computer's Memory

  • Let us pretend that we have a friend, named Grace, and we want to remember her phone number: 555-2368
  • We can store our friend's phone number in our memory
  • We even give our friend's phone number a label, like "Grace's phone number"
  • We do not really know where in our brain we store Grace's phone number
  • However, whenever we need her phone number, we say to our self, "What is Grace's phone number" and out pops 555-2368
  • Just like we store our friend's number in our memory, we can store it in a computer's memory
  • We store data in a computer program using a variable

    variable: the name of a place to store data in a computer's memory

  • Just like we do not know where in our brain we store a phone number, we do not know where in computer memory we store data
  • We simply give it a name and let the compiler decide where to store the data
  
Storing Data In the Computer's Memory

  • Let us pretend that we have a friend, named Grace, and we want to remember her phone number: 555-2368
  • We can store our friend's phone number in our memory
  • We even give our friend's phone number a label, like "Grace's phone number"
  • We do not really know where in our brain we store Grace's phone number
  • However, whenever we need her phone number, we say to our self, "What is Grace's phone number" and out pops 555-2368
  • Just like we store our friend's number in our memory, we can store it in a computer's memory
  • We store data in a computer program using a variable

    variable: the name of a place to store data in a computer's memory

  • Just like we do not know where in our brain we store a phone number, we do not know where in computer memory we store data
  • We simply give it a name and let the compiler decide where to store the data
Displaying sum of two integers using two variables only in C programming


Recall How Computer's RAM Memory Works:

https://a67f228e-a-62cb3a1a-s-sites.googlegroups.com/site/deanzacollegecis/home/cis22a/cis-22a-mw-schedule/lesson4/Screen%20Shot%202016-01-09%20at%202.52.54%20PM.png?attachauth=ANoY7crtUfZ8ufLhJy3NkFHADdH4TD0lJxmFOssnOTAGfxPU4eH12KYrxM8M76Kz-cCoIEFWTLGWjghYAsValt9rvyRLRsJePE5Yn64k_IFl7Rfy9bYtWTk0x8EVKff5UxZT09SEtIA69viGfuamR8e5jtKoB4Bgf1kXUP3Nb37I_DOBccqJfFIO5wf9ja9OhAL-0O45iONLQdQD2LPUIAU7ZgnLfgydL1rT1Tq1g_182qqXyORmo2ZUiCAOlSR7cz2tURoUpJf_x3I3bxMjGrahdWaDUJ1Yh54xcy28IKOPYtX3LdpUTNwId2WspKrm122wgNzX4HzM&attredirects=0


  • Each memory location has eight bits, which are known as a byte
  • The memory address is the number that identifies a memory location
  • Some data is too large for a single byte
  • For instance, most numbers are too large for one byte
  • In these cases, the address refers to the first byte
  • The next few consecutive bytes store the additional bits for larger data

Variables

  • When we want to instruct a computer to store or retrieve data from its memory, we don't want to have to refer to the memory location in 1s and 0s.
  • Wouldn't it be nice if we could use a name or label for a location in memory?
    • Most people can remember a name better than a number.
    • We would rather remember a name than a memory location in 1s and 0s.
  • Fortunately, there is a way to give labels to the contents of memory addresses.
  • Variables are labels used to reference locations in computer memory.


We don't want to have to remember memory addresses like this:


Instead we would rather remember memory addresses like this:


  • In the above diagram, num1 is a variable that refers to the contents of memory address 1652num2 is a variable that refers to the contents of memory address 2548, and total is a variable that refers to the contents of memory address 45.
  • When we use variables, we let the computer remember the address and size of the memory, we just remember the name of the variable.


Variables by Analogy

  • We can think of variables as boxes made of computer memory
  • A variable is just like a box that can hold a single thing
  • We need a way to tell one box from another so we give it a name
  • As we discussed, we can make up almost any name we want for the variable
  • For example, we declare a variable "a"
    int a;
    
  • When we first declare a variable the box is empty but has a name
    An empty box labeled a

  • Storing values in a variable is like putting items in a box
  • For example, we assign the variable "a" the value 1
    a = 1;
    
  • We can think of the above statement as putting the value 1 in a box with the variable name "a", like the one shown below (images source: David Goodger)
    Placing the value 1 in the empty box

  • We put names on a box
  • We put values inside of boxes
  • When we want to see the value inside a box we look at it with code like:
    System.out.println("The value stored in box a: " + a);
    
  • If we change the value of a variable, we are putting a new value in the same box, like:
    a = 2;
    
    Replacing the value stored in a with a new value (2)

  • Making a new variable and assigning one variable to another makes a copy of the value and puts it into the new box:
    int b = a;
    
    Box b now has the same value as a (2)

  • We now have two different boxes that have independent values


Variable Declarations

  • To create a new variable, you need to tell the compiler what kind of data to expect.
    • Different data types require different numbers of bytes to store
      • e.g. integers are stored in 2 bytes while doubles are stored in 4 bytes.
    • Different operations can be performed on different types of data
      • e.g. You can't add characters together, but you can add integers together.
  • You also need to give your variable a name.
  • Each variable declaration (statement) needs to be followed by a semi colon ; 
  • Let's look at some examples
double pi;
int numberStudentsClass;
boolean is_answer_correct;
char grade;
boolean tooCool4U;

  • All Java program variables must be declared before using them
  • A declaration statement both names a variable and specifies the type of data it can store
  • General syntax:
    dataType VariableName1, VariableName2, ...;
    
  • Where:
    • dataType: one of the Java data types
    • VariableNameX: the name of the variable

  • When we declare a variable, the compiler sets aside memory space
  • However, the contents of the storage space is undefined until we assign a value
  • For instance, after we declare the following variable, what is its value?
int  my_height;

Rules for Naming a Variable

  1. A variable name is a sequence of letters, numbers, or underscore characters
  2. The first character must be either a letter or an underscore character ( _ )
    • Cannot be a number
    • An _ is allowed but its use is discouraged.
  3. Also, the variable name cannot be one of the Java reserved words (keywords), such as int or double
    1. For a list of reserved words, see: Java Keywords
  4. Spaces are not allowed in variable names
    1. A space is NOT a letter, number or underscore character
  5. Also, variable names are cAsE sEnSiTiVe
    • idIDiD and Id are all valid but different names


Group Activity: Variable Declarations

Open up Eclipse and create a new project called Practice, with a new class called Practice

Inside of Practice.java declare 5 new variables as follows:

  1. A variable to store how many quarters you have been at De Anza
  2. A variable to store your age
  3. A variable to store whether or not programming is fun
  4. A variable to store your middle initial
  5. A variable to the value of pi
  6. Invent your own!
Be ready to share your answers with the class.


Assigning Values to Variables

  • Once we have specified the name and data type for a variable, we want to give it a value.
  • The value should match the data type.
  • We give a variable a value by using the = sign.
  • The variable name goes on the left side of the = sign.
  • The variable value goes on the right side of the = sign.
  • A semi colon ; always goes at the end of the statement.
variableName = expression;

  • where expression is the value we assign to the variable.
  • Below is an example of how to declare and assign a variable.

int numHorses;
numHorses = 12;
  • We can also combine the two statements above into one statement.

int numHorses = 12;

  • Either method is valid though the second option is preferred.


Group Activity Continued:

  • Let's practice by giving values to the variables that we declared in our last group exercise.
  • Be ready to write your examples on the board under the correct column: int, double, boolean, char

Assigning Literals and Complex Expressions to Variables
  • The simplest expression is a literal value:
    length = 25;
    width = 17.5;
    
  • Numbers like 25 and 17.5 are called literal numbers, or just literals, because we literally write them in the usual way
  • In each statement above, the value on right is assigned to the variable on the left
  • We can assign results of more complex expressions to a variable as well
    total = num1 + num2;
    slope = (y2 - y1) / (x2 - x1);
    
  • The expression on the right is evaluated (computed) before assignment to the variable on the left
  • Values placed into a variable replace (overwrite) previous values
  • Reading variables from memory does not change them

Initializing Variables

  • Initial values may or may not be assigned when variables are declared:
    // These are not initialized when declared
    // and have unknown values
    int sum, number1, number2;
    
    // These are initialized when declared
    int sum = 0;
    int number1 = 5, number2 = 10;
    
  • Good programming practice: initialize variables when declared
  • Variables can also change their values as the program progresses
    • Why are they called variables? Their content varies.
int myAge = 28;
//later in program... 
myAge = 29; 

Displaying Variables Using System.out.print()
  • To display the contents of a variable using System.out.print(), the variable should first be declared and have been assigned a value.

System.out.println(myAge); //NO!

int myAge = 12;

  • To display the variable, place the name of the variable inside of the parenthesis of the System.out.print() statement.

         int myAge = 12;

System.out.println(myAge);

  • It is also possible to print a message along with the variable contents by using the + operator inside of the parenthesis of the System.out.print() statement

int myAge = 12;

System.out.println("I am " + myAge + " years old.");


Activity 4.1: My Weekly Salary (10 pts)
  • Find a partner for pair programming.
  • Open up Eclipse.
  • Create a new project called Salary with a new class called Salary.
  • Alter the block comment at the start of your program to include both partners' names and section information. For example
@author Jennifer Parrish
@author Georg Albrecht
  • Declare a variable called hours and assign it the value 40.
  • Declare a variable called wage and assign it a value of your choice.
  • Declare a variable called salary and assign it the value of hours * wage;
  • Run the program and verify that there are no errors.
  • Is this program satisfactory?
  • Now, alter the program to print out the values of the salary you calculated.
  • For example, you could print out the salary like this:

My weekly salary is $600.

  • Submit your program to Canvas.

Review:
  • With a Partner, review our learning objectives.
  • Answer the following question:

What Gets Printed to the Screen?

int oranges = 5;

int apples = 8;

int numFruit = apples + oranges;

System.out.println("Total Fruit: " + numFruit);

oranges = oranges + 1;

apples = oranges;

System.out.println( "Apples: " + apples);

    System.out.println("Oranges: " + oranges);


Homework:
  • Lab 2 due Friday at midnight
  • Quiz 2 due Friday at midnight
  • Assignment 4 due Tuesday at 1:20pm on Canvas