Variables in Java

Welcome back to the Java tutorials. In the last session we focused on different types of data types available in Java. We briefly discussed both the primitive data types as well as non-primitive data types.

Coming back to the current tutorial, today we would discuss about the various types of variables that a user can create in Java. We would talk about the local variables, class variables and instance variables. We would also look at their practical implementations.




Our classes are usually made up data members and the methods to manipulate them. Variables are used as identifiers to store the data which can be exploited and manipulated using methods. As we discussed the various data types in our last tutorial, so each of the variable belongs to a specific data type and that is how we get to know the memory allocated, size, type and the bunch of the operations that can be performed on the data that can be stored in the variable.

Examples:

To be able to perform any operation on the data, we must declare and initialize them using variables. Hence from the above examples, we can come up with the variable declaration and initialization syntax.

Syntax:

data type variable_name = value;

Java provides three types of variables:

  • Local Variables
  • Class Variables
  • Instance Variables

Let us quickly have a look at each one of them.

Local Variables

1

Note: Compiler doesn’t provide any default value to the local variables. Thus, the user is essentially required to initialize the local variables prior to their usage.

Example

Output:

The value of sum is: 27

Class Variables

2

Default Values for Class Variables:

Untitled

Example:




Output:

Shruti’s roll no is: 58

Instance Variables

3

Example:

Output:

name is: Shruti

Rollno is: 59

With this, we come to an end of this tutorial. Stay tuned for the upcoming tutorials. We will keep posting more of the useful stuff on Java. Do share your reviews, comment and queries.

Read Similar Posts



Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.