Java Variables

In this post you will learn about Java variables.

What is a Java Variable?
  • A variable can be called as a container which holds some value in a java program. 
  • Variable has assigned a data type which defines what type of value variable can hold.
  • Variable has a name which locates to the memory.
  • If you want to use variable in a program, there are two steps associated with it you have to perform:
    • Variable Declaration
    • Variable Initialization
i. Variable Declaration
While declaring a variable you have to assign data type with variable name. Variable name has to be unique.

Example: String employee;


ii. Variable Initialization
It means assigning a value to the declared variable.

Example: employee = "John"



Above two steps (declaration and initialization) can also be joined together in one single step.

Example: String employee = "John";

Let's explain above example, 
  • 'String' is data type
  • 'employee' is name of variable
  • "John" is value assigned to variable named employee.



Types of Variables
Java has three types of variables:
  1. Local Variables
  2. Instance Variables
  3. Static Variables
1. Local Variables - Variable that is declared inside a method is local variable. These variables can only be used within that method as their scope lies only inside that method.

2. Instance Variables - Variable that is declared outside of method but inside class is called instance variable. It is not declared as static.

3. Static Variables - Variable which is declared with keyword 'static' and outside the method is called static variable. Static variables are allocated memory when class is loaded in memory. Static variables initialized before instance variables.

Code Example for Java Variable Types:

package com.techlistic.java;

public class JavaVaribales {
 
 // Instance Variables
 int x = 15;
 
 
 // Static Variables
 static String message = "Hello World!";
 
 
 // Main Method
 public static void main(String[] args) {
  
  // Local variables
  int a = 10; 
  int b = 20;
  
  // Some code here
  // ---------
  // ---------
 }
 
 
 // Method
 void myMethod() {

  // Local Variables
  char ch = 'i';
  float num = (float) 1.5;

 }

}



First Java Program  << Previous     ||     Next >>  Java Data Types



Click here to find complete Java Tutorials Series

Author: Vaneesh Behl
Subscribe FB Group Techlistic on FB
Join Telegram channel at https://t.me/techlistic
Feel free to ask queries or share your thoughts in comments or email me.

Comments

Popular Posts

Top 10 Demo Websites to Practice Selenium Webdriver Online

Future of Selenium Automation Testing as a Career Option

How to learn Selenium Webdriver on your own online

Selenium WebDriver - Take Screenshot and Partial Screenshot Commands

Selenium Webdriver - Overview & Features