Java Variables

[S1E2]

Hritika Agarwal
7 min readAug 30, 2020

Introduction

Let’s say we need a program that connects a user with new jobs. We need the user’s name, their salary, and their employment status. All of these pieces of information are stored in our program.

We store information in variables, named locations in memory.

Naming a piece of information allows us to use that name later, accessing the information we stored.

Variables also give context and meaning to the data we’re storing. The value 42 could be someone’s age, a weight in pounds, or the number of orders placed. With a name, we know the value 42 is age, weightInPounds, or numOrdersPlaced.

In Java, we specify the type of information we’re storing. Primitive datatypes are types of data built-in to the Java system.

We must declare a variable to reference it within our program. Declaring a variable requires that we specify the type and name:

// datatype variableName
int age;
double salaryRequirement;
boolean isEmployed;

The above variable types are int, double, and boolean. This lesson will introduce these built-in types and more.

The names of the variables are age, salaryRequirement, and isEmployed.

These variables don’t have any associated value. To assign a value to a variable, we use the assignment operator =:

age = 85;

It’s common to declare a variable and assign the value in one line!

For example, to assign 2011 to a variable named yearCodecademyWasFounded of type int, we write:

int yearCodecademyWasFounded = 2011;

public class Creator {

public static void main(String[] args) {

String name = “James Gosling”;

int yearCreated = 1995;

System.out.println(name);

System.out.println(yearCreated);

}

}

ints

The first type of data we will store is the whole number. Whole numbers are very common in programming. You often see them used to store ages, or maximum sizes, or the number of times some code has been run, among many other uses.

In Java, whole numbers are stored in the int primitive data type.

ints hold positive numbers, negative numbers, and zero. They do not store fractions or numbers with decimals in them.

The int data type allows values between -2,147,483,648 and 2,147,483,647, inclusive.

To declare a variable of type int, we use the int keyword before the variable name:

// int variable declaration
int yearJavaWasCreated;
// assignment
yearJavaWasCreated = 1996;
// declaration and assignment
int numberOfPrimitiveTypes = 8;

doubles

Whole numbers don’t accomplish what we need for every program. What if we wanted to store the price of something? We need a decimal point. What if we wanted to store the world’s population? That number would be larger than the int type can hold.

The double primitive data type can help. double can hold decimals as well as very large and very small numbers. The maximum value is 1.797,693,134,862,315,7 E+308, which is approximately 17 followed by 307 zeros. The minimum value is 4.9 E-324, which is 324 decimal places!

To declare a variable of type double, we use the double keyword in the declaration:

// doubles can have decimal places:
double price = 8.99;
// doubles can have values bigger than what an int could hold:
double gdp = 12237700000;

doubles

Whole numbers don’t accomplish what we need for every program. What if we wanted to store the price of something? We need a decimal point. What if we wanted to store the world’s population? That number would be larger than the int type can hold.

The double primitive data type can help. double can hold decimals as well as very large and very small numbers. The maximum value is 1.797,693,134,862,315,7 E+308, which is approximately 17 followed by 307 zeros. The minimum value is 4.9 E-324, which is 324 decimal places!

To declare a variable of type double, we use the double keyword in the declaration:

// doubles can have decimal places:
double price = 8.99;
// doubles can have values bigger than what an int could hold:
double gdp = 12237700000;

public class MarketShare {

public static void main(String[] args) {

double androidShare = 81.7;

System.out.println(androidShare);

}

}

booleans

Often our programs face questions that can only be answered with yes or no.

Is the oven on? Is the light green? Did I eat breakfast?

These questions are answered with a boolean, a type that references one of two values: true or false.

We declare boolean variables by using the keyword boolean before the variable name.

boolean javaIsACompiledLanguage = true;
boolean javaIsACupOfCoffee = false;

In future lessons, we’ll see how boolean values help navigate decisions in our programs

char

How do we answer questions like: What grade did you get on the test? What letter does your name start with?

The char data type can hold any character, like a letter, space, or punctuation mark.

It must be surrounded by single quotes, '.

For example:

char grade = 'A';
char firstLetter = 'p';
char punctuation = '!';

public class Char {

public static void main(String[] args) {

char expectedGrade = ‘A’;

System.out.println(expectedGrade);

}

}

String

So far, we have learned primitive data types, which are the simplest types of data with no built-in behavior. Our programs will also use Strings, which are objects, instead of primitives. Objects have built-in behavior.

Strings hold sequences of characters. We’ve already seen instances of a String, for example when you printed out "Hello World".

Just like with a primitive, we declare the variable by specifying the type first:

String greeting = "Hello World";

Static Checking

The Java programming language has static typing. Java programs will not compile if a variable is assigned a value of an incorrect type. This is a bug, specifically a type declaration bug.

Bugs are dangerous! They cause our code to crash, or produce incorrect results. Static typing helps because bugs are caught during programming rather than during execution of the code.

The program will not compile if the declared type of the variable does not match the type of the assigned value:

int greeting = "Hello World";

The String "Hello World" cannot be held in a variable of type int.

For the example above, we see an error in the console at compilation:

error: incompatible types: String cannot be converted to int
int greeting = "Hello World";

When bugs are not caught at compilation, they interrupt execution of the code by causing runtime errors. The program will crash.

Java’s static typing helps programmers avoid runtime errors, and thus have much safer code that is free from bugs.

In the Mess.java file, we have declared a bunch of variables with the wrong type

public class Mess {

public static void main(String[] args) {

String year = 2001;

double title = “Shrek”;

int genre = ‘C’;

boolean runtime = 1.58;

char isPG = true;

}

}

when we tried to compile this file,

Naming

Let’s imagine we’re storing a user’s name for their profile. Which code example do you think is better?

String data = "Delilah";

or

String nameOfUser = "Delilah";

While both of these will compile, the second example is way more easy to understand. Readers of the code will know the purpose of the value: "Delilah".

Naming variables according to convention leads to clear, readable, and maintainable code. When someone else, or our future self, reads the code, there is no confusion about the purpose of a variable.

In Java, variable names are case-sensitive. myHeight is a different variable from myheight. The length of a variable name is unlimited, but we should keep it concise while keeping the meaning clear.

A variable starts with a valid letter, or a $, or a _. No other symbols or numbers can begin a variable name. 1stPlace and *Gazer are not valid variable names.

Variable names of only one word are spelled in all lowercase letters. Variable names of more than one word have the first letter lowercase while the beginning letter of each subsequent word is capitalized. This style of capitalization is called camelCase.

// good style
boolean isHuman;
// bad styles
// no capitalization for new word
boolean ishuman;
// first word should be lowercase
boolean IsHuman;
// underscores don't separate words
boolean is_human;

Review of this lesson

Creating and filling variables is a powerful concept that allows us to keep track of all kinds of data in our program.

In this lesson, we learned how to create and print several different data types in Java, which you’ll use as you create bigger and more complex programs.

We covered:

  • int, which stores whole numbers.
  • double, which stores bigger whole numbers and decimal numbers.
  • boolean, which stores true and false.
  • char, which stores single characters using single quotes.
  • String, which stores multiple characters using double quotes.
  • Static typing, which is one of the safety features of Java.
  • Variable naming conventions.

public class MyProfile {

public static void main(String[] args) {

String name= “hritika”;

int age= 18;

double desiredSalary = 100000000000000.8;

char gender =’f’;

boolean lookingForJob = false;

}

}

Practice declaring variables and assigning values to make sure you have a solid foundation for learning more complicated and exciting Java concepts!

Read Previous — Java From Scratch

Read Next — Manuplating Variables in Java

--

--