Greg's Blog

helping me remember what I figure out

Java 102

| Comments

The second part of my Java learning extravaganza. This time looking at variables, operators, expressions and statements. As ever all mistakes are mine…

Variables

Variables allow the storage of an object’s state. A name and a type must be explicitly provided, it takes this form:

“type name”

A type helps define what values the variables can store and the type of operations that can be carried out. For example you can carry mathematical operations on variables of the type integer. These are the different types that are at your disposal:

(integers)
byte == Byte-length integer == 8-bit two’s complement
short == Short integer == 16-bit two’s complement
int == Integer == 32-bit two’s complement
long == Long integer == 64-bit two’s complement

(real numbers)
float == Single-precision floating point == 32-bit IEEE 754
double == Double-precision floating point == 64-bit IEEE 754

(other types)
char == A single character == 16-bit Unicode character
boolean == A boolean value (true or false) == true or false

Since Java also specifies the format and size of these types, you do not have to worry about system dependencies, which is another great abstraction feature for code running on different systems. There is an additional reference type, which consists of arrays, classes and interfaces. These types don’t actual contain values, but rather reference addresses in memory where the values are kept.

The following naming convention is suggested:

“Variable names begin with a lowercase letter, and class names begin with an uppercase letter. If a variable name consists of more than one word, the words are joined together, and each word after the first begins with an uppercase letter, like this: isVisible. The underscore character (_) is acceptable anywhere in a name, but by convention is used only to separate words in constants (because constants are all caps by convention and thus cannot be case-delimited).”

In addition to this a variable is scoped. This scope depends on where the variable is declared, i.e. in relation to other code elements. There are four categories into which they can fall:

A member variable is declared outside of any method or constructor (what is a constructor) and belongs to a class and hence can be accessible from the outside. You usually find them after the declaration of the class and before the first method is defined.

public class YourClassName extends Applet {
int memberNumber = 1;
}

Local variables a declared within a block of code and are only accessible by that method (for example you can define local variables in your main variable).

public static void main(String[] args) {
int localNumber = 1;
}

This variable is no accessible right to the closing curly bracket of the main method.

Method parameters are values that are passed to methods and constructors. These can be values that the method needs to operate on and it’s scope is the entire method. args is an example of a method parameter.

Exception-handler parameters sit between the curly brackets after a catch statement. Rather than being values passed to a method they are arguments.

Final variables

These are variables that are declared once and whose values never change once assigned. Changing the value of a final variable will result in a compile error. You can declare them like such: “final int aFinalVar = 0;”. Alternativaly you can declare them (“final int aFinalVar;”) and then assign them a value later. But once assigned a value has been assigned that’s it no more changes.

Operators

There are three different types of operators: unary (“++” as in i++;), binary (“=” as x=y;) and tertiary (“?:” as in 0 ? 1 : false). unary allows for postfix and prefix notation. Postfix means that the operator appears after the variable (or as it’s also known the operand) and hence this means that the value is read before incrementing/decrementing. Prefix simply means that the operator appears before the operand and this means that values are incremented/decremented before being read. Their role is to perform and operation on a value and as a result return a value. Furthermore operators can be categorised as follows:

Arithmetic Operators: +,-,*,/,% [computes the remainder of a division on two operands]. Generally speaking these carry out operations on two operands [binary]. However +.- have unary function as well. + promotes an operand from byte, short or char to int. - negates a value (i.e. -1).

Relational and Conditional Operators: >, >=, <, <=, ==, !=. These compare two values to determine the relationship [usually true or false]. There more such operators however: && [eg (a>c) and (b<c) are true], || [or], ![false], & [for bolean values: if a&b are true. For numbers it does a bitwise operation], |, ^.

Shift and Logical Operators [bitwise operators]: >> [x >> z, shift x right by z], << [x << z, shift x left by z], >>> [x >>> z, shift x right by z (unsigned)], & [and], | [inclusive or], ^ [xor], ~ [bitwise complement].

Bitwise and operations result in 1 being returned when operand 1 and 2 are set to 1, else it returns 0. If a 1 is in either operand 1 or two then bitwise ”inclusive or” returns 1. The only time it returns 0 is when operand 1 and 2 are set to 0. ”exclusive or” return1 1 whenever operand 1 and 0 are not equal. For example if op1 = 1 and op2 = 0 or op1 = 0 and op2 = 1, then the result is 1. if op1 = 1 and op2 = 1, or even op1 = 0 and op2 = 0 then the result would be 1. Complement operators simply revert the outcome. So if operand bit is 1, then the result is 0

When do you use them? Useful for setting for many Boolean flags.

unsigned?? Not sure yet watch this space…

Assignment Operators: =. These operators basically assign 1 value to another. The other ones are shorthand annotations also assigning one value to another: += [op1 += op2 equal to: op1 = op1 + op2], -= [op1 -= op2 equal to: op1 = op1 - op2], *=, /=, %=, &=, %=, |=, ^=, <<=, >>=, >>>=.

Other Operators

  • ?: = Shortcut if-else statement
  • [] = Used to declare arrays, create arrays, and access array elements
  • . = Used to form qualified names
  • ( params ) = Delimits a comma-separated list of parameters
  • ( type ) = Casts (converts) a value to the specified type
  • new = Creates a new object or a new array
  • instanceof = Determines whether its first operand is an instance of its second operand

Expressions, statements and blocks

Variables and operators from the building blocks of the above entitled section. What is an expression? An expression is a segment of code that carries out computations and returns values. A statement is made of one or several expressions and are grouped together into complete units of execution. Zero or Several statements that are grouped together are known as chunks of code and separated by ”{}”.

Expressions: carry out the work of the program. On top of execution they control the flow of the program. 1 rule is that the values of each part of the expression must have the same matching data type. The order of execution is important and in your coding you should make your expressions as unambiguous as possible (this helps you read your code in the long term as well). You can explicitly indicate the order of execution by using ”()”. If you don’t this is determined by precedence. Here is the order of precedence:

  • postfix operators [] . (params) expr++ expr–
  • unary operators ++expr –expr +expr -expr ~ !
  • creation or cast new (type)expr
  • multiplicative * / %
  • additive + -
  • shift << >> >>>
  • relational < > <= >= instanceof
  • equality == !=
  • bitwise AND &
  • bitwise exclusive OR ^
  • bitwise inclusive OR |
  • logical AND &&
  • logical OR ||
  • conditional ? :
  • assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

If operators are of equal precedence, they are evaluated based on the following rules. Binary operators (other than assignment ones) are executed from left to right. Assignment ones on the other hand are evaluated from right to left.

Statements: Equate roughly to sentences and logically forms a complete unit of execution. There are four groups of statements: assignment (x=1), increment (x++), method call (System.out.println(x)) and object creation (int integerObject = new Integer(4)). However you also have declaration statements (x=1) and control flow statements (if else).

What’s the diff between assignment and declaration? Again watch this space

Blocks: As stated 0 or more statements that are grouped together by curly braces, eg:

if (this is true) {
do something
} else {
do something else
}

Control flow statements

The above code is also an example of a Control Flow Statement. Without control flow statements the interpreter executes the code line by line, reading from left to right. Control flow is used to selectively execute statements or repeatedly execute them. There are four types of control flow statements: looping (for, while, do-while), decision making (if/else, switch/case), exception handling(try/catch/finally/throw), branching (break, continue, label:, return). Please note that goto is a reserved word but not used by Java.

What is an interpreter? Yet another question to haven’t seen the answer yet

  • While” executes the statement if the condition is true
  • Do-While” executes the statement first, then evaluates the condition (the opposite of “while”)
  • for” is a loop and the evaluation is carried out at the start of each loop.
  • if” used to selectively execute the program. Breaks out of the flow once one condition has been met, which could be Boolean or integer based.
  • switch”, another flow control statement that can only evaluate integer values. Note that the value of each case statement must bee unique and also each statement is ran through even if a condition is met. The only way to break out of a “case” is by placing a “break;” statement for when the conditions is met.
  • try/catch” used for exception handling and helps to gracefully resolve an error. The “try” part is for the statement where an error might occur. The “catch” is associated with the “try” and has a statement that attempts to resolve the error if an exception is encountered in the try block.

Branching statements

There are three types of such statements: break, continue and return. The first two can be used with or without a label.

break: This allows the application to break out of a loop and return to the normal flow of the application, i.e. after the loop or switch statement (also known as the innermost switch/for/do-while/while). The labelled approach terminates an outer statement. If can be used for nested loops to terminate both the inner and outer loops to return to the application flow.

continue: is slightly different in that it can allow the control flow to skip to the next iteration. Unlabeled this statement also affects the innermost loop. When labelled it can be used to skip to the next outer iteration of the loop.

return: is used to exit the current method. It can or cannot return a variable/result of the method. Note that if a method is declared as void use just “return” as no value is expected to be returned from such a method. Also note that a value returned from a method must match the type specified by the method’s declared return type.

And thus ends another review of what I have digested this week. Next time, heaps more on objects!!