Section 2.3. Java Basics


[Page 19]

2.3. Java Basics

We're going to start out by simply typing commands in the interactions panenot defining new names yet, but simply using the names and symbols that Java knows.

2.3.1. Math Operators

Try typing the following in the interactions pane.

> 34 + 56 90 > 26 - 3 23 > 3 * 4 12 > 4 / 2 2


As you can see Java understands how to recognize numbers, add, subtract, multiply, and divide. You can type a mathematical expression in the interactions pane and then hit the "Enter" key and it will display the result of the expression. Go ahead and try it.


[Page 20]

Making it Work Tip: Using Another Development Environment

If you are not using DrJava you will need to type all code that we show in the interactions pane in a main method instead. Compile and execute the class with a main method. To get the above example to work in another development environment we could have written the following class definition in a file named "Test.java".


public class Test {   public static void main(String[] args)   {     System.out.println(34 + 56);     System.out.println(26 - 3);     System.out.println(3 * 4);     System.out.println(4/2);   } }


The next step is to compile the Java source file. This changes it from something people can read and understand into something the computer can read and understand. To compile the source file with the free command line tools from Sun do the following:

> javac Test.java


When you compile a Java source file the compiler will create a class file, so if you compile the source file "Test.java" the compiler will create the file "Test.class". This file will have the same name as the source file but will have an extension of ".class". After you have compiled the source you can execute the class. To execute it using the free command-line tools from Sun is to use:

> java Test


We have included this Test class in your bookClasses directory. You can continue to use the Test class and just change the code in the main method to try the examples we show in DrJava's interactions pane. We will explain all about classes and main methods in Chapter 11.

The ability to try things in the interactions pane without having to create a class and a main method is one of the major advantages to using DrJava. Remember that it is free, so even if you use another development environment you can download it and use it too, at least for the interactions pane!

2.3.2. Printing the Result of a Statement

In English you end sentences with a period. In Java you typically end a programming statement with a semicolon. However, in the interactions pane you can leave off the semicolon and it will print the result of whatever you have typed (as you saw in the interactions pane). If you do add the semicolon at the end of a Java statement in the interactions pane, it will execute the statement but not automatically print the result in the interactions pane.

Even though you do not have to type the semicolon after statements in the interactions pane you must type the semicolon at the end of your statements in the definitions pane or the code will not compile.


[Page 21]

Since you will need to provide the semicolon at the end of statements in the definitions pane, you should get used to using them in the interactions pane too. But, how do you show the result of a statement in the interactions pane? The phrase System.out.println() is an important one to know. The meaning for System.out.println() is "Use the PrintStream object known as out in the System class to print out the value of whatever is in the parentheses followed by an end-of-line character." DrJava will print the result of an expression in the interactions pane when you use System.out.println(expression).

You can have nothing in the parentheses which will just move the output to a new line, or it can be a name that the computer knows, or an expression (literally, in the algebraic sense). Try typing System.out.println(34 + 56) by clicking in the interactions area, typing the command, and hitting returnlike this:

> System.out.println(34 + 56); 90 > System.out.println(26 - 3); 23 > System.out.println(3 * 4); 12 > System.out.println(4 / 2); 2 > System.out.println(9 % 4); 1 > System.out.println(9  / 5 * -3 +  32); 29 > System.out.println(3  + 2 * 4); 11 > System.out.println((3 + 2) * 4); 20


The code 34 + 56 is a numeric expression that Java understands. Obviously, it's composed of two numbers and an operation that Java knows how to do, '+' meaning "add." In Java we call math symbols like '+' and '-' operators. The operator '-' means subtract. The operator '*' means multiply. The operator '/' means divide. The operator '%' means calculate the remainder of the first number divided by the second one. This is called the modulus operator.

Notice that you get a different result from System.out.println(3 + 2 * 4); than from System.out.println((3 + 2) * 4);. This is because multiplication has higher precedence than addition (meaning it is done first by default). You can use parentheses to change the default order of evaluation of an expression or to make the order clear.

Common Bug: Matching Parentheses

When you use parentheses you will need an open parenthesis for each close parenthesis. If you don't have a match you will get an error.

> System.out.println(3 + 2) * 4); Syntax Error: ")" > System.out.println((3 + 2 * 4); Syntax Error: ";"




[Page 22]

2.3.3. Data Types in Math Expressions

Java takes how you specify numbers seriously. If it sees you using integers, it thinks you want an integer result. If it sees you using floating point numbers, it thinks you want a floating point result. Sounds reasonable, no? But how about:

> System.out.println(1.0/2.0); 0.5 > System.out.println(1/2); 0


The answer to 1/2 is 0? Well, sure! The numbers 1 and 2 are integers. There is no integer equal to 1/2, so the answer must be 0 (the part after the decimal point is thrown away)! Simply by adding ".0" to a number convinces Java that we're talking about floating point numbers (specifically the Java primitive type double), so the result is in floating point form.

We call integer and floating point numbers two different types of data. By data we mean the values that we use in computation. The type of the data, which is also called the data type, determines how many bits are used to represent the value and how the bits are interpreted by the computer.

2.3.4. Casting

We could also have used casting to get the correct result from the division of two integers. Casting is like using a mold to give some material a new shape. It tells the compiler to change a value to a particular type even if it could lead to a loss of data. To cast you put the type that you want the value changed to inside an open and close parenthesis: (type). There are two floating point types in Java: float and double. The type double is larger than the type float and thus more precise. We will use this type for most of the floating point numbers in this book. Notice that we can cast either the 1 or 2 to double and the answer will then be given as a double. We could cast both the 1 and 2 to double and the result would be fine. However, if we cast the result of the integer division to a double it is too late since the result of integer division of 1 by 2 is 0 since the result is an integer.

> System.out.println((double) 1 / 2); 0.5 > System.out.println(1 / (double) 2); 0.5 > System.out.println((double) (1/2)); 0.0


2.3.5. Relational Operators

We can write Java statements that do simple math operations. But if that was all we could do, computers wouldn't be terribly useful. Computers can also decide if something is true or false.

> System.out.println(3 > 2); true 
[Page 23]
> System.out.println(2 > 3); false > System.out.println('a' < 'b'); true > System.out.println('j' > 'c'); true > System.out.println(2 == 2); true > System.out.println(2 != 2); false > System.out.println(2 >= 2); true > System.out.println(2 <= 2); true > System.out.println(true == false); false


Using symbols we can check if one value is greater than another '>', less than another '<', equal to another '==', not equal to another '!=', greater or equal to another '>=', and less than or equal to another '<='. You can use these relational operators on many items such as numbers and characters as shown above. A character can be specified between a pair of single quotes ('a').

You might find '==' odd as a way to test for equality. But, in Java '=' is used to assign a value, not check for equality, as you will see in the next section.

Notice that Java understands the concepts true and false. These are reserved words in Java, which means that they can't be used as names.

Making it Work Tip: Java Primitive Types

  • Integers are numbers without a decimal point in them. Integers are represented by the types: int, byte, short, or long. Example integers are: 3, 5,02,893, and -2,350. In this book we will only use int to represent integers. Each integer takes up 32 bits of memory (4 bytes).

  • Floating point numbers are numbers with a decimal point in them. Floating point numbers can be represented by the types: double or float. Example doubles are 3.0, -19.23, and 548.675. In this book we will use mostly use double to represent floating point numbers. Each double in memory takes up 64 bits (8 bytes).

  • Characters are individual characters that can be made with one key stroke on your keyboard. Characters are represented by the type: char. Characters are specified inside single quotes, like 'a' or 'A'. Each character in memory takes up 16 bits (2 bytes).

  • True and false values are represented by the type boolean. Variables of type boolean can only have TRue or false as values. While a boolean could be represented by just one bit the size of a boolean is up to the virtual machine.


2.3.6. Strings

Computers can certainly work with numbers and even characters. They can also work with strings. Strings are sequences of characters. Try the following in the interactions pane.


[Page 24]

> System.out.println("Mark"); Mark > System.out.println("13 + 5"); 13 + 5


Java knows how to recognize strings (lists of characters) that start and end with " (a double quote). Notice what happens when you enclose a math expression like 13 + 5 in a pair of double quotes. It doesn't print the result of the math expression but the characters inside the pair of double quotes. Whatever is inside a pair of double quotes is not evaluated, the value of it is exactly what was entered.

Now try the following in the interactions pane.

> System.out.println("Barbara" + "Ericson"); BarbaraEricson > System.out.println("Barbara" + " " + "Ericson"); Barbara Ericson > System.out.println("Barbara " + "Ericson"); Barbara Ericson


You can "add" strings together using a + operator as you see in "Barbara" + "Ericson". It simply creates a new string with the characters in the first string followed by the characters in the second string. This is called appending or concatenating strings. Notice that no space is added automatically. If you want space in your string you will need to put it there using a space between a pair of double quotes as shown above with "Barbara" + " " + "Ericson". Or you can have a space inside a string as shown in "Barbara " + "Ericson".

Now try the following in the interactions pane.

> System.out.println("The total is " + (13 + 5)); The total is 18 > System.out.println("The total is " + 13 + 5); The total is 135


You can "add" a string and a number. It will turn the number into a string and then append the two strings. This does what you would expect to show the result of "The total is " + (13 + 15) but you may not expect what happens with "The total is " + 13 + 5.

The computer evaluates statements from left to right so the computer evaluates this as "add" the string "The total is" to the number 13 by turning the number 13 into a string "13". Next it sees the + 5 as adding a number to the string "The total is 13". It turns the second number into a string and results in The total is 135.

The way to get what you would expect is to use parentheses to enclose the math expression. Just like in algebra the parentheses change the order things are evaluated. The (13 + 5) will be evaluated before the append of the string and the resulting number 18.

If you want to put a double quote inside of a string you will need some way to tell the computer that this isn't the ending double quote. In Java the backslash \ character is used to treat the next character differently. So using \" results in a double quote inside a string. Some other special characters are \n to force a new line and \t to force a tab.


[Page 25]

> System.out.println("Barb says, \"Hi\"."); Barb says, "Hi." > System.out.println("This is on one line.\nThis is on the next"); This is on one line. This is on the next




Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
ISBN: N/A
EAN: N/A
Year: 2007
Pages: 191

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net