Variables and Types
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-128
and127
short
: a number between-32,768
and32,767
int
: a number between-2,147,483,648
and2,147,483,647
long
: a number between -9,223,372,036,854,775,808
to9,223,372,036,854,775,807
float
: a floating point number, a number with decimalsdouble
: a floating point number but with more precisionchar
: a single characterboolean
: a binary value,true
orfalse
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
- Getting Started with TypeScript
- Getting Started with Svelte
- How to Serve Static Files with Nginx and Docker
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- Getting Started with Deno
- How to deploy a Node app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Getting Started with React