Java Variables Examples [Different Variable Types]

 

Introduction to Java variables

Variables are one of the most important elements of any programming language because they are the ones that store different data types. A variable is a container that holds the value while the program is executed. Simply it is a name of a memory location. In a similar way, variables in java perform the same function.

In this tutorial, we will learn about java variables, their data types along with different examples. Moreover, we will also discuss the different types of variables that are supported by the java program and take various examples to see how we can covert one data typed variable into another one.

Advertisement

In a nutshell, this tutorial contains all the subtopic and their explanation that you need to know in order to get started with java variables.

 

Getting started with Java variables

A Java variable is a piece of memory that can contain a data value. A variable thus has a data type depending on the value that has been stored in it. Variables are typically used to store information which our Java program needs to do its job. This can be any kind of information ranging from texts, codes (e.g. country codes, currency codes, etc.) to numbers, temporary results of multi-step calculations, etc. In this section, we will take a look at the syntax, declaration, and initialization of java variables.

 

Primitive data types of Java Variables

The Java programming language is statically typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name, which we will see in the next couple of sections. A primitive type is predefined by the Java programming language and named by its reserved keyword. The following list shows some of the primitive data type variables.

  • Byte: The byte is a data type of 8-bits signed two's complement integer. The minimum value that this type of variable can store is -128 and the maximum value is 127.
  •  short: The short is a data type of 16-bit signed two's complement integer. The minimum value that this type of variable can is -32768 and the maximum value is 32767.
  • int: This is another data type of 32-bits signed two's complement integer. The minimum value that this data type can store is -2 raise to the power 31 ( -231 ) and the maximum value can be -2 raise to the power 32 minus 1 ( 231-1).
  • long: The long is a data type of 64-bit two's complement integer. The long data type has a minimum value of -2 raise to the power of 63 (-263) and a maximum value of 2 raised to the power of 63 minus 1 (263-1). While the unsigned 64-bit long variable can have a minimum value of 0 and a maximum value of 2 raised to the power 64 minus 1 (264-1).
  • float: The float is a single-precision 32-bit data type.
  • double: The double a double-precision 64-bit data type.
  • boolean: The boolean data type has only two possible values which are either true or false.
  • char: The char data type is a singe-64 bit Unicode character. It has a minimum value of \u0000 or 0 and a maximum value of \uffff or 65535.

 

The naming convention of Java Variables

There are a few rules and conventions related to the naming of variables. The following list highlights some of those rules and conventions.

  • Java variable names are case-sensitive. The variable name book is not the same as BOOK or Book.
  • Java variable names must start with a letter, or the $ or _ character. Although starting a variable name with $ sign or underscore (_) is allowed but is not recommended.
  • After the first character in a Java variable name, the name can also contain numbers (in addition to letters, the $, and the (_) underscore character).
  • Variable names cannot be equal to reserved keywords in Java. For instance, the words int or if are reserved words in Java. Therefore you cannot name your variables int or if.
  • Variable names should be short yet meaningful.

 

Definition and initialization of Java variables

In java, it is important to declare variables before storing any data type in it.  Defining or declaring a variable simply means to tell Java that we are going to have a variable of a specified type and name.

The syntax of defining a variable in java looks like this:

Advertisement
int data;
char name;

Once we declared the variables, we are good to store any kind of data but it should have the same data type as our variable have. Initialization of data in java looks like this:

data = 6;
name = 'B';

Java also allows to define and initialize the variable in one line as well. The syntax of initializing and defining variables at the same time looks like this.

int data = 6;
char name = 'B';

Now let us see how it looks like in a real java program. See the following example of java variables in a program.

public class Main {
   public static void main(String[] args){
       char name = 'b';
       int data = 10;
   }

 

Different types of Java Variables

Java program supports different kinds of variables and each of them has its own properties and features. The most popular types of variables in java are

  • Instance variables
  • Local variables
  • Static variables

In this section, we will have a close look at all these four different types of variables and will go through some examples of each type.

 

Examples of Instance Java Variables

Instance variables are declared in a class, but outside a method, constructor, or block. Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed. The instance variables are visible for all methods, constructors, and blocks in the class. Normally, it is recommended to make these variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers. 

The simple syntax of the instance  java variables looks like this:

class Main {

   // public variable
   public String name ="Bashir";

   // private variable
   private String name1 = "Bashir";
}

The instance variables are visible and can be accessed from the methods inside the same class, see the example below:

Advertisement
public class Main{
   public String name;// this instance variable is visible for any child class.
   private String name1;// this instance age variable is visible in Record class only.

   // public String can be accessed in the methods
   public Main (String NewName)
   {
       name = NewName;
   }
   // we have to set variables for private variables
   // private variables can be accessed through setter
   public void setName(String NewName1)
   {
       name1 = NewName1;
   }
   // printing the names
   public void printNewNames()
   {
       System.out.println("Public variable : " + name ); // print the value for “name”
       System.out.println("Private variable :" + name1); //prints the value for “age”
   }
   // main java method
   public static void main(String args[])
   {
       Main student = new Main("Ramiz");
       student.setName("Ramiz Raja");
       student.printNewNames();
   }
}

Output:

Public variable : Ramiz
Private variable :Ramiz Raja

Public and private variables are mostly used in Object-oriented java programming.

 

Examples of local Java Variables

Local java variables are declared inside methods, constructors, or blocks. Java program will create/access the local variables when the method, constructor, or block is entered and the variable will be destroyed once the program exits from the method, constructor, or block. As their name suggests, local variables are visible only within the declared method, constructor, or block. Here is a simple syntax of java local variables.

public void Name() {
      // local variable of string Type
      String Name = "";
   }

Now let us take a real example and print out the local variable defined in the above syntax. See the example below:

public class Main {
   // method
   public void Name() {
       // local variable of string Type
      String Name = "";
      System.out.println("Name is : "+Name);
   }
   // main method
   public static void main(String args[]) {
       // creating new class of Main type
      Main test = new Main();
      // calling Name method
      test.Name();
   }
}

Output:

Name is : Bashir

We already know that local variables can be only accessed by the same method, if we try to access local variables from any other method, it will return an error as shown below:

public class Main {
   // method
   public void Name() {
       // local variable of string Type
      String Name = "Bashir";
   }
   // main method
   public static void main(String args[]) {
       // creating new class of Main type
      Main test = new Main();
      // calling Name method
      test.Name();
      // printing local variable in another method
      System.out.println(Name);
   }
}

Output:

Java Variables Examples [Different Variable Types]

 

Examples of Static Variables

Static variables are also known as class variables which are declared with the static keyword in a class, but not inside a method, constructor, or block. Static variables are stored in the static memory. Their visibility is similar to the instance variable but most of the static variables are declared as public so they are available for other classes as well. They can be accessed by calling with the name of the class. See the simple syntax of java static variables.

  // private static variable
   private static String name;

   // public static variable
   private static String name1;

Now let us take a real example and see how we can use java static variables. See the example below:

class Main
{
   // static variable
  static String name="Bashir";
  public static void main(String args[])
  {
      // printing the static variable
      System.out.println("Name is = "+ name);
  }
}

Output:

Name is = Bashir

 

Java Variable Type Conversion and Typecasting

A variable of one type can receive the value of another type or in a simple word one type of java variable can be converted either directory or directory to another data type variable. Basically, there are two cases with type conversion in java.

The first is converting one type into another indirectly, this happens when a variable of smaller capacity is be assigned to another variable of bigger capacity.

For example see the example below:

int data = 14  
double num;
num = data;

This is indirect conversion while direct conversion of variable is when we explicitly defines the data type. We usually use this method when a variable of larger capacity is be assigned to another variable of smaller capacity.

 

See the example below:

double data = 14; 
int num;
num = (int)data;

Notice that we have explicitly defined the type to be int because data was previously data type of double which has a larger capacity to of storage than int variable.

 

Summary

Variables are one of the important parts of any programming language. Their main function is to store different data and provides the stored data to the program whenever needed. In this tutorial, we learned about java variables. We almost cover everything that you need to know about java variables. We learned about the declaration, initialization, and syntax of variables.

Also, we covered different types of variables available in java along with solving real problems. Moreover, we also discussed how we can convert one data type variable to another data typed variable in java. In a conclusion, this tutorial covers all the information that you need to know about java variables.

 

Further Reading

Java variables
java variables documentation
more about java variables

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment