Start learning free

LESSON 6 OF 671 · WELCOME TO JAVA

Name Errors in Java

Lesson

TL ; DR:

  • A NameError occurs when Java sees a word it does not recognize. Some examples:

  • Misspelling a function name:

    System.out.prntln("Heyooo!"); // NameError: name 'System.out.prntln' is not defined
    

  • Misspelling a variable name:

    String animal = "parrot";
    System.out.println(anmal); // NameError: name 'anmal' is not defined
    

  • When Java encounters a name error, it immediately stops executing your code and throws a NameError instead.




Full lesson:

Humans are prone to making mistakes. Humans are also typically in charge of creating computer programs. To compensate, programming languages attempt to understand and explain mistakes made in their programs.

Here are two common errors that we encounter while writing Java code:


The syntax error:

Syntax errors are mistakes in the use of the Java language, and are analogous to spelling or grammar mistakes in a language like English. For example, the sentence "Would you some tea?" does not make sense – it is missing a verb.

Syntax error means there is something wrong with the way your program is written. Some examples:

1. Misuse of commas when declaring a string:

String greeting = 'Hey there!";

When we run this code we'll get an error: unclosed character literal.

2. Leaving out a parantheses:

System.out.println"Hey");

When we run this code we'll get an error: not a statement.


The reference error:

A reference error occurs when the Java interpreter sees a word it does not recognize. Some examples:

1. Misspelling a class / function name:

System.out.prntln("Hey");

When we run this code we'll get an error: cannot find symbol: method prntln(String).

2. Using a non-existent variable / Misspelling a variable's name:

String animal = "parrot";
System.out.println(aniimal);

When we run this code we'll get an error: cannot find symbol: variable aniimal.


Assignment
Follow the Coding Tutorial and let's practice with errors!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check