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

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

1 week ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

1 week ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

2 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

2 weeks ago

Job Scheduler Implementation

Design a job scheduler that accepts a function f and an integer n. The scheduler…

2 weeks ago

Largest Sum of Non-Adjacent Numbers

Problem Statement (Asked By Airbnb) Given a list of integers, write a function to compute…

2 weeks ago