2.1 Starting to write Java code
A programming language is like a natural language that we speak or write in that it has components (in a natural language these would be the words, sentences, paragraphs, and so on) and rules, or syntax. When you speak you need to follow the rules or the person you are speaking to will not understand you. When you write a program, you also need to follow the rules for the programming language, otherwise the computer will not be able to understand.
When you listen to someone speak you can often work out or guess what they mean even if they don’t follow the rules of language very closely. Computers can’t do that with instructions, though, so programming language syntax is very strict.
As you saw previously, Java code is actually translated into something that the computer can execute. This process is called compiling, and also does the job of checking that your syntax is correct.
In this lecture you will see some short fragments of Java code that will demonstrate the basic components and rules of the language. Once you are familiar with these you will be ready to write classes, and then programs that make use of classes.
2.2 The CodePad in BlueJ
You can experiment with short fragments of Java code using the CodePad feature in BlueJ. The CodePad is an area of the BlueJ interface, shown in the figure below, that allows you to type Java code and immediately see the effect that it has. It is not open by default when you start BlueJ. The demo video shows you how to open and use the CodePad📹 WATCH DEMO: Using the CodePadX
In the previous lecture you saw some examples of information (or data) that is stored and used in a program. Objects have properties, for example, and information is passed to methods as parameters. You will see many other uses for information in programs throughout this module.
In general, programs store information using variables. Variables are stored in the computer’s memory, and can be retrieved from that memory when needed by the program.
A variable is an item of information which has a value and is named by an identifier. It is called a variable because its value may change as the program runs. By giving it an identifier you can always refer to it by name, so that its value can be retrieved from memory.
A variable name in Java must be a legal identifier – a series of characters that begins with a letter. Example: myVariable. The name cannot contain spaces. The name must not be a Java keyword (e.g. class), or true, false or null.
By convention variable names start with a lower case character. If the name consists of more than one word, each following word begins with an uppercase letter.
A variable has a type that determines what kind of values it can hold. As you saw in the previous lecture there can be many different types of data in a program, such as numbers (integers, floating point numbers), characters, and so on.
It is important for the type of a variable to be defined, as the computer needs to store its value. As the value may change, the computer needs to reserve enough space in memory to store any valid value of that type. If a variable is an integer, then the space reserved must be able to hold the minimum and maximum possible values for an integer and any value in between, for example.
In Java, some types of information are stored as primitive types. This means that a single piece of information is stored as the value for a variable which has a primitive type. Java has a key word to identify each type. Primitive data types include:
keyword description byte Byte-length integer short Byte-length integer int Integer long Long integer float Single-precision floating point double Double-precision floating point char A single Unicode character boolean A Boolean value (true or false)
There are different sizes of integer types. A byte uses a single byte of memory and can only store values within the range -128 to 127. The other integer types use more bytes of memory to store each value and can store larger numbers. Float and double types store floating point numbers, and differ in the number of decimal places of precision they can store.
Another useful data type for variables is String. A string stores a collection of characters, so it is not a primitive type.
Java also allows variables which have object types. Object type variables don’t store single values. Instead, they hold references to objects. We will look at object types later in the module.
Declaring a variable
To give a variable a type and a name, and make sure space is reserved for it in memory, you write a variable declaration, e.g.
Note that a variable declaration is a statement in Java that needs to end in a semi-colon. We will look at statements in more detail shortly.
Initialising a variable
Variables can be initialised with an assignment statement when they are declared, e.g.
int myVariable = 10;
Other types of variable
Here are some examples of how to declare and initialise other types of variable. Note the way the value is written in each case. For example, float values can be written as a decimal number followed by the letter f, while double values can be just the number. char values are enclosed in single quotes, String values in double quotes. boolean variables can only have the values true and false.
float myFloat = 10.1f; double myDouble = 10.1; boolean myBoolean = true; char myChar = 'j'; String myString = "java";📹 WATCH DEMO: Declaring variablesX
A variable is not much use unless you do something with it, so now we want to start to write code that does more than simply assign values. Firstly, you need to learn about operators. An operator performs a function on one, two or three operands. An operand can be, for example, a variable name or a literal value. Java operators include the following:💡 Arithmetic operators
💡 Relational and Conditional operators
Assigning using operators
You can assign a new value to a variable once it has been declared. The new value replaces the currently value if the variable has been initialised. The basic assignment operator is =, e.g.
//assigns a value to a variable, replacing its current value x = 3 //assigns the value of variable y to variable x x = y
The = sign has a special meaning in Java programming which is different to its meaning in maths. It assigns the value on its right hand side to the variable named on its left hand side. It does not simply mean that the two sides are equal.
In Java there are also some shortcut assignment operators. For example
x = x + 3
which adds 3 to the value of the variable x, can be written as
x += 3
Similarly, we can have
x-=1, x*=10, x /=2, x %= 3
If you simply want to increment or decrement a variable by 1 you can use one of the shortcut arithmetic operators, for example
Unlike the other arithmetic operators, ++ and – can assign a new value to a variable without the use of an assignment operator.X
Operator Example Description + x + y Adds x and y, also concatenates strings - x - y Subtracts y from x * x * y Multiplies x by y / x / y Divides x by y % x % y Gives remainder on dividing x by y Shortcut Operators ++ x++ Increments x by 1; gives value of x before increment ++ ++x Increments x by 1; gives value of x after increment -- x-- Decrements x by 1; gives value of x before decrement -- --x Decrements x by 1; gives value of x after decrement
Note that if an integer and a floating-point number are used as operands to a single arithmetic operator, the result is floating point.XRelational operators
Operator Example Description > x > y Returns true if x is greater than y >= x >= y Returns true if x is greater than or equal to y < x < y Returns true if x is less than y <= x <= y Returns true if x is less than or equal to y == x == y Returns true if x is equal to y != x != y Returns true if x is not equal to y
Operator Example Description && a && b Returns true if a and b are true || a || b Returns true if a or b is true ! !a Returns true if a is false
An expression is a series of items, which can include literal values, variables, operators and method calls that evaluates to a single value. You sometimes need to use brackets to ensure that operators are applied in the order you want where this differs from the default operator precedence – for example * and / are applied before + and - by default in an expression. You can see a complete table of operator precedence here
//evaluates to Boolean true if x is less than or equal to 12 x <= 12 //evaluates to result of multiplication x * y * z //evaluates to Boolean true if y is between 4 and 9 (y > 3) && (y < 10) //evaluates to 42 (3 * y is evaluated first) x + 3 * y //evaluates to 150 (x+3 is evaluated first) (x + 3) * y //increments x and evaluates to the new value ++x📹 WATCH DEMO: ExpressionsX
A statement forms a complete unit of execution that instructs the computer to perform an action such as assigning a variable. A statement is terminated with a semicolon (;). You have already used statements to declare and initialise variables, but there are many other actions that can be performed using statements.
//assignment x = x + 10; //decrementing x--; //declaration and assignment double y = 12.345;
Note that an expression represents a value, while a statement actually does something. A statement may contain expressions. For example:
x + 10 //is an expression whose value is 10 more than the value of the variable x, while x = x + 10; //is a statement which assigns the value of that expression to the variable x. A statement does not have a value.📹 WATCH DEMO: StatementsX
It is often necessary for a program to display output to the user. In Java you can show output like this:
A System.out statement writes its output to a separate BlueJ window called the Terminal Window. It works in any Java program, not just in the CodePad.📹 WATCH DEMO: Displaying outputX
You’ve been introduced in this lecture to the following concepts:
Variables, Operators, Expressions, Statements, Output
In the next lecture you will start to learn how to write the source code to create your own classes, making use of the Java language concepts in this lecture.Download PDF Version