Categories: Java

Variables in Java

Variables represent named storage locations, whose values can be manipulated during the program run. For instance, to store the name of a student and marks of a student during a program run, we require storage locations that are too named so that these can be distinguished easily.

Declaration of variables:

The declaration of a variable generally takes the following form:

type variablename;

where,

type – is any Java data type

variablename – is the name of the variable. A variablename is an identifier.

example:

int age;
float percent;
double salary;
Initialization:

A simple variable definition does not provide a first value or initial value to the variable. A variable with a declared first value is said to be an initialised variable. Java supports two forms of variable initialization at the time of variable definition:

int val= 1001;

Here, va is initialized with first value of 1001.

Note: while naming variables, make sure to follow identifier naming rules and conventions.

Example:

class Example
{ 
  public static void main(String [] args){
    long hoursWorked=50;
    double payRate=40.0, tacRate=0.10;
    System.out.println("Hours Worked :"+hoursWorked);
    System.out.println("Payment Amount :"+(hoursWorked * payRate));
    System.out.println("Tax Payable :"+(hoursWorked*payRate*taxRate));
    }
}

output:

Hours Worked :50
Payment Amount :2000.0
Tax Payable :200.0

Note: also read about the Data Types in Java

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago