How to write a Hello World application in Java? [duplicate] - java

This question already has answers here:
Why main() method is needed in java main class
(6 answers)
Closed 5 years ago.
I have been trying to make the Hello World Java application. But when I try to run the program it says that my selection has no main type. Here is my source code.
public class HelloWorldClass {
System.out.println("Hello world!");
}

Because it has no main() method where the code would take the starting point. Use this
public class HelloWorldClass {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
Please note there are some of the things you should always take a note of while programming. Which is also known as the syntax of the language.
Java requires you to have the class written as the FileName, HelloWorldClass is the name of the file of yours.
Then, any data type of it. In my case it is void which means it won't return anything to you in the end.
Also, you should write String[] args which is the Parameter to the method. I was last night trying to understand why I should write these? There is a method, which runs without these, but Java recommends you to add the parameters.

When running Java you need a main method so the compiler knows what to run:
public class HelloWorldClass {
public static void main(String[] args)
{
System.out.println("Hello world!");
}
}

Related

Problem with hello world tutorial in dcoder [duplicate]

This question already has answers here:
Error: class X is public should be declared in a file named X.java
(19 answers)
Closed 4 years ago.
New to coding. Searched following query to no avail.
I'm using Dcoder IDE and trying the Hello World tutorial.
The following error message occurs when I try to output my code.
source_file.java:1: error: class HelloWorld1 is public,
should be declared in a file named HelloWorld1.java
public class HelloWorld1
^
1 error
My code is as follows
public class HelloWorld1
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
The file is saved as HelloWorld1.java
How do I resolve this?
Thanks
Your file is saved as source_file.java. In order for your code to compile, it must be named HelloWorld1.java.
To improve the readability of your code it is often a good practice to indent, like this:
public class HelloWorld1 {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Are you sure that the file is saved as HelloWorld1.java? Because in the output you posted it reads it as "source_file.java".

Java - Method picking algorithm [duplicate]

This question already has answers here:
Using null in overloaded methods in Java [duplicate]
(3 answers)
Closed 7 years ago.
I was messing around with methods and was looking, which Method will be executed if I make two Methods named "hello", with different objects they want and pass a "null" to the method:
public static void main(String... args) {
hello(null);
}
public static void hello(Window w) {
System.out.println("Hello");
}
public static void hello(Frame f) {
System.out.println("Bye");
}
The output was every time "Bye", but I still don't understand the logic behind that.
After a short research with google, without of any explanation, I decided to ask the question here.
I hope that someone can explain the selection algorithm or give me a link to a explanation.
The compiler prefers the most specialized type:
public class Parent {
public static void main(String... args) {
hello(null); // takes `Child`
}
public static void hello(Parent _) {
System.out.println("SuperClass");
}
public static void hello(Child _) {
System.out.println("SubClass");
}
}
class Child extends Parent {
}
For the reason, take a look at this thread, #Hayden already mentioned in his comment.
Java will choose the most specific of the two methods provided (See the Java Language Specification)
If more than one member method is both accessible and applicable to a
method invocation, it is necessary to choose one to provide the
descriptor for the run-time method dispatch. The Java programming
language uses the rule that the most specific method is chosen.
As the class hierarchy for Frame is
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
An the class hierarchy for Window is
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
Frame is the most specific method, and then, your public static void hello(Frame f) will be chosen.

Not able understand the error in java

I was trying to know what would happen if I have two classes with the main function.
I used the following code:
class A {
public static void main(String[] args){
System.out.println("Hello,World!");
}
}
class Hello {
public static void main(String[] args){
System.out.println("Hello,World!");
}
}
I compiled it using javac First.java (since no class is specified as public , I named the file as First.java); it got compiled without any error and i ran only the class A.Expecting the Hello class to run itself. DIDN'T HAPPEN(?),maybe the program ran out of scope.
So,
I tried compiling the following java code(I am a beginner) but i got the following error.
Code:
class Hello {
public static void main(String[] args) {
System.out.println("Hello,World!");
}
}
class A {
public static void main(String[] args) {
System.out.println("Hello,World!");
Hello.main();
}
}
I compiled it through javac First.javaand got the following error:
method main in class Hello cannot be applied to given types;
Hello.main();
^
I wanted the program to run first the class A's main function and then class Hello's.
What's going wrong here?
Look at the declaration of Hello.main:
public static void main(String[] args)
Now you're trying to call it like this:
Hello.main();
What would you expect the value of args to be, within the method? You need to provide it with a value for args... and fortunately, you already have one, as you're within a method which uses args as a parameter, also of type String[]. So you should just be able to change your code to:
Hello.main(args);
Note that the two args parameters - one for Hello.main and one for A.main are entirely separate. We happen to use pass the value of one to the provide the initial value for the other, but we could easily have written:
Hello.main(null);
or
Hello.main(new String[] { "Some", "other", "strings" });
instead.
Do this in your second class:
public static void main(String[] args) throws IOException {
MyOtherClass.main(args);
}

"Main method not found" error when starting program? [duplicate]

This question already has answers here:
"Error: Main method not found in class MyClass, please define the main method as..."
(10 answers)
Closed 4 years ago.
I'm learning Java for my course and I've hit a brick wall. I've been tasked with developing a simple command line program. To make things easier I was given the following sample code to modify so I wouldn't have to start from scratch.
package assignment;
public class Main {
private final static String[] mainMenuOpts = {"Students","Lecturers","Admin","Exit"};
private final static String[] studentMenuOpts = {"Add Student","List all Students","Find a Student","Return to Main Menu"};
private Menu mainMenu = new Menu("MAIN MENU",mainMenuOpts);
private Menu studentMenu = new Menu("STUDENT MENU",studentMenuOpts);
private DataStore data = new DataStore();
private java.io.PrintStream out = System.out;
private ReadKb reader = new ReadKb();
/** Creates a new instance of Main */
public Main() {
run();
}
private void run(){
int ret = mainMenu.display();
while(true){
switch(ret){
case 1: students();break;
case 2: lecturers(); break;
case 3: admin(); break;
case 4: exit(); break;
}
ret = mainMenu.display();
}
}
private void students(){
int ret = studentMenu.display();
while(ret != 4){
switch(ret){
case 1: addStudent();break;
case 2: listStudents(); break;
case 3: findStudent(); break;
}
ret = studentMenu.display();
}
}
private void lecturers(){
out.println("\nLecturers not yet implemented");
}
private void admin(){
out.println("\nAdmin not yet implemented");
}
//Student methods
private void addStudent(){
out.println("\n\tAdd New Student");
//prompt for details
//add student to the datastore
//ask if they want to enter another student -
// if so call addStudent again
//otherwise the method completes and the studentMenu will display again
}
private void listStudents(){
out.println("\n\tStudent Listing");
//list all students from the datastore
}
private void findStudent(){
out.println("\n\tFind Student");
out.print("Enter Search String: ");
//reasd search text
//use datastore method to get list of students that contain the search string
//display matching students
}
// end Student methods
private void exit() {
data.save(); //call the datastore method that will save to file
out.println("\n\nGoodbye :)");
System.exit(0);
}
}
I'm using NetBeans and when I try to run the project I get this error:
Error: Main method not found in class assignment.Main, please define the main method as: public static void main(String[] args)
I just want to get the program running so I can understand the code better. I understand the error, but have no idea where to implement the main method in this wall of text. I've been experimenting for hours, but obviously as a newbie I'm completely useless. Any help would be greatly appreciated.
What you have currently is just a constructor named Main, what Java needs is a main method with exact signature as:
public static void main(String[] args)
public - so that it can be called from outside
static - so that no need to create an instance of your class
void - not going to return any value
args - an array for command line parameters that you can specify while running the program
This is the entry point for your application.
When your current code is being invoked, JVM is trying to locate main method, and since its not present in your code, it's throwing the exception which you have received.
Since you have mentioned beginner in your post, its worth mentioning that Java is a case sensitive language - main and Main are not same in Java.
See also: The getting started tutorial.
The correct signature of main is:
public static void main(String[] args) {
new Main();
}
It's even written in the error message you posted.
Remove the ; from the constructor:
public Main() {
run();
}
You have to use main() method in your program.
From here the program execution starts.
like
public static void main(String args[])
{
//This is the starting point of your program.
}
This method must appear within a class, but it can be any class.
In the Java language, when you execute a class with the Java interpreter, the runtime system starts by calling the class's main() method. The main() method then calls all the other methods required to run your application.
The main() method accepts a single parameter: an array of Strings. This parameter is the mechanism through which the runtime system passes command line arguments to your application
It's looking for a method with this signature:
public static void main(String[] args)
To run your code, the main method can look like this:
public static void main(String[] args)
{
new Main();
}
As the rather helpful error message states, you need a main method. See the java tutorials.
main method should exist for your application to run. Java applications need it to know where to begin executing the program.
Put the method in a class of your choice, and then right click file and select 'Run file`.
public static void main(String[] args)
{
// your code here
}
You need add a main method in your main class so that JVM will know where to start from and not a class with a "main" name.
public static void main(String[] args) {
new Main();
}

Exception in thread "main" java.lang.NoSuchMethodError: main [duplicate]

This question already has answers here:
"Error: Main method not found in class MyClass, please define the main method as..."
(10 answers)
Closed 9 years ago.
when i try to compile this:
public class Risk
{
}
class territory
{
public static void main (String[]arg)
{
System.out.println ("hi") ;
}
}
I get this error message:
Exception in thread "main" java.lang.NoSuchMethodError: main
whats going wrong here?
The class containing the main() function must be public, and you may only define one public class per file. You'll want to have two separate files Risk.java and Territory.java.
Risk.java:
public class Risk {
}
Territory.java:
public class Territory
{
public static void main (String[]arg)
{
System.out.println ("hi") ;
}
}
EDIT: It turns out this isn't true - I was able to run your initial code with the following command line:
java territory
But my earlier comments point to the best practice for a real app, such as a Risk game.
What class are you trying to run? If you're using the class territory, that will work. Risk has no main method, though.
Can you figure out why this example causes the same issue?
public class Simple {
public void main(String args[]) {
System.out.println("Inside function");
}
}
Answer: because main() should be public static void!
Could it just be a spacing issue? Your original post shows no space between the ']' and 'arg'.
Try this:
public static void main (String[] arg)
or, if that still doesn't work:
public static void main (String arg[])
What the answer wound up being was that the class i run must contain main or else it won't work. i'm posting this because, though other answers give roughly the same information, they don't make it explicit.

Categories

Resources