Java Meta Language and Examples
The meta-language in this section is an augmented version of that in David Eck’s online textbook. I have collected the meta language throughout David’s book, augmented, and reformatted it into this section.
Identifiers
<identifier> is a sequence of one or more characters
<identifier>
s first character must be letter, $, _<identifier>
s subsequent characters must be letter, digit, $, _<identifier>
s are names for variables, methods, classes, enum- Lowecase and uppercase letters are different, which means
Gusty
andgusty
are two different identifiers. - Any meta language with name is an
<identifier>
. For example,<class-name>
and<type-name>
are<identifier>
s.
Expressions
Expressions – syntactically correct combination of variables, literals, operators, and method calls that evaluate to a value with a specific type. The following meta language shows where expressions are found within Java statements
Expressions within Statements
<variable> = <exp>; // The assignment operator is part of expressions <exp>; <methodCall>( <exp>, … , <exp>); // A method call is part of expressions x = y + Math.sin(Math.random()); if (<boolean-exp>) { <statement-list> } switch (<exp>) { <switch-cases> } while (<boolean-exp>) { <statement-list> } do { <statement-list> } while (<boolean-exp>); for ( <init-exp>; <cont-exp>; <update-exp> ) { <statement-list> }
Operator Precedence
Simple expressions are easy to determine the order of operator evaluation. Complex expressions should contain parentheses to help the reader understand the order of operator evaluation.
Description | Operators |
---|---|
Unary | ++ -- ! unary - unary + type-cast |
Multiply Divide | * / % |
Add Subtract | + - |
Relational | < > <= >= |
Equality | == != |
Boolean and | && |
Boolean or | || |
Conditional | ?: |
Assignment | = += -= *= /= %= |
Operators on the same line have the same precedence. When operators of the same precedence are used in an expression without parentheses, unary operators and assignment operators are evaluated right-to-left, while the remaining operators are evaluated left-to-right. You are most likely familiar with left-to-right evaluation. For example, x * y / z
is evaluated as (x * y) / z
. For right-to-left evaluation consider multiple assignments. i = j = k
is evaluated as i = (j = k)
.
Examples:
x = x + 1; x++; x += 1; // equivalent
x = x++ // does not change x
Conditional Expression
<boolean-expression> ? <exp1> : <exp2>
- The expression evaluates to
if is ```true```. - The expression evaluates to
if is ```false```.
Examples:
next = (N % 2 == 0) ? (N/2) : (3*N+1);
Block
{ <statement-list>; }
<statement-list>
is zero or more; - Also
<statement-list>
is; ... ; - A ; terminates a statement.
<statement>
is one defined in Statements ```java
The following are some example Java blocks.
{
System.out.print("The answer is ");
System.out.println(ans);
}
{ // This block exchanges the values of x and y
int temp; // A temporary variable for use in this block.
temp = x; // Save a copy of the value of x in temp.
x = y; // Copy the value of y into x.
y = temp; // Copy the value of temp into y.
}
Class Declarations
All Java code exists with a class
.
Class Declaration
public class <class-name> { <declaration-list> }
<declaration-list>
is zero or more<declaration>
<declaration>
is<declaration-statement>
<declaration>
is<method-defintion>
<declaration>
is<constructor-definition>
- A variable declared at the class level is called field.
Program Declaration
Class Declaration with main
.
public class <class-name> { <declaration-list> public static void main(String[] args) { <statement-list> } <declaration-list> }
<declaration-list>
is zero or more<declaration>
<declaration>
is<declaration-statement>
<declaration>
is<method-defintion>
<declaration>
is<constructor-definition>
main
is the entry point of a program.-
The “command line” arguments are passed as parameters in the
args
parameter. The identifierargs
is used by convention. Any valid Java identifier may be used. For most of our problems, we do not pass command line arguments. BlueJ allows you to pass parameters. The following shows a program run from a command line and the values ofargs
.$ java myProgram one two three arg[0] contains “one” arg[1] contains “two” arg[2] contains “three”
Statements
Statements – unit of execution terminated by a ; Java has three categories of statements.
- Declaration statement - discussed in Primitive Types
- double d = 3.4;
- Expression Statement
- Assignment expression statement - discussed in Assignment Expression
- d = Math.random();
- Increment/decrement expression statement - discussed in Assignment Expression
- i++;
- Method call statement - discussed in Methods, Simple Objects, and Classes and Objects
- mini.addGas(10);
- Object creation expression statement - discussed in Simple Objects and Classes and Objects
- Car mini = new Car(25);
- Assignment expression statement - discussed in Assignment Expression
- Control flow statements – if, switch, while, do-while, for - discussed in Control Flow
Declaration Statements
There are several <declaration-statement>
s. The meta language for each is provided in its own subsection.
Variable Declaration without Expression
<type-name> <variable-name>
<type-name>
can be any primitive or reference type.- Primitive types are
byte
,short
,int
,long
,float
,double
,char
, orboolean
. - Reference types are
String
,Scanner
,Person
,Car
, and many more.
- Primitive types are
- Variables declared without
<exp>
as part of your declaration are initialized as follows.- numeric variables to 0.
char
variables to the null character, which is'\0'
or 0.boolean
variables tofalse
.- Reference variables are initialized to
null
.
- You may declare mulitple variables by using a comma to separate them.
Examples:
int numberOfPeople;
int i, j, k;
boolean isFinished;
String s;
char firstInitial, middleInitial, lastInitial;
double principal; // Amount of money invested.
double interestRate; // Rate as a decimal, not percentage.
Variable Declaration with Expression
<type-name> <variable-name> = <exp>;
<type-name>
can be any primitive type.- Primitive types are
byte
,short
,int
,long
,float
,double
,char
, orboolean
.
- Primitive types are
- The
<exe>
must evaluate to<type-name>
. - You may declare and initialize multiple variables by using a comma to separate them.
Examples:
int numberOfStudents = 23;
double x = 1.0, y = 2.0;
int i = 0, j = 1;
boolean isFinished = true;
String s = "Hello";
int number = 4;
byte bb = 120;
double myPi = Math.PI;
Object Creation Expression Statement
<type-name> <variable-name> = new <type-constructor>(<parameters>);
<type-name>
can be any reference type.- Reference types are
String
,Scanner
,Person
,Car
, and many more.
- Reference types are
Examples:
String s = new String("Hello");
Person p = new Person("Gusty",22), q = new Person("Emily",25);
Scanner in = new Scanner(System.in);
enum Declaration
enum <enum-type-name> {<list-of-enum-values>}
Examples.
enum Season { SPRING, SUMMER, FALL, WINTER }
Season vacation;
vacation = Season.SUMMER;
Array Declaration
<type-name>[] <variable-name>; <type-name>[] <variable-name> = new <type-name>[<array-len>]; <type-name>[] <variable-name> = {<exp>, ... , <exp>};
Declaring an array creates a reference. You need to create the actual array. This can be done at the time of declaration using the {} with a list of expressions that evaluate to the <type-name>
. This can be done at the time or declaration or after the declaration using new
.
int[] a = new int[100];
int x = a.length // x is 100
int[][] a = new int[5][7];
int[] b = {1,2,3,4};
b = new int[100];
Methdod Definition and Call
Method Definition
<modifiers> <return-type> <method-name> ( <formal-parameter-list> ) { <statement-list> } <modifiers> public – method may be called from objects or outside of the class static – method exists independent of an object <method-name> any Java identifier <return-type> any Java type or void void is for a method that does not return a value <formal-parameter-list> <type-name> <formal-parameter-name>, ..., <type-name> <formal-parameter-name> <type-name> any Java type <formal-parameter-name> any Java identifier <statement-list> <statement>; ... <statement>; each statement is terminated with a ;
The formal-parameter-list is a sequence of variable declarations separated by commas. A formal parameter is a variable. The type of the actual parameter must match that of the formal parameter. The value of the actual parameter is copied into the formal parameter when the method is called.
A method definition has a block with a sequence of statements. The method block may contain inner blocks. The top-level meta language for a method defintion could have been written as follows to emphaise a method block.
<modifiers> <return-type> <method-name> ( <formal-parameter-list> ) <method-block> <method-block> { <statement-list> }
Constructor Definition
A constructor definition is like a method defintion except
- The
<return-type>
is omitted. - The
<constructor-name>
must match the<class-name>
.
<modifiers> <constructor-name> ( <formal-parameter-list> ) { <statement-list> }
Method Call Statement
<method-name> ( <actual-parameter-list> ) <method-name> any Java identifier that matches the name of a defined method <actual-parameter-list> <actual-parameter-exp>, ..., <actual-parameter-exp> <actual-parameter-exp> any Java expression that evaluates to the type of the corresponding actual parameter
The actual-parameter-list is a list of expressions separated by commas. Each actual parameter expression must evaluate to the type of its corresponding formal parameter.
Assignment Statements
The most used statement in programming is an assignment statement. Everyone is familiar with assignment statements, and we have used several assignment statements in discussions prior to this. The meta language for assignment statement is as follows.
<variable-name> = <exp>; <variable-name> += <exp>; <variable-name> -= <exp>; <variable-name> *= <exp>; <variable-name> /= <exp>; <variable-name> %= <exp>; <variable-name>++; ++<variable-name>; <variable-name>--; --<variable-name>;
- = is the assignment operator
- The assignment operator is just like the other operators.
<variable-name>
is a variable that has previously been declared.<exp>
evaluates to the same type as<variable-name>
The following are some example Java assignment statements where in each case the <exp>
is simply a literal. You understand expressions from your previous study. We will study the details of expressions in Expressions.
x = 3.0;
x *= 2;
x /= 3.0;
i = 32000;
i++;
--i;
long l = 32000; // declares l and assigns it a value
String s;
s = "Silly";
s += " Gusty";
char c;
c = 'c';
Control Flow Statements
If Statement
if ( <boolean-expression> ) // two-way <statement1>; else <statement2>; if ( <boolean-expression> ) // one-way <statement>; if ( <boolean-expression> ) { // two-way with block <statement-list> } else { <statement-list> } if ( <boolean-expression> ) { // one-way with block <statement-list> }
if ( x > y ) {
int temp; // A temporary variable for use in this block.
temp = x; // Save a copy of the value of x in temp.
x = y; // Copy the value of y into x.
y = temp; // Copy the value of temp into y.
}
int x = -1; int x = -1;
if (x < 0) if (x < 0)
x = 1; x = 1;
else if (x >= 0)
x = 2; x = 2;
Switch Statement
A switch statement is like a multi-way if statement.
switch (<expression>) { case <constant-1>: <statement-list1> break; // required or flow goes to next case case <constant-2>: <statement-list2 > break; . . // (more cases) . case <constant-N>: <statement-listN> break; default: // optional default case <statement-listN1> } // end of switch statement
<expression>
must evaluate toint
,short
,byte
,char
,String
, or anenum
type.- Multiple
case
s can be used. The following is an example.case 1: case 2: case 3: i = 10; break;
- The
break
is required to cause flow to the end of theswitch
; otherwise, flow continued with the nextcase
.
String computerMove;
switch ( (int)(3*Math.random()) ) {
case 0:
computerMove = "Rock";
break;
case 1:
computerMove = "Paper";
break;
default:
computerMove = "Scissors";
break;
}
System.out.println("The computer’s move is " + computerMove); // OK!
While Loop Statement
A while loop will execute loop body zero times if the <boolean-expression>
is false the first time.
while ( <boolean-expression> ) // one statement <statement1>; while ( <boolean-expression> ) { // block <statement-list> }
Most while loops have the block format.
int number = 1; // The number to be printed.
while(number<6){ //Keep going as long as number is <6.
System.out.println(number);
number = number + 1; // Go on to the next number.
}
Do While Statement
A do while loop will execute the loop body at least one time.
do <statement1>; while ( <boolean-expression> ); // one statement do { <statement-list> // block } while ( <boolean-expression> )
For Loop Statement
for ( <initialization>; <continuation-condition>; <update> ) <statement> for ( <initialization>; <continuation-condition>; <update> ) { <statement-list> }
// Typical counting loop
for(<variable>=<min>; <variable><=<max>; <variable>++) {
<statement-list>
}
for(N=1; N<=10; N++)
System.out.println( N );
Break and Continue Statements
break; continue;
break
- breaks out of a loop, continuing flow with the statement following the loop.break
- breaks out of aswitch
, continuing flow with the statement following theswitch
.continue
- goes back to the beginning of a loop, skipping any statements betweencontinue
and the end of the loop.
Examples:
while (true) { // looks like it will run forever! System.out.print("Enter a positive number: ");
N = TextIO.getlnInt();
if(N>0) //the input value is OK, so jump out of loop
break;
System.out.println("Your answer must be > 0.");
}
// continue here after break
Try-catch Statement
try { <statement-list1> } catch ( <exception-class-name> <variable-name > ) { <statement-list2> }
Examples:
double x;
try {
x = Double.parseDouble(str);
System.out.println( "The number is " + x );
}
catch ( NumberFormatException e ) {
System.out.println( "Not a legal number." );
x = Double.NaN;
}
Empty Statement
; // empty statement
if ( done )
;
else
System.out.println(“Not done yet.”)