Syntax and Semantics

  • Syntax: the rules determining how the language, i.e. the program, is constructed.
      • Example English language: A sentence must start with a capital letter.
      • Example Java (programming language): a command must be ended with a semicolon.
    • In languages used to communicate by humans (ex. English), the meaning is often still understood if the syntax is wrong. However, in programs the syntax must be correct, otherwise the program won't work correctly or at all.
    • Note, however, that a statement can be syntactically correct but still does not do what was intended by the programmer.
      • ex. a=b; is correct syntactically, however b=a; is too. Both statements contain the same variables and functions but the results are different.
      • ex2. System.out.println("Hello World"); and System.out.println("bye"); are both syntactically correct but have different meanings. This leads over into semantics explained below.
  • Semantics: the meaning of a collection of statements, so what you actually want the program to do.
    • Depending on the context, arguments can be created, that are syntactically correct but are meaningless.
      • Example English language: "I watched into the street beside the moon because he felt so metallic". This phrase makes no sense but the syntax is correct.
      • Example if you want to create a program that adds two numbers in Java: c=a*b;. The syntax of this statement is correct, however the semantics is not, since we want to add the numbers and not multiply them.

Last modified by: Jocbe
Last modified: 16th February 2011

  • Jones, Richard. Computer Science Java Enabled. Victoria: IBID Press, 2004.
  • Common sense