r/javahelp • • Jan 26 '24

Can you please explain me why java needs package declaration?

I mean what's the point? Whenever I import something from a java extension file I'll declare a path in my code? No?

Like in JavaScript it's just: import someThing from './utilis/some_thing.js';

So I don't need to declare in that some_thing.js file that it resides in utilis directory.

So why java needs it? It kinda bugs me and I want to understand.

Thanks beforehand!

0 Upvotes

28 comments sorted by

•

u/AutoModerator Jan 26 '24

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

  • 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.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

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: 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.

8

u/AmateurHero new Intermediate("this.user") Jan 26 '24

Packages are meant to give namespaces to code and helps bundles modules of related code. Two common classes that have name collisions are java.util.Date and java.sql.Date.

In addition, there's such thing as package private access modifiers.

-8

u/[deleted] Jan 26 '24

Yeah, I know that. But having same name isn't really a thing, yeah? I mean, when you import stuff it will have different name anyway if it's in other directory.

Yeah, I read about public and not stuff(actually just public for now).

I was more about package dir.dir.dir stuff in the file.java itself.

3

u/AmateurHero new Intermediate("this.user") Jan 26 '24

They do have the same name. You can look at the files for both Date classes I mentioned. They'll both start with public class Date. You instantiate both with Date d = new Date(); Since both are sitting on the classpath available for your application, how do you tell your program which Date class should be used? The import statement with the package!

You might still be wondering, "But why does it have to have the package format? Those files live in their own directory, so why can't they be lib/src/java/sql/Date.java and java/util/Data.java?" I actually don't have the answer to that. In either case, they achieve the same thing.

1

u/GuyWithLag Jan 26 '24

if it's in other directory.

Nope. You can have single directory with a bunch of .java files from different packages, and the compiler will do the right thing.

2

u/arghvark Jan 26 '24

Is this some new feature in Java85 or something? Any time my package statement has not matched my directory structure, all the Java compilers I've ever used threw an error and refused to compile it.

2

u/[deleted] Jan 26 '24

[removed] — view removed comment

-3

u/[deleted] Jan 26 '24

I'm sorry, what resources?

Hmm. Can you please explain how "case sensitivity, maximum length of filenames, maximum length of paths etc." have anything to do with packages? I mean, isn't there any name conventions? And even if that, won't compiler or what throw an error or correct filename? Just wonder.

9

u/arghvark Jan 26 '24

I cannot tell if you're actually asking for information. I'm serious.

There are many different ways to make code outside a module known to that module, as implemented in Java, JavaScript, C, Ada, PL/I, Fortran, etc., etc., etc. They are DIFFERENT. They are NOT WHAT YOU'RE USED TO.

When you use phrases like "In X it's just...", along with a vague question, it looks a lot like the many programmers who want to know why THIS language doesn't do it the way they're used to in some other language. And when they ask this question, they aren't looking for information; some of them are being unintentionally rhetorical, and some just want to argue about how the way they're used to is better. Mostly they do this without the information that they're not really asking for.

So:

What do you mean by package declaration?

Are you asking whether you need to declare a path in your code, or why you don't declare a path in your code? Or neither of those?

Do you mean a filename path? Or a Java package path?

Even "Java extension file" is ambiguous here. Do you mean one or more classes that are part of a Java library?

Code examples would be useful.

Since I don't know and am not willing to guess what you mean, I cannot answer whatever question you actually had in mind.

I do hope you understand already that JavaScript is a scripting language, and that, regardless of its unfortunate name, has nothing to do with the Java language. Their purpose, environments, goals, and especially their design history are worlds apart. I wish the then-owners of Java had taken them to court over the name confusion at the outset, but it's too late now.

-3

u/[deleted] Jan 26 '24 edited Jan 26 '24

I hope you do understand that after learning JS no way in existence I can mistake those two programming languages? Like how can it be possible? I mean, yeah. Some core things are pretty similar but I bet it's same for all programming languages.

There is no meaningful code example, I just started to learn Java yesterday and got to the part where some utilis function or in Java it's called a method(right?) was imported to main file and used there.

First thing first. I mean what I mean. I see that it's needed to declare package in some utilis.java. I don't understand why. I ask. I'm pretty sure it isn't required just for lulz and it actually does something. So I wonder what exactly.

> What do you mean by package declaration?

package dir.dir.dir;

> Even "Java extension file" is ambiguous here. Do you mean one or more classes that are part of a Java library?

someFile.java

p.s. Sorry if I sounded aggressive a bit cause your response sounded a but aggressive to me so I replied accordingly. Anyway, I'm just trying to sort things out. No ill intended.

4

u/arghvark Jan 26 '24

Somone trying to help you starts out with NO context about your level of experience. Yes, there are people who think the languages are related, and asking questions about import and package statements are about at their level. It wasn't an unreasonable thing to wonder.

I just started to learn Java yesterday

This would have been helpful in the original post.

I mean what I mean

People trying to help you have to understand what you mean. We don't know you. We don't know how literal you make your statements, and since you're asking for basic help about the language, it is difficult to make correct assumptions about what you already know.

The overall philosophies of programming in these two languages are worlds apart. JavaScript is a scripting language, meant for (or at least used in) environments where a quickly-written bit of procedural code can get something done that would be difficult or impossible using the bigger technologies in that environment. It also does get used as a general-purpose programming language; I personally think it is ill-suited to that, but it has plenty of adherents.

As a scripting language, it is also used in places where things get implied rather than stated. Where outside libraries come from, the types of variables, scope (which I've never understood in JS), etc., are all 'loose' compared to Java.

Java is a strongly-typed language; this is mostly reflected in variable declaration, where you cannot have a variable without declaring its type. But the philosophy is also seen in the ways it insists you explicitly declare classes, methods, etc. Someone coming from a scripting environment might well say "Why do I have to declare that? The compiler could figure it out!" The reason is that, when the language system leaves things for the compiler to "figure out" and the programmer gets it wrong, it causes bugs that are difficult to find. By explicitly declaring variables with type, for instance, then when the programmer misuses the variable, the COMPILER can tell him "No, you can't do that here", rather than 'figuring out what s/he means' and causing a bug.

So

package level1.level2.ClassA;

indicates to the compiler the intended position of ClassA in the naming hierarchy. The compiler can check that a source file for the class is in the correct directory, therefore ensuring that the programmer has not mistakenly put it in another place. It also helps guard against having the file be accidentally moved from one place to another; if the compiler had to figure out its package, moving the file would change its package, causing a bug that would be more difficult to find.

In your original post, you have

import someThing from './utilis/some_thing.js';

Be aware that 'import' in Java is NOT importing the contents of a file into your code. In Java, 'import' says "there is a class (or there are classes) I'm going to use, here is their location in the naming hierarchy. I would rather not use their full pathname everywhere in my code, so I am declaring the full name(s) here and these are the fullname paths I want to compile and run with."

import java.awt.Color;

This causes every use of Color in that source file to use 'java.awt.Color', not any other class named Color. The class file (which is the equivalent of an object file in the general case) could be part of the Java core library, or another library jar file; it could be located in one place on the compilation machine and a different place on the runtime machine, since the import statement says nothing about where it comes from.

You could leave out the import statement and use "java.awt.Color" in each place where you would otherwise use just "Color". That would be exactly equivalent.

You mention naming conventions in another comment. Java has a few: Class names start with an uppercase letter, and are named with CamelCase. Package names are all always lowercase. Method names are CamelCase, starting with a lowercase letter.

Class names should be nouns, naming things in the system being modeled. Method names should be actions to be taken on the classes.

1

u/[deleted] Jan 26 '24

Oh, shit! Thank you!

When I wrote that languages are similar was more about similar things like how operators work, if statements, switch and so on. So far it looked pretty similar to me. Arrays are a bit different but ain't that much. Yeah, ofc general purpose of both languages is different. I mean, JS is for browser(although with React Native mobile app is available, there are even some AI stuff). Not like I can write some GUI for Windows/Linux with it. JS can do backend stuff as well, ofc.

I don't really know Java much yet, rn. Will learn soon.

About name conventions was more about a comment where the author propsed that package naming can be very bad. So I asked, wouldn't name convention deal with it?

And somehow I expected that majority here would be newbies like me that's why I thought that my experience with Java was given. And my question was pretty newbie. Yeah, I know JS pretty much. Have some OK projects using newest stack. But it's JS, right? Not Java. So I honestly thought that my question was a dead give away about my level of Java knowledge.

Anyway, thank you again! You were of big help!

3

u/arghvark Jan 26 '24

I am glad my comments helped. It's what I aim for here, along with other helpers.

I've done a fair amount of posting, hoping to help, and I've learned that trying to deduce someone's level of expertise and/or guess too much about what they mean is just not a good idea. I can spend significant time that way answering what I thought was the question, only to find out that something else entirely was meant. In addition, I then get castigated for assuming the wrong thing, and people start assuming I don't know what I'm talking about because I answered the wrong thing; so not only did I waste my time, I get belittled for trying to help.

So if/when you post further questions: start from the assumption that you have to explain your context. Provide actual code (with ALL lines indented for reddit code formatting), even if it's just a line or two (like a package statement 8>). Those of us who know more about the language are capable of imagining lots of things you might mean that you might not even be aware of yet.

2

u/blobjim Jan 26 '24 edited Jan 26 '24

Not having a package declaration puts the file in the empty package. So making it optional and taking the package from the file path would be a breaking change (at least without some kind of compiler flag to indicate it should be in a specific package). I think it's just a legacy thing they can't change.

It would also probably require a bunch of changes from existing compilation tools as used by Maven and other tools. It could potentially result in weird errors in existing project builds, and confusion from developers.

I wouldn't be surprised if they actually did pursue this change though, since there are currently other projects to make Java more scripting-language-like and beginner friendly. For example: https://openjdk.org/jeps/458 which says:

Source files in a directory foo/bar under the root directory must declare classes in the named package foo.bar.

which is definitely redundant as you point out. Although it does use the package declaration of the main class to cleverly figure out where the root directory of the package structure is.

Java has a lot of these weird idiosyncrasies 🙂. It's always kind of funny finding them.

0

u/[deleted] Jan 26 '24

So basically it's needed for compiler, right? When it will compile whatever it has to compile and sort things into that compiler result? Am I right?

I just haven't got to that part, I have yet to start some pet project to get familiar with this language

2

u/blobjim Jan 26 '24 edited Jan 26 '24

Yeah, the package definition at the top of a standard .java file tells the compiler what package every class in that .java file is in (you can technically have multiple top-level classes in a Java file as long as the subsequent ones are private, but it's basically never done since it's way too confusing). Every java class exists inside a package (which can be the "empty package" or whatever it's called, but that isn't used in any real applications or libraries).

Which technically means you could lay out your java classes in any directory structure you want to, and if you feed the java compiler those classes together, it can compile them. However, in practice, they need to be in a directory structure that reflects their package name, with each component separated by a dot existing as nested directories.

1

u/[deleted] Jan 26 '24

Thank you!

Sounds a bit weird that compiler needs to tell him where the file is but since I have no idea how compilers work, so...

And I guess, mostly it's because there was a time then people didn't put code files in correct directories/packages??? So that rule was invented. Am I on a right track?

2

u/Skiamakhos Jan 26 '24

Kinda but the main thing with Java as with a lot of modern programming languages is code reuse - you don't want to have to reinvent what others have already done, and there's an awful lot of ready-made Java out there that's free to incorporate into your programs. To make it easy to identify what you're using we have these long package names that usually follow the convention of whatever the organisation is, reverse the web url for their main site, then tack on something to help you organise it, so, what's the project, what is it part of, which bit of the project does it pertain to, and finally you have the class name.

For example I might have my packages all within org.skiamakhos to differentiate them from anything at com.google, org.apache or whatever. Say I have a dice game project I'm working on - everything for that will be org.skiamakhos.dicegame. Let's say it follows the MVC conventions, so I'll likely have org.skiamakhos.dicegame.model for the data model, org.skiamakhos.dicegame.view for the presentation layer (maybe I'm using Vaadin to generate my views) and org.skiamakhos.dicegame.controller for the logic, the rules of the game. Aside from anything else I now know where to find any given piece of code by following this convention.

2

u/[deleted] Jan 26 '24

Big thank you! I think I'm starting to get it. Well, I have yet to start a project with Java to get what you mean but it really helped me.

In JS I usually would just have some view.js file and app.js or App.jsx in src and other components in component folder(and other React stuff in their dirs) and utility functions in utilis.

I guess, really need to start some per project to get a grasp. (Who could thougth, lol)

And big thank you again!

2

u/ggeldenhuys Jan 26 '24

As mentioned before, it adds hierarchy namespaces. But also adds visibility control. You can have a package with 10 classes (files). One can be "public", and all the others "package private". So when you import that package, you'll only be able to access the one public class. This is a very powerful concept. Java modules enhanced this concept considerably.

1

u/[deleted] Jan 27 '24

Yeah, I understand. I think. It's just without actual use I won't be able to truly grasp it. So I just have to dig further, I guess.

Thank you!

1

u/bfpires Jan 26 '24

Package ain't import. You got both

2

u/[deleted] Jan 26 '24

[removed] — view removed comment

1

u/[deleted] Jan 26 '24

I see. Thanks!

p.s. is it me or Java community is a bit toxic? I remember asking stupid(beginner questions) in javascript subs and usually wasn't that much minus bombed.

Minuses are just minuses, they mean nothing irl but funnily enough they make me sad. ROFL.

2

u/[deleted] Jan 26 '24

[removed] — view removed comment

1

u/[deleted] Jan 26 '24

Well, I did. I googled. Saw some answers, still needed to clear things out. I wasn't satisfied by what google gave me. Let alone some sounded like some rubbish because I don't understand Java yet.

It's big of you to presume I just ran here first(and finding this sub) after having a question instead of just google it.

I came exactly because I had some questions and hoped that Java community would eli5 since I'm lacking so far. I didn't expect I just hoped for it. Ofc, I would be fine if I was just ignored.

I was just a bit surprised by a reaction here. I mean, newbie comes and asks newbie questions. Why be so negative?

2

u/[deleted] Jan 26 '24

[removed] — view removed comment

1

u/[deleted] Jan 27 '24

I thought that r/java is not for beginners.

I saw Oracle documentation, it wasn't really that much detailed. Geekforgeeks was of greater help.

But answer for myself was just keep going.

But anyway, thank you!