David Shin
2 min readMar 22, 2021

--

Declaring Variable in Java.

Now for those who are studied in coding pretty sure heard about variables, in fact, variables have used in many other coding languages. Simply a variable is a label or name that was given for memory that holds a value(or data). If variables were declared then part of the memory has used and for that storage, for memory, we put a name(or label) which is called variable.

Resources: https://python3.nl/wiki/variabelen-in-python/

So let’s take a look at how we can declare a variable in Java

Type 1.
int randomNumber; // declaring randomNumber as a variable but not
but not value has been given yet.
Type 2.
int randomNumber2; // Same as Type 1. declaring a variable but this
time the variable has been given with a value.
Type 3.int randomNumber1, randomNumber2, randomNumber3, ... randomNumber10
// Declaring multiple variable with same data type.
Type 4.
int randomNumber1 = 1, randomNumber2 = 2, randomNumber = 3... randomNumber =4
//Same as Type 3 but not each variables has a value.

Ok very similar to javascript where you give a name to a variable but what is that “int” in front of variables? well, let’s put it this way for now, “int” is one of the primitive data of Java, and stores 32 bit signed two’s complement integer. It sounds kind of complicated right? Don’t worry we will discuss the eight primitive data types in Java soon.

So let’s take a look at some examples of how to declare a variable in Java code.

package learningJava;public class ExampleCase{
public static void main(String[] args){
int num; //Declared a variable named num with "int"data
type.
num = 1; // Here we are setting a value to the num
variable.

System.out.prinln(num); // This will print number = 1;
num = 10; //We are not declaring a new variable at here,
but instead with exiting a variable "num" we
are setting a new numeric value which is 10.
System.out.prinln(num); // Print number = 10;

Although you may have noticed that there two times that we used a variable “num’ for setting a value, so is it ok not to set up a data type like “int” again? To answer that, yes we don’t necessarily have to. And these are some rules that are useful when using or declaring a variable in Java.

  • Rules for naming a variable.

1. The variables should follow in order with the alphabet, number, or under Score(under_score). (Variables can’t be named with the number only)

2. Capital case is matters in Java. ex)“ int num” and “int Num ” are not the same.

3. Can’t use “keywords” in Java. ex) “int”, “char”, “void” are not allowed to use as the variable’s name.

4. No space! ex) “int num random ”is a bad variable name, so we use underscore, like“ int num_rnadom”.

--

--