What are variables in java programming

Variables In Java Programming

In this post, we will look at Variables in Java Programming. It is an essential topic that will provide an insight into how a user stores and handles the data in the computer’s memory to use it efficiently.

So, we will cover everything from the definition to the declaration and the different types of variables in java.

What are variables in java?

In Java, variables are nothing but a named memory location. Variables in java stores values of elements while the program executes. All operations done on the variable affects the memory location.

Simply put, Variables are helpful to programmers to handle data that can be manipulated by the program during execution as well. Variables in java are Strongly typed ; hence they all must have a datatype followed by an identifier.

Each variable has a specific Data Type that defines the size and layout of the variable’s memory.

How to Declare a Variable?

We can declare a variable as below:

variable declaration

💡 Did you know?

Assigning value is optional while declaring variables. You can declare variable and assign value to it later in program.

Variable has a name that is used to identify it. The name of the variable is known as the variable’s identifier.

There are some naming conventions that you need to follow while declaring a variable.

  • You can use A to Z or a to z .
  • You can use 0 to 9.
  • You can use special symbol $ and _ to declare a variable.
  • You can not start a variable name with number.
  • You can not have spaces in variable name.
  • You can not use reserved keywords in variable name.
  • Variables names are case sensitive.

You can declare variables in groups as well like this:

How to Initialize Variables?

Each variable holds some data which it describes. We use = operator to assign value to a variable.

Compiler will give compile time error if value does not match with the datatype of the variable.
For example:
You can not assign String literal to int data type.

Let’s understand it with the help of simple program:

When you run above program, you will get the below Output:

What are the different types of variables in java?

There are majorly three Types of Variables in use in Java Programming.

Let’s have a look at each type in detail with some examples.

Local variable

A variable declared inside a method or a block is termed a Local Variable. In Java, Local Variables can also be declared in a block within a method surrounded by curly braces; such variables are known as Block Level Local Variables .

In such a case, the scope of the variable, both in terms of its access and the presence of the variable in the memory, will be valid throughout the block only and not through the entire program. We will understand this with an example.

Note: It is mandatory to initialize the local variables; otherwise, the compiler will throw an error about it. Moreover, we cannot have Keywords like public, private, static associated with Local Variables.

Instance variable

A variable declared at the class level but outside a method or a block is an Instance variable. It is not mandatory to initialize instance variables. Instead, an Instance variable in Java is initialized when an instance of the class or an object is created.

All instance variables will be, by default, initialized by JVM. While allocating space for an object, a slot for each Instance Variable is also created. Thus, we can say Instance Variables are present in memory until the object’s lifetime and are visible to all methods and blocks in the class.

We can use Keywords and Access Modifiers with Instance Variables to restrict the visibility of the variables. Let us understand the use of instance variable with example.

To access the value in the main method, we had to create the object or instance of the Class InstanceDemo; then, we used the dot operator with the object name to access the variable.

If we had accessed it directly without creating the object, the compiler would throw an error: non-static variable g cannot be referenced from a static context . This error means that the main method is static, and we cannot access a non-static variable from a static method. It is mandatory to instantiate the class in this case.

Static variable

A variable that is declared as static and refers to shared property for all class objects is known as a Static variable. Static variables are also class-level variables that can be declared in a method but only in a Static Method . We cannot declare static variables inside a Static Block.

Static Variables in Java make the program memory efficient as static variables get memory allocation only once during class loading. In simple words, all objects of a class will share the same static variable or properties.

Even if we create multiple objects or instances, static members are created only once. The static keyword denotes that a property belongs to the whole class rather than a method. Like Instance variables, Static members are also by default initialized by JVM. Let us understand the use of static variables with an example.

Источник

Variables

As you learned in the previous lesson, an object stores its state in fields.

int cadence = 0; int speed = 0; int gear = 1;

The What Is an Object? discussion introduced you to fields, but you probably have still a few questions, such as: What are the rules and conventions for naming a field? Besides int , what other data types are there? Do fields have to be initialized when they are declared? Are fields assigned a default value if they are not explicitly initialized? We’ll explore the answers to such questions in this lesson, but before we do, there are a few technical distinctions you must first become aware of. In the Java programming language, the terms «field» and «variable» are both used; this is a common source of confusion among new developers, since both often seem to refer to the same thing.

The Java programming language defines the following kinds of variables:

  • Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in «non-static fields», that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another.
  • Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change.
  • Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0; ). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.
  • Parameters You’ve already seen examples of parameters, both in the Bicycle class and in the main method of the «Hello World!» application. Recall that the signature for the main method is public static void main(String[] args) . Here, the args variable is the parameter to this method. The important thing to remember is that parameters are always classified as «variables» not «fields». This applies to other parameter-accepting constructs as well (such as constructors and exception handlers) that you’ll learn about later in the tutorial.

Having said that, the remainder of this tutorial uses the following general guidelines when discussing fields and variables. If we are talking about «fields in general» (excluding local variables and parameters), we may simply say «fields». If the discussion applies to «all of the above», we may simply say «variables». If the context calls for a distinction, we will use specific terms (static field, local variables, etc.) as appropriate. You may also occasionally see the term «member» used as well. A type’s fields, methods, and nested types are collectively called its members.

Naming

  • Variable names are case-sensitive. A variable’s name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign » $ «, or the underscore character » _ «. The convention, however, is to always begin your variable names with a letter, not » $ » or » _ «. Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it’s technically legal to begin your variable’s name with » _ «, this practice is discouraged. White space is not permitted.
  • Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence , speed , and gear , for example, are much more intuitive than abbreviated versions, such as s , c , and g . Also keep in mind that the name you choose must not be a keyword or reserved word.
  • If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6 , the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

Источник

Java Variables

In Java, there are different types of variables, for example:

  • String — stores text, such as «Hello». String values are surrounded by double quotes
  • int — stores integers (whole numbers), without decimals, such as 123 or -123
  • float — stores floating point numbers, with decimals, such as 19.99 or -19.99
  • char — stores single characters, such as ‘a’ or ‘B’. Char values are surrounded by single quotes
  • boolean — stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

Syntax

Where type is one of Java’s types (such as int or String ), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.

To create a variable that should store text, look at the following example:

Example

Create a variable called name of type String and assign it the value «John«:

String name = "John"; System.out.println(name); 

To create a variable that should store a number, look at the following example:

Example

Create a variable called myNum of type int and assign it the value 15:

int myNum = 15; System.out.println(myNum); 

You can also declare a variable without assigning the value, and assign the value later:

Example

int myNum; myNum = 15; System.out.println(myNum); 

Note that if you assign a new value to an existing variable, it will overwrite the previous value:

Example

Change the value of myNum from 15 to 20 :

int myNum = 15; myNum = 20; // myNum is now 20 System.out.println(myNum); 

Final Variables

If you don’t want others (or yourself) to overwrite existing values, use the final keyword (this will declare the variable as «final» or «constant», which means unchangeable and read-only):

Example

final int myNum = 15; myNum = 20; // will generate an error: cannot assign a value to a final variable 

Other Types

A demonstration of how to declare variables of other types:

Example

int myNum = 5; float myFloatNum = 5.99f; char myLetter = 'D'; boolean myBool = true; String myText = "Hello"; 

You will learn more about data types in the next section.

Источник

Читайте также:  Переформатировать jpg в html
Оцените статью