What is the relationship between package and jar file in java? Do you get one jar file for each package?
A package logically organizes your classes. For example, you can declare package com.stackoverflow in each of the source files to keep the all files in the same directory.
A JAR file lets you physically organize your classes. You can take any Java files and store them in a JAR file.
A JAR file may contain multiple packages, and multiple JAR files may contain files that belong to the same package. So, a JAR file is largely a way to store multiple class files in a single physical file.
Package consist of classes..
Jar : collection of packages and classes...
A package is a way of organizing Java types into groups of related types, and is part of the Java language. It doesn't exist as a resource or artifact, rather as a namespace, which means it's part of the type name.
A JAR is not part of the Java language but a file in a ZIP format. It contains loadable forms of Java types, i.e., class files, plus other files needed to deploy an application. Its purpose is to provide a deployment mechanism for Java code and resources.
It's like the difference between a chapter of a novel and a ZIP file containing a file representation of the novel. One is an abstraction, the other a file.
Related
I was watching a lecture on Java when I caught myself not specifying package in Java file.
They lecturer was using Java 11 on Netbeans, and I Java 1.8 on IDEA. By default Netbeans created him a package, and the main java file has package specified.
But on IDEA, I noticed that I don't need to specify package name, when creating .java file inside src\main\java folder. And I have a question why?
Why is src\main\java a folder, and not a package?
What is the difference between a folder and a package?
In Python, they create __init__.py file inside of a package, in order to make Python interpreter see the package. How is it working in Java, if there is no __init__ file? How does Java understand that this is a folder, and that is a package?
Why does Java need to introduce and separate folder and package terms?
Why is src\main\java a folder, and not a package?
Which folders become packages depends on where the "root" is defined. In IDEA, src/java/main is the root. Any folders inside of that are mapped to packages. If for example, you create a folder src/java/main/foo and create a Foo.java in that folder, you will have a class named Foo in a package named foo.
What is the difference between a folder and a package?
A package is a way to group related Java classes. Sometimes a package is implemented as a folder in your file system. Sometimes it is something else. (See below.)
Why does Java need to introduce and separate folder and package terms?
One reason to differentiate between folders and packages is that some packages aren't folders. For example, you can download a .jar file from the Internet which contains a Java library. The library inside that .jar file defines packages and classes that you can use in your own code, but there are no folders for the packages.
The reason for a new term "package" is to create an abstraction that isn't tied to the folders in your local file system.
The difference between a package and a folder is not directly evident unless you define your classpath yourself.
All directories and all zip files you add to the classpath create a baseline. Such as the .../src/main/java folder. Underneath that baseline you can still create folders with classes. But for Java these will be treated as packages.
So in the filesystem packages are resembled by folders. In zip files (and jar files are nothing but zip files with some metadata) there are no filesystem folders but still something folder-like that can be extracted into filesystem folders.
And it is thinkable that people would write even other Classloaders that do not just do simple filesystem or zipfile access. They can do virtually anything which could even range to loading classes from different websites - just based on their package names.
As soon as a class is not in the default package (in a folder on the classpath directly) it needs the package name declared in it's source code. And that is what you spotted. Well done!
Summary: .../src/main/javais the default package (that does not need to be specified) because that folder is added to the classpath when the JVM executes. Any classes in subfolders need their package defined.
A small detail: The classpath is set for the compiled classes, not the java source files. You could keep all java sources in the same directory and just declare by package into which 'folder' the compiled output should go. But it is good practice to organize the source files in the same structure that will be emitted by the compiler. Any IDE will help you maintain that structure.
I am learning about Java 9 from What's New in Java9 and one of the hot topics in the discussion is The Modular JDK.
Are JAR files modules?
How is a module different from a JAR file?
Module: A new language feature introduced in Java 9 (similar to class, interface, package, etc.) that consists of a collection of packages, similar to how a package consists of a collection of types.
JAR: An archive file format that bundles code and resources and which can be loaded by the JVM.
More specifically, a module is defined as follows:
In order to provide reliable configuration and strong encapsulation in a way that is both approachable to developers and supportable by existing tool chains we treat modules as a fundamental new kind of Java program component. A module is a named, self-describing collection of code and data. Its code is organized as a set of packages containing types, i.e., Java classes and interfaces; its data includes resources and other kinds of static information.
...
A module’s self-description is expressed in its module declaration, a new construct of the Java programming language.
...
A module declaration is compiled, by convention, into a file named module-info.class, placed similarly in the class-file output directory.
A module can be compiled into a Jar file, in which case the Jar file is labelled a modular Jar file:
Existing tools can already create, manipulate, and consume JAR files, so for ease of adoption and migration we define modular JAR files. A modular JAR file is like an ordinary JAR file in all possible ways, except that it also includes a module-info.class file in its root directory.
Some other differences between a module and a JAR:
Modules can require other modules in order to allow accessing dependent classes by the requiring module. A Jar has no such dependency concept.
A module can decide which classes and interfaces to export to other modules that require it. A Jar has no such encapsulation mechanism.
A module can be compiled into a modular Jar file, but some modules (e.g. JDK modules) are compiled into another format called JMOD.
The name of a JAR can be changed. As long as the JVM classloader finds the needed class on the classpath (which can be composed of a single JAR, multiple JARs, or a mix between directories or JARs), the name of the JAR file can be anything. However, the name of a module can be explicitly referenced in the declaration of other modules, and such the name defines it and cannot be changed freely.
Strictly speaking, a module is a run-time concept. As others have quoted from The State of the Module system:
A module is a named, self-describing collection of code and data. Its code is organized as a set of packages containing types, i.e., Java classes and interfaces; its data includes resources and other kinds of static information.
This is very similar to JARs, but...
JARs have no meaningful representation at run time
JARs are not "self-describing", which in this case means they do not have a name that the JVM cares about, can not express dependencies or define a proper API
This leaves the question, where do modules come from? There are various ways but the most prominent one for developers is the modular JAR. A modular JAR is just like a plain JAR, but it contains a module descriptor, a file module-info.class that was compiled from a module-info.java. It is that file that defines a module's name, dependencies, and APIs.
So there is a strong connection between JARs and modules: JARs are the containers from which the module system creates modules and (at the moment) each JAR can only contain a single module. It is important to note that even on Java 9 JARs do not have to be modular - plain JARs are totally fine.
Are JAR files Modules? How Module is different from JAR file?
No, a Java Archive is not a Module.
Just for an example, while classes of the same package could have been spread across JARs, the same package now can not be read from multiple modules.
A JAR is a file format that enables you to bundle multiple files
into a single archive file. Typically this contains the class files
and auxiliary resources associated with applets and applications.
on the other hand (I'd tried describing this here ~> java-module as well)
A module is a named, self-describing collection of code and data. Its
code is organized as a set of packages containing types, i.e., Java
classes and interfaces; its data includes resources and other kinds of
static information.
This also consists of the module declaration as specified with the help of module-info.java.
Each module definition is either
A module artifact, i.e., a modular JAR file or a JMOD file containing a compiled module definition, or else
An exploded-module directory whose name is, by convention, the module's name and whose content is an "exploded" directory tree corresponding to a package hierarchy.
As introduced with the module system, a modular image is composed of modules rather than JAR files.
Modularity is foreseen for with dynamic configuration in terms of Modular WAR file as well.
But for the ease of adoption of Modules a Modular JAR file, was introduced in JDK9, such that lets say for a module consisting of a module-info.java such that
module com.foo.bar { }
and other java classes as
com/foo/bar/alpha/AlphaFactory.java
com/foo/bar/alpha/Alpha.java
Existing tools can already create, manipulate, and consume JAR files. A modular JAR file is like an ordinary JAR file in all
possible ways, except that it also includes a module-info.class file
in its root directory. A modular JAR file for the above com.foo.bar
module, e.g., might have the content:
META-INF/
META-INF/MANIFEST.MF
module-info.class
com/foo/bar/alpha/AlphaFactory.class
com/foo/bar/alpha/Alpha.class
...
A modular JAR file can be used as a module, in which case its module-info.class file is taken to contain the module’s declaration.
It can, alternatively, be placed on the ordinary class path, in which
case its module-info.class file is ignored.
All Java projects I have seen use a folder structure that follows the package structure. This results I large number of folders that do not contain any files.
So for example packages start with com.mydomain.mysystem.myutility. This would result in a folders src\com, src\com\mydomain, src\com\mydomain\mysystem that do not contain any files. Most likely the myutility will also only contain only folders.
Most likely there will also be a project folder that contains the name myutility so the complete folder path could be myutility\src\main\java\com\mydomain\mysystem\myutility\otherfolder
This practice is very common but it makes we wonder how useful it is. What is benefit compared to the situation where these extra folders are not created? Using for example myutility\src\main\java\otherfolder
It seems to be just as valid but it saves everybody the extra navigation steps. I can compile Java source files with both approaches just fine.
In a project typically all source is in com\mydomain\mysystem. What is the benefit of putting those 'empty' folders in all projects?
Just to be clear, I am not questioning the usefulness of package structure. Also Maven is clear.
The question is why we use the empty folders that are typically the same throughout the repository for an organisation.
The source (and class) files are organized like that so that the Java compiler (and the runtime environment) can find them.
When the Java compiler compiles your class, it needs the source or class file of each class that your class depends on, so that it can check that the class exists, that all methods are called with the correct arguments, etc. Also, if it find a source file but not class file, or if the class file is older than the source file, it will compile the source file of the class you use.
The compiler could of course just check all subfolders of your class path, or even the entire disk, but that would take a lot of time. Because of this convention the compiler only has to check a single subfolder for each classpath entry. Of course you can think of different solutions to this problem, but the people at (then) Sun thought this was the best option.
Of course, the above also applies to the class files which are loaded at run-time, so also the class files are stored in a similar folder structure.
Note also that Java applications and libraries are often packaged as a Jar file (which basically is a zip file with the same folder structure inside), so in many cases they appear as a single file in the file system.
The reason it is done this way is to prevent conflicts and ensure that classes can be uniquely identified. This means that if 2 classes have the same name they can still be loaded via different imports.
The safest way to do this is by using a domain name, which is by its nature unique:
com.google.<classname> for example.
Your approach will work and saves a few empty folders but is not scalable.
As an intern, I use company code in my projects and they usually send me a jar file to work with. I add it to the build path in Eclipse and usually all is fine and dandy.
However, I got curious to know, what each class contained and when I try to open one of the classes in the jar file, it tells me that I need a source file.
What does this mean? I come from a C/C++ background so is a jar similar to an already compiled .o file and all I can see is the .h stuff? Or is there actual code in the jar file that I'm using that's encrypted so I can't read it?
Thanks for all the answers!
Edit: Thanks, guys, I knew it was a sort of like an archive but I was confused to why when I tried to open the .class files, I got a bunch of random characters. The output was similar when I tried to open a .o file in C so I just wanted to make sure.
Thanks!
A JAR file is actually just a ZIP file. It can contain anything - usually it contains compiled Java code (*.class), but sometimes also Java sourcecode (*.java).
However, Java can be decompiled - in case the developer obfuscated his code you won't get any useful class/function/variable names though.
However, I got curious to what each class contained and when I try to open one of the classes in the jar file, it tells me that I need a source file.
A jar file is basically a zip file containing .class files and potentially other resources (and metadata about the jar itself). It's hard to compare C to Java really, as Java byte code maintains a lot more metadata than most binary formats - but the class file is compiled code instead of source code.
If you either open the jar file with a zip utility or run jar xf foo.jar you can extract the files from it, and have a look at them. Note that you don't need a jar file to run Java code - classloaders can load class data directly from the file system, or from URLs, as well as from jar files.
The best way to understand what the jar file contains is by executing this :
Go to command line and execute jar tvf jarfilename.jar
A jar file is a zip file with some additional files containing metadata. (Despite the .jar extension, it is in zip format, and any utilities that deal with .zip files are also able to deal with .jar files.)
http://docs.oracle.com/javase/8/docs/technotes/guides/jar/index.html
Jar files can contain any kind of files, but they usually contain class files and supporting configuration files (properties), graphics and other data files needed by the application.
Class files contain compiled Java code, which is executable by the Java Virtual Machine.
http://en.wikipedia.org/wiki/Java_class_file
JAR stands for Java ARchive. It's a file format based on the popular ZIP file format and is used for aggregating many files into one. Although JAR can be used as a general archiving tool, the primary motivation for its development was so that Java applets and their requisite components (.class files, images and sounds) can be downloaded to a browser in a single HTTP transaction, rather than opening a new connection for each piece. This greatly improves the speed with which an applet can be loaded onto a web page and begin functioning. The JAR format also supports compression, which reduces the size of the file and improves download time still further. Additionally, individual entries in a JAR file may be digitally signed by the applet author to authenticate their origin.
Jar file contains compiled Java binary classes in the form of *.class which can be converted to readable .java class by decompiling it using some open source decompiler. The jar also has an optional META-INF/MANIFEST.MF which tells us how to use the jar file - specifies other jar files for loading with the jar.
Jar( Java Archive) contains group of .class files.
1.To create Jar File (Zip File)
if one .class (say, Demo.class) then use command jar -cvf NameOfJarFile.jar Demo.class (usually it’s not feasible for only one .class file)
if more than one .class (say, Demo.class , DemoOne.class) then use command jar -cvf NameOfJarFile.jar Demo.class DemoOne.class
if all .class is to be group (say, Demo.class , DemoOne.class etc) then use command jar -cvf NameOfJarFile.jar *.class
2.To extract Jar File (Unzip File)
jar -xvf NameOfJarFile.jar
3.To display table of content
jar -tvf NameOfJarFile.jar
A .jar file is akin to a .exe file.
In essence, they are both executable files.
A jar file is also a archive (JAR = Java ARchive). In a jar file, you will see folders and class files. Each .class file is similar to a .o you might get from C or C++, and is a compiled java archive.
If you wanted to see the code in a jar file, download a java decompiler (located here: http://java.decompiler.free.fr/?q=jdgui) and a .jar extractor (7zip works fine).
JD-GUI is a very handy tool for browsing and decompiling JARs
A .jar file contains compiled code (*.class files) and other data/resources related to that code. It enables you to bundle multiple files into a single archive file. It also contains metadata. Since it is a zip file it is capable of compressing the data that you put into it.
Couple of things i found useful.
http://www.skylit.com/javamethods/faqs/createjar.html
http://docs.oracle.com/javase/tutorial/deployment/jar/basicsindex.html
The book OSGi in practice defines JAR files as, "JARs are archive files based on the ZIP file format,
allowing many files to be aggregated into a single file. Typically the files
contained in the archive are a mixture of compiled Java class files and resource
files such as images and documents. Additionally the specification defines a
standard location within a JAR archive for metadata — the META-INF folder
— and several standard file names and formats within that directly, most
important of which is the MANIFEST.MF file."
Just check if the aopalliance.jar file has .java files instead of .class files. if so, just extract the jar file, import it in eclipse & create a jar though eclipse. It worked for me.
While learning about JAR, I came across this thread, but couldn't get enough information for people like me, who have .NET background, so I'm gonna add few points which can help persons like myself with .NET background.
First we need to define similar concept to JAR in .NET which is Assembly and assembly shares a lot in common with Java JAR files.
So, an assembly is the fundamental unit of code packaging in the .NET environment. Assemblies are self contained and typically contain the intermediate code from compiling classes, metadata about the classes, and any other files needed by the packaged code to perform its task. Since assemblies are the fundamental unit of code packaging, several actions related to interacting with types must be done at the assembly level. For instance, granting of security permissions, code deployment, and versioning are done at the assembly level.
Java JAR files perform a similar task in Java with most differences being in the implementation. Assemblies are usually stored as EXEs or DLLs while JAR files are stored in the ZIP file format.
Source of Information -> 5- Assemblies
What is a Class library in Java? Is it a collection of classes with in a package, or it is a package that has collection of classes?
I'm bit confused. ^_^
It's a collection of classes, usually bundled up in a jar file. All the classes may be in the same Java package, but they don't have to be. A class library in a jar file may also contain resources and meta-data that it needs (e.g. string translations, driver information for other frameworks etc).
Yes, class libraries are just sets of classes in a package.
They could be stored in a folder but mostly they are distributed in JARs (Java ARchives), which are just zipped up class files.
The JavaTM Archive (JAR) file format enables you to bundle multiple files into a single archive file. Typically a JAR file contains the class files and auxiliary resources associated with applets and applications.
You can get more information from this link