Thursday, April 4, 2013

common java syntax error

Common Java syntax errors

Capitalisation of key words

Since you get into the habit of writing class names in capital letters you will occasionally find yourself writing keywords such as class andint with a capital beginning letter. The compiler will object to this and will issue an error message which depends on which keyword was capitalised. The compiler will issue an error message such as:
Line nn: class or interface declaration expected
when, for example, you capitalise the keyword class.

Writing a string over a new line

Sometimes you will need to write a long string. A common error is to have a new line embedded in the string. The compiler will object to this and will issue an error message such as:
Line nn: ';' expected
When this happens the solution is to split the string into two, making sure that neither string has a new line in it, and concatenate them with +. Thus you might replace:
String s = "A very long string which just happens to go over the end of a 
line and causes a problem with the compiler";
with:
String s = "A very long string which just happens to go over the end "+
"of a line and causes a problem with the compiler"

Missing brackets in a no-argument message

When you use a method which has no arguments you should place brackets after the name of the method. For example, if you have declared a method carryOut with no arguments and you want to send a message corresponding to the method to the object objSend then you should code this as:
objSend.carryOut()
rather than:
objSend.carryOut 
The compiler will usually emit an error message of the form:
Line nn: Invalid expression statement

Forgetting to import a package

This one of the most common errors that inexperienced Java programmers make. If you forget to put the required import statement at the beginning of a program, then the compiler will respond with a message such as:
Line nn: Class xxxx not found in type declaration
Don't forget, though, that java.lang is imported automatically and, hence, does not need an import statement.

Treating a static method as if it were an instance method

Static methods are associated with messages sent to classes rather than objects. A common error is to send static method messages to objects. For example, in order to calculate the absolute value of an int value and place it into the int variable you should write:
int result = Math.abs(value);
rather than:
int result = value.abs();
This gives rise to a variety of syntax errors. The most common one is of the form:
Line nn: Method yyyy not found in class xxxx.
where yyyy is the name of the method and xxxx is the name of the class within which it is called.

Case-sensitive errors with classes

This is another category of error which is very common. Java is case sensitive so, for example, it will not recognise string as a valid type in the language as you should have written String. It will generate an error message of the form:
Line nn: Class xxxx not found in type declaration.
where xxxx is the name of the class which has not been given the correct capitalisation.

Case-sensitive errors with variables

It is also quite easy to miss the fact that variables are case sensitive. For example, you may have declared the variable linkEdit as an int and then tried to refer to linkEdit within a class. This gives rise to error messages of the form
Line nn: Undefined variable: xxxx
where xxxx is the name of the variable which has been mistyped.

Missing } brackets

This is a common programming error in any programming language and can be eradicated by means of a proper indentation scheme.

Missing class brackets

A common bracketing error that you will often make is to omit the final } bracket that delimits the end of a class.

Writing the wrong format for a class method

Class methods have the form:
ClassName.MethodName(Argument(s))
A common error is to forget the class name. If you do, then you will get an error message of the form:
Line nn: '}' expected

Specifying method arguments wrongly

When you define classes you should prefix each argument with the name of a scalar type or the name of an existing class. For example:
public void tryIt(int a, int b, URL c)
A common error that programmers from other languages make is to forget to prefix every argument with its type. For example, an erroneous version of the definition above would be:
public void tryIt(int a, b URL c)
This type of error will give rise to error messages of the form:
Line nn: Identifier expected

Forgetting the fact you should send messages to objects

This is a common error committed by programmers who have only recently changed to object-oriented programming. As an example of this consider the method tryIt, which has two int arguments and which delivers an int value. Assume that this method is involved in sending a message to an object destination. This should be written as:
int newVal = destination. tryIt(arg1, arg2)
where the arguments are ints which have been declared somewhere. A common mistake is to write this as:
int newVal = tryIt(destination, arg1,arg2)
This gives rise to error messages of the form:
Line nn: ')' expected

Assuming that == stands for value equality

== is used with scalars as a means of comparing values. However, when it is applied to objects then it compares addresses. For example, the if statement:
if(newObj1 == newObj2){
...
}
will execute the code denoted by the three dots only if the first object occupies the same address as the second object. If the objects occupied different addresses, but still had the same values for their instance variables, then it would evaluate to false. Unfortunately this does not give rise to any syntax errors, but will show up when any program containing the error is executed.

Omitting void in methods

When a method returns no result, but just carries out some action, you need to use the keyword void in front of the name of the method. If you do not use this keyword, then it will give rise to error messages of the form:
Line nn: Invalid method declaration; return type required

Omitting break from case statements

This is an error which is committed in both object-oriented and procedural languages. If you want the branch of a case statement to just finish and exit to the end of the case statement, then don't forget to include the break statement as the last statement in the branch. If you do not do this, then execution will continue with the next branch underneath the one in which the break statement was omitted.

Omitting the return in a method

When a method returns a value, then the body of the method should include at least one return statement which returns the right type of value. Failing to do this will generate an error message of the form:
Line nn: Return required at end of xxxx
where xxxx is the method which does not contain the return.

Making an instance variable private and then referring to it by name in another class

When you tag an instance variable as private you are not allowed to access it by name outside its class. The only way that you can access such instance variables is through methods which are declared in the class in which the instance variables are defined. This gives rise to error messages of the form:
Line nn: Variable xx in class xxxx not accessible from class yyyy
where xx is the private variable, xxxx is the class in which it is defined and class yyyy is the class in which it is referred to.

Using a variable before it is given a value

Again this is a common error found in both object-oriented and procedural languages. In Java, scalars are intialised to zero or some default value so there will be no error indication and any problems that arise will be signaled by erroneous results or some side effect such as an array going over its bounds. Objects will be initalised to null and any attempt to reference an uninitialised object will be caught at run time.

Assuming the wrong type of value is generated by a message

This is a common error to make when using the Java packages. A typical example is using a method which delivers a string that contains digits and treating it like an integer. For example, the method getInteger within java.lang.Integer delivers an Integer and any attempt to use that value as, say, an int will give rise to an error message of the form:
Line nn: Incompatible type for declaration can't convert xxxx to yyyy

Confusing prefix operators with postfix operators

This is an error that comes with any C-like language. Postfix operators such as ++ and -- deliver the old value of the variable to which they are applied, while prefix operators deliver the new value. Thus, if x is 45 and the statement:
y = ++x 
is executed, then y and x both become 46. If the statement
y = x++
is executed, then y becomes 45, while x becomes 46. These errors will not be signalled at compile time, but will emerge during run time.

Forgetting that arguments are passed by reference to methods if they are objects

When an object is used as an argument to a method, then its address is passed over and not a value. This means that you can assign values to such arguments. If you treat them as values this will not strictly be an error, but will not be making use of the full facilities of an object-oriented programming language.

Forgetting that scalars are passed by value to methods

You cannot treat an argument which is a scalar as if it can be assigned to. This will not be signalled as a syntax error. However, it will show up as a run-time error when you write code which assumes that the scalar has been given a value by a method.

Misusing size when applied to strings and arrays

size is an instance variable associated with arrays and a method when associated with strings. If you mix them up by, for example writing:
arrayVariable.size()  
or
stringVariable.size
then the first would generate an error message of the form:
Line nn: Method size() not found in class java.lang.Object 
and the second would generate an error message of the form:
Line nn: No variable size defined in java.lang.String

Using a constructor which does not exist

You may use a constructor which has not been defined. For example, you may have a class X which has a one int constructor, a two int constructor and a threeint constructor and yet you may have used a four int constructor. This would be picked up at compile time and an error of the form:
Line nn: No constructor matching xxxx found in class yyyy
would be generated, where xxxx is the signature of the constructor that you have tried using and yyyy is the name of the class which it should have been defined in.

Calling a constructor in a constructor with the same name

For example, you may have defined a class X with a two int constructor and a one int constructor and inside the two int constructor there is a reference to X(argument). This will be flagged as an error and will generate an error message of the form:
Line nn: Method xxxx not found in yyyy
where xxxx is the name of the constructor and its arguments and yyyy is the name of the class which it is defined in. The solution is to use the this keyword.

Assuming that two-dimensional arrays are directly implemented in Java

This gives rise to erroneous code such as:
int [,] arrayVariable = new [10,20] int
This is illegal and will give rise to an errors of the form:
Line nn: Missing term
and:
Line nn: ']' expected
You can implement many-dimensional arrays in Java, but they are treated like single-dimension arrays which contain single-dimensional arrays which contain single dimension arrays, etc.

Treating a scalar like an object

Scalars such as int and float are not objects. However, sometimes you want to treat them as such, for example when you want to deposit them in a Vector, as in the code:
Vector vec = new Vector();
vec.addElement(12);
If you write code such as that shown above then it will give rise to syntax errors of the form:
Line nn: No method matching xxxx found in yyyy
where xxxx is the name of the method which is used and yyyy is the name of the class which expects an Object. The solution is to use the object wrapper classes found in java.lang to convert them to objects.

Confusing scalars and their corresponding object types

When you have scalars such as int it is easy to write code which assumes that they can be treated as if they were objects. For example, the code:
int y = 22;
Integer x = y; 
will give rise to an error message of the form:
Line nn: Incompatible type for declaration. Can't convert xxxx to yyyy
where xxxx and yyyy are the classes involved.

Mistyping the header for the main method

When you want to execute a Java application you need to declare a method which starts with:
public static void main (String []args){
If you mistype any part of this line or miss out a keyword, then a run-time error will be generated. For example, if you miss out the keyword static then an error message of the form:
Exception in thread main.....
will be generated at run time.

Common Errors while programming

Chapter 1: Introduction to Computers, Programs, and Java
1.  Q: When you compile your program, you receive an error as follows:
2.   
3.  %javac Welcome.java
4.  javac not found
5.   
6.  What is wrong?
  1. A: Two possible reasons: 1. Java is not installed on your system; or 2. Java is installed, but the environment variable PATH is not set.
8.  Q: When you compile your program, you receive an error as follows:
9.   
10.%javac Welcome.java
11.javac: file not found: Welcome.java
12.Usage: javac 
13.use -help for a list of possible options
14. 
15.What is wrong?
  1. A: File Welcome.java does not exist in the directory. Check if Welcome.java is in the current directory.
17.Q: When you run your program, you receive an error as follows:
18. 
19.%java Welcome
20.Exception in thread "main" java.lang.NoClassDefFoundError: Welcome
21. 
22.What is wrong?
  1. A: File Welcome.class does not exist. You have to first compile Welcome.java to produce Welcome.class in the current directory.
24.Q: When you run your program, you receive an error as follows:
25. 
26.%java Welcome
27.Exception in thread "main" java.lang.NoSuchMethodError: main
28. 
29.What is wrong?
  1. A: Please check if you have a main method in Welcome.java or you have spelled the method public static void main(String[] args) correctly.
31.Q: When you compile your program, you receive an error as follows:
32. 
33.%javac Welcome.java
34.Welcome.java:2: cannot find symbol
35.symbol  : class string
36.location: class Welcome
37.  public static void main(string[] args) {
38.                          ^
39. 
40.1 error
41. 
42.What is wrong?
  1. A: Java is case-sensitive. string should be spelled as String.
Chapter 2: Primitive Data Types and Operations
1.  Q: What is wrong in the following code?
2.     
3.  public class Test {
4.    public static void main(String[] args) {
5.      i = 1;
6.      j = i * i * i;
7.    }
8.  }
  1. A: You will get a compile error that indicates symbol i cannot be resolved. Every variable must be declared before being used.
10.Q: What is wrong in the following code?
11.  
12.1  public class Test {
13.2    public static void main(String[] args) {
14.3      int i;
15.4      j = i * i * i;
16.5   }
17.6 }
  1. A: You will get a compile error that indicates variable i is not initialized in line 3.
19.Q: What is wrong in the following code?
20.  
21.1  public class Test {
22.2    public static void main(String[] args) {
23.3      int i;
24.4      int j = 5;
25.5      System.out.println(j * 4.5);
26.6   }
27.7 }
  1. A: The program compiles and runs fine. However, i is never used. This might be a potential programming error. Most IDE now can alert you of this situation.
29.Q: Why does this program display 0?   
30.1  public class Test {
31.2    public static void main(String[] args) {
32.3      int i = 9;
33.4      int j = 5 / 6 * (i * 4);
34.5      System.out.println(j);
35.6   }
36.7 }
  1. A: This type of mistakes is very common for my students. We have covered this repeatedly in the text. Here just to remind you again 5 / 6 is 0, because both 5 and 6 are integers.
38.Q: What is the output of this program?   
39.  public class Test {
40.    public static void main(String[] args) {
41.      System.out.println(2147483647 + 1);
42.    }
43.  }
  1. A: Run this program. You will see the output is -2147483648. Why? 2147483647 is the largest int value. Adding 1 to this value causes overflow. It is not a runtime error in Java This type of mistakes is very common for my students. We have covered this repeatedly in the text. Here just to remind you again 5 / 6 is 0, because both 5 and 6 are integers.
45.Q: What is the output of the following code?   
46.1  public class Test {
47.2    public static void main(String[] args) {
48.3      System.out.println("1 + 2 is " + i + j);
49.4   }
50.5 }
  1. A: The program displays 1 + 2 is 12. If you want the output to be 1 + 2 is 3, put i + j inside the parenthese (i + j) to force i + j to be evaluated first.
52.Q: What is the output of this program?   
53. 
54.  public class Test {
55.    public static void main(String[] args) {
56.      char ch = 'a';
57.      System.out.println('a' + 1);
58.      System.out.println(++ch);
59.    }
60.  }
  1. A: for 'a' + 1, 'a' is converted into int. so 'a' + 1 is 97 + 1 = 98. For ++ch, the result is 'b'.
Chapter 3: Selections
1.  Q: What is wrong in the following code?
2.  1  public class Test {
3.  2    public static void main(String[] args) {
4.  3      int i, j, k;
5.  4      i = j = k = 3;
6.  5      if (i < j < k)
7.  6        System.out.println("i, j, and k are in increasing order");
8.  7   }
9.  8 }
  1. A: i < j evaluates to a boolean value, which cannot be compared with k. The correct expression should be (i < j && j < k).
11.Q: What is the output of the following code?
12.  public class Test {
13.    public static void main(String[] args) {
14.      System.out.println(5.0 - 1.0 - 1.0 - 1.0 - 1.0 - 1.0 == 5.0);
15.    }
16.  }
  1. A: Run the program. You will be surprised to see the output is false. Why? because floating-point numbers are not stored in complete accuracy. You are dealing with approximation for floating-point numbers. Don't compare two floating-point numbers using equality == operators.
18.Q: What is the output of the following code?
19.  public class Test {
20.    public static void main(String[] args) {
21.      boolean done = false;
22.      if (done = true) {
23.        System.out.println("done");
24.      }
25.    }
26.  }
  1. A: Run the program. You will see the output is done. Why? you assign true to done. So, the condition is true. To check whether done is true, you should use done == true, or simply
28.if (done) {
29.  System.out.println("done");
30.}
31.Q: What is the output of the following code?
32.  public class Test {
33.    public static void main(String[] args) {
34.      boolean done = false;
35.      if (done);
36.      {
37.        System.out.println("done");
38.      }
39.    }
40.  }
  1. A: Run the program. You will see the output is done. Why? because the if statement ends with
42.if (done);
  
The semicolon ends the if statement. The lines
{
  System.out.println("done");
}
     
are not part of the if statement.
43.Q: What is the output of the following code?
44.  public class Test {
45.    public static void main(String[] args) {
46.      char = 'a';
47.      switch (ch) {
48.        case: 'a': System.out.print(ch);
49.        case: 'b': System.out.print(ch);
50.        case: 'c': System.out.print(ch);
51.      }
52.    }
53.  }
  1. A: Run the program. You will see the output is aaa. Why? There is no break statement for the case statement. Once a case is matched, the statements starting from the matched case are executed until a break statement or the end of the switch statement is reached. This phenomenon is referred to as the fall-through behavior.
Chapter 4: Loops
1.  Q: What is wrong in the following code?
2.    public class Test {
3.      public static void main(String[] args) {
4.        int i = 0;
5.        while (i < 10) {
6.          System.out.println("Welcome to Java!");
7.        }
8.      }
9.    }
  1. A: i is always 0. This is an infinite loop. This is a common error for while and do-while loops. Make sure the control variable changes to cause the loop to stop eventually.
11.Q: What is wrong in the following code?
12.  public class Test {
13.    public static void main(String[] args) {
14.      int i = 0;
15.      while (i < 10)
16.        System.out.println("Welcome to Java!");
17.      i++;
18.    }
19.  }
  1. A: i++ is not in the body of the while loop. So, this is an infinite loop. If the loop body contains more than one statement, use the braces to group them.
Chapter 5: Methods
1.  Q: What is the output of the following code?
2.    public class Test {
3.      public static void main(String[] args) {
4.        int x = 1;
5.        p(x);
6.        System.out.println("x is " + x);
7.      }
8.   
9.      public static void p(int x) {
10.      x = x + 1;
11.    }
12.  }
13. 
A: x is 1. Invoking p(x), the value of x is passed to the parameter in the method. Variable x defined in the main method and x defined in method p are two independent variables.
14.Q: Does Math.sin(90) return the sine value for angle 90 degree?
15.  
A: No. To return the sine value for angle 90 degree, use Math.sin(Math.PI / 2).
Chapter 6: Arrays
1.  Q: What is wrong in the following code?
2.    public class Test {
3.      public static void main(String[] args) {
4.        int[] x = new int[10];
5.       
6.        for (int i = 0; i <= x.length; i++)
7.          System.out.print(x[i]);
8.      }
9.    }
10. 
A: This is a common error, known as off-by-one. Here the array index is from 0 to 9, but the last i in the loop will be x.length (10). At 10, the index is out of range.
11.Q: What is wrong the following code?
12.  public class Test {
13.    public static void main(String[] args) {
14.      int[] x = new int[10];    
15.      p(x);
16.      System.out.print(x[0]);
17.    }
18.   
19.    public static void p(int[] list) {
20.      list[0] = 10;
21.    }
22.  }
23. 
A: The output is 10. When invoking p(x), the reference value of array x is passed to list. The first element in the array is changed in the method.