Table of Contents
Variables are a fundamental part of any programming language, including Java. Variables are used to store pieces of data and give them a name. When we want to use these variables in some way, we can refer to them by their name.
Primitive Variable Types
Let's explore the primitive types of data that variables can hold.
String: a string of characters, also known as textbyte: a number between-128and127short: a number between-32,768and32,767int: a number between-2,147,483,648and2,147,483,647long: a number between -9,223,372,036,854,775,808to9,223,372,036,854,775,807float: a floating point number, a number with decimalsdouble: a floating point number but with more precisionchar: a single characterboolean: a binary value,trueorfalse
Now that we know the primitive types supported in Java, let's declare our variables.
Declaring
Declaring a variable is how you create them. Here's an example featuring all of the primitive data types:
JAVApublic class Main {
public static void main(String[] args) {
String a = "Sabe.io";
System.out.println(a);
byte b = 6;
System.out.println(b);
short c = 1337;
System.out.println(c);
int d = 12345;
System.out.println(d);
long e = 13371337;
System.out.println(e);
float f = 13.37f;
System.out.println(f);
double g = 13.37;
System.out.println(g);
char h = 'a';
System.out.println(h);
boolean i = true;
System.out.println(i);
}
}
BASHSabe.io
6
1337
12345
13371337
13.37
13.37
a
true
In general, to declare a variable, you must start off with their type, then an equal sign, then the value. This is the general syntax:
JAVAtype name = value;
Since Java is strongly typed, it requires you to give every variable their type.
Variable Naming Rules
There are rules in place for naming Java variables, and here they are:
- The variable name can only contain alphanumeric characters, underscores, and dollar signs
- The variable name must start with a letter, dollar sign, or underscore
- The variable name cannot contain spaces
With that in mind, here are some examples of valid Java variable names:
JAVAapples
_apples
_apples_
$apples
And here are some examples of invalid Java variables names:
JAVA1apples
app les
&apples
%apples
Create an RSS Reader in Node
How to build a Discord bot using TypeScript
How to deploy a PHP app using Docker
How to deploy a MySQL Server using Docker
How to deploy an Express app using Docker
How to deploy a Node app using Docker
Getting Started with Sass
Learn how to use v-model with a custom Vue component
Getting Started with Handlebars.js
Build a Real-Time Chat App with Node, Express, and Socket.io
Using Push.js to Display Web Browser Notifications
Getting Started with React
