What is the use of Byte code in java - java

I am a little bit confused...
I know that classes are loaded by the class loader only when they are needed,that is when we are trying to use static variables or when we are creating instance of that class.Thus if we have for e.g. 3 classes in our program and we are going to use only one,then only that particular class will be loaded and rest are not,but when we run the java compiler,it will create 3 .class files,I know these 3 .class files are byte code files,but then what is this byte code and what is the difference between loading a class and generating bytecode of a class?Where is the use of this byte code?If we are not going to use a particular class,then what is the need of generating a bytecode for that class?

Java is a compiled language. The purpose of compiling into bytecode is to allow the code to run on the JVM on any platform. Platform independence is a feature built into java.
Furthermore, you don't have to compile all three class files unless they have inter-dependencies. You can specify which specific files to compile in the console javac command. If you are using an IDE, check your settings or exclude the undesired class from the project.

Loading a class happens at runtime, when you're preparing to invoke whatever properties the class has.
Generating the bytecode of a class happens at compile time. This allows the code to be run on the virtual machine.
Java is a compiled language, and it runs on top of the Java Virtual Machine. Compiling bytecode translates whatever higher level code (be it Java, Scala, or Clojure) into machine-independent instructions to be read by the JVM. This is why that your (backend-specific) program will generally run without modification on Linux, Windows, and Mac OS X.
The Java language will compile any classes that have dependencies on each other within the path, so if you have a class but it is not used, chances are it will not be compiled. There may be tools that override that, so if you find yourself not using a class, then remove the class so that unnecessary bytecode is not generated.

Difference between languages like C++ and java is byte code. C++ binaries(compiled,assembled,linked) will have the machine(op) codes for the OS it got compiled for. In the case of java the byte code is the target for JVM. Byte code will have the opcodes for JVM. JVM in turn will initiate the respective os calls. So bytecode and JVM makes java programs independent of os.
Reg loading class loading,it happens when the program needs it. This is at runtime. JIT will do the second compilation of class when needed.

When we compile .java we get .class file.
The .class file is called byte code.
The Byte code in Java is nothing but a .class file which is not understandable by humans i.e (00110011). These .class files are generated only after the compilation of .java.
These .class file can be used to run on any platform.

Related

Instrumenting Java 9+ runtime modules

Our tool (http://plse.cs.washington.edu/daikon) calculates program invariants by inserting instrumentation into the Java byte codes for a program. The user code is instrumented during runtime via the normal ClassFileTransformer::transform method.
It is also necessary to track value flows through JDK methods. Thus, we need to instrument the Java runtime as well. We cannot use transform, because hundreds of runtime methods are loaded prior to the first time we get control at transform.
Prior to Java 9, we handled this in an offline step that reads rt.jar, instruments its methods, and writes out a modified version as dcomp-rt.jar. The user placed dcomp-rt.jar on the bootclasspath to ensure our modified Java runtime methods were loaded instead of the standard ones. The user program invocation would look something like:
java -cp .:.../daikon/daikon.jar \
-Xbootclasspath/p:.../daikon/java/dcomp_rt.jar:.:.../daikon/daikon.jar \
-javaagent:.../daikon/java/dcomp_premain.jar={various dcomp arguments} \
{user program} {user program arguments}
Now to Java 9+. Our first approach was to read in and instrument the class files within the Java runtime jmod files (via the new jrt:/ file system) and create a dcomp_rt.jar as before. The problem we are experiencing is that we cannot get the system to use the contents of this jar instead of jrt:/java.base (for example). We tried various --module-path and -Xbootclasspath (only /a is available now, might be part of problem) options to no avail. Still hoping there might be a way to do this?
If not, I'm guessing we need to make modified versions of each of the interesting runtime jmods and then use a --patch-module argument for each of them. Would this ensure our modified code is loaded instead of the standard runtime?
Any thoughts/suggestions?
Well it looks like --patch-module does the trick. I made the same dcomp_rt.jar but with only classes from java.base.jmod. Then used:
--patch-module java.base={full path}/dcomp_rt.jar
Running java with -verbose:class showed all base classes being loaded from my jar.
Is this the best way to accomplish my goal?

Does Java need .class files to run even if defined

I just started Java today and I am getting a NoClassDefFoundError when I run my code:
class Example {
public static final String greeting = "Hi there";
public static void main(String[] args) {
System.out.format("%s", Example.greeting);
}
}
Above is the contents of my example.java code. This code compiles fine in the Eclipse execution, but when I try to run example.java by itself, it fails. Eclipse also created some .class file when I ran this program, but that doesn't make much sense as to why it would fail if I ran the .java by itself in a different directory as all the information of the class Example is found in the .java file itself.
Does Java need the .class file to compile and run despite having the class itself defined in the program and why? I also built the .java file through terminal and it worked fine
Compilation and execution of a Java program is two step process:
During compilation phase Java compiler compiles the source code and generates bytecode. This intermediate bytecode is saved in form of a .class file.
In second phase, Java virtual machine (JVM) also called Java interpreter takes the .class as input and generates output by executing the bytecode.
So yes .class file is essential for execution of the code. .java file is text that you write, but not what the machine can interpret.
Here is the flow diagram of what happens:
To look at it in more depth:
When your Java project builds, it translates the source code (contained in *.java source files) to Java bytecode (most often contained in *.class files). This takes your high-level code one step closer to machine code, but not quite there yet. This bytecode is a collection of compact instructions; easier for a machine to interpret, but less readable.
When you run a Java application on your computer, cellphone, or any other Java-enabled platform, you essentially pass this Java bytecode to the Java Virtual Machine. The interpreter in the Java Virtual Machine usually starts compiling the entire bytecode at runtime, following the principles of so-called just-in-time compilation. This makes for the typical, albeit often slight delay when opening a Java application, but generally enhances the program performance compared to interpreted compilation.
Does Java need the .class file to compile and run despite having the class itself defined in the program and why
The compiled output of a java file (class) is .class file. It contains the bytecode of the program which is run by the JVM. So .class files are required to run the program.
I also built the .java file through terminal and it worked fine
Even through the terminal, when you compile the .java file (class). It creates the .class for each class declared in the .java file. Then you execute the class which contains the main method. The main method is the entry point for the JVM.
For example:
File name: example.java
Compile code: javac example.java
Output is .class file: Example.class. Because name of the class is Example.
Run the program: java Example
Error in your code. Looks like this has been updated in the question.
System.out.format("%s", Student.greeting);
Name of the class is Example not Student. it should be:
System.out.format("%s", Example.greeting);

Why don't we use the .class extension with "java" command?

Why don't we give the filename.class file after java command, instead of only filename?
Suppose we want to compile the test.java program, then we run javac test.java. It is ok!
After that it will produce test.class file but to run the program we run java test instead of java test.class. What is the reason for this?
Because you are not describing a file to run. You are telling Java which class contains the main method - and the class' name is (in your case) filename, not filename.class.
The fact that the bytecode is almost always contained in files on the filesystem is an implementation detail. The classpath you pass to the java command tells it where to look for classes, and then the main class argument tells it which class to use.
(It's different for javac, because this program specifically does take source files and compiles them into bytecode.)
You don't pass a file name to the java command either. You pass it a fully qualified class name. Something like com.yourcompany.yourapp.Main. Java then finds the .class file for this class name, by looking into all the directories and jar files in the classpath.
It's an implementation detail. The Java class loader system can extended by custom code to make it behave differently. For example, some companies have written encrypted class loaders that are capable of decrypting and loading encrypted class files on the fly. You could hypothetically create a similar system that bundles a bunch of classes together into something resembling a .NET assembly instead of a Jar file (which is really just a zip file).
when you execute "java test.class"
You get either
Could not find or load main class test.class
or
Exception in thread "main" java.lang.NoClassDefFoundError: test/class
This is because "java" in "java test.class" is jvm. It looks for main method in class called "class" instead of "test". Dot in "java test.class" has a significant meaning. So how jvm looks at "java test.class", in a package called "test" it looks for a java class named "class".
*test.class*
*test* - package name
*class* - java filename
Hope this helps !!
Just to summarise everything to the details,
when one does
java filename.java
s/he actually runs the java compiler and converts the code to instructions that a JVM understands.
Now when one runs
javac main_file
s/he invokes the JVM to run the entire project whose main method is found in the class main_file
This main_file is actually the fully qualified name of the class i.e. if I have a project ProjectX and this main class is in package src.java.hello.main,
You should run the command
java src.java.hello.main.main_file
Hence this . is actually a reserved thing at JVM end and we cannot give .class as part of the argument to the java command.
The Javac compiler creates file called Xyz.class (Here Xyz is FileName)
that contains the byte version of the program
Java Bytecode is nothing but intermediate Representation of Your Program that contains instruction the Java interpreter will execute.
thus, the output of javac is not code that can be directly executed
in short, javac keyword is used for the Compile the Java program
if we Use .class with javac (Already compiled File .class File) then How can compile already compile file
so Valid Syntax is:
Javac Xyz.java (Compile the Java Program)
java Xyz (Run the Java Program)

What happens when java program starts?

Recently have been touched Java classloaders and suddenly recognized that do not fully understand what happens step-by-step when someone calls
java -jar App.jar
Well I guess
a new instance of JVM is created
it uses ClassLoader to load main class and other classes
byte-code is started to execute from main() method
But still I suppose there are many things I need to know more about it.
Who and how decides which classes should be loaded at startup and which once needed?
I have found two related questions but there it is not explained how to apply that to Java realities.
What happens when a computer program runs?
What happens when you run a program?
•Who and how decides which classes should be loaded at startup and which once needed?
we need to understand the fundamentals of java class loading. Initially bootstrap classloader (it is implemented natively as part of the VM itself) is responsible for loading core system classes. Then there are other class loaders as well like Extension, system, user-defined(optional) class loaders which decide when and how classes should be loaded.
Fundamentals of class loading
The decision is made by the classloader. There are different implementations, some of which pre-load all classes they can and some only loading classes as they are needed.
A class only needs to be loaded when it is accessed from the program code for the first time; this access may be the instantiation of an object from that class or access to one of its static members. Usually, the default classloader will lazily load classes when they are needed.
Some classes cannot be relied on to be pre-loaded in any case however: Classes accessed via Class.forName(...) may not be determined until this code is actually exectued.
Among other options, for simple experiments, you can use static initializer code to have a look at the actual time and order in which classes are actually loaded; this code will be executed when the class is loaded for the first time; example:
class SomeClass {
static {
System.out.println("Class SomeClass was initialized.");
}
public SomeClass() {
...
}
...
}
Your example shows an executable jar, which is simply a normal java archive (jar) with an extra key/value pair in it's manifest file (located in folder "META_INF"). The key is "Main-Class" and the value the fully qualified classname of that class whose "main" method will be executed, if you "run" the jar just like in your example.
A jar is a zip file and you can have a look inside with every zip archive tool.
Whenever you compile a Java program the following steps takes place
First the Class Loader loads the class into the JVM.
After giving the command javac filename.java the compiler checks for compile time errors and if everything is fine then it will generate the .Class files(byte code).
This will be the first phase.
Later the interpreter checks for the runtime errors and if everything is fine without exceptions then the interpreter converts the byte code to executable code.
First phase in java is done by the JIT compiler(Just In Time).

Can i insert Bytecode inside my source code?

Can i write bytecode inside a method of a class so that the compiler bypasses that part since it is already compiled. Something similar to writing assembly programs in C language using "asm"...
I think you mean Java. If that's the case:
Short answer: no.
Long answer:
There is nothing like asm { ... } in Java. But you could (not very clever in most situations) write a .class file (or have bytecode in textual representation and then assemble it in Java to a .class file) from Java and dynamically load and execute it.

Categories

Resources