Recent Changes - Search:

Java Tutorial

edit SideBar

LiteralsAndVariables

These pages make up the course notes for my Java programming course (run at Dallam, Milnthorpe, Cumbria). Hopefully they also make a useful self-learning tutorial.

As mentioned above the Java language is made up of a small set of words, known as Reserved Words (reserved because you can’t use them for anything else, such as class or method names). Most of these words require some data (information) on which to work. We have already encountered one way of providing data in our SayHello class. In the line

	System.out.println("Hello World!");

is the data that we want to print on screen, “Hello World!”. This is known as a literal because we have literally said what we want to see. Literals can also be numbers e.g.

	System.out.println(1234);

Notice that the Hello World Text had double quotes round it “” but the number didn’t. The reason for this is that the compiler needs to be able to distinguish between things that might be instructions and things that are literal text. Consider this:

	System.out.println(System.out.println );

and this

	System.out.println( “System.out.println” );

Try it! The first one will fail and the second one will work. The first one fails because the compiler recognises the second occurrence of System.out.println as something it should work on, but then find it is not a valid statement (it is not the correct syntax).

The second one works because the compiler knows to treat anything inside “” as just literal text, not something the compiler needs to work on. The reason the numeric example works without double quotes is that 1234 cannot be something the compiler needs to treat as a Java language statement, because all parts of Java language statements must begin with an upper or lower case letter or a _ or $. Anything starting with a number will be treated as a literal number.

Continuing with things inside quotes, computers don’t know anything about words, paragraphs, or text in any of the many ways we use it, they only know about individual characters. When we put characters together inside double quotes they are known as a String – i.e. a number of characters strung together, or a String of characters. So “Hello World!” is a literal String.

Literals are very useful but they have their limitations. Suppose we want to add up some numbers and store the result, we could use

	System.out.println( 1 + 2 + 3 + 4 );

which will add the numbers and print the result but it does not store the result. If we wanted o use the result of this calculation later we need to put it somewhere. To do this we need to use a variable. A variable is a slot in memory where we can put a value. To declare a variable we need to know what type of data we want to store. Whole numbers (like 1, 56, 87659) are technically known as integers; numbers with fractional parts or part after the decimal point (e.g. 9.99) are known as floating point numbers; and as mentioned above text is known as string data.

So to declare variables we need to state the type, give it a name and optionally assign a value to it e.g

	int myFirstVar;
	int anotherIntVar = 123;
	float bankBalance;
	float vat = 17.5f;
	String yourName;
	String myName = “Chris”;

As mentioned above we declare a variable by stating its type (e.g. int, float, String) and giving it a name – this can be any name you like as long as it starts with a letter, by convention it should be meaningful name and should start with a lower case letter. It CANNOT contain spaces. The name is used to refer to the contents of the variable later.

In some of the above examples we use literals to ASSIGN values to the variables, and in some we don’t. For those that we don’t, we can always assign a value later. That’s why a variable is called a VARIABLE, its value can be varied (changed) at any time – but only to a value of the same type – we cannot put a String into a variable originally declared as an int.

Other things to note about these examples are use of = to make an assignment and the fact that every line ends with a semi-colon ; This is a requirement of the Java language – it is not that every line should end with a semi-colon, but that every statement should. A long statement may span several lines and so the semi-colon tells the compiler where the statement ends (or where you intend it to end, the compiler may not agree!).

So lets look at using some variables to do something useful. Here is an example that adds up some amounts and then applies VAT (sales tax) to the total. In your IDE create a new class and Copy this code and paste it in, replacing anything that was put there automatically.

public class VatBill {

        /**
        * @param args
        */
        public static void main(String[] args) {

                float item1 = 4.99f; //cost of item 1
                float item2 = 7.99f; //cost of item 2
                float item3 = 9.99f; //cost of item 3
                float vatRate = 17.5f; //VAT as a percentage

                //add up the items to get the net price
                float netPrice = item1 + item2 + item3;
                System.out.println("The net price is " + netPrice);

                //calculate the amount of VAT on the net price
                float vatAmount = vatRate/100 * netPrice;
                System.out.println("The amount of VAT is " + vatAmount);

                //calculate the total price payable
                float totalAmount = netPrice + vatAmount;
                System.out.println("The gross amount (inc VAT) is " + totalAmount);

        }

}

Hopefully this code looks a little familiar from the SayHello example. We again start with a class definition – this time the class name is VatBill , and we still have a main method – remember we must have this and it must be exactly like it is shown. Inside the main method we declare three variable to hold the prices of three items. item1 gets the value 4.99, item2 gets 7.99 and item3 gets 9.99. Notice the f after the literal value, this is just there to keep the compiler happy, what it means is that the literal we have specified is a float (otherwise the compiler assumes it’s a double and then complains – it’s a pretty pedantic compiler …).

Next we add the three items together. When we write item1 + item2 + item3, the compiler knows that we mean add the VALUE stored in the variable called “item1” to the VALUE stored in the variable called item2. We store the result of adding up the items in another variable, netAmount which we use later.

Also notice that the statement

	System.out.println("The net price is " + netPrice);

has something extra in it over the Hello World Example. Here we have a literal String of text and we are joining the value of the netPrice variable on to the end of the String. To join Strings together and to join Strings to other things we use a + (plus) sign. Joining Strings is technically called Concatenation. Here we join a String to a number, the plus sign in this context will concatenate not sum – i.e. it will convert the number to a String of characters and join it to the end of the literal String rather than trying to perform a mathematical addition.

Check that this works, and check your understanding, by:

  • changing the item amounts
  • changing the VAT rate
  • changing the message text.
  • Changing the variable names
  • putting the message text in a variable and then printing that out.
 

Creative Commons License

This work is Copyright Chris Hunter 2007, you may use it for non-commercial purposes
under the Creative Commons license Creative Commons Attribution-Noncommercial-Share Alike.

Edit - History - Print - Recent Changes - Search
Page last modified on September 03, 2007, at 04:25 PM