next up previous
Next: Logical errors Up: Unit 09 Previous: Syntax errors

Semantic errors

Semantic errors indicate an improper use of Java statements.

Let us see some examples of semantic errors.

Example 1: Use of a non-initialized variable:

int i;
i++;    // the variable i is not initialized

Example 2: Type incompatibility:

int a = "hello"; // the types String and int are not compatible

Example 3: Errors in expressions:

String s = "...";
int a = 5 - s;  // the - operator does not support arguments of type String

Example 4: Unknown references:

Strin x;                     // Strin is not defined
system.out.println("hello"); // system is not defined
String s;
s.println();        // println is not a method of the class String

Example 5: Array index out of range (dynamic semantic error)

int[] v = new int[10];
v[10] = 100;           // 10 is not a legal index for an array of 10 elements

The array v has been created with 10 elements (with indexes ranging from 0 to 9), and we are trying to access the element with index 10, which does not exist. This type of error is not caught during compilation, but causes an exception to be thrown at runtime.


next up previous
Next: Logical errors Up: Unit 09 Previous: Syntax errors