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

What is object oriented design patterns

A design pattern is a reusable solution to a commonly occurring problem in software design. They…

4 months ago

Factory Method Design Pattern in OODP

Factory Method is a creational design pattern that deals with the object creation. It separates…

4 months ago

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

10 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

10 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

10 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

11 months ago