what is the file encoding type for java class file?

196 Views Asked by At

What is the file encoding type used for Java class files?

I am not referring to the file.encoding or Charset.defaultCharset() properties.

When javac compiles a .java file to a .class file and saves the resulting file on disk, what file encoding type is used? Is it UTF-8?

Can someone provide more details on this? I do not want to make assumptions.

2

There are 2 best solutions below

3
azer-p On BEST ANSWER

When Java compiles a .java source file into a .class file, the resulting .class file does not use a specific file encoding type like UTF-8. Instead, it follows a binary format known as the Java class file format.

The Java class file format is designed to be platform-independent and is primarily intended to be consumed by the Java Virtual Machine (JVM). It contains a structured set of bytes that represent various elements of the compiled Java code, such as class declarations, methods, fields, and bytecode instructions.

The class file format specifies a specific layout and organization of bytes, including headers, constant pools, access flags, attribute tables, and more. It does not rely on any specific character encoding scheme like UTF-8 because the content of a class file consists of compiled Java bytecode instructions, numeric values, and symbolic references rather than human-readable text.

Therefore, when you compile a Java source file using the javac compiler, the resulting .class file is not encoded as text but as binary data conforming to the Java class file format.

8
Jon Skeet On

Encoding refers to text, not binary data.

Class files are binary data - so there's no notion of a text encoding for them, any more than there is for an MP3 file or a JPEG.

Do not try to read a class file as if it's text - you're almost certain to lose information.