I am trying to write a program, but I’m getting this compiler error:
Main.java:1: error: class WeatherArray is public, should be declared in a file named WeatherArray.java
public class WeatherArray {
^
1 error
I have checked my file names, and my public class is the same as my .java file.
How can I fix this?
Here is my code:
public class WeatherArray {
public static void main(String[] args) {
// ...
}
}
asked Dec 10, 2012 at 23:22
6
Name of public class must match the name of .java file in which it is placed (like public class Foo{}
must be placed in Foo.java
file). So either:
- rename your file from
Main.java
toWeatherArray.java
- rename the class from
public class WeatherArray {
topublic class Main {
Pshemo
122k25 gold badges184 silver badges268 bronze badges
answered Dec 10, 2012 at 23:25
jlordojlordo
37.4k6 gold badges58 silver badges83 bronze badges
4
The name of the public class within a file has to be the same as the name of that file.
So if your file declares class WeatherArray, it needs to be named WeatherArray.java
answered Dec 10, 2012 at 23:25
BostonJohnBostonJohn
2,6012 gold badges26 silver badges48 bronze badges
This happens when you have 1 name for the Java class on hard disk and another name of Java class in the code!!
For example, I renamed my MainActivity
class to MainnActivity
only (!) in the code. I got this error immediately.
There is also a visual indicator in the Project tab of Android Studio — a class inside a class, like you have nested classed, but with an error indicator.
The solution is to simply rename class name in the Project tab (SHIFT
+ F6
) to match the name in the Java code.
answered Jul 15, 2015 at 13:05
sandalonesandalone
41k63 gold badges221 silver badges336 bronze badges
I had the same problem but solved it when I realized that I didn’t compile it with the correct casing. You may have been doing
javac Weatherarray.java
when it should have been
javac WeatherArray.java
answered Aug 27, 2019 at 20:57
You named your file as Main.java. name your file as WeatherArray.java and compile.
answered Dec 10, 2012 at 23:26
PermGenErrorPermGenError
45.8k8 gold badges86 silver badges106 bronze badges
your file is named Main.java where it should be
WeatherArray.java
answered Dec 10, 2012 at 23:27
AlexWienAlexWien
28.4k6 gold badges52 silver badges80 bronze badges
Yes! When you face these type of problem then try to following points
- Check Your .java file name and class name.
- If Class name and public class name are not the same then RENAME class name.
answered Sep 2, 2022 at 20:51
I my case, I was using syncthing. It created a duplicate that I was not aware of and my compilation was failing.
answered Jan 30, 2018 at 22:04
abc123abc123
5275 silver badges16 bronze badges
To avoid this error you should follow the following steps:
1) You should make a new java class
2) Name that class
3) And a new java class is made
André Kool
4,86012 gold badges34 silver badges44 bronze badges
answered Mar 12, 2018 at 15:45
I encountered the same error once. It was really funny. I had created a backup of the .java file with different filename but the same class name. And kept on trying to build it till I checked all the files in my folder.
answered May 3, 2018 at 16:18
Yash P ShahYash P Shah
78111 silver badges15 bronze badges
In my case (using IntelliJ) I copy and pasted and renamed the workspace, and I am still using the old path to compile the new project.
In this case this particular error will happen too, if you have the same error you can check if you have done the similar things.
answered Jul 16, 2018 at 4:42
Ng Sek LongNg Sek Long
4,0852 gold badges30 silver badges38 bronze badges
The terminal is not case sensitive when writing «Javac [x].java», so make sure what you write in the terminal matches the filename and class name.
My class name and file name were both «MainClass», but I was compiling using «Mainclass». Notice I forgot to make the «c» capital.
answered Jan 25, 2019 at 15:21
DylanDylan
3551 gold badge2 silver badges12 bronze badges
From Ubuntu command line:
//WeatherArray.java
public class WeatherArray {
public static void main(String[] args) {
System.out.println("....Hello World");
}}
ls
WeatherArray.java
javac WeatherArray.java
ls
WeatherArray.java WeatherArray.class
java WeatherArray
….Hello World
Of course if you name your java file with different name than WeatherArray, you need to take out public and it would be:
// Sunny.java
class WeatherArray {
public static void main(String[] args) {
System.out.println("....Hello World"); }}
// javac Sunny.java; java WeatherArray
answered Jan 9, 2020 at 16:37
NotTooTechyNotTooTechy
4085 silver badges9 bronze badges
If you make WeatherArray class from public to default.
public class WeatherArray =====> class WeatherArray
then you do not get any error and
you can easily compile your code by just writing
==> javac any_name_you_assign_to_file.java
Now a WeatherArray.class will generate.
To run your code you have to use class name
==> java WeatherArray
answered Jun 30, 2021 at 19:47
Compile WeatherArray.java instead of Main.java
This error comes if you have not saved your source code with the same name of your public class name.
answered Jul 13, 2021 at 13:01
iamfnizamiiamfnizami
1531 silver badge8 bronze badges
If your class name is the same as the filename then check that it does not contain any zero width character
I accidentally copied a class name with invisible whitespace which caused this exception
Eclipse was able to build the file and Gradle was not
This can be very confusing
answered Sep 11, 2021 at 20:50
Check to make sure you don’t have two identical — or
very nearly identical — files in your res/layout folder.
answered Mar 17 at 12:17
BinCodinLongBinCodinLong
7111 gold badge7 silver badges20 bronze badges
Just experience this issue today. Thanks to viewBinding.
Problem was the autoGenerated binding. I had two xml files
- one_two.xml
- onetwo.xml
Solution # 1 : Just use
tools:viewBindingIgnore="true"
in any one file.
Solution # 2 :
Rename the xml file
answered Apr 10 at 8:03
The answer is quite simple. It lies in your admin rights. before compiling your java code you need to open the command prompt with run as administrator. then compile your code. no need to change anything in your code. the name of the class need to be the same as the name of the java file.. that’s it!!
answered Jun 23, 2015 at 20:28
1
error example:
public class MaainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
}
}
correct example:just make sure that you written correct name of activity that is»main activity»
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
}
}
jHilscher
1,8002 gold badges24 silver badges29 bronze badges
answered Apr 12, 2017 at 9:06
1
when you named your file WeatherArray.java,maybe you have another file on hard disk ,so you can rename WeatherArray.java as ReWeatherArray.java, then rename ReWeatherArray.java as WeatherArray.java. it will be ok.
answered Jul 27, 2016 at 9:46
2
- Cause of the
class X is public, should be declared in a file named X.java
Error - Fix the
class X is public, should be declared in a file named X.java
Error
Today, we will go through various stages, starting from demonstrating a compile time error stating class X is public should be declared in a file named X.java
. Then, we will see the reason causing this error, which will lead to its solution via code example.
Cause of the class X is public, should be declared in a file named X.java
Error
Example Code Containing the Specified Error (Main.java
file):
public class Test{
public static void main(String[] param){
HiWorld();
System.exit(0);
}
public static void HiWorld(){
System.out.println("Hi World");
}
}
We have this code in a file named Main.java
while the class name is Test
. Now, compile the code using the javac
command as follows.
As soon as we press the Enter key, it gives the following error.
Main.java:1: error: class Test is public, should be declared in a file named Test.java
public class Test{
^
1 error
What does this error mean? Why is it occurring? It means that we must have the public class named Test
in the Test.java
file, but in our case, we have it in the Main.java
file.
That’s the only reason for this error. How to fix this? We can get rid of it in the following two ways.
Fix the class X is public, should be declared in a file named X.java
Error
Rename the File
To fix this error, rename the file as Test.java
, which contains the Test
class as given below.
Example Code (Test.java
file):
public class Test{
public static void main(String[] param){
HiWorld();
System.exit(0);
}
public static void HiWorld(){
System.out.println("Hi World");
}
}
Compile the Code:
Run the Code:
OUTPUT:
Rename the Class
We can keep the file name as Main.java
for the second solution but rename the class as Main
. See the code snippet below.
Example Code (Main.java
file):
public class Main{
public static void main(String[] param){
HiWorld();
System.exit(0);
}
public static void HiWorld(){
System.out.println("Hi World");
}
}
Compile the Code:
Run the Code:
OUTPUT:
Скопировал код из примера по ссылке, при выполнении выдает ошибку.
https://javarush.com/groups/posts/1927-konstruktorih-bazovihkh-klassov—
СКОПИРОВАННЫЙ КОД
public class Animal {
public Animal() {
System.out.println(«Отработал конструктор Animal»);
}
}
public class Cat extends Animal {
public Cat() {
System.out.println(«Отработал конструктор Cat!»);
}
public static void main(String[] args) {
Cat cat = new Cat();
}
}
ОШИБКА ПРИ ВЫПОЛНЕНИИ
D:JavaWorkProjectsrccomcompanyAnimal.java:11:8
java: class Cat is public, should be declared in a file named Cat.java
ЧТО Не так ???
Спасибо. За помощь.
Я пытаюсь написать программу, но я получаю эту ошибку компилятора:
Main.java:1: error: class WeatherArray is public, should be declared in a file named WeatherArray.java
public class WeatherArray {
^
1 error
Я проверил мои имена файлов, и мой открытый класс такой же, как мой.java файл.
Как я могу это исправить?
Вот мой код:
public class WeatherArray {
public static void main(String[] args) {
// ...
}
}
Ответ 1
Имя открытого класса должно совпадать с именем файла .java, в котором он находится (например, public class Foo{}
должен быть помещен в файл Foo.java
). Так что либо:
- переименуйте ваш файл с
Main.java
наWeatherArray.java
- переименуйте класс из
public class WeatherArray {
вpublic class Main {
Ответ 2
Имя открытого класса в файле должно быть таким же, как имя этого файла.
Поэтому, если ваш файл объявляет класс WeatherArray, его нужно называть WeatherArray.java
Ответ 3
Это происходит, когда у вас есть 1 имя для класса Java на жестком диске и другое имя класса Java в коде !!
Например, я переименовал свой класс MainActivity
в MainnActivity
(!) Только в коде. Я получил эту ошибку немедленно.
На вкладке «Проект» в Android Studio есть визуальный индикатор — класс внутри класса, например, вы вложенные классы, но с индикатором ошибки.
Решение состоит в том, чтобы просто переименовать имя класса на вкладке «Проект» (SHIFT
+ F6
), чтобы совместить имя в коде Java.
Ответ 4
Вы назвали свой файл Main.java. назовите свой файл как WeatherArray.java и скомпилируйте.
Ответ 5
ваш файл называется Main.java, где он должен быть
WeatherArray.java
Ответ 6
У меня была та же проблема, но я решил ее, когда понял, что не скомпилировал ее с правильным корпусом. Возможно, вы занимались
javac Weatherarray.java
когда это должно было быть
javac WeatherArray.java
Ответ 7
Я в моем случае, я использовал syncthing. Он создал дубликат, о котором я не знал, и моя компиляция не срабатывала.
Ответ 8
Чтобы избежать этой ошибки, выполните следующие действия:
1) You should make a new java class
2) Name that class
3) And a new java class is made
Ответ 9
Однажды я столкнулся с такой же ошибкой. Это было действительно смешно. Я создал резервную копию файла.java с другим именем файла, но с тем же именем класса. И продолжал пытаться построить его, пока не проверил все файлы в моей папке.
Ответ 10
В моем случае (используя IntelliJ) я копирую и вставляю и переименовываю рабочее пространство, и я все еще использую старый путь для компиляции нового проекта.
В этом случае эта конкретная ошибка также произойдет, если у вас есть такая же ошибка, вы можете проверить, сделали ли вы подобные вещи.
Ответ 11
Терминал не учитывает регистр при написании «Javac [x].java», поэтому убедитесь, что то, что вы пишете в терминале, соответствует имени файла и имени класса.
Мои имя класса и имя файла были «MainClass», но я компилировал с использованием «Mainclass». Заметьте, я забыл сделать заглавную букву «с».
Ответ 12
Ответ довольно прост! Он лежит в ваших правах администратора. перед компиляцией java-кода вам нужно открыть командную строку, запустив ее как администратор. затем скомпилируйте свой код. не нужно ничего менять в коде. имя класса должно быть таким же, как имя java файла.. это!
Ответ 13
когда вы назвали ваш файл WeatherArray.java, может быть, у вас есть еще один файл на жестком диске, так что вы можете переименовать WeatherArray.java в ReWeatherArray.java, а затем переименовать ReWeatherArray.java в WeatherArray.java. все будет хорошо.
Ответ 14
пример ошибки:
public class MaainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
}
}
правильный пример: просто убедитесь, что вы написали правильное название деятельности, которое является «основным видом деятельности»,
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
}
}
PROBLEM:
- When the class name and the filename of a given Java program doesn’t match then we will get this error.
- Considering an example where the file is named as wiki.java
[pastacode lang=”java” manual=”public%20class%20techy%20%0A%7B%20%20%20%20%20%0A%20%20%20%20%20%20%20%20public%20static%20void%20main(String%5B%5D%20args)%20%0A%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20System.out.println(%22Hello%2C%20wikitechy!%22)%3B%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%7D%09%0A” message=”java code” highlight=”” provider=”manual”/]
1 error found:
File: wiki.java [line: 1]
Error: class techy is public, should be declared in a file named wiki.java
SOLUTION 1:
- Since wiki does not match with techy, the code will not compile properly. To fix this error kind of error, either we need to rename the file or change the class name as “wiki.java”
- As the error message suggests, if we declare a class as public, it needs its wiki.java file. If we don’t want to do that, we don’t define it as public.
Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I’m a frequent speaker at tech conferences and events.
Related Tags
- error: class funfactsactivity is public,
- android studio class is public should be declared in a file named,
- arrays — Java class is public should be declared in a file named,
- Class is public,
- class names are only accepted if annotation,
- error: cannot find symbol,
- Error: class is public,
- error: could not find or load main class helloworld,
- error: could not find or load main class main,
- Error:(9,
- how to declare file in java,
- j2me error: class myClass is public should be declared in a file named,
- Java Error: class is public,
- Java Error: Should be declared in a file named,
- javascript — Class is public,
- main method not found in class,
- modifier private not allowed here,
- should be declared,
- should be declared in a file named .java,
- should be declared in a file named .java public,
- should be declared in a file?