ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

How to use Variables in Java ?.

Updated on September 17, 2014

Introduction

Java is a powerful programming language. It has numerous features which makes it most popular programming language of the world. In this tutorial, you will learn how to use variables in Java. Variables are important in any programming language. Variables are the temporary place holders used to store values in a program. It can be modified or used later in the program. Variables is nothing but a named location in memory. This memory location is used to store values of the programs that can be modified by programming instructions. It is been termed as variable because its values can be changed later in the program.

There are few things which make up and create a variable, such as a name, a data type, a size and a value.

How to define a variable ?.

A Variable contains a name, datatype, size and value. In order to define a variable we have to follow syntax such as :

<Datatype> <Name>;

For example :

  • int age; (Here, int is the datatype and age is name of variable).
  • String description; (Here, String is the datatype and description is name of variable).

As Java is strongly typed language we have to provide a datatype to define a variable. If we don't provide a datatype to a variable compiler will throw a compile time error.

Video tutorial - How to use Variables in Java.

How to define and initialize a Variable in Java ?.

The second form to define a variable is as follows :

<Datatype> <Name> = <Value>;

For example :

  • int age = 45; (Here, int is the datatype, age is name of variable and 45 is the value assigned to variable). It creates a memory location in computer by name age and assign a value 45 to it. So that now age is a place holder for that value.
  • String description = "He is a good programmer"; (Here, String is the datatype, description is name of variable and "He is a good programmer" is the value assigned to variable). It creates a memory location in computer by name description and assign a value "He is a good programmer" to it. So that now descrption is a place holder for that value.

The size depends on the datatype, such as int can have 32 bit, byte can have 8 bits etc. The size tells compiler that variable can take only a particular range of a value. The size of a variable make it easy to be used in situations where size matters.

Instead defining multiple variables one after other, Java also provides a way to define multiple variables simultaneously. So, defining multiple variables simultaneously is a good practice in Java. Lets take an example for this important way to define variables in Java.

int a ;

int b ;

int c;

Instead doing above things in multiple lines, we can perform all these steps in a single step such as :

int a, b, c ;

Java also provides a way to initialize multiple variables simultaneously. Lets look into an example :

int a = 4 ;

int b = 4 ;

above variables can also be initialized simultaneously as :

int a ;

int b = a = 4 ;

Here, both the variables a and b are initialized simultaneously together with a value 4.

public class Variables {
	
	int a;
	int b;
	int c;
	
	// can be written as : 
	// int a , b , c;
	
	int d = 4;
	int e = 4;
	
	// can be written as : 
	// int d;
	// int e = d = 4;
}

Source code - Variables in Java

public class VariablesDemo {

	public static void main(String[] args) {

		// <Datatype> <Name>;
		int age;
		String description; 
		
		// <Datatype> <Name> = <Value>;
		int count = 10;
		String firstName = "Sachin";
		
		System.out.println("The value stored in count is : " + count );
		System.out.println("The value stored in firstName is : " + firstName );
		
		int number1 = 4;
		int number2 = 5;
		
		int sum = number1 + number2;
		
		System.out.println("The value stored in sum is : " + sum);		
		
	}
}

Output of the program -

The value stored in count is : 10
The value stored in firstName is : Sachin
The value stored in sum is : 9

Constant variables in Java.

In Java there are also variables which remain constant. By constant we mean that once assigned a value, there values cannot be modified in the program. A constant variable is been marked with a Java keyword as final. After making a variable final Java treats it differently. A variable marked as final and its value is changed later, a compile time error is thrown. Some of the examples are as follows :

final int age = 5;

final String description = "He is good".

Static variables in Java

In Java there are also variables which can be marked as static variables. Static variables makes variable belong to a class. It can only be accessed through a class to which it belong. Static variables can be marked as static through static keyword. Any variable marked with keyword static belong to a particular class.

For example :

static int age;

static int age = 35;

Here, age belongs to a class in which they are declared and can be accessed by it.

static and final variables in Java

public class Variables {

	// final age variable once assigned a value cannot be 
	// modified later.
	final int age = 45;
	
	// static variable welcome belongs to class Variables
	// and can be accessed by it. 
	static String welcome = "Welcome to Java"; 
	
}

Identifiers in Java

The name provided to the variables is been decided by the identifiers in Java. Identifiers in Java are nothing but names given to variables based on some rules. Below is the video tutorial which demonstrate how to name these variables based on some rules. Some of the rules are as follows :

  1. Identifiers should not be named by reserved keywords in Java. Some of the keywords are int, boolean, class etc.
  2. Identifiers should not start with a number.
  3. Identifiers first letter should start with a character, underscore. Digits can be used there after.
  4. Capital letters should be used to separate two words.
  5. Java identifiers are case - sensitive in nature. For example - birthday , Birthday and BIRTHDAY are three different identifiers in Java.
  6. Usage of dollar sigh or any currency symbols should not be used in naming an identifier.

Video tutorial - Identifiers in Java

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)