LESSON 3
THE BASICS


Java Statements and Expressions

A statement defines a single Java operation. The following are simple Java statements:

	int i = 1;
	import java.awt.Font;
	System.out.println ("This computer is "
		+ color + " " + make)
	m.computer.State = false;


A statement can return a value. If a statement should return a value, it is called an expression. For example, int i = 1; is a statement; int i = 1 + 2; is an expression.

As in Pascal and C, white space within statements is unimportant. A statement can be on one line or on multiple lines. The thing you must remember is to end all Java statements with a semicolon (;). If you don't remember this, the Java compiler will not compile your source code.

Java programs can also contain compound statements. Compound statements are placed within braces ({}). They can be placed anywhere a single statement can be placed.

Java Variables and Data Types

Variables are addresses in memory where values are stored. Each address has a name, a type and a value. Before you can use a variable, you have to reserve a location in memory for it. This is done by a declaration statement. After a variable has been declared, you can assign values to it. As you will see later, you can declare a variable and assign it a value at the same time.

Java has three kinds of variables: class variables, instance variables and local variables. Unlike other languages, it does not have global variables. Instance variables are used to define the attributes of a specific object. Class variables are similar except their values apply to all of a class's instances (including the class itself). Local variables are declared and used inside method definitions. Once a method containing a local variable has executed, the variable ceases to exist.

Declaring Variables

Before a variable can be used in a Java program it must be declared. A variable declaration consists of a type and a variable name:

	int aNumber;
	String title;
	boolean offLine;

Usually variable definitions are declared at the beginning of a method definition, however they can be placed anywhere within a method definition that a regular Java statement can go.

	public static void main (String args[])
	{
	 int counter;
	 String heading;
	 boolean onLine;
	 ...
	}

The names of variables of the same type can be put on the same line:
	int m, n, o;
	String hisName, herName;

You can also initialize a variable when you declare it:
	int x = 1, y = 2, z = 3;
	String herName = "Mary";
	boolean offLine = true;

Note that in the first example, the variables are separated by commas.

Local variables must be given a value before they can be used. If they are not, your program will not compile. This restriction does not apply to instance or class variables.

Variable Names

Variable names in Java cannot start with a number. They can start with an underscore ( _ ), a dollar sign ($) or a letter. After the initial character, a name can contain any letter or number. You should be aware that the Java language is case sensitive. This means variable count is not the same a variable Count. Java variables are usually made up of several words combined into one word. By convention, the first word is lowercase, with all following words capitalized:

	int someSmallNumber;
	long prettyBigNumber;

Variable Types

All variable declarations must have a type, which determines how much memory is set aside for the variable. A variable type can be one of three things:

  • One of eight primitive data types
  • The name of a class or interface
  • An array


This lesson will concentrate on the primitive and class types. You will learn about arrays in lesson 5.

Primitive Types

These data types are called primitive because they are build into the system and are not actual objects. They consist of such types as integers, floating-point numbers, characters and boolean values.

Integer Types

Type

Size

Range

byte

8 bits

-128 to 127

short

16 bits

-32,768 to 32,767

int

32 bits

-2,147,483,648 to 2,147,483,647

long

64 bits

-9,223,372,036,854,775,808 to

9,223,372,036,854,775,807

Java has two types of floating-point numbers (numbers containing a decimal point). They are float (32 bits, single precision) and double (64 bits, double precision).

The type char is used for individual characters (16 bits of precision, unsigned).

The boolean type can have one of two values, true or false.

All the primitive types are in lowercase. You have to be careful when you use these types that they are in lowercase, because there are classes with the same name, but the first letter is in uppercase. The primitive type boolean is different than the class Boolean.

Assigning Values to Variables

After a variable has been declared, you can assign a value to it by using the assignment operator =. For example:

	size = 10;
	computerIsOn = true;

Comments

The symbols /* and */ are used to enclose multiline comments. All the text between the two delimiters is ignored. For example:

	/* When you look at this code next
	   month, you probably will not re-
	   member what it does. So you better
	   state what it does here ...
	*/

You cannot have a comment within a comment (nested).

Double-slashes can be used for single line comments. All the text up to the end of the line is ignored:
	import java.applet.*; // The asterisk stands for anyfile
	import java.awt.*; //import any file beginning with java.awt

There is another type of comment that begins with /** and ends with */. You will learn more about this type of comment in chapter 22.

Expressions and Operators

The simplest form of statement in Java that actually accomplishes anything is called an expression. All expressions when executed, return a value. Most expressions use operators. Operator are special symbols used for arithmetic, assignments, incrementing, decrimenting and logical operations.

Arithmetic

There are five operators used for basic arithmetic:

Arithmetic Operators
Operator Meaning Example
+ Addition 3 + 4
- Subtraction 4 - 3
* Multiplication 2 * 3
/ Division 10 / 5
%> Modulus 10 % 7


Examples of Simple Arithmetic

	class ArithmeticDemo // class definition
	{
	 public static void main (String args []) //Main Method 
		{ // Start compound statement
		 short x = 8;  // Declare variable, initialize
		 int y = 2;
		 float a = 1.14f; // Add f to make sure float
		 float b = 5f;

System.out.println ("x is " + x + ", y is " + y); System.out.println ("x + y = " + (x + y)); System.out.println ("x - y = " + (x - y)); System.out.println ("x / y = " + (x / y)); System.out.println ("x % y = " + (x % y));
System.out.println ("a is " + a + ", b is " + b); System.out.println ("a / b = " + (a / b)); } // End compound statement }

Output

	x is 8, y is 2
	x + y = 10
	x - y = 6
	x / y = 4
	x % y = 0
	a is 1.14, b = 5.0
	a / b = 0.228

Assignments

If several variables are to initialized to the same value, you can string them together like this:

	x=y=z=0
The three variables x, y and z all equal zero.

In the assignment x = x + 4 the right side of the expression is evaluated first, then the assignment takes place, adding 4 to the value of x. Because this operation is so common, Java has several shorthand versions of the operation; see the table below:

Assignment Operators
Expression Meaning
x += y x = x+y
x -=y x = x-y
x *= y x = x*y
x /=y x = x/y


Incrementing and Decrementing

The ++ and -- operators can be used to increment or decrement a variable's value by one (1). For example, x++ results in the same value as the expression x=x+1.

The operators (++ or --) can be placed in front of or behind the value being incremented or decremented. However, where you place the operators (++ or --) can make a difference in the end value. For example, the following expressions yield very different results:

	y = x++;
	y = ++x;

When you place the operator in front of x, the value of x is assigned to y after x has been incremented. If you place the operator after x, y gets the value of x before x is changed. The program below demonstrates the difference:

	class OpPositionDemo
	{
	 public static void main (String args[]) // Main method
		{
		 int x=0;  // initialize variable x
		 int y=0;   // initialize variable y

		 System.out.println ("x and y are " + x + " and " + y);
		 x++;
		 System.out.println ("x++ results in " + x);
		 ++x;
		 System.out.println ("++x results in " + x);
		 System.out.println ("Resetting x back to 0.");
		 x=0;
		 System.out.println ("_______________");
		 y = x++;
		 System.out.println ("y = x++ (behind) results in:");
		 System.out.println ("x is " + x);
		 System.out.println ("y is " + y);
		 System.out.println ("_______________");
		 
		 y = ++x;
		 System.out.println ("y = ++x (in front) results in:");
	  	 System.out.println ("x is " + x);
		 System.out.println ("y is " + y);
		 System.out.println ("_______________");
		}
	}

Output

	x and y are 0 and 0
	x++ results in 1
	++x results in 2
	Resetting x back to 0.
	________________

	y = x++ (behind) results in:
	x is 1
	y is 0
	________________

	y = ++x (in front) results in:
	x is 2
	y is 2
	________________

Comparisons

There are several expressions you can use to test for equality and magnitude. They all return a boolean value of true or false. See the table below:

Comparison Operators
Operator Meaning Example
== Equal x==1
!= Not Equal x != 1
< Less Than x < 1
> Greater Than x > 1
<= Less Than or Equal To x <= 1
>= Greater Than or Equal To x >= 1


The equality operators == and != test if two values are equal or not:

	int x = 3, y = 6;
	boolean result;

	result = (x == y);  // false
	result = (x != y);  // true

The relational operators <, <=, > and >= test if the first value is less than, less than or equal to, greater than, or greater than or equal to the second value. For example:

	result = (x < y);   // true -- 3 < 6

Boolean Operators

There are two boolean operators && (logical AND) and || (logical OR). There is no conditional XOR operator.

AND evaluates to true if both its operands are true; else its false.

	result = (x < 3) && (y > 5);   // false

OR evaluates to false if both its operands are false, else its true.

	result = (x < 3) || (y > 5)   // true

Operator Precedence

Certain operator are evaluated before others. For example, multiplication and division are always done before addition or subtraction, unless the addition and subtraction are enclosed in parentheses. The following table shows the operator precedence. Operators with the highest precedence are at the top of the chart. Operators at the same level of precedence are evaluated from left to right.

Description Operators
High Precedence . [] ()
Unary + - ~ ! ++ --
Multiplicative * / %
Additive + -
Shift << >> >>>
Relational < <= > >=
Equality == !=
Bitwise AND &
Bitwise XOR ^
Bitwise OR |
Conditional AND &&
Conditional OR ||
Conditional ?:
Assignment = op=


String Arithmetic

The addition operator (+) can be used in Java to create and concatenate strings. You have seen some examples of this in this lesson. For example:

	System.out.println ("x and y are " + x + " and " + y);
results in the following output:
	x and y are 0 and 0

The output is a single string. The values of the variables (x and y) are inserted in the appropriate locations in the string.

Copyright (C) 1998 by J. Auciello