Improve Article
Save Article
Improve Article
Save Article
Compile-Time Errors: Errors that occur when you violate the rules of writing syntax are known as Compile-Time errors. This compiler error indicates something that must be fixed before the code can be compiled. All these errors are detected by the compiler and thus are known as compile-time errors.
Most frequent Compile-Time errors are:
- Missing Parenthesis (})
- Printing the value of variable without declaring it
- Missing semicolon (terminator)
Below is an example to demonstrate Compile-Time Error:
C++
#include <iostream>
using
namespace
std;
int
main()
{
int
x = 10;
int
y = 15;
cout <<
" "
<< (x, y)
}
C
#include<stdio.h>
void
main()
{
int
x = 10;
int
y = 15;
printf
(
"%d"
, (x, y));
}
Error:
error: expected ';' before '}' token
Run-Time Errors: Errors which occur during program execution(run-time) after successful compilation are called run-time errors. One of the most common run-time error is division by zero also known as Division error. These types of error are hard to find as the compiler doesn’t point to the line at which the error occurs.
For more understanding run the example given below.
C++
#include <iostream>
using
namespace
std;
int
main()
{
int
n = 9,
div
= 0;
div
= n/0;
cout <<
"result = "
<<
div
;
}
C
#include<stdio.h>
void
main()
{
int
n = 9,
div
= 0;
div
= n/0;
printf
(
"result = %d"
,
div
);
}
Error:
warning: division by zero [-Wdiv-by-zero] div = n/0;
In the given example, there is Division by zero error. This is an example of run-time error i.e errors occurring while running the program.
The Differences between Compile-Time and Run-Time Error are:
Compile-Time Errors | Runtime-Errors |
---|---|
These are the syntax errors which are detected by the compiler. | These are the errors which are not detected by the compiler and produce wrong results. |
They prevent the code from running as it detects some syntax errors. | They prevent the code from complete execution. |
It includes syntax errors such as missing of semicolon(;), misspelling of keywords and identifiers etc. | It includes errors such as dividing a number by zero, finding square root of a negative number etc. |
The difference between compile time and run time is an example of what pointy-headed theorists call the phase distinction. It is one of the hardest concepts to learn, especially for people without much background in programming languages. To approach this problem, I find it helpful to ask
- What invariants does the program satisfy?
- What can go wrong in this phase?
- If the phase succeeds, what are the postconditions (what do we know)?
- What are the inputs and outputs, if any?
Compile time
- The program need not satisfy any invariants. In fact, it needn’t be a well-formed program at all. You could feed this HTML to the compiler and watch it barf…
- What can go wrong at compile time:
- Syntax errors
- Typechecking errors
- (Rarely) compiler crashes
- If the compiler succeeds, what do we know?
- The program was well formed—a meaningful program in whatever language.
- It’s possible to start running the program. (The program might fail immediately, but at least we can try.)
- What are the inputs and outputs?
- Input was the program being compiled, plus any header files, interfaces, libraries, or other voodoo that it needed to import in order to get compiled.
- Output is hopefully assembly code or relocatable object code or even an executable program. Or if something goes wrong, output is a bunch of error messages.
Run time
- We know nothing about the program’s invariants—they are whatever the programmer put in. Run-time invariants are rarely enforced by the compiler alone; it needs help from the programmer.
-
What can go wrong are run-time errors:
- Division by zero
- Dereferencing a null pointer
- Running out of memory
Also there can be errors that are detected by the program itself:
- Trying to open a file that isn’t there
- Trying find a web page and discovering that an alleged URL is not well formed
- If run-time succeeds, the program finishes (or keeps going) without crashing.
- Inputs and outputs are entirely up to the programmer. Files, windows on the screen, network packets, jobs sent to the printer, you name it. If the program launches missiles, that’s an output, and it happens only at run time
edmond
1,3721 gold badge14 silver badges18 bronze badges
answered May 11, 2009 at 1:13
Norman RamseyNorman Ramsey
197k59 gold badges359 silver badges531 bronze badges
12
I think of it in terms of errors, and when they can be caught.
Compile time:
string my_value = Console.ReadLine();
int i = my_value;
A string value can’t be assigned a variable of type int, so the compiler knows for sure at compile time that this code has a problem
Run time:
string my_value = Console.ReadLine();
int i = int.Parse(my_value);
Here the outcome depends on what string was returned by ReadLine(). Some values can be parsed to an int, others can’t. This can only be determined at run time
answered May 10, 2009 at 21:30
pufferfishpufferfish
16.2k14 gold badges56 silver badges64 bronze badges
5
Compile-time: the time period in which you, the developer, are compiling your code.
Run-time: the time period which a user is running your piece of software.
Do you need any clearer definition?
answered May 10, 2009 at 21:08
Yuval AdamYuval Adam
159k92 gold badges302 silver badges392 bronze badges
8
(edit: the following applies to C# and similar, strongly-typed programming languages. I’m not sure if this helps you).
For example, the following error will be detected by the compiler (at compile time) before you run a program and will result in a compilation error:
int i = "string"; --> error at compile-time
On the other hand, an error like the following can not be detected by the compiler. You will receive an error/exception at run-time (when the program is run).
Hashtable ht = new Hashtable();
ht.Add("key", "string");
// the compiler does not know what is stored in the hashtable
// under the key "key"
int i = (int)ht["key"]; // --> exception at run-time
answered May 10, 2009 at 21:16
M4NM4N
94k45 gold badges216 silver badges259 bronze badges
1
Translation of source code into stuff-happening-on-the-[screen|disk|network] can occur in (roughly) two ways; call them compiling and interpreting.
In a compiled program (examples are c and fortran):
- The source code is fed into another program (usually called a compiler—go figure), which produces an executable program (or an error).
- The executable is run (by double clicking it, or typing it’s name on the command line)
Things that happen in the first step are said to happen at «compile time», things that happen in the second step are said to happen at «run time».
In an interpreted program (example MicroSoft basic (on dos) and python (I think)):
- The source code is fed into another program (usually called an interpreter) which «runs» it directly. Here the interpreter serves as an intermediate layer between your program and the operating system (or the hardware in really simple computers).
In this case the difference between compile time and run time is rather harder to pin down, and much less relevant to the programmer or user.
Java is a sort of hybrid, where the code is compiled to bytecode, which then runs on a virtual machine which is usually an interpreter for the bytecode.
There is also an intermediate case in which the program is compiled to bytecode and run immediately (as in awk or perl).
answered May 11, 2009 at 2:21
Basically if your compiler can work out what you mean or what a value is «at compile time» it can hardcode this into the runtime code. Obviously if your runtime code has to do a calculation every time it will run slower, so if you can determine something at compile time it is much better.
Eg.
Constant folding:
If I write:
int i = 2;
i += MY_CONSTANT;
The compiler can perform this calulation at compile time because it knows what 2 is, and what MY_CONSTANT is. As such it saves itself from performing a calculation every single execution.
answered May 10, 2009 at 21:09
SpenceSpence
28.2k14 gold badges67 silver badges103 bronze badges
1
Hmm, ok well, runtime is used to describe something that occurs when a program is running.
Compile time is used to describe something that occurs when a program is being built (usually, by a compiler).
answered May 10, 2009 at 21:09
dicrocedicroce
44.7k27 gold badges99 silver badges139 bronze badges
Compile Time:
Things that are done at compile time incur (almost) no cost when the resulting program is run, but might incur a large cost when you build the program.
Run-Time:
More or less the exact opposite. Little cost when you build, more cost when the program is run.
From the other side; If something is done at compile time, it runs only on your machine and if something is run-time, it run on your users machine.
Relevance
An example of where this is important would be a unit carrying type. A compile time version (like Boost.Units or my version in D) ends up being just as fast as solving the problem with native floating point code while a run-time version ends up having to pack around information about the units that a value are in and perform checks in them along side every operation. On the other hand, the compile time versions requiter that the units of the values be known at compile time and can’t deal with the case where they come from run-time input.
answered May 11, 2009 at 0:41
BCSBCS
74.1k67 gold badges185 silver badges291 bronze badges
As an add-on to the other answers, here’s how I’d explain it to a layman:
Your source code is like the blueprint of a ship. It defines how the ship should be made.
If you hand off your blueprint to the shipyard, and they find a defect while building the ship, they’ll stop building and report it to you immediately, before the ship has ever left the drydock or touched water. This is a compile-time error. The ship was never even actually floating or using its engines. The error was found because it prevented the ship even being made.
When your code compiles, it’s like the ship being completed. Built and ready to go. When you execute your code, that’s like launching the ship on a voyage. The passengers are boarded, the engines are running and the hull is on the water, so this is runtime. If your ship has a fatal flaw that sinks it on its maiden voyage (or maybe some voyage after for extra headaches) then it suffered a runtime error.
answered Feb 22, 2018 at 18:48
Jared KJared K
2412 silver badges8 bronze badges
Following from previous similar answer of question What is the difference between run-time error and compiler error?
Compilation/Compile time/Syntax/Semantic errors: Compilation or compile time errors are error occurred due to typing mistake, if we do not follow the proper syntax and semantics of any programming language then compile time errors are thrown by the compiler. They wont let your program to execute a single line until you remove all the syntax errors or until you debug the compile time errors.
Example: Missing a semicolon in C or mistyping int
as Int
.
Runtime errors: Runtime errors are the errors that are generated when the program is in running state. These types of errors will cause your program to behave unexpectedly or may even kill your program. They are often referred as Exceptions.
Example: Suppose you are reading a file that doesn’t exist, will result in a runtime error.
Read more about all programming errors here
answered May 25, 2015 at 5:41
For example: In a strongly typed language, a type could be checked at compile time or at runtime. At compile time it means, that the compiler complains if the types are not compatible. At runtime means, that you can compile your program just fine but at runtime, it throws an exception.
answered May 10, 2009 at 21:10
Stefan SteineggerStefan Steinegger
63.3k15 gold badges128 silver badges192 bronze badges
Here is a quote from Daniel Liang, author of ‘Introduction to JAVA programming’, on the subject of compilation:
«A program written in a high-level language is called a source program or source code. Because a computer cannot execute a source program, a source program must be translated into machine code for execution. The translation can be done using another programming tool called an interpreter or a compiler.» (Daniel Liang, «Introduction to JAVA programming», p8).
…He Continues…
«A compiler translates the entire source code into a machine-code file, and the machine-code file is then executed»
When we punch in high-level/human-readable code this is, at first, useless! It must be translated into a sequence of ‘electronic happenings’ in your tiny little CPU! The first step towards this is compilation.
Simply put: a compile-time error happens during this phase, while a run-time error occurs later.
Remember: Just because a program is compiled without error does not mean it will run without error.
A Run-time error will occur in the ready, running or waiting part of a programs life-cycle while a compile-time error will occur prior to the ‘New’ stage of the life cycle.
Example of a Compile-time error:
A Syntax Error — how can your code be compiled into machine level instructions if they are ambiguous?? Your code needs to conform 100% to the syntactical rules of the language otherwise it cannot be compiled into working machine code.
Example of a run-time error:
Running out of memory — A call to a recursive function for example might lead to stack overflow given a variable of a particular degree! How can this be anticipated by the compiler!? it cannot.
And that is the difference between a compile-time error and a run-time error
answered Mar 7, 2017 at 23:49
In simply word difference b/w Compile time & Run time.
compile time:Developer writes the program in .java format & converts in to the Bytecode which is a class file,during this compilation any error occurs can be defined as compile time error.
Run time:The generated .class file is use by the application for its additional functionality & the logic turns out be wrong and throws an error which is a run time error
answered Dec 22, 2015 at 6:15
prasannaprasanna
691 silver badge1 bronze badge
Run time means something happens when you run the program.
Compile time means something happens when you compile the program.
answered May 10, 2009 at 21:09
ZifreZifre
26.2k11 gold badges83 silver badges105 bronze badges
Compile time:
Time taken to convert the source code into a machine code so that it becomes an executable is called compile time.
Run time:
When an application is running, it is called run time.
Compile time errors are those syntax errors, missing file reference errors.
Runtime errors happen after the source code has been compiled into an executable program and while the program is running. Examples are program crashes, unexpected program behavior or features don’t work.
answered May 8, 2018 at 19:33
Imagine that you are a boss and you have an assistant and a maid, and you give them a list of tasks to do, the assistant (compile time) will grab this list and make a checkup to see if the tasks are understandable and that you didn’t write in any awkward language or syntax, so he understands that you want to assign someone for a Job so he assign him for you and he understand that you want some coffee, so his role is over and the maid (run time)starts to run those tasks so she goes to make you some coffee but in sudden she doesn’t find any coffee to make so she stops making it or she acts differently and make you some tea (when the program acts differently because he found an error).
answered Apr 14, 2019 at 13:08
Ala’aAla’a
751 silver badge4 bronze badges
Compile Time:
Things that are done at compile time incur (almost) no cost when the resulting program is run, but might incur a large cost when you build the program.
Run-Time:
More or less the exact opposite. Little cost when you build, more cost when the program is run.
From the other side; If something is done at compile time, it runs only on your machine and if something is run-time, it run on your users machine.
answered Feb 10, 2012 at 4:46
I have always thought of it relative to program processing overhead and how it affects preformance as previously stated. A simple example would be, either defining the absolute memory required for my object in code or not.
A defined boolean takes x memory this is then in the compiled program and cannot be changed. When the program runs it knows exactly how much memory to allocate for x.
On the other hand if I just define a generic object type (i.e. kind of a undefined place holder or maybe a pointer to some giant blob) the actual memory required for my object is not known until the program is run and I assign something to it, thus it then must be evaluated and memory allocation, etc. will be then handled dynamically at run time (more run time overhead).
How it is dynamically handled would then depend on the language, the compiler, the OS, your code, etc.
On that note however it would really depends on the context in which you are using run time vs compile time.
answered Nov 22, 2013 at 16:32
Here is an extension to the Answer to the question «difference between run-time and compile-time?» — Differences in overheads associated with run-time and compile-time?
The run-time performance of the product contributes to its quality by delivering results faster. The compile-time performance of the product contributes to its timeliness by shortening the edit-compile-debug cycle. However, both run-time performance and compile-time performance are secondary factors in achieving timely quality. Therefore, one should consider run-time and compile-time performance improvements only when justified by improvements in overall product quality and timeliness.
A great source for further reading here:
edze
2,9551 gold badge23 silver badges29 bronze badges
answered May 2, 2011 at 7:19
we can classify these under different two broad groups static binding and dynamic binding. It is based on when the binding is done with the corresponding values. If the references are resolved at compile time, then it is static binding and if the references are resolved at runtime then it is dynamic binding. Static binding and dynamic binding also called as early binding and late binding. Sometimes they are also referred as static polymorphism and dynamic polymorphism.
Joseph Kulandai.
answered Jun 7, 2014 at 19:48
The major difference between run-time and compile time is:
- If there are any syntax errors and type checks in your code,then it throws compile time error, where-as run-time:it checks after executing the code.
For example:
int a = 1
int b = a/0;
here first line doesn’t have a semi-colon at the end—> compile time error after executing the program while performing operation b, result is infinite—> run-time error.
- Compile time doesn’t look for output of functionality provided by your code, whereas run-time does.
Davesexcel
6,5832 gold badges26 silver badges42 bronze badges
answered Nov 25, 2015 at 6:04
here’s a very simple answer:
Runtime and compile time are programming terms that refer to different stages of software program development.
In order to create a program, a developer first writes source code, which defines how the program will function. Small programs may only contain a few hundred lines of source code, while large programs may contain hundreds of thousands of lines of source code. The source code must be compiled into machine code in order to become and executable program. This compilation process is referred to as compile time.(think of a compiler as a translator)
A compiled program can be opened and run by a user. When an application is running, it is called runtime.
The terms «runtime» and «compile time» are often used by programmers to refer to different types of errors. A compile time error is a problem such as a syntax error or missing file reference that prevents the program from successfully compiling. The compiler produces compile time errors and usually indicates what line of the source code is causing the problem.
If a program’s source code has already been compiled into an executable program, it may still have bugs that occur while the program is running. Examples include features that don’t work, unexpected program behavior, or program crashes. These types of problems are called runtime errors since they occur at runtime.
The reference
answered Mar 8, 2016 at 15:14
0
Look into this example:
public class Test {
public static void main(String[] args) {
int[] x=new int[-5];//compile time no error
System.out.println(x.length);
}}
The above code is compiled successfully, there is no syntax error, it is perfectly valid.
But at the run time, it throws following error.
Exception in thread "main" java.lang.NegativeArraySizeException
at Test.main(Test.java:5)
Like when in compile time certain cases has been checked, after that run time certain cases has been checked once the program satisfies all the condition you will get an output.
Otherwise, you will get compile time or run time error.
Pang
9,365146 gold badges85 silver badges121 bronze badges
answered Sep 9, 2018 at 7:37
mathanmathan
4193 silver badges10 bronze badges
You can understand the code compile structure from reading the actual code. Run-time structure are not clear unless you understand the pattern that was used.
answered Oct 24, 2019 at 7:58
MagGGGMagGGG
18k2 gold badges28 silver badges28 bronze badges
public class RuntimeVsCompileTime {
public static void main(String[] args) {
//test(new D()); COMPILETIME ERROR
/**
* Compiler knows that B is not an instance of A
*/
test(new B());
}
/**
* compiler has no hint whether the actual type is A, B or C
* C c = (C)a; will be checked during runtime
* @param a
*/
public static void test(A a) {
C c = (C)a;//RUNTIME ERROR
}
}
class A{
}
class B extends A{
}
class C extends A{
}
class D{
}
Mofi
44.8k16 gold badges77 silver badges137 bronze badges
answered Jul 25, 2019 at 4:41
It’s not a good question for S.O. (it’s not a specific programming question), but it’s not a bad question in general.
If you think it’s trivial: what about read-time vs compile-time, and when is this a useful distinction to make? What about languages where the compiler is available at runtime? Guy Steele (no dummy, he) wrote 7 pages in CLTL2 about EVAL-WHEN, which CL programmers can use to control this. 2 sentences are barely enough for a definition, which itself is far short of an explanation.
In general, it’s a tough problem that language designers have seemed to try to avoid.
They often just say «here’s a compiler, it does compile-time things; everything after that is run-time, have fun». C is designed to be simple to implement, not the most flexible environment for computation. When you don’t have the compiler available at runtime, or the ability to easily control when an expression is evaluated, you tend to end up with hacks in the language to fake common uses of macros, or users come up with Design Patterns to simulate having more powerful constructs. A simple-to-implement language can definitely be a worthwhile goal, but that doesn’t mean it’s the end-all-be-all of programming language design. (I don’t use EVAL-WHEN much, but I can’t imagine life without it.)
And the problemspace around compile-time and run-time is huge and still largely unexplored. That’s not to say S.O. is the right place to have the discussion, but I encourage people to explore this territory further, especially those who have no preconceived notions of what it should be. The question is neither simple nor silly, and we could at least point the inquisitor in the right direction.
Unfortunately, I don’t know any good references on this. CLTL2 talks about it a bit, but it’s not great for learning about it.
answered May 11, 2009 at 2:15
KenKen
5722 silver badges5 bronze badges
2
The types of errors encountered when a software developer develops a Java application can be split into two broad categories: compile time errors and runtime errors. As the name implies, compile time errors occur when the code is built, but the program fails to compile. In contrast, Java runtime errors occur when a program successfully compiles but fails to execute.
If code doesn’t compile, the program is entirely unable to execute. As such, it’s imperative to fix compile time errors in Java as soon as they occur so that code can be pushed into an organization’s continuous delivery pipeline, run and tested.
Compile time errors in Java are a source of great frustration to developers, especially as they try to learn the language. Compile time error messages are notoriously unclear, and troubleshooting such errors can be overwhelming.
To help alleviate the frustrations that compile time error often evoke, let’s explore the most commonly encountered compile time errors in Java, and some quick ways to fix them.
Top 10 common Java compile errors and how to fix them
Here are the 10 most commonly encountered Java compile time errors:
- Java source file name mismatch
- Improper casing
- Mismatched brackets
- Missing semicolons
- Method is undefined
- Variable already defined
- Variable not initialized
- Type mismatch: cannot convert
- Return type required
- Unreachable code
1. Class and source file mismatch
The name of the Java source file, as it resides on the filesystem, must exactly match the name of the public Java class as it is defined in the class declaration. If not, the compiler generates the following Java compile time error:
The public type problemcode must be defined in its own file
A Java class declaration looks like this:
public class ThisWillCompile { }
This Java class must be saved in a file named ThisWillCompile.java — or else it won’t compile.
Java provides no lenience here — the source filename must exactly match the name used in the class declaration. If the first letter of the file is lowercase but the class declaration is uppercase, the code will not compile. If an extra letter or number pads the name of the source file, the code will not compile.
Many developers who learn the language with a text editor and DOS prompt often run into this problem of name mismatches. Fortunately, modern IDEs, such as Eclipse and IntelliJ, are designed to keep the Java class and the underlying file name in sync.
2. Improper casing
When I first learned to code, nobody told me that Java was case-sensitive. I wasted untold hours as I tried to figure out why the code I meticulously copied from a study guide did not compile. My frustration was palpable when I learned letter casing can be the only difference between compiler success and coding failure.
The Java compiler treats uppercase and lowercase letters completely differently. «Public» is different from «public» which is different from «puBliC.» For example, this code will not compile:
Int x = 10;
system.out.println(x);
To make matters worse, the associated Java compile error poorly describes the source of the problem.
Int and system cannot be resolved to a type
To fix the problem, simply make the «I» in «Integer» lowercase and make the «s» in «system» uppercase:
int x = 10;
System.out.println(x);
Java’s stringency with upstyling and downstyling letters can frustrate coders who are new to the language. Nevertheless, casing of Java classes and variables means a great deal to other developers who read your code to understand what it does, or what it is supposed to do. As developers deepen their understanding of Java they appreciate the important nuance of properly cased code, such as the use of camel case and snake case.
3. Mismatched brackets
A mismatched brace or bracket is the bane of every programmer. Every open bracket in the code, be it a square bracket, curly bracket or round bracket, requires a matching and corresponding closed bracket.
Sometimes a programmer forgets the closing bracket for a method, or remembers to put in a closing bracket for a method but forgets to close the class. If the brackets don’t all match up, the result is a compile time error.
Not only is a mismatched bracket difficult to identify within a complex class or method, but the associated Java compile error can be outright misleading. For example, the following line of code is missing a round brace after the println:
int x = 10;
System.out.println x);
When the compiler attempts to build this code, it reports the following errors, neither of which properly describe the problem:
Duplicate local variable x
System.out cannot be resolved to a type
The fix to this compile error is to add a leading round bracket after the println to make the error go away:
int x = 10;
System.out.println (x);
One way to help troubleshoot mismatched brackets and braces is to format the code. Online lint tools do this, and most IDEs have built-in formatters. It is much easier to identify mismatched brackets and braces in formatted code.
4. Missing semicolons
Every statement in a Java program must end with a semicolon.
This strict requirement can trip up some developers who are familiar with other languages, such as JavaScript or Groovy, which do not require a semicolon at the end of every line of code.
Adding to potential confusion, not every line of Java code is a statement. A class declaration is not considered a statement, so it is not followed by a semicolon. Likewise, a method declaration also is not considered a statement and requires no semicolon.
Fortunately, the Java compiler can warn developers about a missing semicolon. Take a look at the following line of Java code:
System.out.println (x)
The Java compiler points directly at the problem:
Syntax error, insert ';' to complete Statement.
And the code below shows the semicolon is correctly added:
System.out.println (x);
5. Method is undefined
Another issue that often befuddles new developers is when and when not to use round brackets.
If round brackets are appended to a variable, the compiler thinks the code wants to invoke a method. The following code triggers a «method is not defined» compiler error:
int x();
Round braces are for methods, not variables. Removal of the braces eliminates the problem:
int x;
6. Variable is already defined
Developers can change the value of a variable in Java as many times as they like. That’s why it’s called a variable. But they can only declare and assign it a data-type once.
The following code will generate a «variable already defined» error:
int x = 10;
int x = 20;
Developers also can use the variable «x» multiple times in the code, but they can declare it as an int only once.
The following code eliminates the «variable already defined» error:
int x = 10;
x = 20;
7. Local variable not initialized
Can you tell what’s wrong with the following code?
int x ;
System.out.println (x);
Class and instance variables in Java are initialized to null or zero. However, a variable declared within a method does not receive a default initialization. Any attempt to use a method-level variable that has not been assigned a value will result in a «variable not initialized» error.
The lack of variable initialization is fixed in the code below:
int x = 0;
System.out.println (x);
8. Type mismatch
Java is a strongly typed language. That means a variable cannot switch from one type to another mid-method. Look at the following code:
int x = 0;
String square = x * x;
The String variable is assigned the result of an int multiplied by itself. The multiplication of an int results in an int, not a String. As a result, the Java compiler declares a type mismatch.
To fix the type mismatch compile error, use datatypes consistently throughout your application. The following code compiles correctly:
int x = 0;
int square = x * x;
9. Return type required
Every method signature specifies the type of data that is returned to the calling program. For example, the following method returns a String:
public String pointOfNoReturn() {
return "abcdefu";
}
If the method body does not return the appropriate type back to the calling program, this will result in an error: «This method must return a result of a type.»
There are two quick fixes to this error. To return nothing from the method, specify a void return type. Alternatively, to specify a return type in the method signature, make sure there is a return statement at the termination of the method.
10. Unreachable code
Poorly planned boolean logic within a method can sometimes result in a situation where the compiler never reaches the final lines of code. Here’s an example:
int x = 10;
if ( x < 10 ) {
return true;
}
else {
return false;
}
System.out.println("done!");
Notice that every possible pathway through the logic will be exhausted through either the if or the else block. The last line of code becomes unreachable.
To solve this Java compiler error, place the unreachable code in a position where it can execute before every logical pathway through the code is exhausted. The following revision to the code will compile without error:
int x = 10;
if ( x < 10 ) {
System.out.println("done!");
return true;
}
else {
System.out.println("done!");
return false;
}
Be patient with Java compile errors
It’s always frustrating when a developer pushes forward with features and enhancement, but progress is stifled by unexpected Java compile errors. A little patience and diligence — and this list of Java compile time errors and fixes — will minimize troubleshooting, and enable developers to more productively develop and improve software features.
Overview
A compiler translates the entire program written in a high-level language to machine language before execution, and the process of translation of high-level language to machine language is known as compilation. The code is just translated into the machine-level language but not evaluated during the compilation.
Errors encountered during the compilation of programs are known as compilation errors. Runtime is the period of time when a program is running, and the errors encountered at this time are known as runtime errors.
Scope of the Article
- In this article, we will look at the difference between compile-time vs run-time.
- Some of the errors that are encountered at the compile-time and run-time.
- We will also understand the different types of compile-time errors, such as syntax and Semantic errors. And also errors at the run-time.
Introduction
Computers understand only binary language, If we want to communicate with computers, we have to use binary language. Imagine writing a program to add two numbers in just 1’s and 0’s. Sounds impossible, right? To overcome this problem, we write codes in a high-level language. Writing a program in a high-level language might be easy for us, but the computer doesn’t understand the high-level language. To fix this problem, we make use of compilers. A compiler translates the entire program written in a high-level language to machine language before execution.
Let us take an example of a robot. The robot responds to a set of commands for which they are programmed. Suppose you give a command for which the robot is not programmed. The robot won’t do anything but go blank. Even computers understand only a few words; if you say something the computer does not know, it’ll get confused and shows an error.
With this basic knowledge, It will be easy for us to understand compile-time vs run-time errors.
Before jumping into the difference between compile-time vs run-time errors, Let us understand what is compile time.
What is Compile Time?
Compile time is the period when the programming code is converted to machine code.
In the above illustration, We can see that a compiler converts the High-level language into low-level language. If there are any errors in the high-level language, the compiler shows a compilation error.
Compile-time errors
These are the errors that occur at the time of compilation. There are mainly two types of Compile-time errors.
- Semantic errors.
- Syntax errors.
Semantic errors
The code having absurd meaning refers to semantic errors. In other words, meaningless statements are termed semantic errors.
Syntax errors
Syntax refers to the rules that define the structure of a language. The syntax error is an incorrect construction of the source code.
What is Run Time?
So far, in our compile time vs runtime journey, we have understood what compile-time is. Now let us understand what is run-time?
Runtime is the period of time when a program is running and generally occurs after compile time.
Run-time errors
These are the errors that occur during the execution of the program. The compiler does not detect the Runtime errors. One of the few basic runtime exceptions is «Array Index Out of Bound.» Let us take an example
#include<stdio.h> int main(){ int ary[] = {10,9,8,7,6,5}; printf("ary[0] is %dn", ary[0]); printf("ary[10] is %dn", ary[10]); return 0; }
In the above code, we have declared an array with 6 elements. If we try to access the 10th element in the array, An error is encountered because we have declared 6 elements in the array, and we are trying to access the 10th element, Which does not exist.
The output of the above code is as follows:
ary [0] is 10 ary[10] is -1303609165
We can observe that arr[10] accesses a memory location that stores a garbage value. Such errors are known as array out of bounds in C.
Difference Between Compile Time Errors vs Runtime Errors
Compile-time error | Run-time error |
---|---|
These errors are detected during the compile-time | These errors are detected at the run-time |
Compile-time errors do not let the program be compiled | Programs with run-time errors are compiled successfully, but an error is encountered when the program is executed |
Compile-time errors can occur because of wrong syntax or meaningless statements | Run-time errors occur because of absurd operations |
Examples of Compile-time Errors and Run-time Errors
Now that we have understood the basic definition of the errors, what is compile time vs runtime, types of errors in compile time vs runtime let’s look at some examples to make the concepts clear.
Compile-time errors
Syntax errors
Syntax errors can be of different types, Such as
- Missing semicolon.
- Missing Parenthesis (}).
- Printing the value of a variable without declaring it.
Missing Semicolon
#include <stdio.h> void main(){ printf("I love scaler !"): }
As we can see in the program, we have put «:» instead of «;» which is the wrong syntax. Therefore the compiler will throw a compile-time syntax error something like this.
main.c:4:30: error: expected ‘;’ before ‘:’ token 4 | printf("I love scaler !"): | ^ | ;
Semantic Errors
Let’s look at an example,
#include<stdio.h> void main(){ int x,y,z; x=y=z=2; x*y=z; printf("%d",z); }
In the above code at line 5, x * y = z; is a semantic error because we know that values are assigned to the left side variable after the execution of the right-hand expression.
Here in the above example, we have x*y as the operand on the left-hand side and z on the right-hand side, which is incorrect.The output for the above code looks something like this:
main.c:5:8: error: lvalue required as left operand of assignment 5 | x*y=z; | ^
Missing Parenthesis
Parenthesis plays a significant role in the syntax of the code. An extra or a missing parenthesis can change the logic of the whole code, or sometimes it will yield an error.
#include<stdio.h> void main() { int i; for (i = 0; i < 2; i++) { printf("The value of i is %d", i); }
In the above example, we can see that the closing parenthesis of the for loop is missed. Let us look at the output of this code.
main.c:7:1: error: expected declaration or statement at end of input 7 | } | ^
We can see that the compiler says that a parenthesis is missing.
Printing the value of undeclared variable
Variables are used to store information to be referenced and manipulated in a computer program. If we try to print a variable without declaring it, an error will occur while running the program.
#include <stdio.h> void main() { int a=1,b=5; printf("%d",c); }
In the above code, it is clear that we declared the variables a and variable b of integer datatype. In line 6, we are trying to print the value of variable c, which had not been declared. Such mistakes will result in a compile-time error.
The output of the above program will be as follows:
main.c:6:17: error: ‘c’ undeclared (first use in this function) 6 | printf("%d",c); | ^
Runtime errors
#include<stdio.h> int main() { int a = 1; a = a / (a - a); printf("%d", a); return 0; }
In the above program, we can see that the value of a will be divided by 0 (Because «a» is initialized to «1» and we have «a-a» in the denominator).
This results in a solution that is not defined. Therefore we get a runtime error something like this.
main.c:6:8: warning: division by zero [-Wdiv-by-zero] 6 | a=a/(a-a); | ~^~~~~~
Finally, We are at the end of the topic compile time vs runtime errors. I’m sure you would have understood the concept of compile-time vs runtime errors clearly.
Conclusion
*Compile time is the period when the programming code is converted to the machine code.
- Compile-time errors are the errors that are encountered at the time of compilation of the program. They are Syntax errors and Semantic errors.
- Syntax errors are the compile-time errors that occur due to the use of the wrong syntax.
- Semantic errors occur because of the absurd use of logic.
- Runtime is the period of time when a program is running and generally occurs after compile time.
- Run-time errors occur when we try to access index out of bound, ‘divide by zero`, etc.
Runtime and compile time, these are two programming terms
that are more frequently used in java programming language. The programmers specially beginners find it little difficult to understand what exactly they are. So
let’s understand what these terms
means in java with example.
In java running a program happens in two steps, compilation and then execution. The image below shows where does compile time and runtime takes place
in execution of a program.
What is compile time in Java
After writing the program, programmer needs to compile that
program. As soon as the programmer starts compiling the program
using
javac
compiler, the compile time gets started, and it ends when either
a .class file is generated after successful compilation or an
error is thrown in compilation. In other way we can say, the
process of compiling a program is referred as compile time.
For an example if you wrote a program and saved it as
MyFirstProgram.java
, Once you start compiling this program using
javac
command as
javac MyFirstProgram.java
,
the compile time gets started and it ends when a .class file as
MyFirstProgram.class
is generated or any error is thrown in compilation.
What happens at compile time in java ?
At compile time, the
java compiler(javac) takes the source code(.java file) and checks if there is any syntax, type-checking or any semantic errors inside the program. If there is no error, the
compiler generates a .class(bytecode) file for that .java file. If there is any compilation error, java compiler displays that error in command window(eg cmd).
What is compile time error in java ?
If a program element(class, method, variable, statements etc) is not written as per it’s syntax in java, the compiler throws
error for that element while compiling the program. We call these errors as compile time errors as these errors are detected at compile time by the java compiler.
Does java compiler generates .class file even if it throws compilation error ?
No, it will not generate .class file, it will only display the compilation error in console(eg. cmd) window.
Let us see compile time error by an example. The most
common mistake that beginners do is, they forget to add
semicolon(;) at the end of a statement which results as a compilation error while compiling the program.
class
MyFirstProgram {public static void
main(String [] args) { System.out.println("first statement"
)// missing semicolon(;)
System.out.println("second statement"
); } }
Once you compile above program as javac MyFirstProgram.java
, it will display a compilation error in console window like below :
Compile time Error:
MyFirstProgram.java:3: error: ';' expected System.out.println("first statement") // missing semicolon(;) ^ 1 error
What is Runtime in Java
As soon as the programmer starts executing the program using
java
command, runtime gets started and it ends when execution of
program ended either successfully or unsuccessfully. In other way the process of running a program is known as
runtime.
For an example if you wrote a program and saved it as
MyFirstProgram.java
. After compilation when you execute the command
java MyFirstProgram
for running the program, runtime gets started and it ends when either
the output of program is generated or any runtime error is thrown.
What is runtime error in java ?
Errors which comes during the execution(runtime) of a program are known as runtime errors.
If a program contains runtime error, it won’t run successfully,
rather that error will be displayed in command window(eg. cmd) at the time of execution.
Let us suppose if you wrote a program MyFirstProgram.java
like below, After compilation when you run the below
program using java MyFirstProgram
command, it
will throw a runtime error.
class
MyFirstProgram {public static void
main(String [] args) {int
num1 = 10;int
num2 = 0; System.out.println(num1/num2);// Runtime error: Divide by zero exception
} }
Runtinme Error:
Exception in thread "main" java.lang.ArithmeticException: / by zero at MyFirstProgram.main(MyFirstProgram.java:5)
Difference between runtime and compile time
Compile time is a process in which java compiler compiles the java program and generates a .class
file. In other way, in compile time
java source code(.java file) is converted in to .class file using java compiler. While in runtime, the java virtual machine loads the .class
file in memory
and executes that class to generate the output of program.
Difference between compile time error and runtime error
Compile time errors are the error that comes while compiling the program whereas runtime errors are errors that comes at the time of execution(run-time) of the program. An example of
compile time error is "not adding a semicolon(;) at the end of a statement"
in your java program while "dividing a number by zero"
is an example of runtime error.
★★★
- Without compilation you can not run the program,
compile first then run. - The output of a program is generated in runtime, not in
compile time. - If you made any changes in program after compilation, you need to compile the program again to see the changes in output.
A «compile-time» error is one which prevents your code from compiling. This page describes 14 of the most common errors you will encounter. Compile-time errors are divided into three categories:
- Lexical: These generally occur when you include disallowed characters in your code (e.g.
int #people = 10;
). - Syntactical: These occur when your code is «out of order» (e.g.
for (int i=0; i++; i<10)
). - Semantic: These occur when the meaning of your code is unclear (e.g. two variables with the same name).
Note that the exact wording of these errors may vary, depending on which development environment you are using.
Errors described on this page (click to jump to that error):
- Cannot return a value from a method of type void
- ‘Class’ or ‘interface’ expected
- Class should be delcared abstract; it does not define…
- Else without if
- Expected: ;, {, }, (, or )
- Identifier expected / Illegal character
- Incompatible types / Inconvertible types (cannot cast)
- Method does not return a value / Missing return statement
- Method not found
- Not a statement
- Return type required
- Unreachable statement
- Variable already defined
- Variable not declared
Cannot return a value from a method of type void
When a method is declared as having a return type of void
, it cannot contain any return
statements which return a value (it can, however, contain a return
statement by itself, which will simply end the execution of the method). This problem is usually caused by accidentally making a method be of type void
when it shouldn’t be or by accidentally including a return
statement where there shouldn’t be one.
Example 1: Incorrect Code | Example 1: Fixed Code |
This method has a return type of |
We change the return type of this method in order to fix the problem. |
01 public void getName() 02 { return this.name; 03 } |
01 public String getName() 02 { return this.name; 03 } |
‘Class’ or ‘interface’ expected
This error will most likely be caused when you omit the keyword class
or interface
, as seen in the example below.
Example 1: Incorrect Code | Example 1: Fixed Code |
Here, we do not have either keyword present. |
We add in |
01 public Test 02 { 03 public void someMethod() 04 { System.out.println("Hello, world!"); 05 } 06 } |
01 public class Test 02 { 03 public void someMethod() 04 { System.out.println("Hello, world!"); 05 } 06 } — OR — 01 public interface Test 02 { 03 public void someMethod(); 04 } |
Class should be delcared abstract; it does not define…
This error arises when implementing an interface. Recall that when you say implements SomeInterface
for a certain class, you guarantee that you have written all of the methods specified within that interface. If you are missing at least one of the methods which is listed in the interface, Java will not let your code compile.
As an example, consider an interface TestInterface
which looks like:
public interface TestInterface { public int methodOne(); public String methodTwo(String z); public boolean methodThree(); }
Using TestInterface
, consider the following example.
Example 1: Incorrect Code | Example 1: Fixed Code |
We receive an error message in this case because we implement |
To allow this program to compile, we add in a «stub» for the required method. This is the quick way around the problem: in most cases, you will want to actually write a method body for this method so that it does what it was intended to do. |
01 public class Test implements TestInterface 02 { 03 private int y = 700; 04 05 public int methodOne() 06 { int x = this.y - 1; 07 return x; 08 } 09 10 public String methodTwo(String z) 11 { String label = "Val: " + z; 12 return label; 13 } 14 } |
01 public class Test implements TestInterface 02 { 03 private int y = 700; 04 05 public int methodOne() 06 { int x = this.y - 1; 07 return x; 08 } 09 10 public String methodTwo(String z) 11 { String label = "Val: " + z; 12 return label; 13 } 14 15 public boolean methodThree() 16 { return false; 17 } 18 } |
Note that when you are implementing methods in the interface, the method signatures must match exactly. That is, if the interface expects that you implement a method public String longer(String a, String b)
, then you must write a method with exactly the same name, exactly the same return type, and exactly the same parameters (in this case, two String
s).
Else without if
This error occurs when you have an else
or else if
clause without an if
clause above it. This is most likely because you have accidentally forgotten/added extra { or } braces, or you have placed an else
clause in the wrong place, as illustrated in the example below. The key idea is that every else
clause needs to have an associated if
clause which occurs before it.
Example 1: Incorrect Code | Example 1: Fixed Code |
Here, we have accidentally placed the |
We place the |
01 String text = "abaaba"; 02 03 if (text.length() >= 6) 04 { text += text; 05 else 06 { text += text.substring(3); 07 } 08 } |
01 String text = "abaaba"; 02 03 if (text.length() >= 6) 04 { text += text; 05 06 } 07 else 08 { text += text.substring(3); 09 } |
Expected: ;, {, }, (, or )
Java is very specific about use of characters such as semicolons, brackets, or braces. Forgetting a semicolon is the simplest of these errors, and is fixed by placing a semicolon at the end of the line which causes the error. Brackets can be more complicated, because you may have to read through several nested if
statements or loops in order to make sure that all brackets «match up» with each other properly. This is one of the reasons why indenting your code properly is a good idea.
Example 1: Incorrect Code | Example 1: Fixed Code |
Here, lines 6, 7, and 10 will give us compile-time errors because we have forgot to include brackets, a semicolon, and a close-brace respectively. |
We add these in to fix the problems. |
01 public class Test 02 { 03 public void getName() 04 { int k = 10; 05 06 if k == 10 07 { k++ 08 } 09 } 10 |
01 public class Test 02 { 03 public void getName() 04 { int k = 10; 05 06 if (k == 10) 07 { k++; 08 } 09 } 10 } |
Identifier expected / Illegal character
An identifier is another term for a variable. In Java, every variable name must begin with a letter/underscore and can then have any combination of letters, numbers, and underscores. The example below illustrates two cases you may run into.
Example 1: Incorrect Code | Example 1: Fixed Code |
The variable name |
To fix this, we change these to valid variable names. |
01 private String[] 10Names; 02 private int wtPer#ofPeople; |
01 private String[] tenNames; 02 private int wtPerNumberOfPeople; |
Incompatible types / Inconvertible types (cannot cast)
In a Java assignment statement, the type of the variable on the left hand side must be the same as the type of the variable on the right hand side (or it needs to be able to be cast first in order to make it work). The example below would give three ‘incompatible types’ error messages.
Example 1: Incorrect Code | Example 1: Fixed Code |
Lines 5, 6, and 7 all give us errors. This is because an |
We change these three statements so that the primitive type / Object type is the same on both sides of the assignment (=) sign. |
01 String theAge = "Twenty-two"; 02 int x = 22; 03 boolean b = false; 04 05 theAge = x; 06 x = b; 07 b = theAge; |
01 String theAge = "Twenty-two"; 02 int x = 22; 03 boolean b = false; 04 05 theAge = "Thirty-three"; 06 x = 33; 07 b = true; |
Note that one common exception to this rule is that an int
value can be assigned to a char
value and vice-versa (this is because every character is actually represented as an integer ASCII value).
This error may also occur when trying to pass a value of one type into a method which expects another. An example of this is below.
Example 2: Incorrect Code | Example 2: Fixed Code |
Here, we try to pass a |
To fix this, we change the type of the variable which is being passed. Alternately, we could have also changed the type of the actual parameter to be a |
01 String theAge = "Twenty-two"; 02 int result = calcNewAge(theAge); 03 04 public int calcNewAge(int theAge) 05 { return theAge / 2 + 7; 06 } |
01 int theAge = 22; 02 int result = calcNewAge(theAge); 03 04 public int calcNewAge(int theAge) 05 { return theAge / 2 + 7; 06 } |
You may also get a similar error if you are attempting to cast incorrectly. Recall that a primitive type may not be cast to an object or vice-versa. When casting between two objects, recall that object «A» may be cast to be of the same type as object «B» only if B’s class extends A’s class. As an example, consider a class Cat
which extends the class Animal
.
Example 3: Incorrect Code | Example 3: Fixed Code |
Here, lines 2 and 3 are incorrect attempts at casting because neither |
Line 2 is a correct cast because |
01 Cat c = new Cat("Sparky", "black"); 02 Animal a = (Animal) c; 03 String theCat = (String) c; |
01 Animal a = new Animal("Sparky"); 02 Cat c = (Cat) a; |
Method does not return a value / Missing return statement
In Java, every method which does not have a return type of void
must have at least one return
statement.
Example 1: Incorrect Code | Example 1: Fixed Code |
The return type of this method is |
Instead of printing these values to the screen, we return them. |
01 public String getFortune() 02 { if (this.age >= 19) 03 { System.out.println("Good times ahead"); 04 } 05 else 06 { System.out.println("Hailstorms unavoidable"); 07 } 08 } |
01 public String getFortune() 02 { if (this.age >= 19) 03 { return "Good times ahead"; 04 } 05 else 06 { return "Hailstorms unavoidable"; 07 } 08 } |
This compile-time error can have a very subtle point which is often overlooked. If the return type of a method is not void
, Java needs to ensure that the method will return a value in every possible case. That is, if all of your return
statements are nested within if
statements, Java will disallow the compilation process to continue because there is a chance that no return
statement will be reached. The example below illustrates this.
Example 2: Incorrect Code | Example 2: Fixed Code |
In this example, we get a compile-time error because Java sees a possibility of this method not returning a value (if |
To fix this, we ensure that the method will return a value in all possible cases by adding an |
01 public String chatMethod() 02 { if (this.age <= 18) 03 { return "MSN"; 04 } 05 else if (this.age > 19 && this.age <= 30) 06 { return "ICQ"; 07 } 08 } |
01 public String chatMethod() 02 { if (this.age <= 18) 03 { return "MSN"; 04 } 05 else if (this.age > 19 && this.age <= 30) 06 { return "ICQ"; 07 } 08 else 09 { return "BBS"; 10 } 11 } |
Note that an easy way to «fix» this error is to simply add a meaningless return
statement at the end of the method, such as return -1;
or return null;
. This often leads to problems elsewhere, such as causing the method to return unintended values.
Method not found
In Java, recall that a method’s signature consists of the method’s name and the types of its actual parameters. For example, the method public void move(int howFar)
has the signature move(int)
. When a method call is made, a method with a signature exactly matching that of the method call must exist (e.g. the method name, the number of parameters, and the types of all parameters must match exactly). This error is illustrated below.
Example 1: Incorrect Code | Example 1: Fixed Code |
Line 3 calls a method which has signature |
To fix this, we can modify the |
01 String first = "CN Tower"; 02 String second = "Calgary Tower"; 03 String res = this.larger(first, second); 04 05 public int larger(int a, int b) 06 { if (a > b) 07 { return a; 08 } else 09 { return b; 10 } 11 } |
01 String first = "CN Tower"; 02 String second = "Calgary Tower"; 03 String res = this.larger(first, second); 04 05 public String larger(String a, String b) 06 { if (a.length() > b.length()) 07 { return a; 08 } else 09 { return b; 10 } 11 } |
Also note that this error may occur if you do not have the correct import
statements at the top of your class.
Not a statement
Each line of Java code must have some sort of meaningful purpose. The compile-time error «not a statement» is usually the result of typing only part of a statement, leaving it incomplete and meaningless. One example of how this may occur (there are many) is seen below. In general, asking yourself «what was I trying to do with this line of code?» is sufficient to fix the problem.
Example 1: Incorrect Code | Example 1: Fixed Code |
Line 5 will cause the error in this case, as the line |
We change this line to be a valid, meaningful statement («set the value of |
01 int grades[] = new int[2]; 02 int x; 03 grades[0] = 96; 04 grades[1] = 93; 05 grades[1]; 06 System.out.println(x); |
01 int grades[] = new int[2]; 02 int x; 03 grades[0] = 96; 04 grades[1] = 93; 05 x = grades[1]; 06 System.out.println(x); |
Return type required
For each method, Java requires a return type (e.g. String, int, boolean
). Note that void
is also considered to be a «return type» even though a method with a void
return type does not return a value.
Example 1: Incorrect Code | Example 1: Fixed Code |
An error is caused because the |
Two possible solutions to this problem are suggested (each would depend on the context of how the method is to be actually used in your program). |
01 private theAnswer() 02 { System.out.println("42"); 03 } |
01 private void theAnswer() 02 { System.out.println("42"); 03 } — OR — 01 private int theAnswer() 02 { return 42; 03 } |
Unreachable statement
This error usually occurs if you have a statement placed directly after a return
statement. Since Java executes code line-by-line (unless a method call is made), and since a return
statement causes the execution of the program to break out of that method and return to the caller, then anything placed directly after a return
statement will never be reached.
Example 1: Incorrect Code | Example 1: Fixed Code |
Line 4 is directly after a |
We switch lines 3 and 4 to ensure that nothing is after the |
01 public String oneMoreA(String orig) 02 { String newStr = orig + "A"; 03 return newStr; 04 this.counter++; 05 } |
01 public String oneMoreA(String orig) 02 { String newStr = orig + "A"; 03 this.counter++; 04 return newStr; 05 } |
You (may) also get this error if you place a statement outside of a method, which could be the result of { and } braces not being matched up properly.
Variable already defined
This compile-time error is typically caused by a programmer attempting to declare a variable twice. Recall that a statment such as int temp;
declares the variable named temp
to be of type int
. Once this declaration has been made, Java can refer to this variable by its name (e.g. temp = 15;
) but does not let the programmer declare it a second time by including the variable type before the name, as seen in the example below.
Example 1: Incorrect Code | Example 1: Fixed Code |
Here, we have declared the variable |
We have fixed the problem by only declaring the variable once (at line 3) and we refer only to the variable’s name on line 6. |
01 int a = 7; 02 int b = 12; 03 int temperature = Math.max(a, b); 04 05 if (temperature > 10) 06 { int temperature = 0; 07 } |
01 int a = 7; 02 int b = 12; 03 int temperature = Math.max(a, b); 04 05 if (temperature > 10) 06 { temperature = 0; 07 } |
You may also get this error if you have tried to declare two variables of different types using the same variable name (in Java, every variable must have a unique name). The example below illustrates this using two variables of type int
and String
.
Example 2: Incorrect Code | Example 2: Fixed Code |
Here we are trying to declare two variables using the same variable name of |
We fix the problem by ensuring that each variable has a unique name. |
01 int temperature = 22; 02 String temperature = "Hot Outside"; |
01 int temperature = 22; 02 String tempDescription = "Hot Outside"; |
The only time where repetition of variable names or declarations are allowed is if the two variables are in different scopes. Recall that the scope of a variable is determined by the set of braces, { and }, in which it is enclosed. This is illustrated in the two examples below.
Example 3: Correct Code | Example 4: Correct Code |
This is allowed because the delarations on lines 4 and 7 are being done within different scopes. One is within the scope of the |
Similarly, this is also allowed because |
01 int temp = 22; 02 03 if (temp >= 20) 04 { String desc = "Hot"; 05 } 06 else if (temp >= 10 && temp < 20 ) 07 { String desc = "Nice"; 08 } |
01 public void cold() 02 { int temp = -27; 03 } 04 05 public void hot() 06 { int temp = 27; 07 } |
Variable not declared
This error occurs when a variable is not declared within the same (or an «outer») scope in which it is used. Recall that the scope of a variable declaration is determined by its location with { and } braces. The example below illustrates a simple case of this error. To fix this problem, make sure that the variable is declared either in the same scope in which it is being used, or it being delcared in an «outer» scope.
Example 1: Incorrect Code | Example 1: Fixed Code |
The variable |
To fix the problem, we declare |
01 boolean newAcct = true; 02 double deposit = 17.29; 03 04 if (newAcct == true) 05 { double balance = 100.0; 06 } 07 08 if (deposit > 0) 09 { balance += deposit; 10 } |
01 boolean newAcct = true; 02 double deposit = 17.29; 03 double balance = 0; 04 05 if (newAcct == true) 06 { balance = 100.0; 07 } 08 09 if (deposit > 0) 10 { balance += deposit; 11 } |
Return to Main Page
Created by Terry Anderson (tanderso at uwaterloo dot ca) for use by ISG, Spring 2005
Errors in Java occur when a programmer violates the rules of Java programming language.
It might be due to programmer’s typing mistakes while developing a program. It may produce incorrect output or may terminate the execution of the program abnormally.
For example, if you use the right parenthesis in a Java program where a right brace is needed, you have made a syntax error. You have violated the rules of Java language.
Therefore, it is important to detect and fix properly all errors occurring in a program so that the program will not terminate during execution.
Types of Errors in Java Programming
When we write a program for the first time, it usually contains errors. These errors are mainly divided into three types:
1. Compile-time errors (Syntax errors)
2. Runtime errors
3. Logical errors
Compile-time errors occur when syntactical problems occur in a java program due to incorrect use of Java syntax.
These syntactical problems may be missing semicolons, missing brackets, misspelled keywords, use of undeclared variables, class not found, missing double-quote in Strings, and so on.
These problems occurring in a program are called syntax errors in Java.
Since all syntax errors are detected by Java compiler, therefore, these errors are also known as compile time errors in Java.
When Java compiler finds syntax errors in a program, it prevents the code from compile successfully and will not create a .class file until errors are not corrected. An error message will be displayed on the console screen.
These errors must be removed by debugging before successfully compile and run the program. Let’s take an example program where we will get a syntax error.
Program source code 1:
public class CompileTimeErrorEx { public static void main(String[] args) { System.out.println("a") // Syntax error. Semicolon missing. } }
Compile time error in Java code: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Syntax error, insert ";" to complete BlockStatements
When you will try to compile the above program, Java compiler will tell you where errors are in the program. Then you can go to the appropriate line, correct error, and recompile the program.
Let’s create a program where we will try to call the undeclared variable. In this case, we will get unresolved compilation problem.
Program source code 2:
public class MisspelledVar { public static void main(String[] args) { int x = 20, y = 30; // Declare variable sum. int sum = x + y; // Call variable Sum with Capital S. System.out.println("Sum of two numbers: " + Sum); // Calling of undeclared variable. } }
Compile time error in Java code: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Sum cannot be resolved to a variable
Program source code 3: Missing parenthesis in for statement.
public class MissingBracket { public static void main(String[] args) { int i; int sum = 0; // Missing bracket in for statement. for (i = 1; i <= 5; i++ // insert " ) Statement" to complete For Statement. { sum = sum + i; } System.out.println("Sum of 1 to 5 n"); System.out.println(sum); } }
Compile time error in Java code: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Syntax error, insert ") Statement" to complete ForStatement
Program source code 4: Missing double quote in String literal.
public class MissingDoubleQuote { public static void main(String[] args) { String str = "Scientech; // Missing double quote in String literal. System.out.println(str); } }
Compile time error in Java code: Exception in thread "main" java.lang.Error: Unresolved compilation problem: String literal is not properly closed by a double-quote
We may also face another error related to the directory path. An error such as
javac : command not found
means that you have not set the path correctly.
Runtime Errors in Java
Runtime errors occur when a program is successfully compiled creating the .class file but does not run properly. It is detected at run time (i.e. during the execution of the program).
Java compiler has no technique to detect runtime errors during compilation because a compiler does not have all of the runtime information available to it. JVM is responsible to detect runtime errors while the program is running.
Such a program that contains runtime errors, may produce wrong results due to wrong logic or terminate the program. These runtime errors are usually known as exceptions.
For example, if a user inputs a value of string type in a program but the computer is expecting an integer value, a runtime error will be generated.
The most common runtime errors are as follows:
1. Dividing an integer by zero.
2. Accessing an element that is out of range of the array.
3. Trying to store a value into an array that is not compatible type.
4. Passing an argument that is not in a valid range or valid value for a method.
5. Striving to use a negative size for an array.
6. Attempting to convert an invalid string into a number.
7. and many more.
When such errors are encountered in a program, Java generates an error message and terminates the program abnormally. To handle these kinds of errors during the runtime, we use exception handling technique in java program.
Let’s take different kinds of example programs to understand better. In this program, we will divide an integer number by zero. Java compiler cannot detect it.
Program source code 5:
public class DivisionByZeroError { public static void main(String[] args) { int a = 20, b = 5, c = 5; int z = a/(b-c); // Division by zero. System.out.println("Result: " +z); } }
Output: Exception in thread "main" java.lang.ArithmeticException: / by zero at errorsProgram.DivisionByZeroError.main(DivisionByZeroError.java:8)
The above program is syntactically correct. There is no syntax error and therefore, does not cause any problem during compilation. While executing, runtime error occurred that is not detected by compiler.
The error is detected by JVM only in runtime. Default exception handler displays an error message and terminates the program abnormally without executing further statements in the program.
Let’s take an example program where we will try to retrieve a value from an array using an index that is out of range of the array.
Program source code 6:
public class AccessingValueOutOfRangeError { public static void main(String[ ] args) { int arr[ ] = {1, 2, 3, 4, 5}; // Here, array size is 5. System.out.println("Value at 5th position: "+arr[5]); } }
Output: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at errorsProgram.AccessingValueOutOfRangeError.main(AccessingValueOutOfRangeError.java:9)
Logical Errors in Java Program
Logical errors in Java are the most critical errors in a program and they are difficult to detect. These errors occur when the programmer uses incorrect logic or wrong formula in the coding.
The program will be compiled and executed successfully but does not return the expected output.
Logical errors are not detected either by Java compiler or JVM (Java runtime system). The programmer is entirely responsible for them. They can be detected by application testers when they compare the actual result with its expected result.
For example, a programmer wants to print even numbers from an array but he uses division (/) operator instead of modulus (%) operator to get the remainder of each number. Due to which he got the wrong results.
Let’s see the following source code related to this problem.
Program source code 7:
public class LogicalErrorEx { public static void main(String[] args) { int a[]={1, 2 , 5, 6, 3, 10, 12, 13, 14}; System.out.println("Even Numbers:"); for(int i = 0; i <a.length; i++) { if(a[i] / 2 == 0) // Using wrong operator. { System.out.println(a[i]); } } } }
Output: Even Numbers: 1
As you can see the program is successfully compiled and executed but the programmer got the wrong output due to logical errors in the program.
Seldom does a program run successfully at its first attempt. A software engineer in a company also commits several errors while designing the project or developing code.
These errors in a program are also called bugs and the process of fixing these bugs is called debugging.
All modern integrated development environments (IDEs) such as Eclipse, NetBeans, JBuilder, etc provide a tool known as debugger that helps to run the program step by step to detect bugs.
If you need professional help with Java homework assignments online, please address experts from AssignmentCore to get your Java projects done with no errors.
In this tutorial, we have familiarized different types of errors in java that may possibly occur in a program.
Thanks for reading!!!
Next ⇒ Exception handling Interview Programs for Practice
⇐ Prev Next ⇒
Both of these are types of errors. In this article, we will discuss the major difference between compile-time errors and runtime errors, but let us first know a bit more about errors.
An error or exception refers to an interruption in the execution of code due to which we cannot attain the expected outcome to the end-users. We classify these errors on the basis of the event when we generate the error.
What are Compile Time Errors?
These errors occur when we violate the rules present in a syntax. The compile-time error indicates something that we need to fix before compiling the code. A compiler can easily detect these errors. It is the reason why we call them compile-time errors. Here are the most frequent errors (compile-time):
- Terminator- missing semicolon.
- Missing parenthesis.
- Printing the overall value of a variable with no declaration.
What are Runtime Errors?
These errors occur during the run-time program execution after a successful compilation. Division error is one of the most common errors (runtime). It occurs due to the division by zero. It is very difficult for a compiler to find out a runtime error because it cannot point out the exact line at which this particular error occurs.
Difference Between Compile Time Errors and Runtime Errors
Here is a list of the differences present between Compile Time Errors and Runtime Errors.
Parameters | Compile Time Errors | Runtime Errors |
Detection | Compilers can easily detect compile-time errors during the development of code. | A compiler cannot easily detect a runtime error. Thus, we need to identify it during the execution of code. |
Reference | A compile-time error generally refers to the errors that correspond to the semantics or syntax. | A runtime error refers to the error that we encounter during the code execution during runtime. |
Fixation | We can easily fix a compile-time error during the development of code. | A compiler cannot identify a runtime error. But we can fix it after the execution of code and identification of the code in prior. |
Keep learning and stay tuned to get the latest updates on GATE Exam along with GATE Eligibility Criteria, GATE 2023, GATE Admit Card, GATE Application Form, GATE Syllabus, GATE Cut off, GATE Previous Year Question Paper, and more.