Statements and Expressions


As was quoted earlier, "Java has adopted wholesale the basic statements of C++, which in turn come directly from C". In this section we will focus on some of the important differences.

In general, there is no comma expression.
Consider the following C program which contains a comma expression.

#include < stdio.h>
int main(){
int t;
int i=2;
int j=4;
t=(i+=2,j==i);
printf("%i\n",t);
return 0;
}

Running it produces 1 as output.

However, compiling

class Testit{
public static void main(String args[]){
boolean t =true;
int i=2;
int j=4;
t=(i+=2,j==i); }
}
Produces

C:\JAVA> javac Testit.java
Testit.java:6: ')' expected.
t=(i+=2,j==i)

However, one can use comma's for sequential execution within the control expressions of a for statement.

In particular,

public class T1{
    public static void main(String args[]){
        int i,j;
        for(i=1,j=2;(i+j)< 10;i++,j++)
    System.out.println(new Integer(i+j).toString());
    }
}

compiles and produces


C:\drop> java T1
Symantec Java! JustInTime Compiler Version 210.054 for JDK 1.1.2
Copyright (C) 1996-97 Symantec Corporation

3
5
7
9

The control expression of a conditional statement must be boolean valued.
In particular, gone is everyone's favorate run time bug, using = in place of ==.

Valid C code such as

int a;
a=expression;
if(a = 1) /* it is now! */
{ something}

produces a Java compile error.


The goto statement has been eliminated.
The role of the unrestricted goto has been controversial for some time. On one hand it can be misused to create "spaghetti logic" in programs. At the same time there are situations where it provides the ideal programming solution to a flow of control problem. Having removed the goto Java provides alternatives to handle situations where it would provide a suitable solution.

Next a labeled break statement.

class BreakTest{
    public static void main(String args[]){
    boolean t=true;
    a:{
        b:{
            c:{
                System.out.println("before");
               if(t)break b;
               }//c
            System.out.println("will not execute");
        }//b
        System.out.println("next to execute");
    }//a
   }//main
}//class

Here is the output.

C:\JAVA> java BreakTest
before
next to execute

At first glance, it appears that labeled breaks and continues can be used to simulate a goto, however, there are restrictions on their use as illustrated by the following output which results from removing the if clause from the statement containing the break

 BreakTest.java:11: Statement not reached.
            System.out.println("will not execute");
            ^
1 error
Interestingly, if you insert the line

if(true) break b;

The program compiles and runs as before. More on this point later.

Table of Contents