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.
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.
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".
This question already has answers here:
Main method in a static inner class.?
(4 answers)
Closed 1 year ago.
How to execut main method, if it is present in static inner class?
Main method is present in static inner class and we need to execute that main method.
class A {
static class B {
public static void main(String[] args) {
System.out.println("Done");
}
}
}
Try something like this:
java A$B
Update according to comments:
In linux shell you should escape $. So the command became:
java 'A$B'
Its just like simple class. Run command java A$B
When inner class is compiled, it is prepended with outer class name
In this case you two class files. i.e . A.class and A$B.class
java command takes the classname as the argument and not the filename
So simple command java A$B will do the work
If you have anonymous classes then the classnames will be like OuterClass$1, OuterClass$1 and so on.
So if you modify your example as follows, now including anonymous and method local inner classes
import java.io.Serializable;
public class A {
static class B {
public static void main(String[] args) {
System.out.println("Done");
Serializable obj = new Serializable() {
};
Serializable obj1 = new Serializable() {
};
class MethodLocalClass {
}
}
}
}
Then the class files you will get are A.class, A$B.class, A$B$1.class, A$B$2.class for the anonymous classes and A$B$1MethodLocalClass.class.
Hope this example helps a bit :)
If your .java file have inner/nested classes, post compilation those are generated as TheClass$xxx.class files by the compiler.
See this:
Inner class definitions produce additional class files. These class
files have names combining the inner and outer class names, such as
MyClass$MyInnerClass.class.
So you should do: java A$B.
In Eclipse go to Run -> Run Configurations -> then select Java Application in the left column -> click the new configuration icon in the top left.
In my case it automatically picked up my inner class with a main method. This was just a simple example class and I wanted to test it without creating another test/client class.
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!
Ok, this might be kiddies question in java. We can't define two public classes in one file. But, in one of the examples from the book SCJP study guide, this example was mentioned:
public abstract class A{
public abstract void show(String data);
}
public class B extends A{
public void show(String data){
System.out.println("The string data is "+data);
}
public static void main(String [] args){
B b = new B();
b.show("Some sample string data");
}
}
When I copy pasted this into netbeans immediately compile error was thrown, that public class A should me mentioned in separate file. Is that example from SCJP styudy guide really wrong? Also in some of the mock test I found many questions having such pattern but in none of the options was a compiler error was mentioned. Getting worried here
yes, 2 top level public classes are not allowed in one file
Well, if one is being so picky: you can have multiple classes defined with a public modifier in the same file, that is, using the static nested(inner) class.
like this:
File -> Test.java
public class Test {
public static class SomeNestedClass {
}
}
Yes you can have two classes in the same file. You can have them by removing the public access modifier from both the class name, like shown below,
abstract class A{
public abstract void show(String data);
}
class B extends A{
public void show(String data){
System.out.println("The string data is "+data);
}
public static void main(String [] args){
B b = new B();
b.show("Some sample string data");
}
}
you can make 2 public classes in one file , inside a class that contains them .
it's also recommended to add "static" for them , if you do not need any reference to the container class .
You can put two public classes in one file, for example in the file Circle.java:
public class Test {
public static void main(String args[]) {
double cir = Circle.findCircumference(7.5);
System.out.print("Circumference of circle=" + cir);
}
}
public class Circle {
public static double findCircumference(double radius) {
return 2 * Math.PI * radius;
}
}
If you then run javac Circle.java, you will get an error:
Circle.java:1: error: class Test is public, should be declared in a file named Test.java
public class Test {
^
1 error
But if you run it with java Circle.java, then it will work.
Why? Probably because the java command, since java 11 (see here), can run also single source-file programs.
Imagine you could place two public classes in one file, then think about the work of the compiler: it has to build a .class file from your .java file that represents exactly one class (otherwise the .class ending wouldn't make any sense).
The way the JAVA Compiler works it will simply create a .class file with the name of your file and will search for the class with the name of the file in your given file – so it depends on your file name which class will be correctly compiled and which will not.
Long story short: no, you can't put two public classes in one file because the compiler wouldn't be able to handle that correctly.
(Edit: it of course is possible to define new classes INSIDE the one public class that has the same name as your file.)