Variables
Variables are elements in code that can store data.
Data Types
Data in Java have data types to help differentiate objects from each other. There are two general categories of data types— Primitives and Composites. We'll go over commonly used data types here.
Primitives
Primitives are simple data types that don't take up a lot of data and are generally very simple.
Integer (int)
Whole numbers, no decimals.
int num = 1;
Doubles
numbers with decimals. Also known as floats
.
double num = 0.24;
Characters (chars)
Digits, icons, or letters. Note that a digit's value is different from what it looks like.
char c = 'A'; char fourAsDigit = '4'; (not the same as the number 4)
Booleans
Conditions, used for logic
boolean incomingTest = true; boolean studying = false; boolean correctMath =
(2 == 4); // true
Composites
Composites generally are made from groups of smaller primitives. Due to their complexity, (except for strings) they are treated differently by the computer. Here are some noticeable ones:
Strings
Store text (multiple chars)
string intro = "Hello World!"
Arrays
Store multiple values of the same type
int[] array = {5, 4, 3, 2, 1} char[] msg = {'H', 'E', 'L', 'P'}
User-Created Data Types
Don't worry about this— we'll cover it later. Its fields and purposes could change depending on what it's used for.
Object o = new Object() Animal cat = new Animal("Cat");
Creating & Modifying Variables
All you need to do is define a variable name and set its data type. It's that simple.
Variables are kinda useless if you can't assign them values. To do this, just set the variable's name to some value, like so:
Note that you can only assign variable values the same type as the variable or your code will break. For example, you can only set variables that have a data type of "String" strings.
Last updated