I'm having trouble compiling a java code using packages on linux

I don't know exactly the command to compile a java file on linux that shares the same package. I tried to follow this tutorial: https://www.webucator.com/how-to/how-compile-packages-java.cfm but the following error is appearing:

Error: Could not find or load main class Classe01
Caused by: java.lang.NoClassDefFoundError: pacote1/Classe01 (wrong name:Classe01)

Follows the code below:

/* Classe01.java */
package pacote1;

public class Classe01{

   public static void main(String[] args){
      Classe02 obj1 = new Classe02("abc");
      Classe02 obj2 = new Classe02("abc");
      System.out.println(obj1==obj2);
   }
}


/* Classe02.java */
package pacote1;

public class Classe02{
  private String valor;

  public Classe02(String s){
    valor = s;
  }
  public String getValor(){
    return valor;
  } 
}
Author: Larissa Benevides Vieira, 2019-09-09

1 answers

Larissa, as you are compiling in hand, has to take into account some considerations:

1° you write the code in the .java files, but before creating the JAR executable you must compile the .java files into .class.

2° you must create a file that tells JAVA where your method public static void main(String[ ] args) is, this file is known as MANIFEST.

3° Once you've compiled and created MANIFEST you can already package everything into an executable .jar.

Com these considerations in mind, first let's compile your classes .java em .class.
To do this, through the terminal or CMD go to the same level of your folder pacote1 (do not enter package1, just be at the same level as it) and type in the terminal:

javac pacote1/*.java

This command will compile all files with extension .java that are inside the folder pacote1, you will see that 2 more files have appeared, Classe01.class and Class02.class.

Now let's create MANIFEST, still at the same level as your pacote1 folder create a MANIFEST file.txt and inside it put the contents below:

Main-Class: pacote1.Classe01
Name: pacote1/Classe01.class
Java-Bean: True

Now you just need to run the command below so that your compiled classes and manifest are packaged in a .jar file.

jar cfm seuArquivo.jar manifest.txt pacote1/*.class

And to test run the command:

java -jar seuArquivo.jar

Note: doing this compilation in hand is very laborious, since any change you make in the code will have to compile the classes and generate the .jar again, except if to use third-party libraries, you will have to inform them in MANIFEST, I recommend using an IDE because it already automates this whole process.

 2
Author: Murilo Portugal, 2019-09-11 10:31:09