Showing posts with label java variable. Show all posts
Showing posts with label java variable. Show all posts

Thursday, July 25, 2013

Variables with a Fixed Set of Integer Values

You will usually would like variables which will have values solely from a predefined fastened set. for instance, suppose you wish to outline associate degree whole number variable with the name weekday, which can store associate degree whole number worth representing each day of the week. The variable ideally must be restricted to seven potential values, one for every of Monday through Sunday. this is often a state of affairs wherever a facility known as associate degree enumeration may be a natural alternative. you'll outline associate degree enumeration in Java for this case with the subsequent declaration statement:

enum Day

This defines a replacement kind, Day, for variables which will store only 1 or alternative of the values such that between the braces. The names Monday, Tuesday, and then on through to Sunday square measure known as enumeration constants, and that they establish the sole values that square measure allowed for variables of kind Day. In fact, these names can correspond to whole number values, ranging from zero during this case, however they're not constant as whole number variables as a result of they exist solely inside the context of the enumeration, Day. Note the absence of a punctuation at the tip of the definition of the Day enumeration. as a result of you're shaping a kind here, no punctuation is needed once the closing brace. I used a capital D at the start of the kind name, Day,because by convention, sorts that you simply outline begin with a capital. The names for the enumeration constants would sometimes be written starting with a minuscule letter, however during this case I used a capital at the start as a result of that’s however the times of the week square measure sometimes written. you'll even as well write the enumeration constants with a minuscule letter.

Wednesday, July 24, 2013

Fixing the Value of a Variable

Sometimes you will declare and initialize a variable with a value that should never change. For example:

int feet_per_yard = 3;
double mm_per_inch = 25.4;

Both these values should be fixed. There are always 3 feet to a yard, and an inch will always be 25.4 millimeters. Although they are fixed values for which you could use a literal in calculations, it is very convenient to store them in a variable because using suitable names makes it clear in your program what they mean. If you use the value 3 in your program code it could mean anything - but the name feet_per_yard leaves no doubt as to what it is.

However, ideally you’d like to prevent these variables from varying if possible. Accidental changes to the number of feet in a yard could make the results of your program suspect to say the least. Java provides you with a way to fix the value of any variable by using the final keyword when you declare it. For example:

final int FEET_PER_YARD = 3; // Constant values
final double MM_PER_INCH = 25.4; // that cannot be changed

The final keyword specifies that the value of a variable is final and must not be changed. The compiler will check your code for any violations of this and flag them as errors. I’ve used uppercase letters for the names of the variables here because it is a convention in Java to write constants in this way. This makes it easy to see which variables are defined as constant values. Obviously, any variable you declare as final must have an initial value assigned, as you can’t specify it later.

Now that you know how to declare and initialize variables of the basic types, you are nearly ready to write a program. You just need to look at how you express the calculations you want carried out, and you store the results.

Declaring Floating-Point Variables

You declare floating-point variables in a similar way to what you’ve already used for integers. You can declare and initialize a variable of type double with the following statement:

double sunDistance = 1.496E8;

This declares the variable with the name sunDistance and initializes it with the appropriate value. Declaring a variable of type float is much the same. For example:

float electronMass = 9E-28F;

This defines and initializes the variable electronMass. You can, of course, declare more than one variable in java program of a given type in a single statement:

float hisWeight = 185.2F, herWeight = 108.5F;

Remember that you must put the F or f at the end of literals of type float. If you leave it out, the literal will be of type double, and the compiler won’t convert it automatically to type float.

Declaring Integer Variables

As you saw earlier, you can declare a variable of type long with the statement:

long bigOne;

This statement is a declaration for the variable bigOne. This specifies that the variable bigOne will store a value of type long. When this statement is compiled, 8 bytes of memory will be allocated for the variable bigOne. Java does not automatically initialize a variable such as this. If you want your variables to have an initial value rather than a junk value left over from when the memory was last used, you must specify your own value in the declaration. To declare and initialize the variable bigOne to 2999999999, you just write:

long bigOne = 2999999999L;

The variable will be set to the value following the equal sign. It is good practice to always initialize your variables when you declare them. Note that if you try to use a variable in a calculation that has not had a value assigned to it, your program will not compile. There are also circumstances where the compiler cannot determine whether or not a variable has been initialized before it is used if you don’t initialize it when you declare it, even though it may be obvious to you that it has been. This will also be flagged as an error, but if you get into the habit of always initializing variables when you declare them, you’ll avoid all of these problems.

You can declare a variable just about anywhere in your program, but you must declare each variable before you use it in a calculation. The placement of the declaration has an effect on whether a particular variable is accessible at a given point in a program, and we will look deeper into the significance of this in the next chapter. Broadly, you should group related variable declarations together, immediately before the block of code that uses them. You can declare and define multiple variables in a single statement. For example:

long bigOne = 999999999L, largeOne = 100000000L;

Here I have declared two variables of type long. A comma separates each variable from the next. You can declare as many variables as you like in a single statement, although it is usually better to stick to declaring one variable in each statement, as it helps to make your programs easier to read. A possible exception occurs with variables that are closely related - an (x,y) coordinate pair representing a point, for example, which you might reasonably declare as:

int xCoord = 0, yCoord = 0; // Point coordinates

On the same line as the declaration of these two variables, we have a comment following the double slash, explaining what they are about. The compiler ignores everything from the double slash (//) until the end of the line. Explaining in comments what your variables are for is a good habit to get into, as it can be quite surprising how something that was as clear as crystal when you wrote it transmogrifies into something as clear as mud a few weeks later. You can add comments to your programs in other ways that we will see a little later in this blog. You can also spread a single declaration over several lines if you want. This also can help to make your program more readable. For example:

int miles = 0, // One mile is 8 furlongs
furlongs = 0, // One furlong is 220 yards
yards = 0, // One yard is 3 feet
feet = 0;

This defines four variables of type int in a single statement with the names miles, furlongs, yards, and feet. Each variable has 0 as its initial value. Naturally, you must be sure that an initializing value for a variable is within the range of the type concerned; otherwise, the compiler will complain. Your compiler is intelligent enough to recognize that you can’t get a quart into a pint pot, or, alternatively, a long constant into a variable of type int, short, or byte. Because the statement is spread over four lines, I am able to add a comment on each of the first three lines to explain something about the variable that appears on it. To complete the set of variables that store integers you can declare and initialize a variable of type byte and one of type short with the following two statements:

byte luckyNumber = 7;
short smallNumber = 1234;

Here the compiler can deduce that the integer literals are to be of type byte and short, respectively, and convert the literals to the appropriate type. It is your responsibility to make sure the initial value will fit within the range of the variable that you are initializing. If it doesn’t, the compiler will reject the statement and output an error message.

Most of the time you will find that variables of type int will cover your needs for dealing with integers, with type long being necessary now and again when you have some really big integer values to deal with. Variables of type byte and short do save a little memory, but unless you have a lot of values of these types to store, that is, values with a very limited range, they won’t save enough to be worth worrying about. They also introduce complications when you use them in calculations, as you’ll see shortly, so generally you should not use them unless it is absolutely necessary. Of course, when you are reading data from some external source, a disk file for instance, you’ll need to make the type of variable for each data value correspond to what you expect to read.

Integer Data Types

There are four types of variables that you can use to store integer data. All of these are signed; that is,they can store both negative and positive values. The four integer types differ in the range of values they can store, so the choice of type for a variable depends on the range of data values you are likely to need. The four integer types in Java are:

byte : -128 to +127 and occupy 1 byte (8 bits)
short : -32768 to 32767 and occupy 2 bytes (16 bits)
int : -2147483648 to 2147483647 and occupy 4 bytes (32 bits)
long : -9223372036854775808 to 9223372036854775807 and occupy 8 bytes (64 bits)

Although I said the choice of type depends on the range of values that you want to be able to store, in practice you’ll be using variables of type int or type long to store integers most of the time, for reasons that I’ll explain a little later. Let’s take a look at declarations of variables of each of these types:

byte smallerValue;
short pageCount;
int wordCount;
long bigValue;

Each of these statements declares a variable of the type specified.

The range of values that can be stored by each integer type in Java, as shown in the preceding table, is always the same, regardless of what kind of computer you are using. This is also true of the other primitive types that you will see later in this chapter and has the rather useful effect that your program will execute in the same way on computers that may be quite different. This is not necessarily the case with other programming languages.

Of course, although I have expressed the range of possible values for each type as decimal values, integers are stored internally as binary numbers, and it is the number of bits available to store each type that determines the maximum and minimum values.

For each of the binary numbers shown here, the leftmost bit is the sign bit, marked with an s. When the sign bit is 0 the number is positive, and when it is 1 the number is negative. Binary negative numbers are represented in what is called 2’s complement form. If you are not familiar with this, you will find an explanation of how it works in Appendix B.

Variables and Types

As I mentioned earlier, each variable that you declare can store values only of a type consistent with the data type of that variable. You specify the type of a particular variable by using a type name in the variable declaration. For instance, here’s a statement that declares a variable that can store integers:

int numberOfCats;

The data type in this case is int and the variable name is numberOfCats. The semicolon marks the end of the statement. The variable, numberOfCats, can only store values of type int. Of course, int is a keyword. Many of your variables will be used to reference objects, but let’s leave those on one side for the moment,as they have some special properties. The only things in Java that are not objects are variables that correspond to one of eight basic data types, defined within the language. These fundamental types are referred to as primitive types, and they allow you to define variables for storing data that fall into one of three categories:

[1] Numeric values, which can be either integer or floating point
[2] Variables that store the code for a single Unicode character
[3] Logical variables that can assume the values true or false

All of the type names for the basic variable types are keywords in Java so you must not use them for other purposes. Let’s take a closer look at each of the primitive data types and get a feel for how you can use them.

Variable Names and Unicode

Even though you may be entering your Java programs in an environment that stores ASCII characters,all Java source code is in Unicode. Although the original source code that you create may be ASCII, it is converted to Unicode characters internally, before it is compiled. While you can write any Java language statement using ASCII, the fact that Java supports Unicode provides you with immense flexibility. It means that the identifiers that you use in your source program can use any national language character set that is defined within the Unicode character set, so your programs can use French, Greek, or Russian variable names, for example, or even names in several different languages, as long as you have the means to enter them in the first place. The same applies to character data that your program defines.

Tuesday, July 23, 2013

Naming Your Variables

The name that you choose for a variable, or indeed the name that you choose for anything in Java, is called an identifier. An identifier can be any length, but it must start with a letter, an underscore (_), or a dollar sign ($). The rest of an identifier can include any characters except those used as operators in Java (such as +, –, or *), but you will be generally better off if you stick to letters, digits, and the underscore character.

Java is case-sensitive, so the names republican and Republican are not the same. You must not include blanks or tabs in the middle of a name, so Betty May is out but you could have BettyMay or even Betty_May. Note that you can’t have 6Pack as a name since you cannot start a name with a numeric digit. Of course, you could use sixPack as an alternative.

Subject to the restrictions I have mentioned, you can name a variable almost anything you like, except for two additional restraints - you can’t use keywords in Java as a name for something, and a name can’t be anything that could be interpreted as a constant value - as a literal, in other words. Keywords are words that are an essential part of the Java language. You saw some keywords in the previous chapter,and you will learn a few more in this chapter. If you’d like to know what they all are now, see the complete list in Appendix A. The restriction on constant values is there because, although it is obvious why a name can’t be 1234 or 37.5, constants can also be alphabetic, such as true and false, for example,which are literals of type boolean. Of course, the basic reason for these rules is that the compiler has to be able to distinguish between your variables and other things that can appear in a program. If you try to use a name for a variable that makes this impossible, then it’s not a legal name.

Data and Variables

A variable is a named piece of memory that you use to store information in your Java program a piece of data of some description. Each named piece of memory that you define in your program is able to store data only of one particular type. If you define a variable to store integers, for example,you can’t use it to store a value that is a decimal fraction, such as 0.75. If you’ve defined a variable that you use to refer to a Hat object, you can only use it to reference an object of type Hat. Since the type of data that each variable can store is fixed, the compiler can verify that each variable you define in your program is not used in a manner or a context that is inappropriate to its type. If a method in your program is supposed to process integers,the compiler will be able to detect when you inadvertently try to use the method with some other kind of data - for example, a string or a numerical value that is not integral.

Explicit data values that appear in your program are called literals. Each literal will also be of a particular type: 25, for example, is an integer literal of type int. I will go into the characteristics of the various types of literals that you can use as I discuss each variable type.

Before you can use a variable you must specify its name and type in a declaration statement. Before I describe how you write a declaration for a variable, let’s consider what flexibility you have in choosing a name.