TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Variables in Java
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Java BasicJava Tutorials

Variables in Java

Last updated: Sep 12, 2023 2:25 am
By Meenakshi Agarwal
Share
7 Min Read
Java Variables Explained
How to use local, static, and instance variables in Java
SHARE

This tutorial covers another fundamental concept of Java, i.e., variables. It will help you learn how to define and use variables in Java programs.

Contents
What does a variable mean?Why should you use variables in Java?How to declare variables in Java?Local variableInstance variableStatic variable

The variables are the basic building blocks of every programming language. They are essential to implement business logic in the code.

Java Variables Explained
How to use local, static, and instance variables in Java

Learn to Use Variables in Java

The tutorial has the following sections to help you learn quickly.

What does a variable mean?

Variables, as the name suggests, can hold a particular value and can also accept modifications time in time out.

In terms of a programming language, a variable is a name pointing to a memory location.

In Java, one should define all the variables before using them.

Why should you use variables in Java?

Consider a scenario where you wish to do arithmetic calculations using a Java program. Assume, you did some initial calculations and came up with a numerical value.

You feed the value (say 1) into your Java program and use that value at about 100 lines in your code.

Now, you decide to re-check your calculations and realize that a blunder occurred at some point as the actual value was 0.5, not 1.

In this case, you can either go on changing the value at all 100 places from 1 to 0.5 or use a variable instead.

How to declare variables in Java?

To use a variable, you need to declare it first. And it is also quite straightforward:

int myVar;

There are a few thumb rules to note while you create a variable in Java.

  • First, never start a variable name with “_” or “$” symbols.
  • Ensure that the variable name makes sense in the context of the value you are storing in it.
  • Also, having multiple variables with the same name doesn’t work if they are in the same scope.

For declaring a variable, first, specify the keyword, i.e., the data type, and then type its name.

For example –

int value; // value is name of the variable and int is the keyword

The above is an un-initialized variable. You can also give a default value. See below.

int value = 0; // variable initialized with zero

boolean isOdd = true; // boolean variable set to true whereas its default value is false

char letter = 'J'; // variable to store characters

Until this point in time, three variables “value,” “isOdd,” and “letter” have entered in program’s memory.

learn to use local java variables

The variable “value” points to a memory location which the user can change to assign any value. Similarly, other variables also have memory allocated and can store specific values.

Must Read – Data types in Java

Types of variables

There are three major types of variables in Java:

Local variable

Any variable that appears inside a constructor, a method, or a block is a local one.

These types of variables incarnate whenever a constructor or a method or a block gets invoked and destroyed subsequently upon losing their scope.

The extent of these variables exists just inside the block in which they get used.

Below is a demo program using the local variables.

public class MyProgram
{
    public static void main(String[] args)
    {
        String myMessage; // local variable, has scope in the main function only.
        myMessage = "I'm learning Java.";
        System.out.println(myMessage);
    }
}

Executing the above code gives the following result:

I'm learning Java.

Instance variable

An instance variable is one that has its definition inside the class but outside any of its function, constructor, or block.

Please note that it is non-static and each object of the class will have its respective copy of the instance variable.

An instance variable gets allocated along with the class object and remains until the object persists.

In contrast to the local ones, you may apply appropriate access specifiers for these variables. If you don’t indicate any, then the default specifier will be used.

Below is a demo program using the instance variable.

public class Book
{
    public String name; // instance variable accessible to any child class.
    private String author; // instance variable accessible only in Book class.

    // Constructor method
    public Book(String value) {
        name = value;
    }

    // Class method to set the private instance variable
    public void setAuthor(String value) {
        author = value;
    }

    // Class method to get the private instance variable
    public void getAuthor() {
        System.out.println("Written by: " + author);
    }

    public static void main(String[] args)
    {
        Book first = new Book("Java");
        first.setAuthor("James Gosling");

        Book second = new Book("Python");
        second.setAuthor("Guido van Rossum");

        System.out.println("Book name: " + first.name);
        first.getAuthor();
        
        System.out.println("\n");

        System.out.println("Book name: " + second.name);
        second.getAuthor();
    }
}

Executing the above code gives the following result:

Book name: Java
Written by: James Gosling

Book name: Python
Written by: Guido van Rossum

Static variable

Static variables are otherwise called Class variables.

Similar to instance variables, they also have a definition at the class level. But they do differ in a way as we need to prefix the “Static” keyword to declare them. And each class object shares a single copy of them.

The static variables go live at the beginning of program execution and terminate when the application ends. To get to static variables, we don’t need to make any object of that class.

Check out the below program to get more clarity on the functionality of static variables.

// Java program to demonstrate the
// use of a static variable
public class StaticDemo
{
    static int counter = 0;

    // Constructor method incrementing the counter 
    // for every new object getting created
    public StaticDemo() 
    { 
        counter++;
    } 
  
    public static void main(String[] args) 
    { 
          StaticDemo static1 = new StaticDemo(); 
          StaticDemo static2 = new StaticDemo(); 
          StaticDemo static3 = new StaticDemo(); 

          System.out.println("Total objects created: " + counter);
    } 
}

Executing the above code gives the following result:

Total objects created: 3

You Might Also Like

A Simple Guide to Exception Handling in Java

Difference Between Spring and Spring Boot

How to Use Java String Format with Examples

Java IRC Bot with Sample Code

Generate Random Number in Java – 10 Ways

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Java Data Types Explained
Next Article Operators in Java

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x