Can we run a Java program without main method? - java

For example I want to print statement like -
System.out.println("Hello");
How can the above line be printed on console without using the public static void main(String arg[]); in the class.

You will soon be able to do that with JShell, this allow you to type java expression in a shell to get the result, without having to compile the program. Here is a simple example from JShell - Java 9 interpreter (REPL) - Getting Started and Examples
> jdk-9/bin/jshell -v
jshell> void helloJShell() { System.out.println("hello JShell"); }
| created method helloJShell()
jshell> helloJShell();
hello JShell
You could then simply do
jshell> System.out.println("hello");
I didn't get time to try this yet but it look as simple as this.

Related

In JShell, how to load Java code from a string?

I have implemented a method that generates Java code:
public static String generate() { ... }
It returns Java code as a String, i.e. I might get
"public class X { public static String x() { return \"x\"; } }"
as a value returned by generate. Now, I am in a JShell Tool (JEP-222) session, and I can call generate, but I fail to load the result of generate into JShell itself.
Ideally I'd like to achieve the following
jshell> eval(generate());
| created class X
jshell> X.x();
$2 ==> "x"
In the above (hypothetical) JShell sesssion, eval is the function that I am looking for.
Possible solutions I already tried:
I know that this would be possible by calling JShell#eval but I failed to obtain the JShell object that represents the currently running JShell.
It might be that there is some facility in JShell that allows lifting a String to a Snippet. I couldn't find something like that, but if there is, it might be helpful.
I know that I can /open a file, so it might be possible to write the String to a file and then open/load it. However this is a two-step process, and I would prefer to have a solution that is simpler.

Array Index Out of Bounds - Class Name Convenction

I'm using the terminal in Mac to try and output some strings using javac. However there are some symbols that don't seem to work, for instance the dollar sign and asterisk:
public class BirdDisplay{
public static void main(String... args){
System.out.println(args[1]);
}
}
and then:
javac BirdDisplay.java
java BirdDisplay sparrow $someBird
I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at BirdDisplay.main(BirdDisplay.java:3)
As far as I know $ is accepted in class names and is a valid identifier, what is the cause of this exception?
You're using it from a shell, where $ is doing environment/shell variable substitution. This has nothing to do with Java - it's how the shell is invoking the process.
Just put it in single quotes:
java BirdDisplay sparrow '$someBird'
Note that the use of a $ as a valid Java identifier is irrelevant, as you're not using it in any source code - the value $someBird purely being used as data in your program (or will be once you've prevented the shell from performing variable substitutions).
As Daisy pointed out, this is because you are running your program in the shell, where $someBird is interpreted as an environment variable. Because $someBird is not an environment variable, the shell replaces it with nothing and you have a command-line arguments array of length 1 instead of length 2. As such, your program has no value for args[1] and you get java.lang.ArrayIndexOutOfBoundsException. You can test this by running this code to print out the length of args:
public class BirdDisplay{
public static void main(String... args){
System.out.println(args.length);
}
}
And now when you do:
javac BirdDisplay.java
java BirdDisplay sparrow $someBird
You will see 1 instead of 2

Invoke java method through perl and get the return value without using inbuilt functions

I have a Java program which has a static method
private static int checkURL(String currentURL)
From my perl script, I want to call this method and get return value of this method.
I have a constraint that I can't use any inbuilt Perl modules offered by CPAN.
I am thinking to call Java through system() command in Perl but issue is how to call this method and get the return code?
call external command and get back result (straight from http://www.perlhowto.com/executing_external_commands)
#-- scalar context
$result = `command arg1 arg2`;
Using Java module
use Java;
my $java = new Java;
my $obj = $java->create_object("com.my.Class","constructor parameter");
$obj->checkURL("http://www.google.com/");
$obj->setId(5);
Iniline::Java is also a famous module for Java/Perl integration.
Edit: I have a constraint that I can't use any inbuilt perl modules offered by CPAN.
Oh sorry I didn't see that. I had tried something like below some time ago.
Hello.java
class Hello {
// Your program begins with a call to main().
public static void main(String args[]) {
System.out.println("This is a simple Java program to test return code.\n");
System.exit(100);
}
}
test.pl
#!/usr/bin/perl
use strict;
use warnings;
my $command = "java Hello";
print "Command is $command:\n";
system($command);
my $retval = $? >> 8;
print "The return code is $?\n";
print "retval is $retval\n";
Run it
perl test.pl
Output
Command is java Hello:
This is a simple Java program to test return code.
The return code is 25600
retval is 100

No console output when running LuaJava Hello, World program

I'm starting out to learn Lua script usage in Java via LuaJava; my IDE is Eclipse.
But when I execute this simple Hello World snippet there is no output in the Eclipse console.
Took the code snippet from here
package com.cpg.lua;
import org.keplerproject.luajava.LuaState;
import org.keplerproject.luajava.LuaStateFactory;
public class Hello
{
public static void main(String[] args)
{
LuaState luaState;
luaState = LuaStateFactory.newLuaState();
luaState.openLibs();
luaState.LdoFile("hello.lua");
luaState.close();
}
}
hello.lua
function hello()
print("Hello World from Lua!")
end
hello()
But the script beneath works perfectly well.
hello2.lua
print("Hello World from Lua!")
Anyone know why the script with the function definition inside does nothing when called from Java but when executed through the console works perfectly?
I haven't tried or seen a function called like that. But you can call the hello() function from the Java like this:
LuaState l = LuaStateFactory.newLuaState();
l.doFile("main.lua");
l.getGlobal("hello");
l.call(0, 0);

Different results when compiling with command prompt and BlueJ

I'm just starting Java ... again.
I just made a simple program
class first
{
public static void main()
{
System.out.println("Hello!");
}
}
This runs perfectly fine in BlueJ but it gives an error during run-time when running from command prompt.
This is the error
Exception in thread "main" java.lang.NoSuchMethodError: main
It's because I didn't give String args[] in the main parameter list
Till now, I used to give it subconsciously. I know that the string array contains all the parameter values when running but then why is it running in BlueJ?
(BlueJ is a student-friendly Java editor and compiler)
Your program is valid and will compile to the same thing whether you compile from BlueJ or from the command line.
However, blueJ will let you run any static method in a class (so you can test your functions) where as the command line java command will (only) look for a special main method to run. This main method tages a String array with all the command line parameters and your program should look like this even though you don't use these command line parameters:
class first
{
public static void main(String[] args)
{
System.out.println("Hello!");
}
}

Categories

Resources