0% found this document useful (0 votes)
165 views

Code Into Java Byte Code. (With .Class Extension)

The Java compiler (javac) compiles Java source code files (.java) into bytecode (.class) files. The bytecode can run on any system with a Java Virtual Machine (JVM). The JVM interprets the bytecode and converts it into machine-specific code that can be executed by the host computer's CPU. Java's compiler and interpreter allow programs written in Java to run on any platform that has a JVM without being recompiled.

Uploaded by

jairadh786
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
165 views

Code Into Java Byte Code. (With .Class Extension)

The Java compiler (javac) compiles Java source code files (.java) into bytecode (.class) files. The bytecode can run on any system with a Java Virtual Machine (JVM). The JVM interprets the bytecode and converts it into machine-specific code that can be executed by the host computer's CPU. Java's compiler and interpreter allow programs written in Java to run on any platform that has a JVM without being recompiled.

Uploaded by

jairadh786
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 14

Java Compiler

To commence with Java programming, we must know the significance of Java Compiler.
When we write any program in a text editor like Notepad, we use Java compiler to compile it.
A Java Compiler javac is a computer program or set of programs which translates java source
code into java byte code. 
The output from a Java compiler comes in the form of Java class files (with .class extension).
The java source code contained in files end with the .java extension. The file name must be
the same as the class name, as classname.java. When the javac compiles the source file
defined in a .java files, it generates bytecode for the java source file and saves in a class file
with a .class extension.
The most commonly used Java compiler is javac, included in JDK from Sun Microsystems.
Following figure shows the working of the Java compiler:

Once the byte code is generated it can be run on any platform using Java Interpreter (JVM). It
interprets byte code (.class file) and converts into machine specific binary code. Then JVM
runs the binary code on the host machine. 
How to use Java Compiler
When you run javac command on the command prompt, it shows the following output.
C:\>javac
Usage: javac <options> <source files>
where possible options include:
-g Generate all debugging info

-g:none Generate no debugging info

-g:{lines,vars,source} Generate only some debugging info

-nowarn Generate no warnings

-verbose Output messages about what the compiler is doing


-deprecation Output source locations where deprecated APIs are used

-classpath <path> Specify where to find user class files and annotation processors

-cp <path> Specify where to find user class files and annotation processors

-sourcepath <path> Specify where to find input source files

-bootclasspath <path> Override location of bootstrap class files

-extdirs <dirs> Override location of installed extensions

-endorseddirs <dirs> Override location of endorsed standards path

-proc:{none,only} Control whether annotation processing and/or compilation is


done.

-processor <class1>[,<class2>,<class3>...]Names of the annotation processors to run;


bypasses
default discovery process

-processorpath <path> Specify where to find annotation processors

-d <directory> Specify where to place generated class files

-s <directory> Specify where to place generated source files

-implicit:{none,class} Specify whether or not to generate class files for


implicitly referenced files

-encoding <encoding> Specify character encoding used by source files

-source <release> Provide source compatibility with specified release

-target <release> Generate class files for specific VM version

-version Version information

-help Print a synopsis of standard options

-Akey[=value] Options to pass to annotation processors

-X Print a synopsis of nonstandard options

-J<flag> Pass <flag> directly to the runtime system


C:\>

Above output shows the different options of javac tool.


Using java compiler to compile java file:
Following example shows how a Compiler works. It compiles the program and gives the
Syntax error, if there is any. Like in this example, we haven't initialized 'a' and we are using it
in the next statement as 'int c=a+b'. That is why its showing a syntax error.
class A{
 public static void
main(String[] args){
     int a;
     int b=2;
     int c=a+b;
    System.out.println(c);
    }
 }
Output of program:
C:\Program
Files\Java\jdk1.6.0_01\bin>javac
A.java
A.java:6: variable a might not
have been initialized
int c=a+b;
^
1 error

C:\Program
Files\Java\jdk1.6.0_01\bin>
Now, lets tweak this example. In this we have initialized 'a' as 'int a =2'. Hence, no syntax
error has been detected.
class A{
  public static void
main(String[] args) {
     int a=2;
     int b=2;
     int c=a+b;
    System.out.println(c);
    }
 }
Output of program:

C:\Program
Files\Java\jdk1.6.0_01\bin>javac
A.java
C:\Program
Files\Java\jdk1.6.0_01\bin>java A
4

Java Interpreter
We can run Java on most platforms provided a platform must has a Java interpreter. That is
why Java applications are platform independent. Java interpreter translates the Java
bytecode into the code that can be understood by the Operating System. Basically, A Java
interpreter is a software that implements the Java virtual machine and runs Java applications.
As the Java compiler compiles the source code into the Java bytecode, the same way the Java
interpreter translates the Java bytecode into the code that can be understood by the
Operating System.
When a Java interpreter is installed on any platform that means it is JVM (Java virtual
machine) enabled platform. It (Java Interpreter) performs all of the activities of the Java run-
time system. It loads Java class files and interprets the compiled byte-code. You would be
glad to know that some web browsers like Netscape and the Internet Explorer are Java
enabled. This means that these browsers contain Java interpreter. With the help of this Java
interpreter we download the Applets from the Internet or an intranet to run within a web
browser. The interpreter also serves as a specialized compiler in an implementation that
supports dynamic or "just in time," compilation which turns Java byte-code into native
machine instructions. 
Throughout Java programming, we'll build both, the standalone Java programs and applets. 
Sun's Java interpreter is called java. Lets learn how to start a standalone application with it.
Load an initial class and specify it. Some options can also be specified to the interpreter, and
any command-line arguments needed for the application as well:
% java [interpreter options] class name [program arguments] 
The class should be specified as a fully qualified class name including the class package, if
any. 
Note :  Moreover, we don't include the .class file extension. Here are a few examples:
% java animals.birds.BigBird
% java test
Once the class is loaded, java follows a  C-like convention and searches for the class that
contains a method called main(). If it finds an appropriate main() method, the interpreter
starts the application by executing that method. From there, the application starts additional
threads, reference other classes, and create its user interface.
Now, lets see how to go about an Applet. Although Java applet is a compiled Java code, the
Java interpreter can't directly run them because they are used as part of a larger applications.
For this we use Java Applet Viewer. It is a command line program to run Java applets. It is
included in the SDK. It helps you to test an applet before you run it in a browser. We will
learn more about it later.
The Figure below shows the working of Java Interpreter:

Java Debugger

Java debugger helps in finding and the fixing of bugs in Java language programs. The Java
debugger is denoted as jdb. It works like a command-line debugger for Java classes. 
jdb session
The way to start the jdb session is to have jdb launch a new JVM (Java virtual machine)
with the main class. Then the application of the main class is debugged by substituting the
command jdb in command-line. For instance, if the main class of the application is
TempClass, the following command is used to debug it:
% jdb TempClass  
There is another way to use jdb i.e.to attach jdb to Java VM which is already running. 
There are few options which are used to debug a VM with jdb. These are:
option  purpose
Enables
-Xdebug  debugging in the
VM
- Loads in-process
Xrunjdwp:transport=dt_socket,server=y,suspend=n  debugging
libraries and
specifies the kind
of connection to
be made
The following command will run the TempClass application to which the jdb will connect
afterwords.
% java -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n
TempClass
Now the jdb will be attached to the VM in this way:  % jdb -attach 8000 
You can go through the basic jdb commands that the Java debugger supports.
cont
Ihis command Continues the execution of the debugged application after a breakpoint,
exception, or step. 

run
Use run command to start the execution after starting jdb, and setting any necessary
breakpoints,  use run command to start the execution . When jdb launches the debugged
application then only this command is available. 
print
This command is used to display Java objects and primitive values. The actual value is printed
for the variables or fields of primitive types. For objects, a short description is printed. 
Few examples of print command are:
 print TempClass.myStaticField
 print myObj.myInstanceField
 print myObj.myMethod() 
dump
 This command is similar to print command. For objects, it is used to print the current value of
each field defined in the object including Static and instance fields.
The dump command supports the same set of expressions as the print command. 
Exceptions
If any kind of exception occurs in the program, the VM will print an exception trace and exits.
It will only print this exception when there isn't any catch statement in the throwing thread's
call stack.
There is another command to be used to stop the debugged applications at other thrown
exceptions. The command is catch command. For instance,  "catch
java.io.FileNotFoundException" or "catch mypackage.BigTroubleException. 
Also the ignore command negates the effect of a previous catch command.
help, or ?
The command which helps in displaying the list of recognized commands is the help or ?
command.

threads
This command list the threads that are currently running. The name and current status are
printed for each thread. The index is also printed that can be used for other commands, for
example:
4. (java.lang.Thread)0x1 main running
This example shows that the thread index is 4, the thread is an instance of java.lang.Thread,
the thread name is "main", and it is currently running.

thread
This command selects a thread to be the current thread. Some jdb commands are based on the
setting of the current thread. The thread index specifies the thread as explained in the threads
command above. 

where
The command where is used to dump the stack of the current thread. Whereas the command
where all is used to dump the stack of all threads in the current thread group. And the where
thread index command is used to dump the stack of the specified thread.

Breakpoints
The way to use Breakpoints is to set it in jdb at line numbers or at the first instruction of a
method, for example:
 stop at TempClass:14 (sets a breakpoint at the first instruction for line 14 of the source file
containing TempClass)
 stop in TempClass.<init> (<init> identifies the TempClass constructor)
It is essential to specify the argument types whenever we overload any method in order to
select  the proper method for a breakpoint. For example,
"TempClass.myMethod(int,java.lang.String)", or "TempClass.myMethod()".
We also use the clear command to remove breakpoints using a syntax as in "clear
TempClass:20" and the cont command continues execution. 

Command Line Options

 Use jdb in place of the Java application launcher on the command line, it accepts most of the
same options as the java command, which includes -D, -classpath, and -X<option>.
Some more options by jdb:
-sourcepath <dir1:dir2:...>
Uses the given path in searching for source files in the specified path. If this option is not
specified, the default path of "." is used. 
-attach <address>
Attaches the debugger to previously running VM using the default connection mechanism. 
-launch
As soon as the jdb start sup,launch option launches the debugged application immediately.
We need not to use the run command after using this option. 
-Joption
It passes option to the Java virtual machine, where option is one of the options described on
the reference page for the java application launcher. For example, -J-Xms48m sets the startup
memory to 48 megabytes.
Lets tweak an example:
public class Y {
public static int add(int
a, int b)
{
return a+b;
}
public static int
sub(int a, int b)
{
return a-b;
}
public static void
main(String args[])
{
int a = 10;
int b = 20;
int c;
c = add(a, b);
System.out.println(c);
c = sub(a, b);

System.out.println(c);
}
}

After compiling and running the above program, we will initialize the java debugger and we will use
the Stop command to out a breakpoint. After that we will use run command to start the jdb. In the
similar way we can use other commands as well.
C:\javac>jdb Y
Initializing jdb ...
> stop at Y:6
Deferring breakpoint Y:6.
It will be set after the class is
loaded.
> run
run Y
Set uncaught
java.lang.Throwable
Set deferred uncaught
java.lang.Throwable
>
VM Started: Set deferred
breakpoint Y:6

Breakpoint hit: "thread=main",


Y.add(), line=6 bci=0
6 return a+b;

main[1] where
[1] Y.add (Y.java:6)
[2] Y.main (Y.java:17)
main[1] methods Y
** methods list **
Y <init>()
Y add(int, int)
Y sub(int, int)
Y main(java.lang.String[])
java.lang.Object <init>()
java.lang.Object
registerNatives()
java.lang.Object getClass()
java.lang.Object hashCode()
java.lang.Object
equals(java.lang.Object)
java.lang.Object clone()
java.lang.Object toString()
java.lang.Object notify()
java.lang.Object notifyAll()
java.lang.Object wait(long)
java.lang.Object wait(long, int)
java.lang.Object wait()
java.lang.Object finalize()
java.lang.Object <clinit>()

Javah -  Header File Generator

In Java programming we need to implement some native methods. You must be wondering
about what's native methods.
 
Firstly, The native methods are in pure C code, not C++. The function prototypes are in an
object-oriented form of C which are being provided by javah , but they are still not object
methods.

Secondly, We can call native methods applications only. However due to some security
reasons, we cannot call applets from native methods.

Thirdly,  native methods are platform-specific. This is the most important point to remember,
you have to build a dynamically loadable library to link your java application with the native
operating system (Windows OS, Machintosh, Linux, Unix ..).  For each native platform your
application targets, a dynamically loadable library is needed to be shipped.. That means any
system-specific code has to be ported along with the java code.
On the other hand, native methods are the only way to use any system features not
provided by the Java Virtual Machine.
To implement these methods Javah generates C header and source files that are used by C
programs to reference an Object's instance variables from native source code. The name of the
header file and the structure declared within it are derived from the name of the class.
By default javah creates a header file for each class listed on the command line and puts the
files in the current directory. As stated above the name of the header file is derived from the
name of the class. If any class inside the package is passed to javah, the package name gets
prepended to both the header file name and the structure name.
Following are some options to use : 
-o outputfile

This option concatenates the resulting header or source files for all the classes listed on the
command line into outputfile. 
-help
Print help message for javah usage.
-d directory

This option sets the directory where javah saves the header files or the stub files. Only one of
-d or -o may be used.
-classpath path

Specifies the path javah used to look up classes. Overrides the default or the CLASSPATH
environment variable if it is set. Directories are separated by semi-colons. Thus the general
format for path is:
.;<your_path>

For example:
.;C:\users\dac\classes;C:\tools\java\classes
-stubs
Causes javah to generate C declarations from the Java object file.
-verbose
Indicates verbose output and causes javah to print a message to stdout concerning the status of
the generated files.
-version
Prints out javah version information.

Javadoc
Sun Microsystems has provided a computer software tool known as Javadoc. This tool is used
to generate API documentation into HTML format from Java source code. It is interesting to
know that Javadoc is the industry standard for documenting Java classes.
 Javadoc is a program that is already included in JDK. We can use Javadoc to run over the
source code to produce documentation of our classes in the HTML files . We have to tag our
code with by using some comment formats to use javadoc tag on our source code. For instance
Javadoc comments looks like this:
NOTE : To start a Javadoc comments use /** to start, and */ to end, and use tags such as
@param, @return, and @exception in between to describe the workings of a method.
The format is given below to use the Javadoc comments:
/**
* Summary of the sentence.
*  information about the
* program, class, method or variable 
* then the comment, using as many lines
* as necessary.
*
* zero or more tags to specify any type
* of information, such as parameters and return
* values for a method
*/

Start with comment delimiter (/*) followed by another (*). The next line starts with an asterisk
and write as many line as you want starting with an asterisk. The last line ends with the
delimiter (*/). The first sentence to start with is a "summary sentence" showing the description
of the program, class, method or variable. We can write few more lines if required, but not any
blank lines. After writting the general description, a sequence of tags follows leaving a blank
line.
Use different tags to display different situations. The example below shows a Javadoc
comment without tags that describes the variable declared immediately below it:

/**
* The number of employees in a company. This variable must not be
* negative or greater than 200.
*/
public int numEmployees;

One interesting thing to know about Javadoc comments is that we can embed HTML tags to
format the text. For example:

/** 
* <B>Java declaration</B> 
*/ 

Lets have a look on Javadoc tags


 Tag   Description
 @version   Shows the version number of a class or method.
 @author   Shows the Developer name
 @return   Documents the return value. This tag should not
be used for constructors or methods defined with a
void return type.
 @deprecated  Marks a method as deprecated. Some IDEs will
issue a compilation warning  if the method is
called. 
 @see   Documents an association to another method or
class.
 @param   Defines a method parameter. Required for each
parameter.
 @throws   Documents an exception thrown by a method. A
synonym for @exception   introduced in Javadoc
1.2.
 @since   Documents when a method was added to a class.
 @exception   Documents an exception thrown by a method —
also see @throws.
 private  Displays all classes and members
 use  It creates class and package usage pages
 Windowtitle  It shows the window title of the document
 Header  It includes for header text of the page
 Footer  It includes footer text for the page  
 Bottom  It includes bottom text for the page
 Package  Shows package classes and members
 Protected  shows protected classes and members
 Classpath  Helps to find user class files
 noindex  doesn't provide the index
 nohelp  doesn't provide the help link
 notree  doesn't provide class hierarchy
 To document source code developers use certain commenting styles and Javadoc tags. A Java
block comment starting with /** will begin a Javadoc comment block This comment block
will be included in the HTML. Some tags are provided in the above table which begins with
an "@" (at sign).
The Java Applet Viewer

Applet viewer is a command line program to run Java applets. It is included in the SDK. It
helps you to test an applet before you run it in a browser. Before going any further, lets see
what an applet is?

An applet is a special type of application that's included as a part of an HTML page and can
be stored in a web page and run within a web browser. The applet's code gets transferred to the
system and then the Java Virtual Machine (JVM) of the browser executes that code and
displays the output.. So for running the applet,  the browser should be Java enabled. To create
an applet, we need to define a class that inherits the Applet.
We generally use web browsers to run applets. Its not always mandatory to open a Web
browser for running an applet. There is another way as well. The other way to run an applet is
through Java applet viewer. This is a tool that acts as a test bed for Java applets. The working
of Applet viewer is a bit different from a Web browser, though they are logically same. The
Applet viewer runs on the HTML documentation, and uses embedded applet tags. The
difference in using the applet viewer and the web browser to run the applet is that the applet
viewer only deals with the applet code not the HTML cod i.e. it doesn't display HTML code.
So we should test our program in applet viewer and web browser to confirm its working.
The applet viewer command connects to the documents or resources designated by urls. It
displays each applet referenced by the documents in its own window.
The syntax for the applet viewer is:

appletviewer Options URL 

Where the URL specifies the location of the applet program and the Options argument
specifies how to run the Java applet. We can use only one option -debug that starts the applet
viewer in the Java debugger. Using this option we can debug an applet.
The following program shows how to build an applet and the HTML file for it. Firstly create a
class. Then start the applet using init method. After that enter a string as str = "This is my first
applet". Use paint method to give the dimensions of the applet. Beneath that is the HTML file
which shows how to give the body for applet.
Here is the Java File:
import java.applet.*;
import java.awt.*;
public class Myapplet extends
Applet{
String str;
public void init(){
str = "This is
my first applet";
}
public void
paint(Graphics g){

g.drawString(str,
50,50);
}
}

Here is the HTML File:


<HTML>
<BODY>
<applet
code="Myapplet",height="200"
width="200">
</applet>
</BODY>
</HTML>
After building the program, run the applet and the applet viewer as shown below.
C:\javac> javac
Myapplet.java

C:\javac>appletviewer
Myapplet.html
When we run the applet viewer it will display the window as shown below.

You might also like