The «java: compilation failed: internal java compiler error» is a type of compilation error that occurs when the Java compiler fails to generate the bytecode due to an unexpected issue or bug in the compiler itself.
It is a rare type of error that typically occurs due to a bug in the Java development kit (JDK) or the Java virtual machine (JVM) that runs the code. These errors are usually unpredictable, and developers often have little control over them. They can be frustrating to deal with, as they provide little information about the nature of the problem and can be difficult to debug.
This article aims to provide step-by-step guidance on how to identify and troubleshoot these errors using various tools and techniques, and help developers understand the nature of internal Java compiler errors and provide practical solutions to avoid and resolve them.
What causes «java: compilation failed: internal java compiler error»
Internal Java compiler errors occur when the Java compiler is unable to compile the source code due to an unexpected condition or error encountered during the compilation process. This type of error can occur due to a variety of reasons, including incorrect syntax in the code, incorrect usage of Java language constructs, memory or disk space issues, or bugs in the Java compiler itself.
These errors are typically indicated by messages such as «An internal compiler error occurred» or «Java compiler internal error».
Common types of internal Java compiler errors
Internal Java compiler errors can be difficult to troubleshoot because they indicate a problem with the compiler itself rather than with the source code being compiled. Here are some common types of internal Java compiler errors:
- Error: java.lang.NullPointerException — This error occurs when the compiler encounters a null reference in the code being compiled.
- Error: java.lang.ArrayIndexOutOfBoundsException — This error occurs when the compiler encounters an array index that is out of bounds.
- Error: java.lang.ClassCastException — This error occurs when the compiler encounters an invalid cast operation.
- Error: java.lang.StackOverflowError — This error occurs when the compiler encounters a stack overflow due to too many recursive calls. Read []
- Error: java.lang.OutOfMemoryError — This error occurs when the compiler runs out of memory during the compilation process. Read
Related Solutions to Java Errors
- Dealing with Java’s OutOfMemoryError: Metaspace
- Solving Java Memory Error: GC Overhead Limit Exceeded
- Solving java.lang.outofmemoryerror: java heap space emr
Step-by-step guide for troubleshooting internal Java compiler errors
When you encounter an internal Java compiler error during the compilation process, it can be frustrating to figure out what went wrong. However, there are some steps you can take to troubleshoot the issue and get your code compiling again.
Check your Java Development Kit (JDK) version
Ensure that you have the correct JDK version installed on your system. It’s recommended to use the latest stable version. To check the version of the Java Development Kit (JDK) installed on your system, you can follow these steps:
Open a terminal or command prompt: Depending on your operating system, open the terminal or command prompt application. You can usually find it in the «Utilities» or «Accessories» folder on Windows or in the «Applications» or «Utilities» folder on macOS.
Type the command: In the terminal or command prompt, enter the following command and press Enter:
java -version
Enter fullscreen mode
Exit fullscreen mode
View the JDK version: After executing the command, the terminal or command prompt will display information about the installed Java version. Look for a line that begins with «java version» or «openjdk version.» The version number should be displayed after that.
For example, the output might look like:
In this example, the JDK version is 11.0.13.
Note: If the java command is not recognized or the version information is not displayed, it might indicate that the JDK is not properly installed or not added to the system’s PATH environment variable. In such cases, you may need to install or configure the JDK correctly before proceeding.
Check for external dependencies to solve «java: compilation failed: internal java compiler error»
If your project relies on external libraries or dependencies, ensure that they are correctly configured and up to date. Outdated or incompatible libraries can sometimes cause internal compiler errors.
To check for external dependencies in a Java project, you can follow these steps:
-
Open your project: Launch your Java Integrated Development Environment (IDE) such as Eclipse, IntelliJ IDEA, or NetBeans and open the project you want to check for external dependencies.
-
Locate the build file: In most Java projects, the external dependencies are managed using a build automation tool like Apache Maven or Gradle. Look for a file named pom.xml (for Maven) or build.gradle (for Gradle) in the root directory of your project. These files contain the configuration for your project’s dependencies.
-
Inspect the dependencies file: Open the pom.xml or build.gradle file in your IDE’s editor. The dependencies section of the file specifies the external libraries that your project relies on.
-
For Maven (pom.xml):
In the pom.xml file, look for the section. Inside this section, you will find individual elements representing the external libraries. Each element specifies the library’s coordinates, such as the group ID, artifact ID, and version. -
For Gradle (build.gradle):
In the build.gradle file, locate the dependencies block. Inside this block, you will find entries that define the external libraries. The format may vary slightly depending on the Gradle version, but typically it will include statements like implementation, compile, or api, followed by the library coordinates.
-
Review the dependencies: Examine the dependency declarations in the file. Each declaration typically includes information about the external library, such as its group ID, artifact ID, and version. You can identify the libraries your project depends on by checking these declarations.
-
Check for updates or issues: After identifying the dependencies, you can perform the following tasks:
-
Verify if the dependencies are still valid and active libraries. Search for the libraries online or refer to their official documentation or repositories to ensure they are still maintained and available.
-
Check for newer versions of the dependencies. If newer versions are available, consider updating your project to benefit from bug fixes, improvements, or additional features. However, be cautious of any potential compatibility issues that may arise with the new versions.
-
Ensure that the declared versions of the dependencies are compatible with each other. Conflicting versions can lead to issues, so it’s important to resolve any conflicts by updating the version numbers accordingly.
-
Address any deprecation warnings or errors related to the dependencies. Deprecation warnings indicate that certain features or methods may be removed in future versions. It’s advisable to update your code to use alternative approaches or newer libraries to maintain compatibility.
These steps will help you identify and assess the external dependencies in your Java project. By reviewing and managing your project’s dependencies effectively, you can ensure that your code has access to the required libraries and stays up to date with the latest developments.
Review your code for errors
Although the error message suggests a problem with the compiler itself, it’s still worth examining your code for any syntax errors, missing semicolons, or other issues. Fixing any potential problems can help eliminate false positives from the compiler.
Most Java integrated development environment (IDE) comes with features that help you detect errors in your code. Simply follow the instructions to check for errors in your code, and clean them up to eliminate any temporary build artifacts or inconsistencies that may be causing the compilation error.
Reinstall the JDK to solve «java: compilation failed: internal java compiler error»
As a last resort, if all else fails, try uninstalling and reinstalling the JDK. This can help ensure a clean installation and potentially resolve any corrupted or misconfigured components.
To reinstall the Java Development Kit (JDK), you can follow these steps:
- Uninstall the existing JDK: Before reinstalling the JDK, it’s recommended to uninstall the existing version from your system. The uninstallation process may vary depending on your operating system. Here are general instructions for common operating systems:
-
Windows: Go to «Control Panel» > «Programs» > «Programs and Features.» Find the JDK entry in the list of installed programs, right-click on it, and select «Uninstall» or «Remove.»
-
macOS: Open «Finder» and navigate to the «Applications» folder. Find the JDK installation folder, typically named «Java Development Kit» or «JDK,» and move it to the trash.
-
Linux: The exact process may vary depending on the Linux distribution and package manager you are using. You can use the package manager’s commands to uninstall the JDK. For example, if you installed the JDK using apt on Ubuntu, you can run sudo apt remove openjdk-{version}-jdk to uninstall it.
-
Download the latest JDK: Visit the official Oracle website or the website of the JDK provider to download the latest version of the JDK. Make sure to choose the appropriate installer for your operating system.
-
Run the installer: Once the JDK installer has finished downloading, run the installer executable. Follow the prompts and select the desired installation options. Make sure to review and accept any license agreements during the installation process.
-
Configure environment variables (if necessary): After the installation, you may need to set up the necessary environment variables to ensure that your system recognizes the newly installed JDK. The steps for configuring environment variables vary depending on your operating system. Here are general guidelines:
-
Windows: Set the JAVA_HOME environment variable to the JDK installation directory. Add the JDK’s bin directory to the system’s PATH variable.
-
macOS and Linux: Open the terminal and add the JDK’s bin directory to the PATH variable by modifying the appropriate configuration file (e.g., .bashrc, .bash_profile, or .profile). Set the JAVA_HOME environment variable to the JDK installation directory.
- Verify the installation: To confirm that the JDK has been reinstalled correctly, open a new terminal or command prompt window and run the java -version command. It should display the version number of the newly installed JDK.
By following these steps, you can reinstall the JDK on your system, ensuring a clean installation and resolving any potential issues that may have occurred with the previous installation.
Preventing Internal Java Compiler Errors from Occurring
Internal Java compiler errors can be frustrating and difficult to troubleshoot. However, there are several best practices that developers can follow to avoid encountering these errors in the first place:
- Keep your Java compiler up to date by regularly checking for updates and installing them as needed.
- Write clean and well-structured code that adheres to Java coding conventions.
- Use a reputable IDE with strong error-checking capabilities to catch any errors before the code is compiled.
- Test your code thoroughly to catch any errors or unexpected behavior before it is compiled.
- Consider using automated testing tools to ensure that your code is working as expected and to catch any errors that may occur during runtime.
By following these best practices, developers can minimize the risk of encountering internal Java compiler errors and ensure that their code is running smoothly and efficiently.
Avoiding java: compilation failed: internal java compiler error with Online Java IDE
A lot of installation-related issues such as java: compilation failed: internal java compiler error can be avoided by having a consistent and stable environment setup, especially if you’re coding across different devices.
There are online Java compilers available that could help you simplify the installation and configuration process, as the online Java compiler is already set up with a preconfigured development environment.
In Lightly, you can also work side-by-side with an AI assistant for debugging and code completion to make your coding process smoother and bug-free. The online Java compiler in Lightly is prebuilt with coding essentials from terminal access, cloud storage, databases, syntax highlighting, GitHub integration, and more. You can also use Maven as your build tool.
Troubleshooting Internal Java Compiler Error During Compilation
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.
When I compile a Java project using IntelliJ IDEA, it gives me the following output (and error):
Information:Eclipse compiler 4.6.2 was used to compile java sources
Information:Module "sinoWeb" was fully rebuilt due to project configuration/dependencies changes
Information:2017/3/23 11:44 - Compilation completed with 1 error and 0 warnings in 5m 32s 949ms
Error:java: Compilation failed: internal java compiler error
I’m quite confused confused by this! Below are my settings:
asked Mar 23, 2017 at 3:46
5
- On Intellij IDEA Ctrl + Alt + S to open settings.
- Build, Execution, Deployment -> Compiler -> Java Compiler
- choose your java version from Project bytecode version
- Uncheck Use compiler from module target JDK when possible
- click apply and ok.
answered Oct 31, 2018 at 10:58
Musab BozkurtMusab Bozkurt
1,7811 gold badge6 silver badges5 bronze badges
5
I solved this issue by increasing the default value(700) of Build process heap size on IntelliJ’s compiler settings.
answered Feb 2, 2018 at 15:17
sezerugsezerug
1,1469 silver badges10 bronze badges
1
I changed my compiler to Eclipse and run my project. Afterwards changed back to Javac and problem solved. I don’t know exact problem but it can help who is looking for solution.
answered Jul 24, 2017 at 7:41
omerhakanbiliciomerhakanbilici
8841 gold badge18 silver badges26 bronze badges
2
In my case, using Java 11, I had:
public List<String> foo() {
...
return response.readEntity(new GenericType<List<String>>() {});
and Intellij suggested I should use <>
instead of GenericType<List<String>>
, as such:
public List<String> foo() {
...
return response.readEntity(new GenericType<>() {});
I did that in four functions and the project stopped compiling with an internal compiler error, reverted and it compiled again. Looks like a bug with type inference.
answered Jul 26, 2019 at 7:16
Tony BenBrahimTony BenBrahim
7,0902 gold badges37 silver badges49 bronze badges
3
In my case it was because of lombok
library with intellij 2019.2 & java11.
According to this IDEA bug after workaround idea works again:
Disable all building from intelliJ and dedicate the build to Maven.
answered Sep 16, 2019 at 10:27
FilomatFilomat
7631 gold badge11 silver badges16 bronze badges
3
In JIdea 2020.1.2 and above,
This is may be the language-level set in Project Structure is not compatible with the target byte-code version.
You have to change the target bytecode version .
- Go to Settings [ Ctrl+Alt+S ]
- Select Java Compiler
- Select module in the table
- Change the byte-code version to map what you selected in the previous step for language-level
NOTE :
How to check the language-level
- Go to Project Structure [ Ctrl+Alt+Shift+S
] - Select Modules sub section
- Select each module
- Under sources-section, check Language Level
answered Aug 8, 2020 at 3:04
primeprime
14.5k14 gold badges99 silver badges131 bronze badges
1
For me the module’s target bytecode version was set to 5. I changed it to 8 and the error is gone:
answered Apr 17, 2020 at 10:40
velocityvelocity
1,63021 silver badges24 bronze badges
I met the same problem
I solved it by changing the Target bytecode error from 1.5 to 8
Brad Mace
27.3k17 gold badges102 silver badges149 bronze badges
answered Jan 9, 2021 at 9:49
kl wkl w
811 silver badge2 bronze badges
You have to disabled the Javac Options: Use compiler from module target JDK when possible.
answered Apr 17, 2019 at 14:04
0
In my case, it was response type in restTemplate
:
ResponseEntity<Map<String, Integer>> response = restTemplate.exchange(
eurl,
HttpMethod.POST,
requestEntity,
new ParameterizedTypeReference<>() { <---- this causes error
}
);
Should be like this:
ParameterizedTypeReference<Map<String, Integer>> responseType = new ParameterizedTypeReference<>() {};
ResponseEntity<Map<String, Integer>> response = restTemplate.exchange(
url,
HttpMethod.POST,
requestEntity,
responseType
);
answered May 19, 2020 at 9:38
dev_in_progressdev_in_progress
2,4842 gold badges21 silver badges33 bronze badges
1
It May is not be relevant to this case, but:
I got this error when I change the Explicit type argument List of:
new ParameterizedTypeReference<List<SomeDtoObject>>()
to <>
:
new ParameterizedTypeReference<>()
in restTemplate
call after Intellij gave the warning to use <>
instead.
It got fixed when I undo my changes back into the Explicit type argument.
answered May 3, 2022 at 18:00
Changing the Language Level in the Project Settings (Ctrl + Alt + Shift + S) to Java 8 solved the problem for me
answered Jul 27, 2018 at 7:52
Chris K.Chris K.
1,0608 silver badges10 bronze badges
I had the same problem. I fixed changing my settings. Target bytecode version for equals Project bytecode version.
answered Jun 15, 2020 at 21:30
What worked for me is to update the Open JDK version
answered Jun 17, 2020 at 11:26
I got the same error with Community edition 2020.3 on Windows 10 with an older version of the JDK (openjdk version «11» 2018-09-25).
Updating the JDK to javac 11.0.10 fixed the issue.
Here’s the stack trace that showed up with the error when using openjdk version «11» 2018-09-25:
java: compiler message file broken: key=compiler.misc.msg.bug arguments=11, {1}, {2}, {3}, {4}, {5}, {6}, {7}
java: java.lang.AssertionError
java: at jdk.compiler/com.sun.tools.javac.util.Assert.error(Assert.java:155)
java: at jdk.compiler/com.sun.tools.javac.util.Assert.check(Assert.java:46)
java: at jdk.compiler/com.sun.tools.javac.comp.DeferredAttr$2$1.setOverloadKind(DeferredAttr.java:172)
java: at jdk.compiler/com.sun.tools.javac.comp.ArgumentAttr.visitReference(ArgumentAttr.java:283)
java: at jdk.compiler/com.sun.tools.javac.tree.JCTree$JCMemberReference.accept(JCTree.java:2190)
java: at jdk.compiler/com.sun.tools.javac.comp.ArgumentAttr.attribArg(ArgumentAttr.java:197)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.attribTree(Attr.java:653)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.attribArgs(Attr.java:751)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.visitApply(Attr.java:1997)
java: at jdk.compiler/com.sun.tools.javac.tree.JCTree$JCMethodInvocation.accept(JCTree.java:1634)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.attribTree(Attr.java:655)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.visitSelect(Attr.java:3573)
java: at jdk.compiler/com.sun.tools.javac.tree.JCTree$JCFieldAccess.accept(JCTree.java:2110)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.visitApply(Attr.java:2006)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.visitReturn(Attr.java:1866)
java: at jdk.compiler/com.sun.tools.javac.tree.JCTree$JCReturn.accept(JCTree.java:1546)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.attribStat(Attr.java:724)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.attribStats(Attr.java:743)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.visitBlock(Attr.java:1294)
java: at jdk.compiler/com.sun.tools.javac.tree.JCTree$JCBlock.accept(JCTree.java:1020)
java: at jdk.compiler/com.sun.tools.javac.comp.DeferredAttr.attribSpeculative(DeferredAttr.java:498)
java: at jdk.compiler/com.sun.tools.javac.comp.DeferredAttr.attribSpeculative(DeferredAttr.java:481)
java: at jdk.compiler/com.sun.tools.javac.comp.DeferredAttr.attribSpeculativeLambda(DeferredAttr.java:456)
java: at jdk.compiler/com.sun.tools.javac.comp.DeferredAttr$DeferredAttrNode$StructuralStuckChecker.canLambdaBodyCompleteNormally(DeferredAttr.java:900)
java: at jdk.compiler/com.sun.tools.javac.comp.DeferredAttr$DeferredAttrNode$StructuralStuckChecker.visitLambda(DeferredAttr.java:878)
java: at jdk.compiler/com.sun.tools.javac.tree.JCTree$JCLambda.accept(JCTree.java:1807)
java: at jdk.compiler/com.sun.tools.javac.comp.DeferredAttr$DeferredAttrNode$StructuralStuckChecker.complete(DeferredAttr.java:832)
java: at jdk.compiler/com.sun.tools.javac.comp.DeferredAttr$DeferredType.check(DeferredAttr.java:335)
java: at jdk.compiler/com.sun.tools.javac.comp.DeferredAttr$DeferredAttrNode.process(DeferredAttr.java:779)
java: at jdk.compiler/com.sun.tools.javac.comp.DeferredAttr$DeferredAttrContext.complete(DeferredAttr.java:626)
java: at jdk.compiler/com.sun.tools.javac.comp.Infer.instantiateMethod(Infer.java:214)
java: at jdk.compiler/com.sun.tools.javac.comp.Resolve.rawInstantiate(Resolve.java:605)
java: at jdk.compiler/com.sun.tools.javac.comp.Resolve.selectBest(Resolve.java:1563)
java: at jdk.compiler/com.sun.tools.javac.comp.Resolve.findMethodInScope(Resolve.java:1733)
java: at jdk.compiler/com.sun.tools.javac.comp.Resolve.findMethod(Resolve.java:1802)
java: at jdk.compiler/com.sun.tools.javac.comp.Resolve.findMethod(Resolve.java:1776)
java: at jdk.compiler/com.sun.tools.javac.comp.Resolve$10.doLookup(Resolve.java:2654)
java: at jdk.compiler/com.sun.tools.javac.comp.Resolve$BasicLookupHelper.lookup(Resolve.java:3293)
java: at jdk.compiler/com.sun.tools.javac.comp.Resolve.lookupMethod(Resolve.java:3543)
java: at jdk.compiler/com.sun.tools.javac.comp.Resolve.resolveQualifiedMethod(Resolve.java:2651)
java: at jdk.compiler/com.sun.tools.javac.comp.Resolve.resolveQualifiedMethod(Resolve.java:2645)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.selectSym(Attr.java:3721)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.visitSelect(Attr.java:3601)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.visitLambda(Attr.java:2598)
java: at jdk.compiler/com.sun.tools.javac.comp.DeferredAttr$4.complete(DeferredAttr.java:374)
java: at jdk.compiler/com.sun.tools.javac.comp.DeferredAttr$DeferredType.check(DeferredAttr.java:321)
java: at jdk.compiler/com.sun.tools.javac.comp.Resolve$MethodResultInfo.check(Resolve.java:1060)
java: at jdk.compiler/com.sun.tools.javac.comp.Resolve$4.checkArg(Resolve.java:887)
java: at jdk.compiler/com.sun.tools.javac.comp.Resolve$AbstractMethodCheck.argumentsAcceptable(Resolve.java:775)
java: at jdk.compiler/com.sun.tools.javac.comp.Resolve$4.argumentsAcceptable(Resolve.java:896)
java: at jdk.compiler/com.sun.tools.javac.comp.Infer.instantiateMethod(Infer.java:181)
java: at jdk.compiler/com.sun.tools.javac.comp.Resolve.checkMethod(Resolve.java:644)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.checkMethod(Attr.java:4120)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.checkIdInternal(Attr.java:3913)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.checkMethodIdInternal(Attr.java:3814)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.checkId(Attr.java:3803)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.visitSelect(Attr.java:3696)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.visitLambda(Attr.java:2595)
java: at jdk.compiler/com.sun.tools.javac.comp.DeferredAttr$DeferredAttrNode.process(DeferredAttr.java:811)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.visitIdent(Attr.java:3553)
java: at jdk.compiler/com.sun.tools.javac.tree.JCTree$JCIdent.accept(JCTree.java:2243)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.attribExpr(Attr.java:702)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.visitExec(Attr.java:1773)
java: at jdk.compiler/com.sun.tools.javac.tree.JCTree$JCExpressionStatement.accept(JCTree.java:1452)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.visitMethodDef(Attr.java:1098)
java: at jdk.compiler/com.sun.tools.javac.tree.JCTree$JCMethodDecl.accept(JCTree.java:866)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.attribClassBody(Attr.java:4683)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.attribClass(Attr.java:4574)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.attribClass(Attr.java:4523)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.attribClass(Attr.java:4503)
java: at jdk.compiler/com.sun.tools.javac.comp.Attr.attrib(Attr.java:4448)
java: at jdk.compiler/com.sun.tools.javac.main.JavaCompiler.attribute(JavaCompiler.java:1341)
java: at jdk.compiler/com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:973)
java: at jdk.compiler/com.sun.tools.javac.api.JavacTaskImpl.lambda$doCall$0(JavacTaskImpl.java:104)
java: at jdk.compiler/com.sun.tools.javac.api.JavacTaskImpl.handleExceptions(JavacTaskImpl.java:147)
java: at jdk.compiler/com.sun.tools.javac.api.JavacTaskImpl.doCall(JavacTaskImpl.java:100)
java: at jdk.compiler/com.sun.tools.javac.api.JavacTaskImpl.call(JavacTaskImpl.java:94)
java: at org.jetbrains.jps.javac.JavacMain.compile(JavacMain.java:231)
java: at org.jetbrains.jps.incremental.java.JavaBuilder.compileJava(JavaBuilder.java:501)
java: at org.jetbrains.jps.incremental.java.JavaBuilder.compile(JavaBuilder.java:353)
java: at org.jetbrains.jps.incremental.java.JavaBuilder.doBuild(JavaBuilder.java:277)
java: at org.jetbrains.jps.incremental.java.JavaBuilder.build(JavaBuilder.java:231)
java: at org.jetbrains.jps.incremental.IncProjectBuilder.runModuleLevelBuilders(IncProjectBuilder.java:1441)
java: at org.jetbrains.jps.incremental.IncProjectBuilder.runBuildersForChunk(IncProjectBuilder.java:1100)
java: at org.jetbrains.jps.incremental.IncProjectBuilder.buildTargetsChunk(IncProjectBuilder.java:1224)
java: at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunkIfAffected(IncProjectBuilder.java:1066)
java: at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunks(IncProjectBuilder.java:832)
java: at org.jetbrains.jps.incremental.IncProjectBuilder.runBuild(IncProjectBuilder.java:419)
java: at org.jetbrains.jps.incremental.IncProjectBuilder.build(IncProjectBuilder.java:183)
java: at org.jetbrains.jps.cmdline.BuildRunner.runBuild(BuildRunner.java:132)
java: at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:302)
java: at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:132)
java: at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler.lambda$channelRead0$0(BuildMain.java:219)
java: at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
java: at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
java: at java.base/java.lang.Thread.run(Thread.java:834)
java: Compilation failed: internal java compiler error
java: Errors occurred while compiling module 'project'
javac 11 was used to compile java sources
Finished, saving caches...
Compilation failed: errors: 1; warnings: 100
answered Apr 3, 2021 at 23:17
Setting -> Build -> Compiler -> Java Compiler
The Target bytecode version of the module is wrong. I set it to 1.8, then it worked.
answered Jul 6, 2021 at 5:54
rosarosa
871 silver badge3 bronze badges
In my case I had to go to help > show logs in files
which opens up the idea.log
and build-log
folders something like
/home/user/.cache/JetBrains/IntelliJIdea2021.2/log/build-log/
where I set the log level to DEBUG in the log4j.rootLogger=debug, file
in build-log.properties
I then ran build again and saw
2021-11-27 19:59:39,808 [ 133595] DEBUG - s.incremental.java.JavaBuilder - Compiling chunk [module] with options: "-g -deprecation -encoding UTF-8 -source 11 -target 11 -s /home/user/project/target/generated-test-sources/test-annotations", mode=in-process
2021-11-27 19:59:41,082 [ 134869] DEBUG - s.incremental.java.JavaBuilder - java:ERROR:Compilation failed: internal java compiler error
which lead me to see that this might me related to junit test compilation failing. It turns out I had an older/mismatching of the vintage engine and the jupiter engine which are likely to have different java versions relating in the error above. Changing them to be the same ${version.junit}
removed the error.
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-commons</artifactId>
<version>1.7.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${version.junit}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${version.junit}</version>
<scope>test</scope>
</dependency>
In short some of your dependency jars may have mismatching java versions.
answered Nov 27, 2021 at 19:27
1
Was facing the same issue with Java 11. Solved by changing language level
File -> Project Structure -> Project
Change «Language Level» to SDK Default
answered Aug 10, 2022 at 17:35
Updated Java compiler to correct «Target bytecode version» which in my case is 8 :
answered May 6, 2021 at 10:25
blue-skyblue-sky
52.1k153 gold badges428 silver badges753 bronze badges
one reason may be jdk version donot macth minimal version of your project.
answered Jul 16, 2021 at 3:41
1
Be aware of JDK-8177068 issue, which leads to internal error like
java.lang.NullPointerException
at jdk.compiler/com.sun.tools.javac.comp.Flow$FlowAnalyzer.visitApply(Flow.java:1233)
at jdk.compiler/com.sun.tools.javac.tree.JCTree$JCMethodInvocation.accept(JCTree.java:1628)
at jdk.compiler/com.sun.tools.javac.tree.TreeScanner.scan(TreeScanner.java:49)
at jdk.compiler/com.sun.tools.javac.comp.Flow$BaseAnalyzer.scan(Flow.java:393)
at jdk.compiler/com.sun.tools.javac.tree.TreeScanner.visitExec(TreeScanner.java:213)
...
It was fixed in JDK 11.0.12 and JDK 14 b14, so upgrade helped.
answered Aug 10, 2021 at 12:52
Nikita BosikNikita Bosik
8531 gold badge14 silver badges20 bronze badges
I switched across to the cmd line mvn compile
build and it showed a more meaningful error.
Fatal error compiling: error: invalid target release: 17 -> [Help 1]
Checking my JAVA_HOME
it was set to 11. Once I adjust my project to use 11 as well I got past this and onto another error (which was solved separately).
answered Aug 22, 2022 at 10:57
Shane GannonShane Gannon
6,8107 gold badges42 silver badges64 bronze badges
Otherwise you can remove .m2 folder. Try to reload project.
answered Oct 8, 2022 at 20:39
1
In my case, I was using Spring Framework 6.0.0 and JDK 11 as the same time. This is not supported according to spring framework wiki. After I degraded the spring framework version to 5.3.24, it solved.
You can check your spring framework version in this way.
spring framework version
answered Dec 13, 2022 at 6:08
In my case, a mvn clean install recreated the generated-sources in target, it seems that this caused the issue.
answered Jul 13 at 10:16
In my case, deleting the .idea
folder and then reimporting the project again solves this problem. This problem happens to me when I run a unit test.
answered Aug 23 at 2:38
paulpaul
3724 silver badges17 bronze badges
у меня есть два файла типа java class
package com.company;
public class Vector3 {
private double x;
private double y;
private double z;
public Vector3(){
x = 0;
y = 0;
z = 0;
}
public Vector3(double x, double y, double z){
this.x = x;
this.y = y;
this.z = z;
}
public void setX(double x){
this.x = x;
}
public void setY(double y){
this.y = y;
}
public void setZ(double z){
this.z = z;
}
public double getX(){
return x;
}
public double getY(){
return y;
}
public double getZ(){
return z;
}
public double lenghtVector(){
return Math.sqrt((x*x+y*y+z*z));
}
public double scalarProduct(Vector3 v2){
return (this.x*v2.x+this.y*v2.y+this.z*v2.z);
}
public double getAngle(Vector3 v2){
double numerator = this.x*v2.x+this.y*v2.y;
double denominator = (Math.sqrt(this.x*this.x+this.y*this.y)*Math.sqrt(v2.x*v2.x+v2.y*v2.y));
return numerator/denominator;
}
public void info(){
System.out.println("x="+this.x+" y="+this.y+" z="+this.z);
}
public Vector3 vectorProduct(Vector3 v2){
Vector3 v3 = new Vector3();
v3.x = this.y*v2.z-this.z*v2.y;
v3.y = this.z*v2.x-this.x*v2.z;
v3.z = this.x*v2.y-this.y*v2.x;
return v3;
}
public Vector3 plus(Vector3 v2){
Vector3 v3 = new Vector3();
v3.x = this.x + v2.x;
v3.y = this.y + v2.y;
v3.z = this.z + v2.z;
return v3;
}
public Vector3 minus(Vector3 v2){
Vector3 v3 = new Vector3();
v3.x = this.x - v2.x;
v3.y = this.y - v2.y;
v3.z = this.z - v2.z;
return v3;
}
public static Vector3[] arrayVector(int N){
Vector3[] result = new Vector3[N];
for (int i=0; i<N; i++ ){
result[i] = new Vector3(i,i,i);
}
return result;
}
}
и второй
package com.company;
public class Class {
public static void main(String[] args) {
Vector3 v1 = new Vector3(4,5,6);
Vector3 v2 = new Vector3(1,2,3);
Vector3 v3 = v2.plus(v1);
v3.info();
Vector3[] arrayVector = Vector3.arrayVector(5);
for (int i=0; i<5; i++ ){
arrayVector[i].info();
}
}
}
при компиляции выдает ошибку
«C:\Program Files\Java\jdk-16.0.1\bin\java.exe» «-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2021.1.1\lib\idea_rt.jar=52092:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2021.1.1\bin» -Dfile.encoding=UTF-8 -classpath C:\java\untitled\out\production\untitled com.company.Main
Error: Could not find or load main class com.company.Main
Caused by: java.lang.ClassNotFoundException: com.company.Main
Process finished with exit code 1
в jave пару дней только учусь, так что не судите строго.
Содержание
- Ошибка компилятора Java: незаконное начало выражения
- 1. Обзор
- 2. Отсутствующие Фигурные Скобки
- 3. Модификатор Доступа Внутри Метода
- 4. Вложенные методы
- 5. символ или строка Без кавычек
- 6. Заключение
- Читайте ещё по теме:
- Распространенные ошибки компиляции командной строки в Java
- 2. Пример ошибки
- 3. Решение проблемы
- 4. Дополнительные советы и рекомендации
- 4.1. Использование неправильного расширения файла
- 4.2. Ошибка основного класса
- 5. Вывод
- Русские Блоги
- Интеллектуальная рекомендация
- [Структура данных и алгоритм] Array Приложение 3: Сжатие разреженного матрицы (реализация Java)
- springmvc
- GCC Learning (2) U-boot.lds
- Конфигурация переменной установки и среды JDK-9
- Определение начального значения переменной modelica
Ошибка компилятора Java: незаконное начало выражения
См. Примеры, иллюстрирующие основные причины ошибки “незаконное начало выражения” и способы ее устранения.
1. Обзор
“Незаконное начало выражения”-это распространенная ошибка, с которой мы можем столкнуться во время компиляции.
В этом уроке мы рассмотрим примеры, иллюстрирующие основные причины этой ошибки и способы ее устранения.
2. Отсутствующие Фигурные Скобки
Отсутствие фигурных скобок может привести к ошибке “незаконное начало выражения”. Давайте сначала рассмотрим пример:
package com.baeldung; public class MissingCurlyBraces < public void printSum(int x, int y) < System.out.println("Calculation Result:" + calcSum(x, y)); public int calcSum(int x, int y) < return x + y; >>
Если мы скомпилируем вышеуказанный класс:
$ javac MissingCurlyBraces.java MissingCurlyBraces.java:7: error: illegal start of expression public int calcSum(int x, int y) < ^ MissingCurlyBraces.java:7: error: ';' expected public int calcSum(int x, int y) < .
Отсутствие закрывающей фигурной скобки print Sum() является основной причиной проблемы.
Решение проблемы простое — добавление закрывающей фигурной скобки в метод printSum() :
package com.baeldung; public class MissingCurlyBraces < public void printSum(int x, int y) < System.out.println("Calculation Result:" + calcSum(x, y)); >public int calcSum(int x, int y) < return x + y; >>
Прежде чем перейти к следующему разделу, давайте рассмотрим ошибку компилятора.
Компилятор сообщает, что 7-я строка вызывает ошибку “незаконное начало выражения”. На самом деле, мы знаем, что первопричина проблемы находится в 6-й строке. Из этого примера мы узнаем, что иногда ошибки компилятора не указывают на строку с основной причиной , и нам нужно будет исправить синтаксис в предыдущей строке.
3. Модификатор Доступа Внутри Метода
В Java мы можем объявлять локальные переменные только внутри метода или конструктора . Мы не можем использовать модификатор доступа для локальных переменных внутри метода, поскольку их доступность определяется областью действия метода.
Если мы нарушим правило и у нас будут модификаторы доступа внутри метода, возникнет ошибка “незаконное начало выражения”.
Давайте посмотрим на это в действии:
package com.baeldung; public class AccessModifierInMethod < public void printSum(int x, int y) < private int sum = x + y; System.out.println("Calculation Result:" + sum); >>
Если мы попытаемся скомпилировать приведенный выше код, мы увидим ошибку компиляции:
$ javac AccessModifierInMethod.java AccessModifierInMethod.java:5: error: illegal start of expression private int sum = x + y; ^ 1 error
Удаление модификатора private access легко решает проблему:
package com.baeldung; public class AccessModifierInMethod < public void printSum(int x, int y) < int sum = x + y; System.out.println("Calculation Result:" + sum); >>
4. Вложенные методы
Некоторые языки программирования, такие как Python, поддерживают вложенные методы. Но, Java не поддерживает метод внутри другого метода.
Мы столкнемся с ошибкой компилятора “незаконное начало выражения”, если создадим вложенные методы:
package com.baeldung; public class NestedMethod < public void printSum(int x, int y) < System.out.println("Calculation Result:" + calcSum(x, y)); public int calcSum ( int x, int y) < return x + y; >> >
Давайте скомпилируем приведенный выше исходный файл и посмотрим, что сообщает компилятор Java:
$ javac NestedMethod.java NestedMethod.java:6: error: illegal start of expression public int calcSum ( int x, int y) < ^ NestedMethod.java:6: error: ';' expected public int calcSum ( int x, int y) < ^ NestedMethod.java:6: error: expected public int calcSum ( int x, int y) < ^ NestedMethod.java:6: error: not a statement public int calcSum ( int x, int y) < ^ NestedMethod.java:6: error: ';' expected public int calcSum ( int x, int y) < ^ 5 errors
Компилятор Java сообщает о пяти ошибках компиляции. В некоторых случаях одна ошибка может привести к нескольким дальнейшим ошибкам во время компиляции.
Выявление первопричины имеет важное значение для того, чтобы мы могли решить эту проблему. В этом примере первопричиной является первая ошибка “незаконное начало выражения”.
Мы можем быстро решить эту проблему, переместив метод calcSum() из метода print Sum() :
package com.baeldung; public class NestedMethod < public void printSum(int x, int y) < System.out.println("Calculation Result:" + calcSum(x, y)); >public int calcSum ( int x, int y) < return x + y; >>
5. символ или строка Без кавычек
Мы знаем, что String литералы должны быть заключены в двойные кавычки, в то время как char значения должны быть заключены в одинарные кавычки.
Если мы забудем заключить их в соответствующие кавычки, компилятор Java будет рассматривать их как имена переменных .
Мы можем увидеть ошибку “не удается найти символ”, если “переменная” не объявлена.
Однако если мы забудем дважды заключить в кавычки Строку , которая не является допустимым именем переменной Java , компилятор Java сообщит об ошибке “незаконное начало выражения” .
Давайте посмотрим на это на примере:
package com.baeldung; public class ForgetQuoting < public int calcSumOnly(int x, int y, String operation) < if (operation.equals(+)) < return x + y; >throw new UnsupportedOperationException("operation is not supported:" + operation); > >
Мы забыли процитировать строку |//+ внутри вызова метода equals , и + , очевидно, не является допустимым именем переменной Java.
Теперь давайте попробуем его скомпилировать:
$ javac ForgetQuoting.java ForgetQuoting.java:5: error: illegal start of expression if (operation.equals(+)) < ^ 1 error
Решение проблемы простое — обертывание String литералов в двойные кавычки:
package com.baeldung; public class ForgetQuoting < public int calcSumOnly(int x, int y, String operation) < if (operation.equals("+")) < return x + y; >throw new UnsupportedOperationException("operation is not supported:" + operation); > >
6. Заключение
В этой короткой статье мы рассказали о пяти различных сценариях, которые приведут к ошибке “незаконное начало выражения”.
В большинстве случаев при разработке приложений Java мы будем использовать среду IDE, которая предупреждает нас об обнаружении ошибок. Эти замечательные функции IDE могут значительно защитить нас от этой ошибки.
Тем не менее, мы все еще можем время от времени сталкиваться с этой ошибкой. Поэтому хорошее понимание ошибки поможет нам быстро найти и исправить ошибку.
Читайте ещё по теме:
Источник
Распространенные ошибки компиляции командной строки в Java
Предполагается, что при компиляции Java-программ в командной строке любое несоответствие в ожидаемых параметрах или аргументах командной строки приведет к ошибке.
В этом руководстве мы сначала исследуем ошибку «Имена классов принимаются только в том случае, если обработка аннотаций запрошена явным образом» . Затем мы рассмотрим некоторые другие распространенные ошибки компиляции.
2. Пример ошибки
Представим, что у нас есть следующий класс DemoClass :
package com.foreach; public class DemoClass // fields and methods >
Теперь попробуем скомпилировать DemoClass с помощью команды javac :
Приведенная выше команда выдаст ошибку:
error: Class names, 'DemoClass', are only accepted if annotation processing is explicitly requested 1 error
Ошибка, похоже, связана с обработкой аннотаций и немного загадочна, поскольку в DemoClass нет кода, связанного с обработкой аннотаций . Фактическая причина этой ошибки заключается в том, что DemoClass не является исходным файлом для обработки аннотаций .
Исходные файлы обработки аннотаций представляют собой удобный способ создания дополнительного исходного кода во время компиляции . В отличие от стандартных исходных файлов Java, для компиляции этих исходных файлов не требуется указывать расширение файла .java .
3. Решение проблемы
Давайте снова скомпилируем DemoClass с правильным расширением имени файла .java :
Как и ожидалось, исходный файл будет скомпилирован в файл DemoClass.class .
4. Дополнительные советы и рекомендации
Хотя это легко исправить, если мы знаем правильный способ компиляции, мы все равно можем столкнуться с аналогичными трудностями при компиляции или запуске приложений.
4.1. Использование неправильного расширения файла
Давайте теперь попробуем скомпилировать исходный файл с помощью приведенной ниже команды, в которой есть опечатка — « .JAVA» в верхнем регистре:
Это приведет к тому же сообщению об ошибке, которое мы видели выше:
error: Class names, 'DemoClass.JAVA', are only accepted if annotation processing is explicitly requested 1 error
4.2. Ошибка основного класса
Давайте представим, что у нас есть класс DemoApplication с основным методом:
public class DemoApplication public static void main(String[] args) System.out.println("This is a DemoApplication"); > >
Давайте теперь запустим приложение с помощью команды java :
java DemoApplication.class
Результатом является ClassNotFoundException :
Error: Could not find or load main class DemoApplication.Class Caused by: java.lang.ClassNotFoundException: DemoApplication.Class
Теперь давайте попробуем запустить приложение без каких-либо расширений файлов — даже .class или .java :
Мы должны увидеть вывод на нашей консоли:
This is a DemoApplication
5. Вывод
В этой статье мы узнали, как неправильное использование или отсутствие расширения файла .java вызывает ошибки при компиляции классов из командной строки. Кроме того, мы видели несколько других ошибок, связанных с неправильным использованием аргументов командной строки как при компиляции, так и при запуске автономных приложений.
Источник
Русские Блоги
1. Чтобы различать ошибки времени компиляции и ошибки времени выполнения, вы должны сначала понять, что такое компиляция? Что работает?
Сначала взгляните на эту картинку:
Период компиляции — это процесс передачи исходного кода Java, который мы написали компилятору для выполнения.переводРоль этого процесса в основномПроверьте синтаксис исходного кода Java, Если нет синтаксических ошибок, скомпилируйте исходный код в файл байт-кода (т.е. файл класса)
Среда выполнения — это процесс загрузки файла байт-кода (файла .class) в память и передачи его на виртуальную машину Java до конца выполнения программы.Проверьте логические ошибки программыЕсли логической ошибки нет, функция программы реализуется и результат выводится.
2. Различия в распределении памяти между компиляцией и временем выполнения。
time Время компиляции — только для генерации некоторой оперативной памяти управляющей программы в файле байт-кода программы.инструкцияПростоKnowРазмер выделения памяти и место хранения,Нет конкретной операции выделения。
② Время выполнения — это памятьРеальное распределениеОпределите память, выделенную программойразмерИ эти переменные должны храниться в памятирасположение。
3. При разработке java-проекта в Eclipse, как отличить ошибку компиляции от ошибки времени выполнения?
errors Ошибки компиляции обычно относятся к синтаксическим ошибкам или очевидным логическим ошибкам.
Например: отсутствие точки с запятой, меньше скобок, неправильное написание ключевых слов и т. д., часто рисуют красные линии в затмении.
error Ошибка операции — это логическая ошибка, сгенерированная после запуска на основе ошибки компиляции.
Например: исключение нулевого указателя, делитель 0, доступ за пределы допустимого и т. д., как правило, вызывает исключение.
4. Примеры
Следующая программа, отредактируйте и запустите, результат ()
public class Test< public void main(String[] args)< System.out.println("Hello world"); > >
Результат:Компилировать без ошибок, новремя выполненияПроизошло исключение.
Интеллектуальная рекомендация
[Структура данных и алгоритм] Array Приложение 3: Сжатие разреженного матрицы (реализация Java)
Посмотрите прямо под код программы: Результатом заключается в следующем: Финансируется в: https://blog.51cto.com/xplaf/1976965.
springmvc
Что такое SpringMVC Легкий каркас, похожий на struts2 Используйте режим архитектуры mvc для разделения веб-слоя springmvc — это webmvc в весенней структуре Сопоставление запросов, используемое для упр.
GCC Learning (2) U-boot.lds
Проанализируйте файл uboot.lds 1 Использование output_format (по умолчанию, Big, Little), указание формата вывода, формат ELF, 32 -бит инструкции ARM, небольшой конец. 2 output_arch (ARM) Указанная ар.
Конфигурация переменной установки и среды JDK-9
JDK -9 выпущен в сентябре 2017 года, учитываяОфициальное утверждение сайтаOracle не будет опубликовать дальнейшие обновления Java SE 8 к своим сайтам скачивания для коммерческого использования после к.
Определение начального значения переменной modelica
Когда я впервые использую Modelic, я не знаю, как определить начальное значение переменной. Обычно система по умолчанию устанавливает начальное значение равным 0, в результате чего некоторые симуляции.
Источник