×

Java Variable Declaration

In this article, you will be acknowledged about java variable declaration. You will be able to learn and interpret about declaring a variable in Java.

Variable in Java

Variables are necessary for the Java programming language to function and manage data. According to the file formats and data types, Java creates a variety of variables. Declaring a variable inside a program involves setting it up to operate various pieces of information.

A variable in Java is in fact a data container that stores data values while a Java application is running. Each variable is given a data type that describes the types and numbers of elements it can hold. The address of a memory location for data is called a variable.

A new variable with the necessary characteristics is created by the Java variable declaration. To define a variable in a program, you need four fundamental components according to the programming language.

  • Data-type
  • Variable name
  • initial value
  • Semicolon

Data-Type:

It displays the type of variable value.

Variable name:

A unique name must be used when declaring a variable in Java. People recommend to declare variables with short, simple names.

Initial value:

The variable's initial value is necessary in Java. It is not necessary to declare a variable with an initial value inside the main class. The default constructor must be used to assign the starting value. The initial value must be declared in the "final variable."

Semicolon:

The variable creation statement comes to a close with the semicolon.

Declaring Variable

In Java, there are two methods for declaring variables. Assigning the variable's initial value is the first strategy. Variables are declared using the second technique without an initial value.

Establish a variable and set its initial value.

The syntax would be as follows

Data-type  variable_name = value;

With the help of the provided variable, we initialize the data, which is then produced. The class's default method is affected by the declaration method.

Let us understand it with the example program

File name: WithIn

public class WithIn {  
    public static void main(String[] args)   
{  
        int z = 22;  
        String a = "Zack";  
        double c = 3.14;  
        Boolean k = false;  
        System.out.println("Name:" +a+ "\nAge:" +z);  
        System.out.println("Number:" +c+ "\nBoolean:" +k);  
    }  
}  

Output

Name: Zack
Age: 22
Number: 3.14
Boolean: false

Establish a Variable without an Initial Value

The syntax would be as follow

Data-type variable_name;

Data does not need to be initialized with the specified variable. In any method, assign a value and output that value. Within and outside from the standard method, the declaration method is functional. Inside the class's default method, every variable data is displayed.

Let us understand it with basic example programs

File name: WithoutIn.java

public class WithoutIn.java {  
    public static void main(String[] args) {  
        int z;  
        String a;  
        double c;  
        Boolean k;  
        float s;  
        z = 23;  
        a = "Edmund";  
        c = 45.22;  
        k = true;  
        s= 7.3f;  
        System.out.println( "Name:" +a + "\n Age:" +z);  
        System.out.println( "Number:" +c+ "\n Boolean:" +k);  
        System.out.println( "float:"  +s);  
    }  
}  

Output

Name: Edmund
Age: 23
Number: 45.22
Boolean: true
float: 7.3f 

Different types of variables in Java

In java, basically there exist three types of variables. They namely are:

  • Local Variable
  • Static Variable
  • Instance Variable

Local Variable

A local variable is one that is defined inside a block, method, or method constructor. These variables are generated when the block or the method is called, and they are destroyed when the block or just the method is called again. These variables are only accessible inside the block during which they have been defined since their scope only extends to that block. Before accessing the local variable within the defined scope, it must first be established.

Let us go through the example program to understand this.

File name: Declocal.java

import java.io.*;
class Declocal {
public static void main(String[] args)
{
int var = 100; // Now this is a local variable
System.out.println("The Local Variable: " + var);
}
}

Output

The Local Variable: 100

Instance Variable

Non-static instance variables are declared outside of every method, method constructor, or block of a class. Instance variables are generated when a class object is formed and eliminated when the object is terminated since they are defined in a class. We can implement access specifiers with instance variables, unlike local variables. The basic access specifier would be applied if no access specifier is specified. An instance variable does not need to be initialized. The default setting is 0. Only by constructing objects can one access instance variables.

Let us go through the example program to understand this.

File name: Decinstance.java

import java.io.*;
class  Decinstance {
                  public int f; // The instance variable is declared here
                   public Decinstance()// This is the default constructor
{ 
this.f = 99; 
}
public static void main(String[] args)
{
Decinstance d = new Decinstance();
System.out.println("One less than hundred is: " + d.f);
}
}

Output

One less than hundred is: 99

Static Variables

Class variables are another name for static variables. As instance variables, these variables are similarly specified. Static variables, on the other hand, are declared within a class using the static keyword, but outside of any function, constructor, or block. However, we are only permitted to only have single instance of such a static variable per class, irrespective of the number instances we make. At the start of execution of a program, static variables are defined, and they are promptly removed when it is finished. Initializing static variables is not necessary. 0 is the default setting. The compiler will display a warning message if we attempt to reach the static variable like that of an object instance (via an object), but the program won't crash.

Let us understand it with an example program

File name: Decstatic.java

import java.io.*;
class Decstatic{
public static String ztr = "Lift the call!!"; //The static variable is declared here
public static void main (String[] args) {
System.out.println("Geek Name is : "+Decstatic.ztr);
}
}

Output

Lift the call!!

Instance Variable and Static Variables

Instance variables and static variables have different properties.

  • While we cannot have more than one instance of a static variable each class, regardless of how many instances we generate, each object will possess its own duplicate of an instance variable.
  • Because each object has a unique copy of a instance variable, changes made to one object's instance variable will not be recognized in modifications made to other objects. Since static variables are shared by all objects in a class, changes made to one object will be mirrored in all other objects as well.
  • Through object references, we can get to instance variables, and the class name gives us direct access to static variables.

Declaration of variable in java using parameterize method

Make a variable using the default way, then parameterize it. Here, a variable can be declared as a parameter in the method. Assign a value to the method, then output that value.

  • In the procedure that was altered, create variables.
  • Variable return in the method.
  • Set up a value's default method of initialization.
  • Due to the format of the arguments, the variable declaration doesn't really require a semicolon.

Uniform data type variables of the same name are created through Java variable declaration. Let us understand it with a simple example program.

File name: Parmethod.java

public class Parmethod {  
    public void methdta(int sdt_id, String sdt_name){        
        System.out.println("ID Number:" +student_id);  
        System.out.println("Name:" +student_name);  
    }  
    public static void main(String[] args) {  
             Parmethod s = new Parmethod();  
             s.methdta(68, "Rebecca");  
    }  
}  

Output

ID Number: 68
Name: Rebecca

Java requires non-primitive values for variable declaration. Variables are required by Java for functions like class, array, interfaces, and others. In order to allocate memory and store data, the array needed a variable.

Let us understand it with a basic example program

File name: Arrvariable.java

public class ArrVariable {  
   public static void main(String[] args) {  
// Declaring the variables in array with the indication of array size and its index  numbers
        int arr[]=new int[5];   // Set the variable name as well as index as the data's initial                                                                          //values.
        arr[0]=50;  // As needed, display the variable data.
        arr[1]=100;    
        arr[2]=150;    
        arr[3]=200;
        arr[4]= 250;    
        for(int i=0;v1<arr.length;i++)   
        System.out.println(arr[i]);  
    }  
}  

Output

50
100
150
200
250

Conclusion

Declaring variables in Java takes up memory and produces variables. The variable specifies values that are unstable or subject to change. Basic Java encapsulation, interfaces, classes, as well as methods are used in the variable definition. In every method of a Java code, variables are declared and used.


Related Topics

Big Decimal class in Java

The fairly Big pretty Decimal class provides operations for arithmetic, rounding, comparison and format conversion in a sort of big way. It can handle generally large and very small floating-point...

6 minutes read.

How to Convert String to char in Java

How to Convert String to char in Java There are two methods to convert String to char are: Using charAt() method Using tocharArray() method Using charAt() method This is the method of String class that...

3 minutes read.

JRE (Java Runtime Environment)

JRE is an installation package that provides an environment to run the Java program on any Operating System. It does not deal with the development process of any application. It is a part...

2 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Java program to determine whether all leaves are at same level

In this program, we must determine whether or not all of the binary tree's leaves are at the same level. If a node has no child nodes, it is said to...

3 minutes read.

Java String join() method

Java String join() method returns a joined String with given delimiter Syntax: public static String join(CharSequence delimeter,charSequence...elements) public static String join(CharSequence delimeter,Iterable<?extens charSequence>elements) Parameters: delimiter: char value to be added with each element elements: char value...

1 minute read.

Interleaving string in Java

If the string Str3 contains all of the characters from Str1 and Str2, it is considered interleaving Str1 and Str2. Keep in mind that the order of all characters in...

5 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Compile time vs Runtime in java

Introduction: This article will discuss compile time vs. runtime in java. Compile time and runtime are two programming terms utilized in software improvement. Compile time is when the source code is...

3 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 minutes read.

Constructor in Java with Example

Java Constructor  The constructor is used for object initialization. It's a block of code that initializes a newly created object. It contains a collection of statements that are executed at the...

5 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.