I'm teaching my friend some Java, and we're running into issues trying to run the compiler on her Hello World program. The code had a pretty glaring error (Sysrem.out.println), but otherwise was totally valid Java, but for some reason the compiler didn't report the error. Here's what happened:
When we ran javac Hello.java in Windows Command Prompt, it printed out a blank line and then a new command prompt line, as if the operation had succeeded, but it clearly hadn't - a class file wasn't created, and of course the code had an error so we knew it wouldn't be successful.
When we ran javac -verbose Hello.java, it printed out the gory details of the class files it was loading, but then that was it. While it didn't end by saying it had written a class file, it also didn't print out the error.
After we fixed the error, the program compiled and ran without a problem, so it seems to be that javac just doesn't like printing out compiler errors.
What could be going on here, why isn't the compiler reporting this error like it should?
The complete code:
public class Hello {
public static void main(String[] args) {
Sysrem.out.println("Hello, world!");
}
}
The command prompt:
C:\Users\MyFriendsName\Documents>javac Hello.java
C:\Users\MyFriendsName\Documents>
What this actually boils down to is whether an empty file is a valid Java program. Surprisingly, it is!
Here is the grammar for a CompilationUnit ... which is the technical term that that JLS uses for a Java source file:
CompilationUnit:
OrdinaryCompilationUnit
ModularCompilationUnit
OrdinaryCompilationUnit:
[PackageDeclaration] {ImportDeclaration} {TypeDeclaration}
ModularCompilationUnit:
{ImportDeclaration} ModuleDeclaration
(Reference: JLS 7.3)
Note that the OrdinaryCompilationUnit element allows you to have a source file that consists of:
no package statement
no import statements
no type declarations
In other words, an empty file, or a file that just contains comments.
In short, if you tell javac to compile an empty file, it won't produce any compilation errors ... because it is "valid" Java source code file.
Well, I discovered the issue: Turns out my friend had never hit Save on her file after creating it, and in what I'm assuming is just some unintuitively-designed expected behavior, javac doesn't complain about being fed a blank file!
Here's exactly what happened:
Create the file
Write the buggy code but don't save the file
Attempt to compile the code and hit the issue described in my question
Correct the bug in the code and save the file
Compile and run the code without a problem
Related
Sorry if this question has already been answered some where, I have not had any luck turning up a solution. This is my first SO post, if information is missing/unclear, or the formatting sucks, let me know, I will update the post.
I am using TestNG version 6.13.1 (also tested with 7.0.0-beta1). I am running this command (not the full command, the class path is massive, and there are multiple -D options)
java -cp <classpath stuff...> -DappiumPort=30000 org.testng.TestNG -usedefaultlisteners false /Users/.../adbservice/test-results/3567/test_config/Test_Suite_testT13googleMaps.xml
expecting that testNG will recognize the first argument as a switch, and turn the default listeners off. This is based on reading Turning off test-output in TestNG and http://testng.org/doc/documentation-main.html#testng-xml, and other less relevant documents.
What actually happens is testNG appears to treat all the arguments as if they are file paths, and I get a very helpful error message
ProcessResults(exitCode=0, output=java.io.FileNotFoundException: /Users/.../adbservice/-usedefaultlisteners false testng.xml (No such file or directory)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:196)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:139)
at org.testng.xml.Parser.parse(Parser.java:148)
at org.testng.xml.Parser.parse(Parser.java:233)
at org.testng.TestNG.parseSuite(TestNG.java:290)
at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:334)
at org.testng.TestNG.initializeEverything(TestNG.java:974)
at org.testng.TestNG.run(TestNG.java:988)
at org.testng.TestNG.privateMain(TestNG.java:1330)
at org.testng.TestNG.main(TestNG.java:1299)
The command itself is issued from Java, using a wrapper around a ProcessExecutor. The code looks like
new ProcessExecutor()
.command(cmd)
.readOutput(true)
.timeout(waitForTimeMs, TimeUnit.MILLISECONDS)
.execute();
I can get the same error if I capture the command input and paste it into the shell, so it seems that it is not a problem with the java code itself, but I figured I would include that information for completeness.
My question is, how can I make this call to testNG work using the command line arguments? There seem to be few alternatives because I have packaged tests which are executed in a shell process.
Edit
Since this is such a common case, I am convinced there is something wrong on my side. I tested that theory out by creating a really simple java project with a smoke test, and then ran it with
java -cp .:testng-6.13.1.jar:jcommander-1.72.jar:build/libs/test-1.0-SNAPSHOT.jar org.testng.TestNG -usedefaultlisteners false testng.xml
which worked exactly as described in the documentation. Therefore I think there is something going on with the input to java and how it is being processed that is causing the error with testNG.
Edit 2
Did some further investigation on my side, eventually I tried the original generated java command with the parameters ( -usedefaultlisteners false) on the command line, and lo and behold it worked, or at least, it did some stuff before bombing out, instead of complaining about the parameters being invalid file paths, which was my original result when running on the command line. Maybe I had the wrong directory or some such the first time, but this suggests that it is a problem with handling the command with this ProcessExecutor.
Edit 3
Paydirt. It turns out the ProcessExecutor library does not handle command line input with spaces as one might expect, so for example,
Lists.newArrayList(
"java", "-cp", ".:", "org.testng.TestNG", "-enabledefaultlisteners false", "testng.xml"
)
will error, but
Lists.newArrayList(
"java", "-cp", ".:", "org.testng.TestNG", "-enabledefaultlisteners", "false", "testng.xml"
)
works. It seems like that should be documented in the ProcessExecutor library docs.
I am a new beginner of Java. I wrote a Hello.java file with a extend jar package "algs4.jar"(my textbook asked me to use their own output/input library(Algorithm 4th Edition)), which can print a 'Hello,World!\n' string on the shell when executed.
It was compiled without any error, (command:javac -cp E:\AlgorithmExercise\lib\algs4.jar E:\AlgorithmExercise\codes\Hello\Hello.java)
but when I tried to run the class (command: java codes.Hello.Hello), I got this error.
I guessed the reason of this error is because I forgot to enter the path of the algs4.jar package. so I modified the command: java -cp .;E:\AlgorithmExercise\lib\algs4.jar codes.Hello.Hello, but the terminal informed me that it "cannot find or load the main class."
I am absolutely cannot understand what's going on, my classpath has no mistake on configure.
I'm trying to call a java program from python using command line. The code is as follows:
subprocess.check_output(["java", "pitt.search.semanticvectors.CompareTerms", "-queryvectorfile","termvectors.bin","term1","term2"])
I get the following error:
Error: Could not find or load main class pitt.search.semanticvectors.CompareTerms
This happens when I run the program from PyDev (version 2.5 in Eclipse 3.7.2). However, if I run the same code from the terminal, it works and I get the result I want.
I'm almost sure that the problem is related with some configuration of PyDev and how it handles the java CLASSPATH, which is:
/Users/feralvam/Programas/semanticvectors-3.4/semanticvectors-3.4.jar:/Users/feralvam/Programas/lucene-3.5.0/lucene-core-3.5.0.jar:/Users/feralvam/Programas/lucene-3.5.0/contrib/demo/lucene-demo-3.5.0.jar:
The class "pitt.search.semanticvectors.CompareTerms" is in "semanticvectors-3.4.jar".
Any help you could give me would be really appreciated.
Thanks!
The solution proposed by #eis worked. Now, the command is:
subprocess.check_output(["java", "-classpath", "/Users/feralvam/Programas/semanticvectors-3.4/semanticvectors-3.4.jar:/Users/feralvam/Programas/lucene-3.5.0/lucene-core-3.5.0.jar:/Users/feralvam/Programas/lucene-3.5.0/contrib/demo/lucene-demo-3.5.0.jar:", "pitt.search.semanticvectors.CompareTerms", "-queryvectorfile","/Users/feralvam/termvectors.bin","term1","term2"])
HI All,
I got an issue, all of a sudden Java stopped working completely. I start getting error like "Could not create the virtual machine". There is no issue with the memory (it has 3GB RAM) and was working fine for over a 6 months in this system without any issue.
Here are some peculiar behaviors -
When I start eclipse I see Java virtual machine dialog box with error messages like
"Could not find main class org.eclipse......support.legacysystemproperties"
Eclipse is able to start(with above error), but while running the program, I get error like "Could not create Java Virtual Machine" in a dialog box and after I click OK on that dialog box, I see error like "unrecognized option -dfile.encoding=cp1252
I used text editor, wrote a class Test.java (without any package), compiled it (Edit #1:javac Test.java). But when I execute the program (Edit #1:java Test), I get the following error -
Exception in thread "main" java.lang.NoClassDefFoundError: test (wrong name: Test).
Edit #1:
Note : The compiled file, Test.class is successfully created in the directory. I did recheck the path and classpath environment variables. All seem to be correct.
Please note that there seems to be some issues with cases which affected the Java.
I did uninstall Java (all versions), re-installed, but nothing helped. Also, I did run CCleaner to clean registry, Malwarebytes' Anti-Malware, but none helped so far.
Appreciate if someone could help me to resolve the issue.
I did googled for this and found that some have experienced similar issues, but none of them have found solution yet other than some suggestion that re-installation of Windows OS itself, which I want to avoid it. I did system restore, but that failed for some other
reason.
Please note that am using Java for over 10 years. This is first time am having such issue. This is something to do with Windows Registry or some other system configuration, but I am not able to find out the exact problem.
Anyways awaiting some good suggestion.
EDIT: Okay, so it looks like the Java executable is getting the command line arguments lower-cased.
Step 1: Verify
You can double-check whether this affects all command line arguments by creating a class with a lower-case name which just dumps its arguments:
public class test {
public static void main(String[] args) {
for (String arg : args) {
System.out.println(arg);
}
}
}
Compile and run this with a variety of inputs.
Step 2: Check scope
Assuming step 1 confirms the problem, if you've got .NET installed you can see whether it affects that as well. Create a file Test.cs:
using System;
class Test
{
static void Main(string[] args)
{
foreach (string arg in args)
{
Console.WriteLine(arg);
}
}
}
Compile this with "csc Test.cs" having found csc in the .NET framework directory (e.g. in c:\Windows\Microsoft.NET\Framework\v4.0.30319 for .NET 4).
Run it like this:
Test foo BAR Baz
and see what happens
Step 3: If step 2 showed that the issue is limited to java.exe:
Check your path, and work out where you're actually running java.exe from
Try explicitly running java.exe from your JRE or JDK directory
I get this error when I compile my java program:
error: Class names, 'EnumDevices', are only accepted if annotation
processing is explicitly requested
1 error
Here is the java code (I'm running this on Ubuntu).
import jcuda.CUDA;
import jcuda.driver.CUdevprop;
import jcuda.driver.types.CUdevice;
public class EnumDevices {
public static void main(String args[]) {
CUDA cuda = new CUDA(true);
int count = cuda.getDeviceCount();
System.out.println("Total number of devices: " + count);
for (int i = 0; i < count; i++) {
CUdevice dev = cuda.getDevice(i);
String name = cuda.getDeviceName(dev);
System.out.println("Name: " + name);
int version[] = cuda.getDeviceComputeCapability(dev);
System.out.println("Version: " +
String.format("%d.%d", version[0], version[1]));
CUdevprop prop = cuda.getDeviceProperties(dev);
System.out.println("Clock rate: " + prop.clockRate + " MHz");
System.out.println("Threads per block: " + prop.maxThreadsPerBlock);
}
}
}
Here is the javac command:
javac -cp /home/manish.yadav/Desktop/JCuda-All-0.3.2-bin-linux-x86_64 EnumDevices
How do I compile this program?
You at least need to add the .java extension to the file name in this line:
javac -cp /home/manish.yadav/Desktop/JCuda-All-0.3.2-bin-linux-x86_64 EnumDevices
From the official faq:
Class names, 'HelloWorldApp', are only accepted if annotation processing is explicitly requested
If you receive this error, you forgot to include the .java suffix when compiling the program. Remember, the command is javac HelloWorldApp.java not javac HelloWorldApp.
Also, in your second javac-example, (in which you actually included .java) you need to include the all required .jar-files needed for compilation.
I was stumped by this too because I was including the .Java extension ... then I noticed the capital J.
This will also cause the "annotation processing" error:
javac myclass.Java
Instead, it should be:
javac myclass.java
Using javac ClassName.java to compile the program,
then use java ClassName to execute the compiled code. You can't mix javac with the ClassName only (without the java extension).
The error "Class names are only accepted if annotation processing is explicitly requested" can be caused by one or more of the following:
Not using the .java extension for your java file when compiling.
Improper capitalization of the .java extension (i.e. .Java) when compiling.
Any other typo in the .java extension when compiling.
When compiling and running at the same time, forgetting to use '&&' to concatenate the two commands (i.e. javac Hangman.java java Hangman). It took me like 30 minutes to figure this out, which I noticed by running the compilation and the running the program separately, which of course worked perfectly fine.
This may not be the complete list of causes to this error, but these are the causes that I am aware of so far.
I learned that you also can get this error by storing the source file in a folder named Java
chandan#cmaster:~/More$ javac New.java
chandan#cmaster:~/More$ javac New
error: Class names, 'New', are only accepted if annotation processing is explicitly requested
1 error
So if you by mistake after compiling again use javac for running a program.
How you can reproduce this cryptic error on the Ubuntu terminal:
Put this in a file called Main.java:
public Main{
public static void main(String[] args){
System.out.println("ok");
}
}
Then compile it like this:
user#defiant /home/user $ javac Main
error: Class names, 'Main', are only accepted if
annotation processing is explicitly requested
1 error
It's because you didn't specify .java at the end of Main.
Do it like this, and it works:
user#defiant /home/user $ javac Main.java
user#defiant /home/user $
Slap your forehead now and grumble that the error message is so cryptic.
Perhaps you may be compiling with file name instead of method name....Check once I too made the same mistake but I corrected it quickly .....#happy Coding
first download jdk from https://www.oracle.com/technetwork/java/javase/downloads/index.html.
Then in search write Edit the System environment variables
In open window i push bottom called Environment Variables
Then in System variables enter image description here
Push bottom new
In field new variables write "Path"
In field new value Write directory in folder bin in jdk like
"C:\Program Files\Java\jdk1.8.0_191\bin"
but in my OS work only this "C:\Program Files\Java\jdk1.8.0_191\bin\javac.exe"
enter image description here
press ok 3 times
Start Cmd.
I push bottom windows + R.
Then write cmd.
In cmd write "cd (your directory with code )" looks like C:\Users\user\IdeaProjects\app\src.
Then write "javac (name of your main class for your program).java" looks like blabla.java
and javac create byte code like (name of your main class).class in your directory.
last write in cmd "java (name of your main class)" and my program start work
To avoid this error, you should use javac command with .java extension.
Javac DescendingOrder.java <- this work perfectly.
I created a jar file from a Maven project
(by write mvn package or mvn install )
after that i open the cmd , move to the jar direction and then
to run this code the
java -cp FILENAME.jar package.Java-Main-File-Name-Class
Edited : after puting in Pom file declar the main to run the code :
java -jar FILENAME.JAR
If you compile multiple files in the same line, ensure that you use javac only once and not for every class file.
Incorrect:
Correct: