This question already has answers here:
Java Puzzler- What is the reason? [closed]
(4 answers)
Closed 9 years ago.
I tried to implement this code:
package java.lang;
public class String {
public static void main(String[] args) {
for (int i=1;i<=1000;i++)
{
String str= "1";
}
}
}
But I'm getting
Error: Main method not found in class java.lang.String, please define
the main method as: public static void main(String[] args)
I've googled and tried everything, but don't know how to get rid of it?
Please avoid using the package java.lang as well.
And change the name class to something other than String.
String is already defined as a final class in java; as part of the java.lang package.
You could use the class name String elsewhere (i.e. your own packages) but not as any of your java.lang package classes.
Change your class name from String to something other than that. String is already a keyword in java.
package java.lang;
public class S1 {
public static void main(String[] args) {
for (int i=1;i<=1000;i++)
{
String str= "1";
}
}
}
A few things:
No need to do package java.lang; And you should implement either a whole subpackage like package java.somePackage.* or just a specific class package java.net.HttpURLConnection. Importing packages unnecessarily is a bad practice. Seems like you are new to Java, get your good standards as accurately from the scratch as possible.
Change your classname to something else, as suggested by other answer providers. String is a fundamental class (not primitive type). It is more like static class library for general use.
The rest is fine. I am a bit confused about your statement within for loop. But it is syntactically correct. We are not responsible for that.
Should be fine now!
Related
This question already has answers here:
What does "Could not find or load main class" mean?
(61 answers)
What is the purpose of defining a package in a Java file? [closed]
(11 answers)
Closed 6 months ago.
I am just starting to learn Java. I have made a project of Java using Visual Studio Code. The file path looks like this project/src/own/test.java.
I have written a simple program:
package own;
import java.util.Random;
import java.util.Scanner;
import static java.lang.System.out;
public class test {
public static void main (String[] args){
int randomNumber = new Random().nextInt(7);
System.out.println("Enter a number");
Scanner keyboard = new Scanner(System.in);
int inputNumber = keyboard.nextInt();
if (randomNumber == inputNumber){
System.out.println("You won!");
}else{
System.out.println("You loose!");
}
keyboard.close();
}
}
Every time I run this is the vscode terminal, it says:
Error: Could not find or load main class test
But it runs fine if package own; line is not there. Vscode automatically included this line. Can anyone tell me why that is so? What is the use of package own.
Classes in Java almost always have to specify their "package...". Almost because there are some exceptions.
This reserved word is used for several important things, such as:
With package you identify in which zone of the project your class is located, in general, each java project has src/main/java/mypackage
src, main, and java are directories, not packages (you can look up the difference between these). So the classes here will not have a package, you can execute a main method but this class will be invisible inside your project
If you are at the "mypackage" level, from this path the class is already visible inside your project and the class will carry the "package mypackage";
By having your class with "package mypackage;" you can import this class to another class, and use the methods of the first class in the second class
package mypackage;
public class ClassOne {
public static String goodMorning(){
System.out.println("good morning");
}
}
And this class is in another file
package mypackage;
import mypackage.ClassOne;
public class ClassTwo{
public static void main(String args...){
ClassOne.goodMorning();
}
}
If you know PHP it works similar to "require_once" (although they are similar import and require_once do not work the same)
I mentioned above about "visibility" and it is that packages are also used to know the scope of an access modifier, in java there are 4 of these: public, private, protected and default (by default it is when you do not put an access modifier )
//public access modifier
public class One{
public String attribute;
public void method(){
}
}
//private access modifier
private class Two{
private String attribute;
private void method(){
}
}
//protected access modifier
protected class Three{
protected String attribute;
protected void method(){
}
}
//default access modifier
class Four{
String attribute;
void method(){
}
}
Find out what each one is for.
And another thing it is useful for, is organizing classes by packages, you can organize a collection of classes in a better way, this is important for large projects.
There are still more things but as you say that you are learning I do not want to overload you with information, go easy, greetings.
I'm new to Java so not really sure if it's an error on my part. My project has two packages within. I'm trying to use an object belonging to a class of package lovo in an object of a class of package j2. The constructor of object belonging to package lovo is now being treated as a method. Why is that?
package j2;
import lovo.kulo;
public class J2
{
public static void main(String[] args)
{
kulo kla ;
kla = new kulo();
//kla.kulo();
}
}
package lovo;
public class kulo {
public void kulo(){
System.out.print("This is supposed to be a constructor");}
}
When i run there is no output, however when i remove the comment and add it as code there is an output. Since it's a constructor shouldn't it print as soon as the object is created?
It is indeed a method. To make it a constructor, remove the void return type. It'll also be less confusing if you follow Java naming conventions and begin class names (and therefore constructor names) with an uppercase letter.
This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Cannot make a static reference to the non-static method
(8 answers)
Closed 5 years ago.
For some reason when I'm trying to call methods using a main method or try changing variables declared outside the main method I get forced into having to change everything to static. This is fine in places but when it comes to needing to change values later in the code for example using a Scanner for input the main method just takes it to a whole new level trying to make me change the Scanner library etc.
This example shows what happens if I try calling a method.
This example shows what happens when I try alter the value of a variable declared outside my main method.
I have never faced an issue like this before when writing java code I've tried recreating the classes/ project files etc but nothing works. I've tried looking everywhere for a solution but I can't seem to find one probably due to the fact that I don't know what to search for. I've probably made myself look like a right idiot with my title haha! Any suggestions people?? Thanks in advance!
Maisy
It can be a bit confusing to get out of "static land" once you are in your main() method. One easy way is to have another object contain your "real" (non-static) top level code and then your main method creates that object and starts it off.
public static void main() {
MyEngine engine = new MyEngine();
// core logic inside of start()
engine.start();
}
I hope that this was clear enough for you. Good luck Maisy!
When calling methods form a main you have to instantiate the class they are in, unless it's a static function
this is because that a class is a sort of template and there is nothing saved about it before it get instantiated
public class TestClass{
public static void main(String[] args){
TestClass testClass = new TestClass();
testClass.method();
}
public method method(){}
}
in the example above i instantiated a TestClass and then called on the testClass instance
there is some functions and variables on classes you might want static, because a static on a class is shared between ALL instances, and can be called on the class, say you want to know how many instances were created then something like this can be done.
public class TestClass{
public static void main(String[] args){
TestClass testClass = new TestClass();
testClass.method();
System.out.print(TestClass.instances +""); // note that i call on
//the class and not on an instance for this static variable, and that the + ""
//is to cast the int to a string
}
public static int instances = 0; // static shared variable
public TestClass(){instances++;} // constructor
public method method(){}
}
You need to do some Object Oriented Programming tutorial and to learn some basic.
As answer for your problem to call without using static you have to create an instance of the main Class
let suppose the following class Foo
public class Foo{
private int myVarInteger;
public int getMyVarInteger(){ return this.myVarInteger;}
public void setMyVarInteger(int value){this.myVarInteger = value;}
public static void main(String[] args){
Foo myClassInstanceObject = new Foo();
// now we can access the methods
myClassInstanceObject.setMyVarInteger(5);
System.out.println("value ="+myClassInstance.getMyVarInteger());
}
}
This question already has answers here:
Why are filenames in Java the same as the public class name? [closed]
(7 answers)
Closed 8 years ago.
in java, filename should be same as that of main class. It is the way of telling compiler that this is the entry point for you. but why this thing works:
class xyz{
public static void main(String[] args){
System.out.println("a");
}
}
even when saved with different filename.
And why this thing does not when saved with diffrent filename:
public class xyz{
public static void main(String[] args){
System.out.println("a");
}
}
public classes have to be in a file with the correct filename. Non-public classes can be in any file you want. Even multiple classes in the same file if it is convenient.
Note that:
class xyz
Is not a public class so it cannot be acessed from outside of the file. Therefor it does not need to have the same name. But in this case:
public class xyz
You do have a public classe, that it gonna be acessed from outside of the file, so it does need to have the same name.
Conclusion: public classes need to have the file name exatly the same as the class.
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.