Академический Документы
Профессиональный Документы
Культура Документы
INTRODUCTION .................................................................................................................................... 3
KEY DIFFERENCES BETWEEN C++ AND JAVA: ................................................................... 3
A FIRST SIMPLE PROGRAM............................................................................................................ 4
A CLOSER LOOK AT PROGRAM ..................................................................................................... 5
DATA TYPES AND VARIABLES ...................................................................................................... 6
EXPRESSIONS ........................................................................................................................................ 7
CONTROL FLOW .................................................................................................................................... 9
INHERITANCE AND POLYMORPHISM..................................................................................... 10
PACKAGES AND INTERFACES...................................................................................................... 12
EXCEPTION HANDLING .................................................................................................................. 13
APPLETS .................................................................................................................................................. 15
USEFUL LINKS FOR JAVA:............................................................................................................. 16
REFERENCES ......................................................................................................................................... 16
APPENDIX A
CONVERTING C++ MAGIC 8 BALL TO JAVA (WITH A GUI)....................................... 16
APPENDIX B
EASIER LIFE THROUGH SWING: JFILECHOOSER ............................................................ 24
APPENDIX C
JAVAMAIL: WRITING A SIMPLE E-MAIL PROGRAM....................................................... 28
Introduction
Java is a high-level, third generation programming language, like C,
FORTRAN, Smalltalk, Perl, and many others. You can use Java to write
computer applications that crunch numbers, process words, play games,
store data or do any of the thousands of other things computer software can
do.
Java is Object-Oriented
In C++ you can have functions that are not attached to classes. The main
function in C++ is explicitly not attached to a class.
In Java, all function, including the main function, are attached to classes that
means within class. Everything is an object here.
Java is a Platform-Independent
When Java program is compiled; it produces a special format called byte
code and not executable code. Java bytecode is executed by Java run-time
system, which is called Java Virtual Machine. In its standard form, JVM is an
interpreter for bytecode. Java bytecode is exactly the same on every
platform. Only JVM needs to be implemented on every machine. Thus details
of JVM differ from platform to platform. The interpreter reads the byte code
and translates it into the native language of the host machine on the fly.
Since the byte code is completely platform independent, only the interpreter
and a few native libraries need to be ported to get Java to run on a new
computer or operating system. Thus due to JVM, Java becomes architecture
neutral.
Java is Multithreaded
Java is inherently multi-threaded. A single Java program can have many
different threads executing independently and continuously. Three Java
applets on the same page can run together with each getting equal time from
the CPU with very little extra effort on the part of the programmer.
To write the code you need a text editor. You can use any text editor like
Notepad, Brief, emacs or vi. You should not use a word processor like
Microsoft Word or WordPerfect since these save their files in a proprietary
format and not in pure ASCII text. If you absolutely must use one of these,
be sure to tell it to save your files as pure text. Generally this will require
using Save As... rather than Save.
By convention, the name of source file should be same as name of the class
which contains main. Java is case sensitive.
C:\>javac HelloWorld.java
The javac compiler creates a file called HelloWorld.class that contains the
bytecode version of the program.
To run the program, you must run the Java Interpreter, called java and pass
the class name HelloWorld, as shown here:
C:\>java HelloWorld
When java source code is compiled, each individual .class file is produced for
each class which contains its bytecode. So when you write java HelloWorld,
you are specifying the class file which interpreter needs to look for and
execute the code.
Let us look at several key features which are common to all Java programs.
/* This is a simple Java program*/
The argument passed as a parameter args to the main method are command
line arguments. It’s an array of Strings starting at args[0]. All parameters in
Java are passed by value that means a copy of variables is created and
passed.
Java provides a built-in static object, called System.out that performs output
to the standard output device. println prints the string followed by newline
character. System.out is an instance of java.io.PrintStream class.
Expressions
Expressions make use of literals explained above, variables and operators.
The Assignment Operator, the Dot Operator, Arithmetic Operator, Bitwise
Operator, Increment/Decrement Operator and Logical Operator are similar to
one in C++. Creating a new object involves the use of new operator.
Although, signature of method does not include the return type, Java does
not allow two methods with same signature to return different types.
Unlike C++, Java does not allow operator overloading.
String Concatenation
Strings can be composed using the concatenation operator (+).
e.g. String str1= “hello”;
String str2= “there”;
String str3=str1+str2;
would result into hellothere.
This shows how Java converts nonstring constants into strings, when they
are involved in a string concatenation operation.
Operator Precedence
multiplicative */%
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
conditional ?:
Casting in Expressions
Casting is an operation that allows us to change the type of a variable.
Casting from int to double can be done but casting from double to int results
into lost of precision. Such implicit casts are not performed in Java. As we
saw earlier, implicit casting is done only with string concatenation.
Decision statement (If and Switch) and loops (for-do, while-do, do-while) in
Java are similar to that of any other high level languages. break and continue
are also used similarly for restricted forms of jumps.
Arrays
Arrays in Java are similar to objects. It can be declared as follows:
int[ ] myArray;
myArray = new int[10];
int myArray[ ];
int[ ][ ] twiceTheArray;
twiceTheArray = new int[10][10];
Another Example
As we have learned basic concepts of Java above, let us look at an example
which deals with Files. This program takes 2 command line argument as
input, adds them and write the output to a file.
import java.io.*;
str= args[0]+args[1];
System.out.println("You entered:" + str );
FileWriter fout;
try {
fout= new FileWriter (fileName);
fout.write(str);
fout.flush();
} catch (FileNotFoundException e)
{
System.out.println("Output file can not be opened");
}
}
}
Here we have subclass A which inherits superclass B. Notice the use of java
keyword extends which signifies the inheritance. In the constructor of class
A, constructor of superclass is called. Remember that x, y, and z are private
in superclass.
Second form of super acts somewhat like this, except it always refers to the
superclass of subclass. e.g.
class A { int k; }
class B extends A {
int k;
B(int m, int n) {
super.k = m; //k in A
k = n; //k in B
}
}
super always refers to the superclass immediately above the calling class.
Dynamic dispatch
When a method in subclass has same name and type signature as a method
in superclass then method in subclass is called to override method in
superclass. Now when a overridden method is called from subclass, it always
refer to subclass version. Superclass method is hidden.
Dynamic method dispatch is the mechanism by which a call to overridden
methods is resolved at run-time. Using dynamic dispatch Java implements
run-time polymorphism. e.g.
class A {
void print() {
System.out.println (“I am within A”);
}
}
class B extends A {
void print() { //overridden print
System.out.println (“I am within B”);
}
}
class C extends A {
void print() { //overridden print
System.out.println (“I am within C”);
}
}
class Dispatch {
public static void main (String args[]) {
A a = new A(); //object of type A
B b = new B(); //object of type B
C c = new C(); //object of type C
A r; //reference of type A
r=b;
r.print();
r = c;
r.print()’
}
}
Java does not allow multiple inheritance for the sake of simplicity. Thus one
subclass can extend only one superclass. However. Multiple inheritance can
be implemented using interfaces about which we will learn below.
Abstract Class
Remember abstract class we talked above. Abstract class can be inherited by
another subclass. but it needs to implement all the methods in that interface
because some of the methods might not be implemented. This is the reason
that an abstract class can not be instantiated using new operator.
Interfaces
Interfaces must be public. Now a class can implement this interface the way
it wants. But that class must implement all the methods declared in the
interface. So general form will be:
class A implements Stack {…..}
or it can be class A extends B implements Stack {….}
However, one interface can extend as many interfaces it wants. This is how
multiple inheritance is achieved. e.g.
Public interface X extends Y, Z {….}
Here Y and Z are interfaces which are inherited by X.
Now class W can implement X so that it obtains methods of X, Y as well as Z.
Exception Handling
An exception is abnormal condition which occurs in code at run time. There
are errors about which we can not do except returning gracefully displaying
error message. But we can handle exception manually.
All exception types are subclass of the built in class Throwable. Exception is
subclass of Throwable. This class is used for exception conditions that user
programs should catch. Then subclass of Exception is RuntimeException.
Exceptions of this type are automatically defined for the programs that we
write and include things such as divide by zero and invalid array indexing.
Throwing exception
Exceptions can be generated by java run time system or can be manually
generated. Java exception is an object which is thrown in the method
caused an error. That method catches the exception or passes it on and
exception is handled. e.g. if we try to delete 10th element from array of 5
elements, the code may throw a BoundryViolationException as follows:
If (insertIndex () > size ()) {
throw new
BoundryViolationException (“no element at this index”);
Catching Exception
If an exception is to be handled in the method itself then we put the code of
method in try block and have control flow to jump to a predefined catch
block. After catch block, if finally block is not defined then control goes to
first statement after last line of the entire try-catch block. e.g.
If this code does not catch a thrown exception, the flow of control will exit
and go to the method that called this method. If it’s not catching this
exception then it will jump to part which called this code and so on.
Eventually, if no code catches exception, Java runtime exception catches
exception.
Applets
Applets are small applications that are accessed on internet server,
transported over the internet, automatically installed, and run as part of web
document.
A Simple Applet Example
import java.awt.*;
import java.applet.*;
<html>
<applet code ="Myapplet.class" width=300 height =100>
</applet>
</html>
Getting Java:
http://java.sun.com/j2se/1.4.2/download.html
Installing Java:
http://java.sun.com/j2se/1.5.0/install.htm
REFERENCES
The complete Reference Java2 by Herbert Schildt
Data Structures and Algorithms in Java by Goodrich and Tamassia
Appendix A
#include <iostream.h>
#include <string>
#include <time.h>
//Function Prototypes
int roll(int die, int numberRolls);
int main()
{
//variable declarations
char userContinueAnswer;
int randomIndex = 0;
int startCount = 0;
int newCount = 0;
string question;
string answer[6] = {"Yes","No","Try Again Later","Maybe","Most Definately"
,"Absolutely Not"};
if ( i < 7)
cout << ".\n";
else
cout << "The Magic Eight Ball Predicts:\n\n";
}
randomIndex = roll(6,1)-1;
cout << answer[randomIndex] << "\n\n";
cout << "Would you like to ask the eight ball another question?\n"
<< "(Y/N):";
cin >> userContinueAnswer;
system("PAUSE");
return 0;
}
return sum;
}
First we need to change the C++ library includes into Java import
statements:
Change: Into:
#include <iostream.h> import java.io.*;
#include <string> import java.util.*;
#include <time.h> import java.math.*;
Next, we need to make a class that will contain all of our functions
since we cannot have free standing functions in Java. Also main
needs an instantiation of the class in it.
Change: Into:
//Function Prototypes class Magic8BallGUI
int roll(int die, int numberRolls); {
final int numAnswers = 5;
int main()
{ public static void main(String[]
args)
{
Magic8BallGUI myBall;
myBall = new Magic8BallGUI();
Also we need to change the C++ type “string” into the java
equivalent “String.” Follow that by changing the cout statement into
a System.out.println call:
Change: Into:
string question; String question;
string answer[6] = {"Yes","No","Try String answer[6] = {"Yes","No","Try
Again Later","Maybe","Most Again Later","Maybe","Most
Definately" Definately"
,"Absolutely ,"Absolutely
Not"}; Not"};
From here on out, when you see a cout statement, replace it with a
System.out.println statement.
These lines are necessary in Java to get complex input from the command
line. The InputStreamReader “wraps” the System.in stream and then is
wrapped itself by the Buffered Reader. A Buffered Reader gives us access to
a large number of input functions that will make getting input easier. Trying
to read from a Buffered Reader can cause an exception, so Java code must
added to handle that. On the plus side, the Buffered Reader takes care of
many formatting issues, so the ignore statement or something similar is not
needed.
Change: Into:
cin >> question; try {question = bis.readLine();}
cin.ignore(2000,'\n'); catch( Exception e){ System.exit(0);
}
Next, we convert the C++ specific time call into Java time calls. Note
that Java allows you to directly call the System to get the current
time.
Change: Into:
startCount = clock(); startCount =
while( ((newCount-startCount) / System.currentTimeMillis();
CLOCKS_PER_SEC) < 1) while( ((newCount-startCount) /
{newCount = clock();} 1000) < 1)
{newCount =
System.currentTimeMillis();}
Next convert the C++ random function call into a Java random
function call. Both of these are function calls that are user created.
Change: Into:
randomIndex = roll(6,1)-1; randomIndex =
myBall.randomIndex(myBall.numAnswers);
Change: Into:
cin >> userContinueAnswer; try {userContinueAnswer=
(char)is.read();}
cout /*<< "\n: " << catch( Exception e){ System.exit(0); }
userContinueAnswer */<< "\n\n";
try {bis.readLine();} catch( Exception
} e)
{ System.exit(0); }
System.out.println(userContinueAnswer
+ "\n");
}
For our last modification we must change the C++ random function
into a Java random function. Notice that Java has built in functions
and objects for handling random number generation. This code goes
immediately after the code above and ends the class.
Change: Into:
System("PAUSE"); }//end of main
return 0;
} int randomIndex(int range)
{
if ( range <= 0 )
//This function will generate a random return 0;
number x, where start*numberRolls <=
x <= end*numberRolls Random generator = new
//Each die roll is treated as a seperate Random();
event. This gives us the correct return generator.nextInt(range);
probability curve.
//i.e. rolling a 10 or an 11 on 3d6 is }
more likely then a 3 or 18.
int roll(int die, int numberRolls)
{ }//end of class
int sum = 0;
return sum;
}
mport java.io.*;
import java.util.*;
import java.math.*;
class Magic8BallGUI
{
//varaible declarations
Magic8BallGUI myBall;
myBall = new Magic8BallGUI();
String answer[] = {"Yes","No","Try Again Later","Maybe","Most
Definately"
,"Absolutely Not"};
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader bis = new BufferedReader(is);
char userContinueAnswer = 'Y';
int randomIndex = 0;
long startCount = 0;
long newCount = 0;
String question;
System.out.println("Magic 8 Ball Program\n\n");
if ( i < 7)
System.out.println(".");
else
System.out.println("The Magic Eight Ball Predicts:\n");
}
randomIndex = myBall.randomIndex(myBall.numAnswers);
System.out.println(answer[randomIndex] + "\n");
System.out.println(userContinueAnswer + "\n");
if ( range <= 0 )
return 0;
Random generator = new Random();
return generator.nextInt(range);
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
Next, add these statements to your main function before any of the other
functions:
int response = 0;
myPane.setLayout(new FlowLayout());
myPane.add(myLabel);
myPane.add(myBar);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.add(myPane);
myFrame.pack();
The first statement once again sets the “look and feel” of the system to be as
much like the current OS as possible. The next four statements create the
GUI elements that we will be using to display our GUI. Finally, we add the
GUI elements to a pane, and then place the pane inside the frame; like a
pane of glass inside a window frame. Finally we “pack” the frame to make it
ready for display by the JVM.
The rest of the main function has radically shrunk and changed due to the
GUI so just copy and paste this code to replace the while loop and the code
following the while loop in the main function.
while( response == 0 )
{
myFrame.setVisible(true);
myFrame.setVisible(false);
randomIndex = myBall.randomIndex(myBall.numAnswers);
JOptionPane.showMessageDialog(null,answer[randomIndex]);
response = JOptionPane.showConfirmDialog(null,"Would you like to ask
the Magic 8 Ball Another Question?" ,"Another
Fortune?",JOptionPane.YES_NO_OPTION
,JOptionPane.QUESTION_MESSAGE);
}
System.exit(0);
} // end of main
Save, compile, and run. Notice that with a GUI the program has shrunk
considerably and it looks much better. Also Note that the
JOptionPane.ShowMessageDialog function call can be done without being
predeclared. It also shows the window that asks whether the user would like
to continue along with an option for yes or no. If the user selects “Yes” the
dialog returns 0, and if the user selects “No” it returns 1.
Appendix B
The idea behind this program is to show how a simple event can be
processed using Swing, as well as showing how Swing’s built in graphical
interfaces make your life much easier.
Below is the code for the file “fileScroll.java” which has been provided for
you. Compile and run the program to get a feel for how it works.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//Main
public static void main(String ar[]){
JFrame f=new fileScroll();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(640,400);
f.setVisible(true);
}
//Constructor
fileScroll()
{
//Take advantage of the JFrame constructor
super("File Viewer");
try{UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName() );}
catch( Exception e){System.exit(0);}
try{
//Initialize Elements
Container c=getContentPane();
JPanel p1=new JPanel();
p1.add(bt01);
p1.add(myText);
c.add(p1);
}
catch ( Exception e) {}
}
if(ae.getActionCommand()=="Open")
{
int fd=fc.showOpenDialog(fileScroll.this);
if(fd==JFileChooser.APPROVE_OPTION)
{
int count = 0;
boolean eof = false;
String text = "";
String line = "";
File myFile = fc.getSelectedFile();
BufferedReader myReader = new BufferedReader(new
FileReader(myFile.getPath() ) );
while(!eof)
{
line = myReader.readLine();
if (line == null || count == 18)
eof = true;
else
{
count++;
if ( line.length() < 59)
text = text + line + '\n';
else
text = text + line.substring(0,39) + '\n';
}
}
myText.setText(text);
}
}
}
catch(Exception ex){}
}
}
The first thing to notice is that the fileScroll class extends (inherits from)
JFrame and implements the ActionListener interface. This gives this class a
JFrame GUI for free and the blueprint for adding GUI “events”.
Next, notice the call of super(“File Viewer”) in the class’s constructor. This
calls the super class’s constructor, or in other words JFrame’s constructor.
This means that everything we need to do in our constructor is already done
in JFrame’s constructor, so we call its constructor rather then duplicating the
code.
These lines:
bt01.setMnemonic('O');
bt01.setActionCommand("Open");
bt01.addActionListener(this);
Set up three things on the JButton bt01. The setMnemonic command allows
users to press Alt-O to activate the button. The setActionCommand sets the
event generated by this button being pressed to “Open”. Finally the
addActionListener(this) command adds an action listener to the button that
“listens” for events.
If the user did not hit the “Cancel” button in the JFileChooser screen, a call is
made to fc.getSelectedFile() which returns a File object that represents the
file the user chose in the JFileChooser. A few lines later we create a
FileReader wrapped by a BufferedReader to get input from the file. The call
myFile.getPath() is very useful because it handles returning a file path string
that will work in the given operating system.
Appendix C
/*
* Created on Apr 4, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
/**
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
try
{
//from
mess.setFrom(new InternetAddress(from));
//to and CC
InternetAddress toAddr = new InternetAddress(recipient);
InternetAddress ccAddr = new InternetAddress(cc);
mess.addRecipient(Message.RecipientType.TO, toAddr);
mess.addRecipient(Message.RecipientType.CC, ccAddr);
//subject
mess.setSubject(subject);
//message body
mess.setText(body);
//this command actually sends the message using the Transport Layer in
//a network model
Transport.send(mess);
}
catch( Exception e)
{ e.printStackTrace(); System.exit(0); }
This program has many things going on in it, but first we will compile and run
the program. Make two modifications before this, change the cc and
recipient strings to your personal txstate e-mail address. Run the program,
and then check your e-mail. If this program will not compile, make sure that
you have installed Enterprise Java on your system because JavaMail requires
Enterprise Java libraries.
The first object that is created in the program is a session. This is analogous
to an internet session if you have done internet programming. It keeps track
of all the information related to your connection to the internet.
Next we create a properties object and add our mail host to the properties.
This mail host is where we will be sending our message so it can be
forwarded for delivery. Our session will use this property to route our e-mail.
We create a message object next that uses our session object to create a
message of the default mime type. After initializing the message with data
about the recipient, the sender, etc… we send the message to the TCP/IP
transport using the Transport.send(mess) call.