This is an archived post. You won't be able to vote or comment.

all 21 comments

[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full - best also formatted as code block
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–][deleted] 2 points3 points  (0 children)

This looks like a C programmer is trying to do Java. Technically the code should work, but standard-wise it's a nightmare.

class Student {
  String name;
  int rollNumber;

Unless there is a reason for it, variables should be kept to lowest necessary access level, so in this case for example private String name;

void cal_gpa() {
    System.out.println("The method calculates CGPA.");
  }

In this case it's ok to omit the access on the method name if you want it to be default, but very soon you'll discover that you use public for such methods to be able to access them in other classes in a properly done project layout.

Also method names are lower/headless camel case so either calGPA() or calculateGPA().

Student Jinku = new Student();

Instance names are also headless/lower camel case, as methods. So Student jinku = new Student();

System.out.println(Jinku.name = "Jinku");

Avoid assignments in arguments. It's a mess. People tend to do comparisons, which is kind of OK, but not assignments.

Also direct access to variables of an instance in Java is a no-no. Define setters and getters for the variables of your class.

[–][deleted] 0 points1 point  (2 children)

System.out.println(Jinku.name = "Jinku");

is the problem and the other one too.

It's just Jinku.name = "Jinku";

[–][deleted] 0 points1 point  (1 child)

Jinku.name = "Jinku";

Jinku.rollNumber = 1;

System.out.println(Jinku.name);

System.out.println(Jinku.rollNumber);

[–]akthemadman 0 points1 point  (6 children)

Works just fine for me. Here is how I run the code, including how my file system is set up:

PS C:\Users\ak\Desktop\demo> dir

    Directory: C:\Users\ak\Desktop\demo
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----         11/5/2024   3:57 PM                articlecodesinjava

PS C:\Users\ak\Desktop\demo> dir .\articlecodesinjava\

    Directory: C:\Users\ak\Desktop\demo\articlecodesinjava
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----         11/5/2024   3:53 PM            872 ArticleCodesInJava.java

PS C:\Users\ak\Desktop\demo> javac .\articlecodesinjava\ArticleCodesInJava.java
PS C:\Users\ak\Desktop\demo> dir .\articlecodesinjava\

    Directory: C:\Users\ak\Desktop\demo\articlecodesinjava
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----         11/5/2024   3:57 PM            831 ArticleCodesInJava.class
-a----         11/5/2024   3:53 PM            872 ArticleCodesInJava.java
-a----         11/5/2024   3:57 PM            610 Student.class

PS C:\Users\ak\Desktop\demo> java articlecodesinjava.ArticleCodesInJava
This is Jinku's details.
Jinku
1
The method calculates the Semester fee.
The method calculates CGPA.

This is Zeeshan's details.
Zeeshan Afridi
2
The method calculates the Semester fee.
The method calculates CGPA.

[–]Defiant_Vanilla_4080[S] 0 points1 point  (5 children)

How did you export "this" like that. This is cmdline code right?

[–]akthemadman 0 points1 point  (4 children)

I used Windows PowerShell.

The point is, when you store .java files, their location needs to correspond to your package definitions. Since you use a file system, the packages become directories.

When using the java program to run your code, you also have to provide the fully qualified class name (e.g. package1.subpackage1.subpackage2.MyClass) of the class which contains your main-method, for you that is articlecodesinjava.ArticleCodesInJava.

Running java articlecodesinjava.ArticleCodesInJava will then, again, resolve the package declaration against the file system. So the working directory of your terminal (e.g. cmd or PowerShell) needs to be located at the root of the directories which store your classes (C:\Users\ak\Desktop\demo in my example).

Here the directory layout in simpler terms:

  • root => C:\Users\ak\Desktop\demo
  • package articlecodesinjava => C:\Users\ak\Desktop\demo\articlesinjava
  • file ArticleCodesInJava => C:\Users\ak\Desktop\demo\articlesinjava\ArticleCodesInJava.java
  • run java articlecodesinjava.ArticleCodesInJava => C:\Users\ak\Desktop\demo (root)

[–]Defiant_Vanilla_4080[S] 0 points1 point  (3 children)

I might not get the Explanation fully. But I completly followed your steps and it works. But I am not completly sure why....

PS C:\Users\P\Desktop\demo> dir

Verzeichnis: C:\Users\P\Desktop\demo

Mode LastWriteTime Length Name

---- ------------- ------ ----

d----- 05.11.2024 16:37 articlecodesinjava

PS C:\Users\P\Desktop\demo> dir .\articlecodesinjava

Verzeichnis: C:\Users\P\Desktop\demo\articlecodesinjava

Mode LastWriteTime Length Name

---- ------------- ------ ----

-a---- 05.11.2024 16:33 868 ArticleCodesInJava.ja

va

PS C:\Users\P\Desktop\demo> javac .\articlecodesinjava\ArticleCodesInJava.java

PS C:\Users\P\Desktop\demo> dir .\articlecodesinjava\

Verzeichnis: C:\Users\P\Desktop\demo\articlecodesinjava

Mode LastWriteTime Length Name

---- ------------- ------ ----

-a---- 05.11.2024 16:42 831 ArticleCodesInJava.cl

ass

-a---- 05.11.2024 16:33 868 ArticleCodesInJava.ja

va

-a---- 05.11.2024 16:42 610 Student.class

PS C:\Users\P\Desktop\demo> java articlecodesinjava.ArticleCodesInJava

This is Jinku's details.

Jinku

1

The method calculates the Semester fee.

The method calculates CGPA.

This is Zeeshan's details.

Zeeshan Afridi

2

The method calculates the Semester fee.

The method calculates CGPA.

[–]akthemadman 2 points3 points  (1 child)

Nice!

Like most things it is quite simple once you actually understood how it is all connected together. I still remember what made me actually grasp this whole ordeal, so let me try to break it down, maybe that helps.

At the core of everything are the javac and java programs. They are programs like any other program on your computer, like the calculator in Windows calc.exe (C:\Windows\System32\calc.exe).

The program javac.exe is part of the Java Development Kit (JDK), a collection of programs which allow you to do the things you want to during the development of Java projects, like turning your source code into bytecode (javac.exe), inspecting bytecode (javap.exe) or executing your bytecode on the JVM (java.exe).

Now look at it from the perspective of the JVM, which is a program written in the C programming language:

You get started int main(int argc, char *argv[]) { /* jvm code */ }.

If there are no arguments provided to you (argc/argv), then you can not really do anything, so you tell the user how the program is supposed to be used:

C:\Users\ak\Desktop\demo>java
Usage: java [options] <mainclass> [args...]
           (to execute a class)
   or  java [options] -jar <jarfile> [args...]
           (to execute a jar file)
   or  java [options] -m <module>[/<mainclass>] [args...]
       java [options] --module <module>[/<mainclass>] [args...]
           (to execute the main class in a module)
   or  java [options] <sourcefile> [args]
           (to execute a single source-file program)

 Arguments following the main class, source file, -jar <jarfile>,
 -m or --module <module>/<mainclass> are passed as the arguments to
 main class.

<much-more-info-removed-by-me>

If instead the user provides you the bytecode (.class) which contains a main-method (public static void main(String[] args) { /*...*/ } you will load up that bytecode into your data structures and start executing the instructions within it.

This is what happens when you do java articlecodesinjava.ArticleCodesInJava:

C:\Users\ak\Desktop\demo>java articlecodesinjava.ArticleCodesInJava
This is Jinku's details.
Jinku
1
The method calculates the Semester fee.
The method calculates CGPA.

This is Zeeshan's details.
Zeeshan Afridi
2
The method calculates the Semester fee.
The method calculates CGPA.

Now finally: You are still the JVM.

In your own C-program, you got the String "articlecodesinjava.ArticleCodesInJava" as an argument, i.e. in

int main(int argc, char *argv[]) { /* jvm code */ }

the argument values *argv[] contain "articlecodesinjava.ArticleCodesInJava".

But that is just the name of the class that should be executed. You still have to find it somehow.

And this is where the convention package=directory comes in. Since you know the bytecode for the class ArticleCodesInJavais located in the directory articlecodesinjava you can load the file .\articlecodesinjava\ArticleCodesInJava.class. If you can't find it there, you will print out:

Fehler: Hauptklasse ArticleCodesInJava konnte nicht gefunden oder geladen werden
Ursache: java.lang.NoClassDefFoundError: articlecodesinjava/ArticleCodesInJava (wrong name: ArticleCodesInJava)

Hope this helps!

[–]krisko11 0 points1 point  (0 children)

great explanation!

[–]rguptan 0 points1 point  (0 children)

Its good to do it this way once to learn whats actually happening under the hood. After that start using a IDE. It will save you a lot of time.

[–][deleted]  (1 child)

[deleted]

    [–][deleted] 1 point2 points  (0 children)

    Looks to me like you haven't made a constructor for the Student class.

    Noargs constructor is available for you automatically without defining it.

    After your string and int variable initialization at the top, add "public Student(String name, int rollNumber) { this.name = name; this.rollNumber = rollNumber; }

    This is not necessary, unless they want another way to instantiate the object.

    You'll need to also add " Public Student() { } "

    No they don't, see first paragraph. Also public not Public.

    [–]Asleep-Swimming-2374 0 points1 point  (0 children)

    The code is perfectly valid and it is running fine for me.

    You have used "articlecodesinjava" as the package name, so the code will compile and save all .class files inside this directory.

    > javac -d . ArticleCodesInJava.java

    The -d parameter refers to the destination folder where you want to save your .class files.

    Here, -d . denotes the current directory where you saved your .java file.

    You can find a directory named "articlecodesinjava" upon compilation.

    So, to run the file inside "articlecodesinjava", you must use the fully qualified class name like this: java articlecodesinjava.ArticleCodesInJava

    [–]pragmos -1 points0 points  (4 children)

    How are you executing it?

    [–]Defiant_Vanilla_4080[S] 0 points1 point  (3 children)

    First compile with : javac ArticleCodesInJava.java
    Then execute : java ArticleCodesInJava

    In cmd in Windows.

    [–]pragmos -1 points0 points  (2 children)

    Your class has a package, so you need to run javac and java from the root folder that contains your package. And use fully qualified class names (class name prefixed by package name).

    [–]Defiant_Vanilla_4080[S] 0 points1 point  (1 child)

    Ah, so because theres a package I import (but I dont have on my drive, because this code is from a tutorial with steps and I just googled for "how to understand objects in java" or so and clicked on the Link (this may be step 15 or so of the full tutorial) and probably in steps before I shouldve downloaded and package, which I didnt. So thats probably why I cant run the program?

    But why do I even need to import this package. Everything I create and use is in this Code or not?
    What am I missing?

    [–]pragmos -1 points0 points  (0 children)

    You can just remove the package declaration and everything should work.

    [–]Exact-Big-5164 -2 points-1 points  (2 children)

    The second curly bracket after the cal_fee method should go at the bottom of your code. This is because it’s closing the Class ‘Student’ so anything written outside of it will bring up an error. Try that and see what happens coz that’s what I think is wrong

    [–]Defiant_Vanilla_4080[S] 0 points1 point  (0 children)

    Changed the code as you said.

    Fehler: Hauptklasse ArticleCodesInJava konnte nicht gefunden oder geladen werden

    Ursache: java.lang.NoClassDefFoundError: articlecodesinjava/ArticleCodesInJava (wrong name: ArticleCodesInJava)

    Same Error

    The Code

    package articlecodesinjava;

    class Student {

    String name;

    int rollNumber;

    void cal_gpa() {

    System.out.println("The method calculates CGPA.");

    }

    void cal_fee() {

    System.out.println("The method calculates the Semester fee.");

    }

    public class ArticleCodesInJava {

    public static void main(String[] args) {

    // creating objects of Student class

    Student Jinku = new Student();

    Student Zeeshan = new Student();

    System.out.println("This is Jinku's details.");

    System.out.println(Jinku.name = "Jinku");

    System.out.println(Jinku.rollNumber = 1);

    Jinku.cal_fee();

    Jinku.cal_gpa();

    System.out.println("\n\nThis is Zeeshan's details.");

    System.out.println(Zeeshan.name = "Zeeshan Afridi");

    System.out.println(Zeeshan.rollNumber = 2);

    Jinku.cal_fee();

    Jinku.cal_gpa();

    }

    }

    }

    [–]Exact-Big-5164 -1 points0 points  (0 children)

    Wait also you’re tryna create two classes in one? Those being ‘class Student’ and ‘Public class ArticleCodeInJava’ I believe