Constant and variable in java

Difference between constant and variable in java

differnce between the constant and variable in java

In this article, we learn about the difference between constant and variable.

Constant:

Constant, refers to a fixed value that doesn’t change during the execution of a program. The value of constants appears right in a program. Literals is another name of constant. We use the constants to create values that assign to variables. Constants can make our program easy to read and understood by others.

Point to remember

The name of the identifier should be in capital letters that we want to declare as constant. For example,

  • As we use the private access-specifier before the constants name. At that point, we can’t change the value of the constant of that particular class.
  • And if we use the public access-specifier before the constants name. In the program, the value of the constant can be change.

How to define constant

Java does not directly support the constant. To define a variable as a constant, We use the “Static” and “Final” Keywords before declaring a variable. Scope of the constant can b local and can be global.

Constant declared as private:

import java.util.Scanner; public class ConstantExample1 < //declaring constant private static final double PRICE=234.90; public static void main(String[] args) < int unit; double total_bill; System.out.print("Enter the number of units you have used: "); Scanner sc=new Scanner(System.in); unit=sc.nextInt(); total_bill=PRICE*unit; System.out.println("The total amount you have to deposit is: "+total_bill); >> 

AS a result:

Constant declared as public:

In the above example, We declare a constant PI as public. Inside the main() method, we have assigned 3.14 in the constants PI. After that, we have invoked the printValue() method. When we execute the program, it throws an error that cannot assign a value to the final variable PI

 public class < //declaring PI as constant public static final double PI= 3.14; public static void main(String[] args) < printValue(); //trying to assign 3.15 in the constant PI PI = 3.15; printValue(); >void printValue() < System.out.print("The value of PI cannot be changed to " + PI); >> 

As a result:

Variable

A variable is an identifier that provides a storage location used to store a data value. The data stored at a particular location in memory. That we accessed by using the variable name.
A variable is a symbolic name given to a location in the computer memory. Where we store the value, which can be used in the program. The value of the variable can change during the execution of the program. It may take different values at different times during the execution of the program.
The name of the variable that we choose must be meaningful to understand, what it represents in the program.

There are three types of variables in Java:

Local Variables:

Local variables are variables that, defined within the function. The scope of this is local. This means you only can use the local variable within the functions that define them.

public class StudentDetails < public void StudentAge() < // local variable age int age = 0; age = age + 5; System.out.println("Student age is : " + age); >public static void main(String args[]) < StudentDetails obj = new StudentDetails(); obj.StudentAge(); >>

As a result:

Читайте также:  Python проверить вхождение строки

Instance Variable:

Instance variables are non-static variables . They are declared in a class outside any method, constructor or block.

import java.io.*; class Marks < // These variables are instance variables. // These variables are in a class // and are not inside any function int engMarks; int mathsMarks; int phyMarks; >class MarksDemo < public static void main(String args[]) < // first object Marks obj1 = new Marks(); obj1.engMarks = 50; obj1.mathsMarks = 80; obj1.phyMarks = 90; // second object Marks obj2 = new Marks(); obj2.engMarks = 80; obj2.mathsMarks = 60; obj2.phyMarks = 85; // displaying marks for first object System.out.println("Marks for first object:"); System.out.println(obj1.engMarks); System.out.println(obj1.mathsMarks); System.out.println(obj1.phyMarks); // displaying marks for second object System.out.println("Marks for second object:"); System.out.println(obj2.engMarks); System.out.println(obj2.mathsMarks); System.out.println(obj2.phyMarks); >> 

As a result:

Marks for first object: 50 80 90 Marks for second object: 80 60 85

Static Variables:

Static variables are also called as Class variables. These variables are declared similarly as instance variables. The difference is that static keyword is used to declare a static variable within a class outside any method constructor or block.

import java.io.*; class Emp < // static variable salary public static double salary; public static String name = "Harsh"; >public class EmpDemo < public static void main(String args[]) < // accessing static variable without object Emp.salary = 1000; System.out.println(Emp.name + "'s average salary:" + Emp.salary); >>

As a result:

Harsh's average salary:1000.0

Difference between constant and variable

Constant Variables
Constant has fixed value that doesn’t change during the execution of a program The value of the variable can change during the execution of the program
Constants are usually written in numbers. Variables are specially written in letters or symbols.
Constants usually represent the known values in an equation, expression or in line of programming. Variables, on the other hand, represent the unknown values.
Constants are used in computer programming. Variables also have its uses in computer programming and applications.

Источник

Java Variables & Constants Tutorial

In this Java tutorial we learn about variables and constants and how they store temporary data while the program runs.

We discuss how to declare or initialize variables and constants, how to use them and change variable values.

Finally, we look at operands in Java, lvalues and rvalues.

  • What is a variable
  • Variable types in Java
  • How to declare a variable in Java
  • How to assign a value to a variable in Java
  • How to initialize a variable with a value in Java
  • How to declare/initialize multiple variables inline in Java
  • How to use a variable in Java
  • How to change a variable’s value in Java
  • What is a constant
  • How to initialize a constant in Java
  • Java operands: lvalues and rvalues
  • Examples of common variable data types in Java
  • Summary: Points to remember

What is a variable

A variable is a temporary data container that stores a value in memory while the application is running.

As an example, let’s consider a calculator program.

When we perform an addition for example, the app stores the result in a variable that we can use to perform any additional calculations we need.

In the example above, the letters ‘x’ and ‘y’ store the resulting data from the arithmetic.

Variables are used all over our apps to store runtime data. When the app is closed, or the variable is no longer used by the program, the value in memory is removed.

Читайте также:  Сколько памяти занимает массив java

Variable types in Java

There are three types of variables in java:

1. A local variable is defined within a function, or method. It’s local to that function’s scope.

2. An instance variable is defined within a class, but outside of a class method. It’s local to the object (an instance of a class).

3. A static variable is a non-local variable that can be shared among all instances of a class (objects).

In this tutorial, to keep things simple, we will cover local variables inside the ‘main()’ function.

We won’t cover functions in this tutorial. For the moment you don’t have to worry about the ‘main’ function or the class it’s in.

How to declare a variable in Java

To declare a variable, we specify its data type, followed by a name and a semicolon to terminate the statement.

 The data type simply tells the compiler what type of value will be stored in the variable.

We cover all the data types available in Java in the lesson on Data Types .

 In the example above, we declare a variable with the name ‘num’ that can store integers (whole numbers).

Our variable doesn’t have any data inside it yet, we just reserved space in memory for it.

How to assign a value to a variable in Java

To assign data to a variable, we specify the name of the variable, then the assignment operator = , followed by a value that matches the data type.

  We only use the data type when we’re declaring or initializing the variable, not when assigning or changing a value.
  In the example above, we assign the value of 5 to the variable ‘num’.

The statement reads: variable ‘num’ has value of 5

How to initialize a variable with a value in Java

We will often know the value we want to assign to the variable beforehand, so we can use initialization syntax to declare a variable and assign a value to it at the same time.

To do this we simply combine the declaration and assignment together.

 In the example above, we initialize a new variable with the value of 5.

How to declare/initialize multiple variables inline in Java

We can declare or initialize multiple variables of the same type at the same time in Java.

To do this we separate each variable name with a comma. If we initialize them, we assign the value after each variable name.

  Note that the elipses (…) only indicate that more variables can be declared/initialized this way. It’s not included in the syntax.
   In the example above, we initialize three integer variables with separate values inline.

How to use a variable in Java

To use a variable, we simply specify its name wherever we need to use it in our code.

   In the example above, we mutate the ‘result’ variable’s value in the second arithmetic and print it to the console. Then, we mutate it again by manually assigning a new value to it.
5 + 3 = 8 5 * 3 = 15 New value: -1

We cannot mutate a variable with just any other type of value than it was declared with.

For example, we can’t assign a string value to variable above, it would raise (generate) an error.

  When we try to run the example above, the compiler raises a ‘mismatch type’ error.
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from String to int

The compiler couldn’t typecast the string into a number. We can only convert certain types into certain other types.

We discuss typecasting in the lesson on Data Types .

What is a constant

A constant is a variable that cannot have it’s value changed during runtime.

We use constants when we do not want a value to accidentally change, like the value of Pi, or gravity.

How to initialize a constant in Java

A constant cannot be declared without a value, because a value cannot be assigned later on. There would also be no point to an empty constant.

To initialize a constant with a value, we use the final keyword in front of the data type.

 As mentioned in the Basic Syntax lesson , the convention for naming constants is uppercase words with underscores as word separators (uppercase snake).
 In the example above, we specify that ‘PI’ is final, it cannot have its value changed at runtime.

If we try to mutate the constant, the compiler will raise an error.

Java has two types of expressions, lvalues and rvalues.

The operand on the left side of the assignment operator ( = ) is the Lvalue, and the operand on the right side is the Rvalue.

An Lvalue can have a value assigned to it so it’s allowed to appear either on the left or the right side of an assignment.

An rvalue cannot have a value assigned to it so it may only appear on the right side of an assignment.

The following quick example shows some popular types of variables we can create.

Источник

Оцените статью