Home >Java >javaTutorial >Variables in Java

Variables in Java

WBOY
WBOYOriginal
2024-08-30 15:10:381153browse

Variables are the basic units used to store any information in Java. The variable name is the name allotted for these units. A Java code may need information in the form of a numeric or a string value. The same set of values may be required in multiple stages of a code. This is where a variable comes into the picture.

All these required values can be assigned to different variables that will be stored in their respective memory locations; hence a variable is nothing but the name of a memory location. Storing values to variables is more efficient than repeating the values everywhere in the code. Also, it helps when there is a change in the value required, as just changing it at one place of the variable declaration will be sufficient rather than having to change at multiple locations.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Declaration of Variables

A variable cannot be used until and unless it is declared, and the datatype we assign during declaration defines the type of value it can hold. Various data types such as int, float, string, char, Boolean, long, double can be assigned to a variable.

The general syntax to declare a variable in Java is as follows:

Ex: int a = 1;

Where,

  • int – datatype
  • a – variable name
  • 1 – variable value

The following diagram gives the pictorial representation of the same:

Variables in Java

Initialization of Variables

Assigning a default value to the variable is called the initialization of that variable. A variable can be initialized both during declaration and during the later stages of the program as required. Examples: Following are some of the values we can assign to a variable with respect to its particular data type:

  •  int i; i=10;
  •  string city; city=”Bangalore”;
  •  char a; a=’H’;
  •  float dec; dec=3.5;
  •  Boolean val; val=true;

Types of Variables

There are 3 types of variables in Java:

  • Local Variable
  • Instance Variable
  • Static Variable

1. Local Variables

  • These are variables declared inside a particular method or block or constructor in which they are in.
  • Their variable value, which is stored during declaration, is valid only within the scope of that method and is lost when the method is exited.
  • A local variable with the same variable name can be declared in multiple methods or blocks without any conflict.

Example: In the following example, we are considering “num” and “name” as local variables. Code:

public class PatientDetails{
public void Patient()
{
// local variable num
//local variable name
int num = 1200;
string name = "Harish";
id = id + 1;
System.out.println("Patient Name is: " + name + " Patient Number is: " + num);
name = "Sudha";
System.out.println("Patient Name is: " + name + " Patient Number is: " + num);
}
public void DoctorDetails()
{
int num = 12000;
string name = "Vijay";
num = num +1;
System.out.println("Doctor Name is: " + name + " Doctor ID is: " + num);
name = "Suma";
System.out.println("Doctor Name is: " + name + " Doctor ID is: " + num);
}
public static void main(String args[])
{
PatientDetails pat = new PatientDetails();
pat. Patient();
pat.DoctorDetails();
}
}

Output:

The patient Name is: Harish
Patient Number is: 1200
The patient Name is: Sudha
Patient Number is: 1201
Doctor Name is: Vijay
Doctor ID is: 12000
Doctor Name is: Suma
Doctor ID is: 12001

This shows that the same local variable names “num” and “name” when declared in two different methods, i.e. Patient and DoctorDetails, can be used for assigning any number of different values.

Example:

The same local variables “num” and “name” will be invalid if we try to display their value outside of their method.

Code:

public class PatientDetails{
public void Patient()
{
// local variable num
//local variable name
int id = 1200;
}
public static void main(String args[])
{
System.out.println("Patient Number is: " + num);
//printing local variable outside it's method
}
}

Output:

Compilation Error in java code:-
prog.java:12: error: cannot find symbol
System.out.println(“Patient Number is: ” + num);
^
symbol: variable num
location: class PatientDetails
1 error

2. Instance Variables

  • Instance variables are those which are declared inside a class and not within any method.
  • They are created when an object is created, and their value is lost when the object is destroyed.
  • Initialization of these variables is not mandatory, and by default, the value is taken as zero.
  • They are non-static variables, meaning the variable’s memory will be allocated whenever a new object is created.

Example:

Here a, b, c are the instance variables that are declared in two different instances by two different objects.

Code:

import java.io.*;
class Marks {
// a, b, c are instance variables
// a, b, c variables are being declared inside a class and not function
int a;
int b;
int c;
}
class MarksDemo {
public static void main(String args[])
{
// first object declaration
Alpha alp1 = new Alpha();
alp1 .a= 44;
alp1 .b= 77;
alp1 .c= 88;
// second object declaration
Alpha alp2 = new Alpha();
alp2 .a= 77;
alp2 .b= 55;
alp2 .c= 74;
// displaying variable values for first object
System.out.println("Values for first object:");
System.out.println(alp1.a);
System.out.println(alp1.b);
System.out.println(alp1.c);
// displaying variable values for second object
System.out.println("Values for second object:");
System.out.println(alp2.a);
System.out.println(alp2.b);
System.out.println(alp2.c);
}
}

Output:

Values for the first object:
44
77
88
Values for the second object:
77
55
74

3. Static Variables

  • Static variables are declared at the beginning of the program, preceded by the static keyword.
  • Like instance variables, the initialization of static variables is not mandatory, and their default value is 0.
  • Only one static variable name will be created when the program is started and lost when execution has ended.
  • The memory for these variables is allocated only once at the time of loading the class and can be shared by multiple objects.
  • When the objects are different, the changes made in the value of the static variable in one of the objects will be reflected in all unlike instance variables where the values declared in one object will not be reflected in others.

Example:

Code:

import java.io.*;
class Students {
//static variable rollno
public static double rollno;
public static String name = "Lilly";
public static classnum;
}
public class StudentDetails {
public static void main(String args[])
}
{
// no need of object to access static variables
Students .rollno= 101;
Students.classnum=3;
System.out.println(Students .name + "'s rollno is:" + Students .rollno + "and class number is:" + Students.classnum);
}
}

Output:

Lilly’s rollno is 101, and the class number is: 3

Conclusion – Variables in Java

Variables form the elemental part of a Java program. They point to a particular memory location when they are created, and the same is released when the object is not referenced anymore. This memory which is released, will be swept away when garbage collection takes place. This process can also be considered as the life cycle of a variable.

The above is the detailed content of Variables in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Default Package in JavaNext article:Default Package in Java