Syntax errors & Semantic Errors PDF

Title Syntax errors & Semantic Errors
Course Programming 1
Institution University of the People
Pages 2
File Size 74.2 KB
File Type PDF
Total Downloads 51
Total Views 161

Summary

Programming 1 CS1102 Discussion Forum for reference only...


Description

The Java language, like other programming and natural languages, has syntax rules (Eck, 2020). These rules contain exact instructions and restrictions for the right code writing to allow the compiler to understand and translate it. When the code contains a syntax error, the compiler can't translate it into Java bytecode and informs the programmer about the syntax error. For example, the syntax rules require putting a semicolon at the end of each expression statement. The example code does not follow this rule:

public class DiscussionForum1Example { public static void main(String[] args) { System.out.println(27/2) } }

So, if I’ll try to run this code, I’ll get the message about the syntax error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Syntax error, insert ";" to complete BlockStatements

at DiscussionForum1Example.main(DiscussionForum1Example.java:5) The fixed code: public class DiscussionForum1Example { public static void main(String[] args) { System.out.println(27/2); } }

The output: 13

After fixing the code by adding the semicolon, the code was executed without any error message, but the output is not as expected. 27 divided by 2 equals 13.5 but not 13. So, here we meet another type of error - semantic error. The interpreter will not warn us about this type of error, and the program will function right, but not as the programmer expected. In my example, I ignored the fact that when I ask Java to divide two integers, the division's result will be an integer. To get the right result of my expression, I have to convert at least one of the integers into double, and then the output will also be double type.

The fixed code:

public class DiscussionForum1Example { public static void main(String[] args) { System.out.println(27.0/2); } }

The output: 13.5

As expected....


Similar Free PDFs