bsm
bsm

Reputation: 1893

How to run single Java file from a project in Eclipse?

I want to run one Java file from a project in Eclipse. There is code to insert into database in that Java file, I want to check from that single file whether its working or not. Is there any way to run a single Java file from a project?

Upvotes: 26

Views: 114659

Answers (7)

Ramesh Kotha
Ramesh Kotha

Reputation: 8322

Create a JUnit TestCase and run the Test, you can right click on the java file and choose JUnit Testcase, select which methods do you want test and run the Testcase.

or

You can simply write a public static void main(String[] args) but you have to change your java class.

so i prefer Junit to test individual java classes.

Upvotes: 2

tenorsax
tenorsax

Reputation: 21223

'Run as' item in context menu may contain various options depending on the file type, such as 'Ant Build' for ant scripts or 'Java Application' for java classes, etc. If you class has main() method you should have an option 'Java Application' to execute it.

Upvotes: 0

Bozho
Bozho

Reputation: 597076

Yes - right-click it and choose Run as -> Java application. You just need a main method.

Upvotes: 10

thagorn
thagorn

Reputation: 747

Sure, you just need a main function for any independent file.

Create a class like so:

public class HelloWorld
{
    public static void main(String[] args) {
        System.out.println("Hello World");

    }

}

and run that.

Upvotes: 7

theDazzler
theDazzler

Reputation: 1059

Yes, just put your main method inside that file and run it.

Upvotes: 1

kosa
kosa

Reputation: 66637

Does it has main method? If so, you can right click on the file and click Run-->Java application, from the pop-up menu.

Upvotes: 2

templatetypedef
templatetypedef

Reputation: 372764

It's important to note that you can't just run arbitrary Java code, but have to have some structure set up (for example, if you're going to call a method, what arguments are you passing in?) To run a specific piece of Java code, you should consider creating a main method in that class that just launches some specific piece of code under the constraints that you'd like. One way to do this would be to add a method public static void main(String[] args) containing the code you want to run. Once you've done this, you can right-click on it, choose the "Run as..." option, and select "Java application" to run the program you've written.

Alternatively, if you just want to check whether some specific piece of code is working, you could consider using JUnit to write unit tests for it. You could then execute the JUnit test suite from Eclipse to check whether that specific piece of code is functioning correctly. This is what I would suggest doing, as it makes it possible to test the software through every step of the development.

Hope this helps!

Upvotes: 35

Related Questions