“Variables in Java”

So today we will be covering variables in Java. We will also see some real life examples to understand these variables more easily. So let us begin.

Java Variables

Variables are containers for storing data values.

In Java, there are different types of variables, for example:

  • String – stores text, such as “Hello”. String values are surrounded by double quotes
  • int – stores integers (whole numbers), without decimals, such as 123 or -123
  • float – stores floating point numbers, with decimals, such as 19.99 or -19.99
  • char – stores single characters, such as ‘a’ or ‘B’. Char values are surrounded by single quotes
  • boolean – stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

Where type is one of Java’s types (such as int or String), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.

To create a variable that should store text, look at the following example:

Create a variable called name of type String and assign it the value “John“.
Then we use println() to print the name variable:

To create a variable that should store a number, look at the following example:

Create a variable called myNum of type int and assign it the value 15:

You can also declare a variable without assigning the value, and assign the value later:

Create a variable called myNum of type int and assign it the value 15:

Note that if you assign a new value to an existing variable, it will overwrite the previous value:

Change the value of myNum from 15 to 20:

Final Variables

If you don’t want others (or yourself) to overwrite existing values, use the final keyword (this will declare the variable as “final” or “constant”, which means unchangeable and read-only):

Other Types

A demonstration of how to declare variables of other types:

Display Variables

The println() method is often used to display variables.

To combine both text and a variable, use the + character:

You can also use the + character to add a variable to another variable:

For numeric values, the + character works as a mathematical operator (notice that we use int (integer) variables here):

From the example above, you can expect:

  • x stores the value 5
  • y stores the value 6
  • Then we use the println() method to display the value of x + y, which is 11

Declare Many Variables

To declare more than one variable of the same type, you can use a comma-separated list:

Instead of writing:

You can simply write:

One Value to Multiple Variables

You can also assign the same value to multiple variables in one line:

Identifiers

All Java variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

It is recommended to use descriptive names in order to create understandable and maintainable code:

The general rules for naming variables are:

  • Reserved words (like Java keywords, such as int or boolean) cannot be used as names
  • Names can contain letters, digits, underscores, and dollar signs
  • Names must begin with a letter
  • Names should start with a lowercase letter, and cannot contain whitespace
  • Names can also begin with $ and _
  • Names are case-sensitive (“myVar” and “myvar” are different variables)

Real-Life Examples

Often in our examples, we simplify variable names to match their data type (myInt or myNum for int types, myChar for char types, and so on). This is done to avoid confusion.

However, for a practical example of using variables, we have created a program that stores different data about a college student:

Calculate the Area of a Rectangle

In this real-life example, we create a program to calculate the area of a rectangle (by multiplying the length and width):

Check Your Learning….

Blogroll


Social, Cultural u0026amp; Behavioral Issues in PHC u0026amp; Global Health
Social, Cultural u0026amp; Behavioral Issues in PHC u0026amp; Global Health
Social, Cultural and Behavioral Foundations of Primary Health Care (JHSPH)

Penny Zeller
Penny Zeller
Random thoughts from a day in the life of a wife, mom, and author

Discover more from Sophia's Tech Journey

Subscribe to get the latest posts sent to your email.

Responses

  1. G&G"s Avatar

    Great post, Sophia! I found the explanation of Java variables quite clear. How do you handle variable scope when working with more complex structures like classes or methods in Java? Any best practices you’d recommend?
    “`

    1. Sophia Avatar

      Hello G&G”s
      Thank you for the praise.
      Currently I don’t have an answer to your question as I am a first year student who is still learning Java and I write my articles as and when I learn it in college. In short when I learn something I study it on internet and then put up the article.
      But I assure you that I will try to find the answer to your question in some time. Till then you can keep reading my other articles and let me know how did you like them.

      Thank you for being my reader.

      Sophia,
      XOXOXO

Leave a Reply to G&G”sCancel reply

Discover more from Sophia's Tech Journey

Subscribe now to keep reading and get access to the full archive.

Continue reading