Let's say i have a code like this :
public class Test {
public static void main(String args[])
{
int x = 5;
// Widening Casting
double myNum = x;
System.out.println(x + " " + myNum);
}
}
Now i write the following commands in powershell changing the value of x from 5 to 6 once in my code and saving it, it works perfectly fine. But tutorials online suggest me to use javac for compilation. Why so?
From Java 11 onwards, the java command is able to compile and run a single Java source file with a static void main(String[]) entry point method. (This feature was added as JEP 330.)
The online tutorials are correct for Java 10 and earlier, and they are correct for cases where more than one Java source file needs to be compiled.
Related
I have created the following Java class and saved it as Test.java, then compiled into Test.class on the command line using javac Test.java:
public class Test {
public Test() {
}
public double power(double number) {
System.out.println("calculating...");
return number * number;
}
}
Furthermore, I have created the following R script and saved it as test.R:
library("rJava")
.jinit(classpath = getwd())
test <- .jnew("Test")
.jcall(test, "D", "power", 3)
When I execute it, for example using R CMD BATCH test.R on the command line, I get the following output, which is what I want:
calculating...
[1] 9
However, when I wrap this script in a Markdown document and compile it using knitr, I lose the message that is printed about the calculation taking place. For example, I save the following script in test.Rmd and compile it using RStudio:
```{r echo=TRUE, warning=TRUE, results='show', message=TRUE}
library("rJava")
.jinit(classpath = getwd())
test <- .jnew("Test")
.jcall(test, "D", "power", 3)
```
This only returns the following output, without the message:
## [1] 9
I read somewhere that the reason is that System.out.println in Java writes to stdout, and whether this is shown in the R console or not depends on the interpreter. For example, the output is shown on Unix systems but not on Windows or in knitr.
My questions:
Is the above interpretation correct?
How can I reliably capture or display the output of System.out.println in R, irrespective of operating system or interpreter?
If that's not possible, what is a better way of designing status messages about the current calculations and progress in Java, such that R can display these messages?
Thanks!
I'll take a stab at answering my own question... Looks like the RJava folks actually offer a built-in solution (thanks Simon Urbanek if you read this). On the side of the Java code, there is the LGPL-licensed JRI.jar, which is delivered with rJava (look at the jri sub-directory in the rJava package directory in your local R library path) and which can be copied/extracted into the Java library path. It's only 82kb, so fairly light-weight.
JRI offers a replacement of the default print stream in Java. Essentially, you redirect the system output into an RConsoleOutputStream provided by JRI. The code in my question above can be modified as follows to print to the R console instead of stdout.
import java.io.PrintStream;
import org.rosuda.JRI.RConsoleOutputStream;
import org.rosuda.JRI.Rengine;
public class Test {
public Test() {
Rengine r = new Rengine();
RConsoleOutputStream rs = new RConsoleOutputStream(r, 0);
System.setOut(new PrintStream(rs));
}
public double power(double number) {
System.out.println("calculating...");
return number * number;
}
}
The below code gets compiled successfully, wherein inside some class, I have written two methods with same name & same type signature. Am using Eclipse Oxygen 4.7.0 and I can see error Duplicate method show(int,int) shown in red. But when I compile the code, its getting compiled successfully with correct output. When I run the same code in command prompt using javac its validly not getting compiled.
package oops2;
class A6
{
int i, j;
void show(int i, int j)
{
System.out.println(" i & j : " +i + " " +j);
}
void show(int k, int l)
{
System.out.println("override or not");
}
void show(String s)
{
System.out.println("Entered str is "+s);
}
}
public class OverrideNoInherit
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
A6 a = new A6();
a.show(20, 30);
a.show("this is it");
}
}
Here, I want to mention that when I click on run on Eclipse, I get a pop-up saying
Errors exist in this project, proceed with launch?
Now, didn't this error mean that there are other classes in same project which had errors & thus did not get compile. I don't think this meant that despite there being errors in code, the programs would get compiled. Then what would be difference between warnings & errors?
Eclipse always compiles classes. The body of methods containing errors are replaced by a method that throws a java.lang.Error containing the compile errors of that class. This is actually helpful for test driven development that allows you to start tests on classes that have compile errors. The methods that are compilable can be tested even if some other parts are currently containing errors.
You've got a special case here. The compiler is able to compile the first occurance of the method but later comes across the duplicate method that can't be added to the class. Because the first method is already compiled and when you enforce the starting of the class despite the warning you see the regular method that was successfully compiled in action.
I want to use matlab function in java application. I create java package from my function by deploytool in matlab. Now, how can i use this package? Can only import the jar file created by deploytool in my java project and use its function?
After a lot of googling, I used this toturial but in the final step, i get error "could not load file".
Also i read about MatlabControl, but in this solution, we should have matlab environment in our system to java code running. But i will run my final app in systems that may not have matlab at all.
So i need a solution to run matlab function in java class even in absence of matlab environment.
Finally I solve my problem. the solution step by step is as follows:
write matlab function:
function y = makesqr(x)
y = magic(x);
Use deploytool in matlab and create java package.
3.create new java application in Eclipse and add main class. import javabuilde.jar and makesqr.jar:
import com.mathworks.toolbox.javabuilder.MWArray;
import com.mathworks.toolbox.javabuilder.MWClassID;
import com.mathworks.toolbox.javabuilder.MWNumericArray;
import makesqr.Class1;
and main.java:
public class main {
public static void main(String[] args) {
MWNumericArray n = null;
Object[] result = null;
Class1 theMagic = null;
try
{
n = new MWNumericArray(Double.valueOf(5),MWClassID.DOUBLE);
theMagic = new Class1();
result = theMagic.makesqr(1, n);
System.out.println(result[0]);
}
catch (Exception e)
{
System.out.println("Exception: " + e.toString());
}
finally
{
MWArray.disposeArray(n);
MWArray.disposeArray(result);
theMagic.dispose();
}
}
}
add javabuilder.jar and makesqr.jar to java build path of your project.
run it.
the Double.valueOf(3), define the input for our function and the output is as follows:
8 1 6
3 5 7
4 9 2
I didn't get properly your problem. Did you already compile the jar file from Matlab code and you are trying to use that, or you are at the last step of the tutorial?
If your answer is the latest case, most probably you forgot the "." before the class path.
From tutorial you linked:
You must be sure to place a dot (.) in the first position of the class path. If it not, you get a message stating that Java cannot load the class.
Also check if the matlab compiler path ("c:\Program Files\MATLAB\MATLAB Compiler Runtime\v82\toolbox\javabuilder\jar\javabuilder.jar" - in the tutorial) is correct for your system.
I'm trying to run project which uses fannj library, but I'm getting error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: Error looking up function 'fann_create_standard_array':
at com.sun.jna.Function.<init>(Function.java:179)
at com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:347)
at com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:327)
at com.sun.jna.Native.register(Native.java:1355)
at com.sun.jna.Native.register(Native.java:1032)
at com.googlecode.fannj.Fann.<clinit>(Fann.java:46)
at javaapplication9.JavaApplication9.main(JavaApplication9.java:14)
Java Result: 1
This is what I did:
I put fannfloat.dll to C:\Windows\System32
I added fannj-0.3.jar to project
I added newest jna.jar to project
here is code:
public static void main(String[] args) {
System.setProperty("jna.library.path", "C:\\Windows\\System32");
System.loadLibrary("fannfloat");
Fann fann=new Fann("D:\\SunSpots.net");
fann.close();
}
SunSpots.net is file from example package. fannfloat.dll: you can get from here.
The "#8" at the end of _fann_create_standard_array indicates that the library is using the stdcall calling convention, so your library interface needs to implement that interface (StdCallLibrary) and it will automatically get the function name mapper applied that converts your simple java name to the decorated stdcall one.
This is covered in the JNA documentation.
It was the first time I had to work with FANN and it took me some time to make it work.
Downloaded Fann 2.2.0. Extract (in my case "C:/FANN-2.2.0-Source") and check the path of the fannfloat.dll file. This is the library that we will use later.
Download fannj-0.6.jar from http://code.google.com/p/fannj/downloads/list.
The dll is compiled for 32 bit environment. So, make sure you have a 32 bit Java installed (even in 64 bit Windows).
I suppose you already have the .net file with your ANN. Write something like this in Java
public class FannTest {
public static void main(String[] args) {
System.setProperty("jna.library.path", "C:/FANN-2.2.0-Source/bin");
Fann fann = new Fann("C:/MySunSpots.net" );
float[] inputs = new float[]{0.686470295f, 0.749375936f, 0.555167249f, 0.816774838f, 0.767848228f, 0.60908637f};
float[] outputs = fann.run( inputs );
fann.close();
for (float f : outputs) {
System.out.print(f + ",");
}
}
}
I've just started using eclipse and java and I'm not used to either one of them. I wrote a simple helloworld-programm, but the next task (school) was to create a program that takes a userinput (from commandline) and responds with the highest number of two. The code I wrote looks like following:
public class Larger {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
if(args.length < 2)
{
System.out.print("Too few parameters submitted.");
return;
}
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
System.out.print(Math.max(num1, num2));
}
}
It all works well when I hit the "run"-button in eclipse, but later when I browse the source-files and tries to run "java Larger.class 2 4" i get an error from java.exe saying that no class was found.
Any idea what this can be?
When it fails, are you invoking the Java process through Eclipse or the command line? It sounds like you're doing it from the command line. In that case, you don't specify the ".class" portion when invoking your Java program. Try :
java Larger 2 4
The "run" button launch your program with the adequate classpath (the bin folder where the .class is generated)
alt text http://ftp.sumylug.osdn.org.ua/pub/mirrors/eclipse.org/downloads/drops/R-3.2-200606291905/new_noteworthy/images/rt-classpath.png
the java needs to refer to that same bin folder, and use the class name (not the class generated binary)
java -cp bin Larger 2 4
To compile javac Large.java
To run java Larger 2 4