Data Types and Variables

LEARNING OBJECTIVES

After this lesson, you will be able to:

  • Identify and describe the Java data types and use cases
  • Describe the different types of variables (locals, instance, constants) and when to use them
  • Use class methods to manipulate data in the Math and String classes
  • Describe the difference between NaN and null

STUDENT PRE-WORK

Before this lesson, you should already be able to:

  • List a few of the basic Java data types
  • Assign a variable in Java (int a = 1;)
  • Describe Objects in Java

Opening (5 min)

In programming, we need a way to store information while our programs are running. This could be anything from names, to numbers, to dates, and many other things, which are all known as data types. These data types are stored in variables, just like algebra class. Today we are going to be exploring how data types and variables are the very basic building blocks of programming and how we actually use them to store information in our programs.

Introduction: Data types in Java (10 mins)

From the Wikipedia:

In computer science and computer programming, a data type or simply type is a classification identifying one of various types of data that determines:

  • the possible values for that type;
  • the operations that can be done on values of that type;
  • the meaning of the data;
  • and the way values of that type can be stored.

Data types are similar across different languages, including English:

Instructor Note: Put the categories on the board and ask for students to provide the data type, or in some other way create a list on the board that includes the data types below. Include both lowercase primitive and capitalized Object types. This chart will be referenced later.

Category DataType Description Example
True/False boolean, Boolean Represents either true or false true, false
Integers short, int, Integer, long, Long Whole numbers, with no delimiter. Can optionally have underscores to make large numbers easier to read 42, 1024, 1_000_000
Decimals float, Float, double, Double Decimals, with no delimiter '42.123', 2.5'
Characters char Single character, surrounded by single quotes 'a', 'A'
Strings String Single words or sentences, surrounded by double quotes "lots of kittens", "a lazy lizard" true, false

There are also a few odd ones:

  • Byte, which is one bit of data. You don't need to worry about it right now.
  • Collections (we'll talk more about this Week 3)

We'll elaborate all of the categories on the board, and show you some helper methods to help you manipulate them.

Check: Come up with a few examples of data and have students predict what type of data it falls into.

Demo: Lets start with Numbers (15 mins)

Starting an IntelliJ Project

Instructor Note: Create a new IntelliJ Project, describing each step aloud.

Steps to Create a new IntelliJ Project: File > New > Project > Next > Create from Template. Note: you are given a class, that is named the same as the file with a main method inside it.

Also Note: What does the // mean? This represents a comment. You can also replace // with a multi-line comment /* write your code here */. Comments are used to clearly articulate what your code is doing so that other developers can easily jump into a project and understand what's going on.

We'll talk more about all of these pieces later, for now, write your code directly within the main method, where the comment says, //Write your code here.

Decimals vs Integers

Check: As you code the following examples, ask the students the following. If they guess correctly, ask them to explain why.

First off, lets talk a bit about those Number data types.

What do you expect to be printed to the console?

int num1 = 5;
System.out.println("num1, type int = " + num1);
=> num1 = 2

How about here?

int num2 = 5 / 2;
System.out.println("num2, type int = 5/2 = " + num2);
=> num2 = 2

But Why is num2 not 2.5? Well, in low-level languages (unlike JavaScript, Ruby or PHP) numbers are strictly typed, and a type is either an integer or decimal. An int stores a Integer, not a decimal, as demonstrated in the previous function.

So, what sort of variable would we use if we wanted to assign a variable to a decimal? How about a float?

float num3 = 5 / 2;
System.out.println("num3, type float = 5/2 = " + num3);
=> num3 = 2

Check: That didn't work quite as expected. Can anyone guess why?

Because both 5 and 2 are automatically assigned data type int, when the calculation is done the answer is also an int ( float a = (float) int a = int b / int c; ). We must tell the computer that the divisors are of a decimal type, not an integer type.

float num4 = 5f / 2f;
System.out.println("num4, type float = 5f/2f = " + num4);
=> num4 = 2.5
double num5 = 5d / 2d;
System.out.println("num5, type double = 5d/2d " + num5);
=> num5 = 2.5

Note: In the previous example, we used both a float and a double data type to save decimal numbers.

Check: What is the difference between float and double and which should you use?

Number data types and Bits

To answer this question, it is helpful to understand that a data type defines not only the type of data but also the methods that can be used to manipulate that data. The primitive data types in Java also has a certain pre-assigned size in memory. This is represented in a number of bits.

Name Width in bits Range
float 32 3.4e–038 to 3.4e+038
double 64 1.7e–308 to 1.7e+308

More memory means more information can fit into that variable. Double's are much larger than floats. What does that mean for working with decimals? Floats are more memory efficient, and doubles provide more accuracy.

Double's are recommended for currency and where accuracy is important. There is also a BigDecimal class, used when even more decimal points are needed.

The same data type differentiation exists in Integers between shorts (did you notice it in our list), ints and longs.

Name Width in bits Range
short 16 -32,768 to 32,768
int 32 -(2^31) to 2^31 (approx 2 billion)
long 64 -(2^63) to 2^63

int will cover almost all of your Integer needs.

Check: What is the most common data type for decimals? What is the most common data type for integers?

Using Standard Arithmetic Operators

Now that we understand a bit more about the Number data types, lets look a bit at what we can do with them.

The standard arithmetic operators - that you've been learning since grade school:

Instructor Note: Depending on time, and student understanding, this can be breezed over. Be sure to mention modulus. as it is the one odd one. If going through each example, ask students to calculate what will be printed to the console.

System.out.println(2 + 2);
System.out.println(2 - 2);
System.out.println(2 / 2);
System.out.println(2 * 2);
System.out.println(2 % 2); // What does this do??

Demo: Using Special number Operators (10 mins)

Coding languages can be a little cheap with the number of operations they allow you to do. For example, how do you square or cube a number? There is a special 'Math' Object, provided by Java, that has some very useful methods. Follow along!

Taking a number to a 'power' ? Then just use Math.pow(num1,num2)

// 3^2 becomes
System.out.println( Math.pow(3,2) );
=> 4

Taking a square root ? Then just use Math.sqrt(num1)

// √(4) becomes
Math.sqrt(4);
=> 2

Need a random number? Then use Math.random().

// returns double value with positive sign greater than or equal to 0.0 and less than 1.0
Math.random()
=> ?
// returns random number in range
int range = Math.abs(max - min) + 1;
(Math.random() * range) + min;

Check: Who provides the Math object? Where do you think you might be able to find more information? (Oracle Math Documentation)

Boolean Values

Java has a special way of storing values that represent true and false. These values are stored in the boolean datatype. A variable of type boolean can only be true or false.

Boolean values are very useful when programming. They can store simple values to keep track of whether a game is over, and they can store the result of an evaluation of a logical expression. Notice below how the the variable isOver21 stores the true or false result of comparing 19 to 21.

boolean isGameOver = false;
boolean isUserLoggedIn = true;
boolean isOver21 = 19 > 21; // store the value false

Chars

Chars are the data type for single letters. Single letters and multiple letters are treated differently in Java. Notice that chars differentiate between being uppercase and lowercase. A lowercase a is not considered equal to an uppercase A.

char foo = 'a';
char bar = 'b';

char baz = 'A';
char qux = 'B';

boolean bool1 = foo == foo; // stores true. 'a' is equal to 'a'
boolean bool2 = foo == bar; // stores false. 'a' is not equal to 'b'
boolean bool3 = foo == baz; // stores false. 'a' is not equal to 'A'

Strings

A string stores a bunched of characters all "stringed" together. The String datatype is different than the char datatype. The char datatype can only ever store one letter at a time. The String datatype can store store an unlimited amount of characters in a row at once.

String name = "Henry";
String sentence = "Today I woke up and had a heartful bowl of cheerios.";

String helper methods

Strings are special. Because they are more complicated than the char datatype they come with pre-defined methods we can use.

To find the length of a string, use it's length property:

"hello".length();
=> 5

To get the first letter of a String:

"hello".charAt(0);
=> "h"

To replace part of a String:

"hello world".replace("hello", "goodbye");
=> "goodbye world"

To make a String uppercase:

"hello".toUpperCase();
=> "HELLO"

To add two Strings together:

"hello".concat(" world");
=> "hello world"

Remember, Strings are special Objects that look like primitives. Use the str1.concat(str2) function. Or concatenate (add together) using + :

String twoStringsTogether = "Hello" + " World";
=> "Hello World"
A special note on Equality among Strings:

What if you want to compare two strings?

Can you remember from the pre-work how to compare variables?

boolean areEqual = (1 == 2);
=> false

What's special about strings?

String blue = "blue";
boolean withSign = (blue == "blue");            //=> true
boolean withWords = (blue).equals("blue");      //=> true

Do you know which one of these would be preferred? Well, lets do another example to show you which and why:

String blue = "blue";
String bl = "bl";
String ue = "ue";
System.out.println(bl+ue);                      //=> blue
boolean withSigns = (bl+ue == blue);            //=> false
boolean withWords = (bl+ue).equals(blue);       //=> true

Why isn't withSigns true? The print out looks the same. Remember, String is actually an object, and Objects are passed by reference.

== compares the place where the object was stored on the computer to access whether they are the same. String blue has a reference to where it is stored on the computer, and that is a different place than String bl is stored. equals, on the other hand, is a method that can be called on an instance(str1) of a String Object. And accesses whether the char arrays in each String are the same, not whether the references are the same.

The long and short of it, use equals when comparing strings.

Check: Why can we call methods on a variable with data type string but not on an int?

Demo: Converting between data types (10 mins)

Sometimes it is necessary to convert between data types. User input is always a string - like when you enter your email address, age, income, etc. If you'd like to operate on those numbers though, you'll have convert it to a type of number.

Remember how we talked about the size of primitive data types? An float is smaller than a double, and a double smaller than a long?

When converting from smaller types to larger types, for example, int(4 byte) to double(8 byte), conversion is done automatically. This is called implicit casting.

int a = 100;
double b = a;
System.out.println(b);

If, on the other hand, you are converting from a bigger data type to a smaller data type, for example, a double(8 byte) to an int(4 byte), the change in data type must be clearly marked. This is called explicit casting.

double a = 100.7;
int b = (int) a;
System.out.println(b);

While that is useful for numbers, to cast successfully, a variable must be an instance of that second Object. What do you think would happen if you tried to cast a String to an int?

There is a different way to convert Strings to numbers.

Did you notice that there is both an int and an Integer data type? The Integer data type is a wrapper around an int that provides certain methods. For example, to convert an String to an Integer, one can use:

String strValue = "42";
int intValue = new Integer(strValue).intValue();

Similar methods exist for all of the wrappers.

NaN

If a String is converted to a number but contains an invalid character, the result of the conversion will be NaN, which stands for: Not A Number.

NaN is toxic, and if a calculation is attempted on that variable or a method called subsequently, your program will break.

Test for NaN using isNaN().

Null

A null value is an empty value. Taken from a StackOverflow post:

"Zero" is a value. It is the unique, known quantity of zero, which is meaningful in arithmetic and other math.

"Null" is a non-value. It is a "placeholder" for a data value that is not known or not specified. It is only meaningful in this context;

Check: When might you get NaN value? What is a null value, by the way?

Independent Practice: Practice! (15 minutes)

Instructor Note: This can be a pair programming activity or done independently.

Download the coding prompt found in VariablePractice and complete all tasks. We will go over the answers in 12 minutes.

Check: Were students able to create the desired deliverable(s)? Did it meet all necessary requirements / constraints?


Conclusion (5 mins)

  • Identify the different types of data?
  • What type of data do you think is passed as a web request?

ADDITIONAL RESOURCES

results matching ""

    No results matching ""