Java: Variables

 Hello and Welcome to Java Blog #3, Java: Variables. This blog will introduce variables, how to define them, and their use. 


Variables, in any programming language, are like containers. They store things in them, which we can access and use when we need to. They are useful for keeping track of things and storing things. 


How do we define variables? In Java, you need to be specific with everything, including defining variables. In some other programming languages, like Python, all you have to do is variable name, equal to, and what it stores. 

With Java, it looks like this:

variable type  variable name = store;


The variable type is the data type. For info on data types in Java, please look at Java: Data Types.  The Data Types include ints, Strings, booleans, chars and doubles. For example:

int num = 2;

Here, int is the data type, num is the variable name, and its value is 2. The value of the variable must go with the data type of the variable (Once again, please look at the Data Types post).

Also, notice the semi-colon at the end. This is Java syntax, and without it at the end of most lines of code in Java, excluding things like classes and the main() method, the Java code will output an error, so make sure you add the semi-colon.


Here are some more examples of declaring variables:

Correct Declarations:

String hello = "Hello everyone!";

boolean eating = false;

double cost = 2.15


Incorrect Declarations:

int num = "Hi";

String Java = "Java is fun!"

char Grade = "Fail";


Most of these examples are associated with the variable value not corresponding with the data type. The second incorrect example does not have a semi-colon, which is why it is wrong.


Finally, there are a few things to remember whilst naming a variable. 

1. The variable name must begin with a letter of the alphabet, or _ or $, although the second two are discouraged. After the first letter, it can have numbers 0 - 9 as well.

2. The variable name can be of any length, although it should be kept concise while getting the reason for having the variable across. 

3. It is best to start the name with a lowercase letter, and then, if the name contains multiple words, start each next word with a capital letter. 

4. The variable names are case-sensitive, so uppercase letters are different from lowercase. For example, Hello, is a different variable from hello. 



Thank you for reading Java: Variables. Please leave any comments or questions in the comments section!







Comments