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.

Importing the Math Class Methods

It would be a lot more convenient if you were able to avoid having to qualify the name of every method in the Math class that you use with the class name. The code would be a lot less cluttered if you could write floor(radius) instead of Math.floor(radius) for example. Well, you can. All you need to do is put the following statement at the beginning of the source file:

import static java.lang.Math.*; // Import static class members

This statement makes the names of all the static members of the Math class available for use in your Java program code without having to qualify them with the class name. This includes constants such as PI as well as static methods. You can try this statement in the PondRadius example. With this statement at the beginning of the source file, you will be able to remove the qualification by the class name Math from all the members of this class that the program uses.

In the statement indicates that all static names are to be imported. If you wanted to import just the names from the Math class that the PondRadius program uses, you would write:

import static java.lang.Math.floor; // Import floor
import static java.lang.Math.sqrt; // Import sqrt
import static java.lang.Math.round; // Import round
import static java.lang.Math.PI; // Import PI

These statements import individually the four names from the Math class that the program references. You could use these four statements at the beginning of the program in place of the previous import statement that imports all the static names.

Automatic Type Conversions in Assignments

When the type of the result of an arithmetic expression on the right of an assignment operator differs from the type of the variable on the left, an automatic cast will be applied to the result as long as there is no possibility of losing information in Java program. If you think of the basic types that we have seen so far as being in the sequence

byte => short => int => long => float => double

then an automatic conversion will be made as long as it is upwards through the sequence of types, that is, from left to right. If you want to go in the opposite direction, from type double to type float or long, for example, then you must insert an explicit cast into your code for the result of the expression on< the right of the assignment operator.

Wednesday, July 24, 2013

Explicit Casting

It may well be that the default treatment of mixed expressions listed in the preceding section is not what you want. For example, suppose you have defined a double variable result; and two variables, three and two, of type int with the values 3 and 2, respectively. If you compute the value of result with the statement

result = 1.5 + three/two;

the value stored will be 2.5, since three/two will be executed as an integer operation and will produce the result 1. You may have wanted the term three/two to produce the value 1.5 in Java program so the overall result would be 3.0. You could do this using an explicit cast:

result = 1.5 + (double)three/two;

This causes the value stored in three to be converted to type double before the divide operation takes place. Then rule 1 applies for the divide operation, and the operand two is also converted to type double before the divide operation is executed.

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.

Floating-Point Literals

Floating-point literals are of type double by default, so 1.0 and 345.678 are both of type double. When you want to specify a value of type float, you just append an f, or an F, to the value, so 1.0f and 345.678F are both literals of type float. If you are new to programming it is important to note that you must not include commas as separators when specifying numerical values in your program code. Where you might normally write a value as 99,786.5, in your code you must write it without the comma, as 99786.5.

When you need to write very large or very small floating-point values, you will usually want to write them with an exponent - that is, as a decimal value multiplied by a power of 10. You can do this in Java by writing the number as a decimal value followed by an E, or an e, preceding the power of 10 that you require. For example, the distance from the Earth to the Sun is approximately 149,600,000 kilometers, more conveniently written as 1.496E8. Since the E (or e) indicates that what follows is the exponent, this is equivalent to 1.496 * 108. At the opposite end of the scale, the mass of an electron is around 0.0000000000000000000000000009 grams. This is much more convenient, not to say more readable, when it is written as 9.0E-28 grams.

Floating-Point Data Types

Numeric values that are not integral are stored as floating-point numbers. A floating-point number has a fixed number of digits of accuracy but with a very wide range of values. You get a wide range of values,even though the number of digits is fixed, because the decimal point can “float.” For example, the values 0.000005, 500.0, and 5000000000000.0 can be written as 5×10-6, 5×102, and 5×1012 respectively - you have just one digit 5 but you get three different numbers by moving the decimal point around.

There are two primitive floating-point types in Java, type float and type double. These give you a choice in the number of digits precision available to represent your data values, and in the range of values that can be accommodated:

float : -3.4E38 (-3.4 * 1038) to +3.4E38 (+3.4 * 1038) and occupy 4 bytes
double : -1.7E308 (-1.7 * 10308) to +1.7E308 (+1.7 * 10308) and occupy 8 bytes

As with integer calculations, floating-point calculations in Java will produce the same results on any computer.

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 Literals

An integer variable stores an integer value, so before you get to use integer variables you need to understand how you write integer values of various types. As I said earlier, a value of any kind in Java is referred to as a literal. So 1, 10.5, and “This is text” are all examples of literals.

Any integer literal that you specify as a sequence of decimal digits is of type int by default. Thus 1, -9999, and 123456789 are all literals of type int. If you want to define an integer literal of type long, you need to append an L to the value. The values 1L, -9999L, and 123456789L are all of type long. You can also use a lowercase letter l, but don’t - it is too easily confused with the digit 1.

You are perhaps wondering how you specify literals of type byte or short. Because of the way integer arithmetic works in Java, they just aren’t necessary in the main. You’ll see a couple of instances where an integer literal may be interpreted by the compiler as type byte or short later in this chapter, but these situations are the exception.

You can also specify integer literals to base 16 - in other words, as hexadecimal numbers. Hexadecimal literals in Java have 0x or 0X in front of them and follow the usual convention of using the letters A to F (or a to f) to represent digits with values 10 to 15, respectively. In case you are a little rusty on hexadecimal values.

If you are not familiar with hexadecimal numbers, you can find an explanation of how these work in Appendix B. All the hexadecimal literals in the preceding table are of type int. If you want to specify a hexadecimal literal of type long, you must append L to the literal just as with decimal literals. For example,0x0FL is a hexadecimal literal that is equivalent to the decimal value 15.

There is a further possibility for integer literals - you can also define them as octal values, which is to base 8, and legal digits in an octal literal can be from 0 to 7. You write literals that are octal numbers with a leading zero, so 035 and 067 are examples of octal numbers. Each octal digit defines 3 bits, so this number base was used a lot more frequently in the days when machines used words of lengths that were a multiple of 3 bits to store a number. You will rarely find it necessary to use octal numbers these days, but you should take care not to use them by accident. If you put a leading zero at the start of an integer literal,the Java compiler will think you are specifying an octal value. Unless one of the digits is greater than 7, which results in the compiler flagging it as an error, you won’t know that you have done this.

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.

Java and Unicode

Programming to support languages that use anything other than the Latin character set has always been a major problem. There are a variety of 8-bit character sets defined for many national languages, but if you want to combine the Latin character set and Cyrillic in the same context, for example, things can get difficult. If you want to handle Japanese as well, it becomes impossible with an 8-bit character set because with 8 bits you have only 256 different codes so there just aren’t enough character codes to go round. Unicode is a standard character set that was developed to allow the characters necessary for almost all languages to be encoded. It uses a 16-bit code to represent a character (so each character occupies 2 bytes), and with 16 bits up to 65,535 non-zero character codes can be distinguished. With so many character codes available, there is enough to allocate each major national character set its own set of codes, including character sets such as Kanji, which is used for Japanese and which requires thousands of character codes. It doesn’t end there though. Unicode supports three encoding forms that allow up to a million additional characters to be represented.

I say each Unicode character usually occupies 2 bytes because Java supports Unicode 4.0, which allows 32-bit characters called surrogates. You might think that the set of 64K characters that you can represent with 16 bits would be sufficient, but it isn’t. Far-eastern languages such as Japanese, Korean, and Chinese alone involve more than 70,000 ideographs, and surrogates are used to represent characters that are not contained within the basic multilingual set that is defined by 16-bit characters.

Java Applications

Every Java application contains a class that defines a method called main(). The name of this class is the name that you use as the argument to the Java interpreter when you run the application. You can call the class whatever you want, but the method which is executed first in an application is always called main(). When you run your Java application, the method main() will typically cause methods belonging to other classes to be executed, but the simplest possible Java application program consists of one class containing just the method main(). As you will see below, the main() method has a particular fixed form, and if it is not of the required form, it will not be recognized by the Java interpreter as the method where execution starts.

You can see how this works by taking a look at just such a Java program. You need to enter the program code using your favorite plaintext editor, or if you have a Java development system with an editor, you can enter the code for the example using that. When you have entered the code, save the file with the same name as that used for the class and with the extension .java. For this example the file name will be OurFirstProgram.java. The program consists of a definition for a class I have called OurFirstProgram. The class definition contains only one method, the method main(). The first line of the definition for the method main() is always of the form:

public static void main(String[] args)

The code for the method appears between the pair of curly braces. This version of the method has only one executable statement:

System.out.println(“Krakatoa, EAST of Java??”);

So what does this statement do? Let’s work through it from left to right:

[1] System is the name of a standard class that contains objects that encapsulate the standard I/O devices for your system - the keyboard for command-line input and command-line output to the display. It is contained in the package java.lang, so it is always accessible just by using the simple class name System.

[2] The object out represents the standard output stream - the command line on your display screen - and is a data member of the class System. The member, out, is a special kind of member of the System class. Like the method main() in our OurFirstProgram class, it is static. This means that out exists even though there are no objects of type System. Using the class name, System, separated from the member name out by a period - System.out - references the out member.

[3] The bit at the rightmost end of the statement, println(“Krakatoa, EAST of Java??”),calls the println() method that belongs to the object out, and that outputs the text string that appears between the parentheses to your display. This demonstrates one way in which you can call a class method - by using the object name followed by the method name, with a period separating them. The stuff between the parentheses following the name of a method is information that is passed to the method when it is executed. As we said, for println() it is the text we want to output to thebcommand line. You can compile this program using the JDK compiler with the command

javac OurFirstProgram.java
or with the -classpath option specified:
javac –classpath . OurFirstProgram.java

If it didn’t compile, there’s something wrong somewhere. Here’s a checklist of possible sources of the problem:

[4] You forgot to include the path to the jdk1.5.0\bin directory in your PATH, or maybe you did not specify the path correctly. This will result in your operating system not being able to find the javac compiler that is in that directory.

[5] You made an error typing in the program code. Remember Java is case-sensitive, so OurfirstProgram is not the same as OurFirstProgram, and of course, there must be no spaces in the class name. If the compiler discovers an error, it will usually identify the line number in the code where the error was found. In general, watch out for confusing zero, 0, with a small letter o,or the digit one, 1, with the small letter l. All characters such as periods, commas, and semicolons in the code are essential and must be in the right place. Parentheses, (), curly braces, {}, and square brackets, [], always come in matching pairs and are not interchangeable.

[6] The source file name must match the class name exactly. The slightest difference will result in an
error. It must have the extension .java. Once you have compiled the program successfully, you can execute it with the command:

java –ea OurFirstProgram

The -ea option is not strictly necessary since this program does not use assertions, but if you get used to putting it in, you won’t forget it when it is necessary. If you need the -classpath option specified:

java –ea –classpath . OurFirstProgram

Assuming the source file compiled correctly, and the jdk1.5.0\bin directory is defined in your path, the most common reason for the program failing to execute is a typographical error in the class name, OurFirstProgram. The second most common reason is writing the file name, OurFirstProgram.class, in the command, whereas it should be just the class name, OurFirstProgram.