What is class file in Java? Example (original) (raw)

What is the class file in Java?

_Class file i_n Java is compiled from of Java source file. When we compile a Java program written in a Java source file ended with a .java extension, it produces one more class file depending upon how many classes are declared and defined in that Java source file. One Java source file can only contain one public class, and its name must match with the name of the file like HelloWorld.java file can contain a public class whose name should be HelloWorld as shown below :

public class HelloWorld {

public static void main(String... args){ System.out.println("I am inside java class HelloWorld"); }

}

if you compile this Java file by

it will produce

=> HelloWorld.class

Class file details in Java

A class file in Java has a .class extension. It contains bytecode, which is instruction for Java Virtual Machine, which translates that bytecode into platform-specific machine level instruction based upon whether the Java program runs on Windows or Linux.

In fact, this combination of a class file, bytecode, and JVM makes Java achieves platform independence. If anyone asks what is byte code in Java, is it machine instruction? You can answer them that it's just meant for JVM and not for a machine.

JVM first loads that file and executes the main method, which is the entry point of the Java application. Remember java compiler or javac command is used to create a class file from the java source file, and the java command is used to run a Java program stored in a class file.

Since the class file contains bytecode in hex format and the class file format is well-documented, anyone can temper with the class file and break Java security grantees. To prevent that every Java class file is verified by Verifier after loading during Byte code verification process and Verifier rejects the class file which violates constraints of Java programming language.

What is class file in Java? Example

Thanks for reading this article so far. If you find my explanation of Java's class files, please share them with your friends and colleagues. If you have any questions or doubts, please ask.