New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here


by: Devyn Shanahan


Devyn Shanahan
Texas State
GPA 3.53


Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Class Notes
25 ?




Popular in Course

Popular in ComputerScienence

This 30 page Class Notes was uploaded by Devyn Shanahan on Wednesday September 23, 2015. The Class Notes belongs to CS 2308 at Texas State University taught by Staff in Fall. Since its upload, it has received 31 views. For similar materials see /class/212822/cs-2308-texas-state-university in ComputerScienence at Texas State University.

Similar to CS 2308 at Texas State

Popular in ComputerScienence




Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 09/23/15
Introduction to JAVA This tutorial is not designed to teach a programming language or how to program in Java but is intended to provide an introduction to Java and get familiar with basic concepts of Java This tutorial assumes that you have taken computer science classes through CS 2308 or have equivalent experience Knowledge of any high level language and object oriented design will also be extremely helpful TABLE OF CONTENTS INTRODUCTION 3 KEY DIFFERENCES BETWEEN C AND JAVA 3 A FIRST SIMPLE PROGRAM A CLOSER LOOK AT PROGRAM DATA TYPES AND VARIABLES Expnpqqrnuq CONTROL FLOW 4 5 6 7 9 INHERITANCE AND POLYMORPH ISM PACKAGES AN D INTERFACES EXCEPTION HANDLI NG APPLETS USEFUL LINKS FOR JAVA39 REF FS APPENDIX A CONVERTING C MAGIC 8 BALL TO JAVA WITH A GUI APPENDIX B EASIER LIFE THROUGH SWING JFTI FPHOOSFR APPENDIX C JAVAMAIL WRITING A SIMPLE EMAIL PROGRAM Introduction Java is a highlevel 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 Key Differences between C and Java No pointers Just references Java has references but there are no pointers This basically means there is no way for you to directly access the memory that has been reserved for an object except through the use of the object or primitive itself It is possible to have multiple objects of the same type referencing the same memory In C it is possible to have multiple object and primitive pointers pointing at the same block of memory and for each to operate on it in a different way Java is ObjectOriented 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 PlatformIndependent When Java program is compiled it produces a special format called byte code and not executable code Java bytecode is executed by Java runtime 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 safe and simple Java was designed from the ground up to allow for secure execution of code across a network even when the source of that code was not trusted and possibly malicious Furthermore Java has strong typing Variables must be declared and variables do not change types when you aren39t looking Casts are strictly limited to casts between types when you are not loosing data Thus you can cast an int to a long but not an int to a String Java implements a robust exception handling mechanism to deal with both expected and unexpected errors The worst that an applet can do to a host system is bringing down the runtime environment It cannot bring down the entire system Most importantly Java applets can be executed in an environment that prohibits them from introducing viruses deleting or modifying files or otherwise destroying data and crashing the host computer A Java enabled web browser checks the byte codes of an applet to verify that it doesn39t do anything nasty before it will run the applet The biggest security issue in computing today is bugs Java by making it easier to write bugfree code substantially improves the security of all kinds of programs Java is Multithreaded Java is inherently multithreaded 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 Java has Garbage Collector One of the most difficult tasks in C is keeping track of objects and then deleting those to free up memory and prevent data leaks In Java there is no delete command because Java does memory garbage collection for free when objects are no longer referenced There is a slight performance decrease associated with this service but it greatly aides in providing reliable crash free programs There are constructors and these do allocate memory on the heap but this is transparent to the programmer Use of try and catch mandatory For the most severe and common errors in Java the use of catch and try is mandatory It is built into Java s grammar that these error checking precautions must be present or else your program will not compile In C catch and try are also available but are not mandatory A First Simple Program Let s start by compiling and running the short sample program This is a simple Java program class HelloWorld public static void main String args SystemoutprintnquotHelo Worldquot 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 Compiling the program To compile the program execute the compiler javac specifying the name of the source file on the command line as shown here Cgtjavac HelloWorldjava The javac compiler creates a file called HelloWorldclass 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 Cgtjava HelloWorld When the program is run following output is displayed Hello World 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 A closer look at Program Let us look at several key features which are common to all Java programs This is a simple Java program Java has 3 kinds of comments 0 As shown above multiple line comment using 0 Simple line or inline comment This is a simple Java program 0 Javadoc comment author param return This is a simple Java program Java can produce documentation if javadoc command is used It produces series of HTML document from collection ofjava source files that have been commented using certain tags eg author param etc This HTML document describes classes methods variables and constants contained in source files Then there is simple class keyword which can be preceded by abstract final or public 0 abstract class contains methods some of which are implemented and some are empty eg sort final class describes that a class have no subclasses public class can be used and instantiated by all classes in the same package main is a method in Java Using some of the modifiers as shown below scope of a method can be restricted 0 public anyone can call public method protected only methods in the same package or of subclasses can call protected method private only methods of the same class not methods of subclass can call a private method If none of above is used then the method can be called by objects of classes in the same package Some additional modifiers 0 Abstract a method declared as abstract will have no code and appears only in abstract class eg public abstract void setElement int i final final method can not be overridden by a subclass static static method is associated with a class itself and not with a particular instance of class So our main is associated with HelloWorld class only and it won t be associated with any of its instance e g HelloWorld hw create object hwmain 0 is not allowed Constructor method has same name as class It has no return value An abstract static or final constructor is not allowed The argument passed as a parameter args to the main method are command line arguments It s an array of Strings starting at args0 All parameters in Java are passed by value that means a copy of variables is created and passed Java provides a builtin static object called Systemout that performs output to the standard output device println prints the string followed by newline character Systemout is an instance ofjavaioPrintStream class Data types and variables Java is strongly typed language Every variable has a type every expression has a type and every type is strictly defined Java defines 8 simple types of data byte short int long float double char boolean Type Identi er Bits Values Character char 16 Unicode 20 8bit signed integer byte 8 128 to 127 Short signed integer short 16 2 bytes 32768 to 32767 Signed integer int 32 4 bytes 2 147483648 to 2147483647 Signed long integer long 64 8 bytes maximum of over 1018 Real number single precision float 32 4 bytes Maximum of over 1038 Real number double precision double 64 8 bytes Maximum of over 10308 Boolean bOOlean true or false Java variable is similar to C variable It is defined by the combination of an identifier a type and an optional initializer Strings are enclosed in double quotes eg Hello Expressions Expressions make use of literals explained above variables and operators The Assignment Operator the Dot Operator Arithmetic Operator Bitwise Operator IncrementDecrement 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 eg String str1 hello String str2 there String str3str1str2 would result into hellothere This shows how Java converts nonstring constants into strings when they are involved in a string concatenation operation Operator Precedence postfix operators expr expr unary operators eXpr eXpr eXpr eXpr multiplicative additive shift ltlt gtgt gtgtgt relational lt gt lt gt instanceof equality bitwise AND amp bitwise exclusive OR A bitwise inclusive OR logical AND ampamp logical OR conditional assignment amp A ltlt gtgt gtgtgt instanceof performs a test to see if a variable or object is the same type as a class of built in variable type The instanceof test returns true below because X is an integer eg int X if X instanceof int Systemoutprintln x is an integerlquot 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 Although explicit casting of an object or base type to a string is not allowed eg String s String 45 Not Allowed To perform such operation instead we may use toString method eg String s IntegertoString45 Control Flow Decision statement If and Switch and loops fordo whiledo dowhile in Java are similar to that of any other high level languages break and continue are also used similarly for restricted forms ofjumps Arrays Arrays in Java are similar to objects It can be declared as follows int myArray myArray new int10 int myArray int betterArray new int10 int nextArray 1 32 4 54 3 65 34 343 int twiceTheArray twiceTheArray new int1010 makeButtons new String quotBackquot quotNextquot 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 importjavaio public class Another public static void main String args throws IOException String fileName quotMyfiledatquot String str SystemoutprintnquotYou enteredquot argsO SystemoutprintnquotYou enteredquot args1 str args0args1 SystemoutprintnquotYou enteredquot str FileWriter fout try fout new FiIeWriter fileName foutwritestr foutflush catch FileNotFoundException e SystemoutprintlnquotOutput file can not be openedquot Explanation If we give 2 string input while running this program as input it will taken as argument 1 and argument 2 Data type of these arguments would be always string Notice here that sign is used as a concatenation As built in class FileWriter is used we need to import javaio package Object of FileWriter is created and concatenated string is written to file As FileWriter might throw an exception if file is not found we need to put it in trycatch block Inheritance and Polymorphism Inheritance is one of the cornerstones of Java A class that is inherited is called supercass and one that does inheriting is called subclass Subclass inherits all the variables and methods defined by supercass and add its own unique elements However subclass can not directly access the members of supercass which are declared as private Java s solution to this problem is the use of keyword super A subclass can call a constructor method in supercass by the use of super as follows super parameterlist Super must always be first statement executed inside subclass s constructor eg class A extends B int k A int x int y int 2 int w super x y 2 call supercass constructor km Here we have subclass A which inherits supercass B Notice the use of java keyword extends which signifies the inheritance In the constructor of class A constructor of supercass is called Remember that x y and z are private in supercass Second form of super acts somewhat like this except it always refers to the supercass of subclass eg class A int k class B extends A int k Bint m int n superk 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 runtime Using dynamic dispatch Java implements runtime polymorphism eg class A void print Systemoutprintln I am within A class B extends A void print overridden print Systemoutprintln I am within B class C extends A void print overridden print Systemoutprintln 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 a r refers to object of superclass A rprint rb rprint r c rprint Ouput of program will be I am within A I am within B I am within C Explanation when a superclass method is overridden and different types of objects are referred to through a superclass reference then java determines which method to execute at run time depending on the type of object referred to that time Overridden methods in java are similar to virtual functions in C 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 Packages and Interfaces Thejava language takes a general and useful approach to the organization of classes into programs Every public class is defined in separate file with extension java A set of all relevant classes all defined in a common subdirectory called a Package Every file in a package starts with the line package ltpackagenamegt Using Other Packages In java we can use classes that are defined in other packages using dot operator eg public boolean Temperature TAMeasuresThermometer thermometer int temp Here TA is package Measures is subpackage and Thermometer is class of this package As you can see as we come to low level in hierarchy we become specific The import command We can use import command similar to include command import ltPackagenamegtltcassnamegt We can import whole package as follows import ltpackagenamegt Thus in any file hierarchy of these declaration would be eg package student import TAMeasu res class MeasureTemp public boolean Temperature TAMeasuresThermometer thermometer int temp Interfaces Interface is just declaring prototype eg consider we want implement stack of interger objects public interface Stack public int size public boolean isempty public int top public void push public int pop Save this file as Stackjava 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 eg 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 2 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 eg if we try to delete 10th element from array of 5 elements the code may throw a BoundryViolationException as follows If insertIndex gt size 0 throw new BoundryViolationException no element at this index The throws clause When a method is declared it is appropriate to specify the exception it might throw It let Java compiler know which exception to prepare for eg public void insertIndex throws BoundryViolationException Thus this exception can be handled somewhere else and not necessarily catch in this methods only eg public class BoundryViolationException extends RuntimeException public BoundryViolationException String e super e Here this exception is handled by RuntimeException class 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 trycatch block eg int index IntegerMAXVALUE try String s maxindex catch BoundryViolationException bve Systemoutprintln the index index is outside of the array 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 importjavaawt import javaappet public class Myapplet extends Applet public void init initialize the applet SystemoutprintlnquotHello Swedenquot Closer look at Applet This applet begins with two import statements Applet interacts through the AWT Abstract Window Toolkit classes and not through consolbased IO classes AWT contains support for a windowbased graphical interface Another imports applet package which contains the class Applet All the applets created must be subclass of Applet To execute an applet in a web browser there need to be a HTML text file which contains the appropriate APPLET tag like shown below lthtmgt ltappet code quotMyappetcassquot width300 height 100gt ltappetgt lthtmgt Save it in file Myapplethtml init method is used to initialize the applet For applet you have 2 files Myappletjava and Myapplethtml Compile using javac Myappletjava This will create class file To view applet appletviewer Myapplethtml Notice that Applet does not have main method Java was designed to allow for secure platform independent software execution which is a big advantage in heterogeneous educational computing environments Java allows use of pointers but restricts potentially dangerous programming styles such as pointer arithmetic and arbitrary array indexing In addition Java provides protection at several layers such as use of private variables and methods It has an extensive collection of meaningfully named error conditions It has simple builtin mechanism for memory management and garbage collection Finally it contains simple constructs for various kinds of computing such as multiprocessing network computing and graphical user interfaces Useful Links for Java Sun s Java Homepage htt 39avasuncom Getting Java httpjava sun rnrnjzse142 I hfml Sun s Java Tutorial htt 39avasuncom docs books tutorial indexhtm Free Java Text Book Excellent Source htt mathhwsedu 39avanotes indexhtm Installing Java htt 39avasuncom 39Zse 150 instahtm REFERENCES The complete Reference Java2 by Herbert Schildt Data Structures and Algorithms in Java by Goodrich and Tamassia Appendix A Converting C Magic 8 Ball to Java with a GUI The idea behind this program is to allow a person to ask the magic 8ball program a question and get one of the responses that you could get from a standard magic 8ba The C version of the code is displayed below include ltiostreamhgt include ltstringgt include lttimehgt using namespace std Function Prototypes int roint die int numberRoIIs int main variabe declarations char userContinueAnswer int randomIndex 0 int startCount 0 int newCount 0 string question string answer6 quotYesquotquotNoquotquotTry Again LaterquotquotMaybequotquotMost Definatelyquot quotAbsolutely Notquot cout ltlt quotMagic 8 Ball Programnnquot whie userContinueAnswer 39N39 ampamp userContinueAnswer 39n39 cout ltlt quotEnter the question you want to ask the magic 8 ball belownnquot cin gtgt question cinignore200039n39 cout ltlt quotnThe magic 8 ball is consideringnquot forint i 0 i lt 8 i startCount clock whie newCountstartCount CLOCKSPERSEC lt 1 newCount clock if i lt 7 cout ltlt quotnquot ese cout ltlt quotThe Magic Eight Ball Predictsnnquot randomIndex ro611 cout ltlt answerrandomIndex ltlt quotnnquot cout ltlt quotWould you like to ask the eight ball another questionnquot ltlt quotYNquot cin gt gt userContinueAnswer cout ltlt quotn quot ltlt userContinueAnswer ltlt quotnnquot systemquotPAUSEquot return 0 This function will generate a random number x where startnumberRos lt x lt endnumberRoIs Each die roll is treated as a separate event This gives us the correct probability curve ie rolling a 10 or an 11 on 3d6 is more likely then a 3 or 18 int rollint die int numberRoIIs int sum 0 for int i 0 i lt numberRoIIs i sum sum intdoubleranddoubleRANDMAX1die1 return sum The first step is to convert this program into an equivalent Java program First we need to change the C library includes into Java import statements Channn Into include ltiostreamhgt importjavaio include ltstringgt importjavauti include lttimehgt importjavamath using namespace std 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 Channn Into Function Prototypes class Magic8BallGUI int rollint die int numberRoIIs final int numAnswers 5 int main public static void mainString args Magic8BallGUI myBall myBall new Magic8BallGUI I Also we need to change the C type string into the java equivalent String Follow that by changing the cout statement into a Systemoutprintln call Channn Into string question String question string answer6 quotYesquotquotNoquotquotTry String answer6 quotYesquotquotNoquotquotTry Again LaterquotquotMaybequotquotMost Again LaterquotquotMaybequotquotMost Definatelyquot Definatelyquot quotAbsolutely quotAbsolutely Notquot Notquot string quot String I quot cout ltlt quotMagic 8 Ball Programnnquot SystemoutprintlnquotMagic 8 Ball Programnnquot From here on out when you see a cout statement replace it with a Systemoutprintln statement Immediately following the Systemoutprintln statement add these lines InputStreamReader is new InputStreamReaderSystemin BufferedReader bis new BufferedReaderis These lines are necessary in Java to get complex input from the command line The InputStreamReader wraps the Systemin 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 Let use the Buffered Reader to get the user s question Change Into cin gtgt question try question bisreadLine cinignore200039n39 catch Exception e Systemexit0 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 Channn Into startCount cock startCount whie newCountstartCount SystemcurrentTimeMiIIis CLOCKSPERSEC lt 1 while newCountstartCount newCount clock 1000 lt 1 newCount SystemcurrentTimeMiis Next convert the C random function call into a Java random function call Both of these are function calls that are user created Channn Into randomIndex ro611 randomIndex myBarandomIndexmyBanumAnswers Next we need to change how we get the user s response as to whether they wish to continue or not The first character is read to get the user s response and then a line is read to clear out the input 1 buffer T 3 these the while loop ends Channn Into cin gtgt userContinueAnswer try userContinueAnswer charisread cout ltlt quotn quot ltlt catch Exception e Systemexit0 userContinueAnswer ltlt quotnnquot try bisreadLine catch Exception e Systemexit0 SystemoutprintnuserContinueAnswer 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 Channn Into SystemquotPAUSEquot end of main return 0 int randomIndexint range if range lt 0 This function will generate a random return 0 number x where startnumberRoIs lt x lt endnumberRoIs Random generator new Each die roll is treated as a seperate Random event This gives us the correct return generatornextIntrange probability curve ie rolling a 10 or an 11 on 3d6 is more likely then a 3 or 18 int rollint die int numberRoIIs end of class int sum 0 for int i 0 i lt numberRolls i sum sum intdoubleranddoubleRANDMA X1die1 return sum Save this file as Magic8BallGUIjava Compile and execute the program Your code should look something like the listing below mportjavaio importjavautil importjavamath class Magic8BallGUI final int numAnswers 5 public static void mainString args varaible declarations Magic8BallGUI myBall myBall new Magic8BallGUI String answer quotYesquotquotNoquotquotTry Again LaterquotquotMaybequotquotMost Definatelyquot quotAbsolutely Notquot InputStreamReader is new InputStreamReaderSystemin BufferedReader bis new BufferedReaderis char userContinueAnswer 39Y39 int randomIndex 0 long startCount 0 long newCount 0 String question SystemoutprintnquotMagic 8 Ball Programnnquot whie userContinueAnswer 39N39 ampamp userContinueAnswer 39n39 SystemoutprintlnquotEnter the question you want to ask the magic 8 ball belownnquot try question bisreadLine catch Exception e Systemexit0 SystemoutprintnquotnThe magic 8 ball is consideringquot forint i 0 i lt 8 i startCount SystemcurrentTimeMiIIis whie newCountstartCount 1000 lt 1 newCount SystemcurrentTimeMiis if i lt 7 Systemoutprintnquotquot ese SystemoutprintnquotThe Magic Eight Ball Predictsnquot randomIndex myBaIIrandomIndexmyBaInumAnswers SystemoutprintnanswerrandomIndex quotnquot SystemoutprintlnquotWould you like to ask the eight ball another questionquot SystemoutprintquotYN quot try userContinueAnswer charisread catch Exception e Systemexit0 try bisreadLine catch Exception e Systemexit0 System outprintn userContinueAnswer quotnquot int randomIndexint range if range lt 0 return 0 Random generator new Random return generatornextIntrange To finish this program off we would like to make use of Java s extensive GUI capabilities to handle all user input and system output Add these statements to your imports import javaxswing importjavaawt import javaawtevent Next add these statements to your main function before any of the other functions int response 0 Setup GUI Options tryUIManagersetLookAndFeel UIManagergetSystemLookAndFeelClassName catch Exception eSystemexit0 JFrame myFrame new JFrame JPanel myPane new JPanel JProgressBar myBar new JProgressBar020000000 JLabel myLabel new JLabelquotThe eight ball is carefully considering your questionquot myPanesetLayoutnew FowLayout myPaneaddmyLa bel myPaneaddmyBa r myFramesetDefaultCloseOperationJ FrameEXITONCLOSE myFrameaddmyPa ne myFramepack 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 JOptionPaneshowMessageDialognullquotWelcome to the Magic Eight Ball Programquot JOptionPaneshowInputDialognullquotPlease enter your questionquotquotMagic 8 BaquotJOptionPaneQUESTIONMESSAGE myFramesetVisibletru e forint i 0 i lt 20000000 i myBarsetValuei myFramesetVisiblefase randomIndex myBallrandomIndexmyBallnumAnswers JOptionPaneshowMessageDialognullanswerrandomIndex response JOptionPaneshowConfirmDialognuquotWould you like to ask the Magic 8 Ball Another Questionquot quotAnother FortunequotJOptionPaneYESNOOPTION JOptionPaneQUESTIONMESSAGE Systemexit0 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 JOptionPaneShowMessageDialog 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 Easier Life through Swing JFileChooser 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 fileScrolljava which has been provided for you Compile and run the program to get a feel for how it works importjavaio importjavaawt import javaawtevent import javaxswing public class fileScroll extends JFrame implements ActionListener these GUI elments declared globally for the class JTextArea myText JFileChooser fc JButton bt01 Main public static void mainString ar JFrame fnew fileScroll fsetDefaultCloseOperationJFrameEXITONCLOSE fsetSize640400 fsetVisibletrue Constructor fileScroll Take advantage of the JFrame constructor superquotFie Viewerquot Setup GUI Options tryUIManagersetLookAndFeel UIManagergetSystemLookAndFeelClassName catch Exception eSystemexit0 decare GUI elements try Initialize Elements myText new JTextArea1860 myTextsetTextquotNo file selectedquot fcnew JFileChooser bt01new JButtonquotOpen File to Viewquot bt01setMnemonic39O39 bt01setActionCommandquotOpenquot bt01 addActionListenerth is Container cgetContentPane JPanel p1new JPaneI p1addbt01 p1addmyText caddp1 catch Exception e public void actionPerformedActionEvent ae try ifaegetActionCommand quotOpenquot int fdfcshowOpenDialogfileScrollthis iffd JFiIeChooserAPPROVEOPTION int count 0 boolean eof false String text String line File myFile fcgetSelectedFile BufferedReader myReader new BufferedReadernew FileReadermyFilegetPath whileeof line myReaderreadLine if line null count 18 eof true else count if lineength lt 59 text text line 39n39 else text text linesubstring039 39n39 myTextsetTexttext 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 Also important is the fcnew JFileChooser line The JFileChooser graphical element is entirely responsible for the file browsing window that appears in the program when you want to choose a file This saves you a tremendous amount of work These lines bt01setMnemonic39O39 bt01setActionComma ndquotOpenquot bt01addAction Listenerthis Set up three things on the JButton thl The setMnemonic command allows users to press AltO to activate the button The setActionCommand sets the event generated by this button being pressed to Open Finally the addActionListenerthis command adds an action listener to the button that listens for events This brings us to the actionPerformed function which processes eventssignals and performs actions based on what signal it received It catches the Open signal and immediately opens the JFileChooser that we created earlier If the user did not hit the Cancel button in the JFileChooser screen a call is made to fcgetSelectedFile 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 myFilegetPath is very useful because it handles returning a file path string that will work in the given operating system Appendix C JAVAMAIL Writing a simple email program This program allows you to send email via the Javamail libraries The code listed below is contained in the file emaijava 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 importjavaio importjavauti importjavaxmai importjavaxmaiinternet public class email String from quoth1037txstatecomquot String recipient quotnutxstatecomquot String subject quotWe want youquot String cc quotnull2txstateeduquot String body quotEat More Puddingquot The session object keeps track of information about your current connection Session mySession The message object is a JavaMail Message Object the provides email functionality Message mess public void SendMessage set properties to send the mail Properties prop new Properties propputquotmaitxstateeduquotquotmailhostquot get a session with defaults and verbose output mySession SessiongetDefaultInstancepropnull mySessionsetDebugtrue try create the message using our newly created session mess new MimeMessagemySession Only InternetAddress Objects can be using in messsages so we need to incapsulate the strings we made eariler from messsetFromnew InternetAddressfrom to and CC InternetAddress toAddr new InternetAddressrecipient InternetAddress ccAddr new InternetAddresscc messaddRecipientMessageRecipientTypeTO toAddr messaddRecipientMessageRecipientTypeCC ccAddr subject messsetSu bjectsu bject message body messsetTextbody this command actually sends the message using the Transport Layer in a network model Transportsendmess catch Exception e eprintStackTrace Systemexit0 public void addOn forint i 0 i lt 100 i body body quot Join Today Eat More Pudding quot public static void mainString args email myEmail new email myEmailaddOn myEmailSendMessage 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 email address Run the program and then check your email 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 email 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 TCPIP transport using the Transportsendmess call


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

Anthony Lee UC Santa Barbara

"I bought an awesome study guide, which helped me get an A in my Math 34B class this quarter!"

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.