Code Into Java Byte Code. (With .Class Extension)
Code Into Java Byte Code. (With .Class Extension)
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
-classpath <path> Specify where to find user class files and annotation processors
-cp <path> Specify where to find user class files and annotation processors
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.
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
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>()
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>
*/
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:
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);
}
}
C:\javac>appletviewer
Myapplet.html
When we run the applet viewer it will display the window as shown below.