Skip to content

Latest commit

 

History

History
350 lines (250 loc) · 8.91 KB

File metadata and controls

350 lines (250 loc) · 8.91 KB

Variables and Data Types

Variables and data types are the foundation of all programming in Java. Think of variables as labeled containers that hold information your program needs to remember, and data types as the rules that tell Java what kind of information each container can hold. Whether you’re tracking a player’s score in a game, storing someone’s name, or calculating the total cost of groceries, you’ll use variables to keep this information organized and accessible.

In this chapter, you’ll learn how to create variables, assign values to them, and understand the different types of data Java can work with. You’ll discover why Java is called a "strongly-typed" language, what that means for your code, and how Java’s type system helps prevent common programming errors. By the end of this section, you’ll be comfortable creating and using variables to build programs that can remember and manipulate information.

All the examples in this chapter work directly in jshell, so you can experiment and see immediate results as you learn.

What Are Variables?

In Java, variables are containers used to store data while the program is running. Variables can be named just about anything, and often are named things that make you think about what you store there.

Think of them as little boxes you can put data into, to keep it there and not lose it. If you wanted to track a number, an age of someone, you can create a variable to keep it in.

int age = 3;

Now, if we wanted to indicate that someone had a birthday, we might add 1 to the variable.

age = age + 1;

At this point, the age variable as 4 in it.

There are some rules about variable names.

  • All Variables must be named.

  • Names can contain letters, digits, underscores, and dollar signs

  • Names must begin with a letter

  • Names can also begin with $ and _ but are often used in special cases

  • Names are case sensitive (y and Y are different variables)

  • Reserved words (like Java keywords) cannot be used as names

  • All variable names must be unique (no two alike)

So this means the following are fine for variable names in Java:

x
area
height
width
currentScore
playerOne
playerTwo
$sumOfCredits
_lastPlay
isPlayerAlive

And uppercase and lowercase letters are different. So each of these are DIFFERENT variables even though they are based on the same word(s).

currentSpeed
current_speed
currentspeed
CURRENT_SPEED

So be careful with UPPERCASE and lowercase letters in variable names.

Declaring a Variable

int x;

This creates a variable x that can hold an integer (int) primitive type. But it has NO value assigned to it, so if we…​

System.out.println(x);  // -> undefined, although it will probably print zero.

If we were to declare a variable named 'cats' and assign it the value 3 (because we have 3 cats?):

int cats = 3;
System.out.println(cats);  // -> 3

Assign a value to a variable

int age = 19;
String name = "James";
System.out.println(name + " is " + age + " years old"); // -> James is 19 years old

age = 21;
name = "Gina";
System.out.println(name + " is " + age + " years old"); // -> Gina is 21 years old

NOTICE how the first time we use age and name we must declare those variables. But the second time (and any use thereafter) we don’t have to put int or String in front of the name.

This is how we make sure we don’t use variables we have not declared (which in Java is a syntax error).

Reassigning a value to a variable

String x = "five";
System.out.println(x); // -> five
x = "nineteen";
System.out.println(x); // -> nineteen

Notice how we don’t use "String" again, when we assign "nineteen" to x. We can assign a variable as many times as we might need to.

int age = 3;
// have a birthday
age = age + 1;
// have another birthday
age = age + 1;
System.out.println(age); // -> 5

Notice here how age’s current value is used, added one to it, and re-assigned back into the variable *age*.

Java, once you declare a variable as an int

int height = 62; // inches
System.out.println(height); // -> 62

height = "very tall"; // Java WILL NOT LET you do this.
System.out.println(height);

height ==> 62
62
|  Error:
|  incompatible types: java.lang.String cannot be converted to int
|  height = "very tall";
|           ^---------^

Java demands that once you tell it height is a int, you cannot change it to a String. You might think, but hey, I’m the programmer, but in fact, Java is protecting you from a common logic error. And in doing so, is shows what we mean by Java being a strongly-typed language. Once you declare something to be of a given type, you cannot change the type while the program is running.

Constants

Constants are like regular variables but they contain values that do NOT change such as a person’s date of birth. Convention is to capitalize constant variable names.

You make a double or int or String a constant by marking it final.

final String DATE_OF_BIRTH = "04-02-2005";
DATE_OF_BIRTH = "04-10-2005"; // <-error

final double SPEED_OF_LIGHT = 670_616_629.0; // miles per hour

SPEED_OF_LIGHT = 700_000_000.0; // ERROR, cannot changed things marked final

An attempt to re-assign a value to a constant (something marked with final) will fail.

Data Types

Java can keep track of a bunch of different kinds of data, and some are known as "primitive data types" and some are reference types (like objects, say, String for one).

  • Number - there are two kinds of numbers: integers and floating point

    • Integers (or int) are like 0, -4, 5, 6, 1234

    • Floating Point (or double) are numbers where the decimals matter like 0.005, 1.7, 3.14159, -1600300.4329

  • String - an array of characters -

    • like 'text' or "Hello, World!"

  • Boolean - is either true or false

    • often used to decide things like isPlayer(1).alive() [true or false?]

It is common for a computer language to want to know if some data is a number or a snippet of text. Tracking what type a piece of data is is very important to the computer. And it is the programmer’s job to make sure all the data get handled in the right ways.

So Java has a few fundamental data types that it can handle. And we will cover each one in turn.

Exercise: Create Variables for Data Types

Create variables for each data type:

  • double

  • int

  • String

  • boolean

Store a value in each.

// Here are some samples.

// integer
int x = 0;

// boolean
boolean playerOneAlive = true;

// float
double currentSpeed = 55.0;

// string
String playerOneName = "Rocco";

// constant integer

final int maxPainScore = 150000;

Now, you try it. Write down a variable name and assign a normal value to it.

// Here are some samples.

// integer
int applesPerBushel =     ;

// boolean
boolean isEngineRunning =          ;

// float
double myGradePointAverage =       ;

// string
String myDogName =         ;

// constant integer

final int floorsInMyBuilding =         ;

Variables are fundamental things in many, many programming languages. We use variables to build programs that can remember and manipulate information dynamically.

Chapter Exercises

Try these exercises in jshell to practice working with variables:

Exercise 1: Basic Variable Declaration and Assignment

Create variables for a student’s information:

String studentName = "Alex";
int age = 20;
double gpa = 3.85;
boolean isEnrolled = true;

System.out.println("Student: " + studentName);
System.out.println("Age: " + age);
System.out.println("GPA: " + gpa);
System.out.println("Enrolled: " + isEnrolled);

Exercise 2: Variable Reassignment

Start with a score and update it:

int score = 100;
System.out.println("Initial score: " + score);

score = score - 15;  // Lost points
System.out.println("After penalty: " + score);

score = score + 25;  // Bonus points
System.out.println("After bonus: " + score);

Exercise 3: Working with Constants

Create constants for a pizza order:

final double PIZZA_PRICE = 12.99;
final double TAX_RATE = 0.08;
final String RESTAURANT_NAME = "Tony's Pizza";

int quantity = 3;
double subtotal = PIZZA_PRICE * quantity;
double tax = subtotal * TAX_RATE;
double total = subtotal + tax;

System.out.println("Order from " + RESTAURANT_NAME);
System.out.println("Quantity: " + quantity);
System.out.println("Subtotal: $" + subtotal);
System.out.println("Tax: $" + tax);
System.out.println("Total: $" + total);

Exercise 4: Variable Naming Practice

Fix these poorly named variables by creating better ones:

// Poor names:
int x = 25;
String s = "John";
double d = 5.75;

// Better names:
int studentAge = 25;
String firstName = "John";
double hourlyWage = 5.75;

System.out.println(firstName + " is " + studentAge + " years old");
System.out.println("Hourly wage: $" + hourlyWage);