What is an object variable in java

Java Variables

A Java variable is a piece of memory that can contain a data value. A variable thus has a data type. Data types are covered in more detail in the text on Java data types.

Variables are typically used to store information which your Java program needs to do its job. This can be any kind of information ranging from texts, codes (e.g. country codes, currency codes etc.) to numbers, temporary results of multi step calculations etc.

In the code example below, the main() method contains the declaration of a single integer variable named number . The value of the integer variable is first set to 10, and then 20 is added to the variable afterwards.

Java Variable Types

In Java there are four types of variables:

A non-static field is a variable that belongs to an object. Objects keep their internal state in non-static fields. Non-static fields are also called instance variables, because they belong to instances (objects) of a class. Non-static fields are covered in more detail in the text on Java fields.

A static field is a variable that belongs to a class. A static field has the same value for all objects that access it. Static fields are also called class variables. Static fields are also covered in more detail in the text on Java fields.

A local variable is a variable declared inside a method. A local variable is only accessible inside the method that declared it. Local variables are covered in more detail in the text on Java methods.

Читайте также:  Javascript ajax xml json

A parameter is a variable that is passed to a method when the method is called. Parameters are also only accessible inside the method that declares them, although a value is assigned to them when the method is called. Parameters are also covered in more detail in the text on Java methods.

Java Variable Declaration

Exactly how a variable is declared depends on what type of variable it is (non-static, static, local, parameter). However, there are certain similarities that

In Java you declare a variable like this:

Instead of the word type , you write the data type of the variable. Similarly, instead of the word name you write the name you want the variable to have.

Here is an example declaring a variable named myVariable of type int .

Here are examples of how to declare variables of all the primitive data types in Java:

byte myByte; short myShort; char myChar; int myInt; long myLong; float myFloat; double myDouble;

Here are examples of how to declare variables of the object types in Java:

Byte myByte; Short myShort; Character myChar; Integer myInt; Long myLong; Float myFloat; Double myDouble; String myString;

Notice the uppercase first letter of the object types.

When a variable points to an object the variable is called a «reference» to an object. I will get back to the difference between primitive variable values and object references in a later text.

The rules and conventions for choosing variable names are covered later in this text.

Java Variable Assignment

Assigning a value to a variable in Java follows this pattern:

Here are three concrete examples which assign values to three different variables with different data types

myByte = 127; myFloat = 199.99; myString = "This is a text";

The first line assigns the byte value 127 to the byte variable named myByte . The second line assigns the floating point value 199.99 to the floating point variable named myFloat . The third line assigns the String value (text) this is a text to the String variable named myString .

You can also assign a value to a variable already when it is declared. Here is how that is done:

byte myByte = 127; float myFloat = 199.99; String myString = "string value";

Java Variable Reading

You can read the value of a Java variable by writing its name anywhere a variable or constant variable can be used in the code. For instance, as the right side of a variable assignment, as parameter to a method call, or inside a arithmetic expression. For instance:

float myFloat1 = 199.99; float myFloat2 = myFloat1; // right hand side value in assignment float myFloat3 = myFloat2 + 123.45; // as part of arithmetic expression System.out.println(myFloat3); // as parameter in method call.

Java Variable Naming Conventions

There are a few rules and conventions related to the naming of variables.

  1. Java variable names are case sensitive. The variable name money is not the same as Money or MONEY .
  2. Java variable names must start with a letter, or the $ or _ character.
  3. After the first character in a Java variable name, the name can also contain numbers (in addition to letters, the $, and the _ character).
  4. Variable names cannot be equal to reserved key words in Java. For instance, the words int or for are reserved words in Java. Therefore you cannot name your variables int or for .

Here are a few valid Java variable name examples:

myvar myVar MYVAR _myVar $myVar myVar1 myVar_1

There are also a few Java variable naming conventions. These conventions are not necessary to follow. The compiler to not enforce them. However, many Java developers are used to these naming conventions. Therefore it will be easier for them to read your Java code if you follow them too, and easier for you to read the code of other Java developers if you are used to these naming conventions. The conventions are:

  • Variable names are written in lowercase. For instance, variable or apple .
  • If variable names consist of multiple words, each word after the first word has its first letter written in uppercase. For instance, variableName or bigApple .
  • Even though it is allowed, you do not normally start a Java variable name with $ or _ .
  • Static final fields (constants) are named in all uppercase, typically using an _ to separate the words in the name. For instance EXCHANGE_RATE or COEFFICIENT .

Java Local-Variable Type Inference

From Java 10 it is possible to have the Java compiler infer the type of a local variable by looking at what actual type that is assigned to the variable when the variable is declared. This enhancement is restricted to local variables, indexes in for-each loops and local variables declared in for-loops.

To see how the Java local-variable type inference works, here is first an example of a pre Java 10 String variable declaration:

From Java 10 it is no longer necessary to specify the type of the variable when declared, if the type can be inferred from the value assigned to the variable. Here is an example of declaring a variable in Java 10 using local-variable type inference:

Notice the var keyword used in front of the variable name, instead of the type String . The compiler can see from the value assigned that the type of the variable should be String , so you don’t have to write it explicitly.

Here are a few additional Java local-variable type inference examples:

var list = new ArrayList(); var myNum = new Integer(123); var myClassObj = new MyClass();

Источник

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.

Источник

Оцените статью