Variables of Java

Java Variables

Variables are containers that store information that can be manipulated and referenced later by the programmer within the code. Java variables have a data type associated with them which can tell us about the size and layout of the variable’s memory.

datatype variable = value
There are three types of comments:
  • Local variable
  • Instance variable
  • Class/static variable

Local variable

A variable which is declared inside the method is called local variable.Inside the method body, A local variable lies only within the method or constructor within which it is created and other methods in the class cannot access it.
Local variable is declared using the static keyword.

Example

public class LocalVariableEx {
    public void localVariable() {
      String name = "Tony";
      int marks = 99;
      System.out.println(name + " scored " + marks + "%.");
  }
            
public static void main(String[] args) {
    LocalVariableEx lve = new LocalVariableEx();
    lve.localVariable();
  }
}
          

Output

Tony scored 99%.

Instance variable

A variable which is declared inside the class but outside the method is called instance variable. It is not declared as static.It is similar to a static variable except that it is declared without using the keyword static. These variables are accessible by all methods or constructors that are inside the class.

Example

public class InstanceVariableEx {
    String name = "Vaigandla Durgesh";
    // Instance variable declaration
    
    public void Printname() {
        System.out.println("Name: " + name);
        // Accessing the instance variable
    }
    
    public static void main(String[] args) {
        InstanceVariableEx ive = new InstanceVariableEx();
        ive.Printname();
    }
  }

Output

Name: Vaigandla Durgesh

class/static variable

A variable which is declared as static is called static variable. It cannot be local, It is similar to a instance variable except that it is declared using the keyword static. These variables are accessible by all methods or constructors that are inside the class.

Example

public class StaticVariableEx {
    static int number = 14;
              
    public static void main(String[] args) {
        number++;
        System.out.println("Number: " + number);
    }
}
          

Output

Number: 15

Data types in Java

Data types in Java Data types represent the different values to be stored in the variable. There are two forms of Data types in Java.

Syntax of Java

Simple program in Java | Hello world Example We will create a file called Main.java and we use the following code to print "Hello learnwithvaigandla" to the screen.




Comments

Popular posts from this blog

Simple program in Java | Hello world Example

A Comprehensive Guide to Java and Its Applications: Exploring the Versatility of Java Programming

Features of JAVA