Java Variables

... by Bittle in Java Tutorial January 23, 2019

What are Variables?

Variables can be either primitive or reference. We can use variables as instance variables (object state), local variables (variables declared in methods), arguments (values sent to a method when calling it), and as return types (values sent back to the caller of the method).

Primitive vs Object Reference

Primitives hold the fundamental values (the simplest pieces of information, such as numbers and characters) while Object references hold references to objects (objects hold states and behaviors like stated previously, and also contain primitives within).

Declaring a variable

In java, you must be careful with type. You can't declare an integer variable (whole number) and assign it a double (decimal). While writing code in java the compiler can detect most variable type problems such as referencing a Dog into a Cat variable. Variables must have a type and name. Primitives can hold different values and are used each for different purposes. For example, when talking about weight you need decimals to be precise, so you can use a double or a float, but when talking about age and only care about the years we can use an integer as your type.

Primitive types:

boolean - true of false

char - character


numeric:

byte - 8 bits

short - 16 bits

int - 32 bits

long - 64 bits


floating point:

float - 32 bits

double - 64 bits


You can assign value to a variable by:

  • Typing a literal value after the equals sign (y = 9, c = 'e', etc)
  • Assigning the value of one variable to another (y = x)
  • A combination of previous assignments (x = y + x + 3)

For example:

double pi = 3.14;
char last = 'e';
boolean isHungry = true;
double radius = 4.8;
double circ = 2 * pi * rad;


Comments (0)

Search Here