36
Java Programming CIS 421 CIS 421 Web-Based Java Web-Based Java Programming Programming

Java Programming CIS 421 Web-Based Java Programming

Embed Size (px)

Citation preview

Page 1: Java Programming CIS 421 Web-Based Java Programming

Java ProgrammingJava Programming

CIS 421CIS 421

Web-Based Java ProgrammingWeb-Based Java Programming

Page 2: Java Programming CIS 421 Web-Based Java Programming

Course TextCourse Text

Text:Text:Computing with Java:

Programs, Objects, Graphics

Alternate 2nd Edition

Art GittlemanArt Gittleman

Scott Jones Publishers Scott Jones Publishers

ISBN: 1-57676-074-XISBN: 1-57676-074-X

Page 3: Java Programming CIS 421 Web-Based Java Programming

Prerequsites, Tests, Public areaPrerequsites, Tests, Public area

Prerequisites: Cis237, Mat 126, and QPA of 2.90

Tests: Two midterms, one final. Public directory: /export/home/public/spiegel/cis421

Page 4: Java Programming CIS 421 Web-Based Java Programming

Turnin scriptTurnin script

Programming Projects are submitted electronically Programming Projects are submitted electronically using turnin scriptusing turnin script

See turnin handoutSee turnin handout Must setup turnin onceMust setup turnin once To invoke:To invoke:

turnin421 <fileturnin421 <file11> <file> <file22> ....> .... each item submitted separated by whitespaceeach item submitted separated by whitespace no limit to # itemsno limit to # items You should receive a confirmation e-mail containing an You should receive a confirmation e-mail containing an

ls –l listing of files submitted (can include ls –l listing of files submitted (can include files files previously submitted)previously submitted)

Files submitted may be overwritten by subsequent turnin of files Files submitted may be overwritten by subsequent turnin of files with same namewith same name

Page 5: Java Programming CIS 421 Web-Based Java Programming

Overview of JavaOverview of Java

Java FeaturesJava Features How Java WorksHow Java Works Applications vs AppletsApplications vs Applets Program-Driven vs Event DrivenProgram-Driven vs Event Driven Graphical User Interfaces (GUI)Graphical User Interfaces (GUI)

Page 6: Java Programming CIS 421 Web-Based Java Programming

Java FeaturesJava Features

Simple, Object-Oriented, FamiliarSimple, Object-Oriented, Familiar Robust and SecureRobust and Secure Architecture Neutral and PortableArchitecture Neutral and Portable High PerformanceHigh Performance Interpreted, Threaded, and DynamicInterpreted, Threaded, and Dynamic

Page 7: Java Programming CIS 421 Web-Based Java Programming

Simple, OO, FamiliarSimple, OO, Familiar

Its simplicity comes from the fact that there are Its simplicity comes from the fact that there are no pointers in Java. Therefore, the no pointers in Java. Therefore, the programmer does not have to manage pointers programmer does not have to manage pointers and the resultant problems that pointers bring.and the resultant problems that pointers bring.

All programs in Java are based on objectsAll programs in Java are based on objects Java uses the familiar syntax and fundamental Java uses the familiar syntax and fundamental

control structures of C/C++control structures of C/C++

Page 8: Java Programming CIS 421 Web-Based Java Programming

Robust and SecureRobust and Secure

Robust programs run without crashing due to Robust programs run without crashing due to programming errors, erroneous input, or programming errors, erroneous input, or failure of external devices. Java has many failure of external devices. Java has many checks at compile-time and provides run-time checks at compile-time and provides run-time exception handling to deal with unexpected exception handling to deal with unexpected events.events.

Security, especially across the internet, requires Security, especially across the internet, requires careful measures, which are implemented in careful measures, which are implemented in Java Java

Page 9: Java Programming CIS 421 Web-Based Java Programming

Architecture Neutral and Portable

Architecture Neutral and Portable

Java programs run on a variety of Java programs run on a variety of processors using various operating processors using various operating systemssystems

Portability depends not only on Portability depends not only on architecture but also on implementation. architecture but also on implementation. Java specifies the language carefully to Java specifies the language carefully to reduce implementation dependencies. reduce implementation dependencies.

Page 10: Java Programming CIS 421 Web-Based Java Programming

High PerformanceHigh Performance

Java versions continually increase Java versions continually increase performance capabilities.performance capabilities.

In network applications, communication In network applications, communication delays usually far exceed performance delays usually far exceed performance delays.delays.

Page 11: Java Programming CIS 421 Web-Based Java Programming

Interpreted, Threaded, and Dynamic

Interpreted, Threaded, and Dynamic

Interpreted, not compiled.Interpreted, not compiled. Threaded – capable of multi_tasking and Threaded – capable of multi_tasking and

concurrent processing, even across the concurrent processing, even across the internetinternet

Dynamic linking to library code as it Dynamic linking to library code as it needs it.needs it.

Java is ideally suited for general, Java is ideally suited for general, interactive, and network programminginteractive, and network programming

Page 12: Java Programming CIS 421 Web-Based Java Programming

How Java WorksHow Java Works

JavaJavaSourceSourceCodeCode

JavaJavaCompilerCompiler

JavaJavaByteByteCodeCode

Java InterpreterJava InterpreterFor Processor 1For Processor 1

Java InterpreterJava InterpreterFor Processor 2For Processor 2

Page 13: Java Programming CIS 421 Web-Based Java Programming

Setting up Unix for JavaSetting up Unix for Java

Make a directory called Make a directory called java java in your home directory.in your home directory. Put this java directory in your CLASSPATH in .cshrc with the Put this java directory in your CLASSPATH in .cshrc with the

command (this is one long line)command (this is one long line)setenv CLASSPATH setenv CLASSPATH ““.:$home/java.:$home/java:whatever_is_there_already“:whatever_is_there_already“ this allows packages starting from your java subdirectorythis allows packages starting from your java subdirectory

Put the directory Put the directory /usr/j2sdk1.4.0_03/bin /usr/j2sdk1.4.0_03/bin in your path variable in your path variable in the .login file.in the .login file.

Give the commands Give the commands source .loginsource .login and and source .cshrcsource .cshrc to make the to make the changes effective.changes effective. These changes are applied automatically on subsequent loginsThese changes are applied automatically on subsequent logins

Page 14: Java Programming CIS 421 Web-Based Java Programming

Testing ChangesTesting Changes

acad > acad > java -versionjava -version

java version "1.4.0_03"java version "1.4.0_03"

Java(TM) 2 Runtime Environment, Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0_03-b04)Standard Edition (build 1.4.0_03-b04)

Java HotSpot(TM) Client VM (build Java HotSpot(TM) Client VM (build 1.4.0_03-b04, mixed mode)1.4.0_03-b04, mixed mode)

acad >acad >

Page 15: Java Programming CIS 421 Web-Based Java Programming

Applications vs AppletsApplications vs Applets

Applications run like programs written Applications run like programs written in other languages. They usually are in other languages. They usually are standalone, running at the command line.standalone, running at the command line.

Applets are usually small applications Applets are usually small applications that are embedded in a web-page and that are embedded in a web-page and run on the internet in a web browser.run on the internet in a web browser.

Page 16: Java Programming CIS 421 Web-Based Java Programming

Building an ApplicationBuilding an Application

Edit the source file either in your favorite editor, Edit the source file either in your favorite editor, or IDE, and save it as or IDE, and save it as <file>.java<file>.java

The file name must be the same as the one and The file name must be the same as the one and only public class name in the fileonly public class name in the file

Compile by giving the commandCompile by giving the command

javac <file>.javajavac <file>.java

at the command line of a DOS or Unix window.at the command line of a DOS or Unix window. Run the program by giving the commandRun the program by giving the command

java <file>java <file>

Page 17: Java Programming CIS 421 Web-Based Java Programming

hello.javahello.java

// File: hello.java// File: hello.java

// Compiler: Sun javac// Compiler: Sun javac

// Compile: javac hello.java// Compile: javac hello.java

// Executable: hello.class// Executable: hello.class

// Execute: java hello// Execute: java hello

////

// Purpose: Prints usual first // Purpose: Prints usual first

// program// program

Page 18: Java Programming CIS 421 Web-Based Java Programming

hello.javahello.java

public class public class hellohello{{ public static void mainpublic static void main(String[] args)(String[] args) {{ int x = 3;int x = 3; System.out.println(“Hello, World!” +System.out.println(“Hello, World!” + “ “\nx = “ + (x) );\nx = “ + (x) ); }}}}

Page 19: Java Programming CIS 421 Web-Based Java Programming

Application ProgramsApplication Programs

The file name must be the same as the The file name must be the same as the one and only public class in the file.one and only public class in the file.

This public class must have a static This public class must have a static method called main (Why static??)method called main (Why static??)public static void mainpublic static void main( String[] args)( String[] args){ { local declarations and statementslocal declarations and statements}}

Page 20: Java Programming CIS 421 Web-Based Java Programming

ExerciseExercise

Setup your Unix account to compile and run a Java Application program. Test it with the HelloWorld program hello.java. The example is in the java/hello subdirectory

in the instructor’s public area

Page 21: Java Programming CIS 421 Web-Based Java Programming

Basic Java Programming Basic Java Programming

The C/C++ componentThe C/C++ component Comments – C/C++ styleComments – C/C++ style Identifiers and keywordsIdentifiers and keywords Types, variables, expressionsTypes, variables, expressions Control structuresControl structures FunctionsFunctions

System outputSystem output Console inputConsole input PackagesPackages

Page 22: Java Programming CIS 421 Web-Based Java Programming

Identifiers and KeywordsIdentifiers and Keywords

A Java identifier must start with a letter, followed by 0 or A Java identifier must start with a letter, followed by 0 or more letters and/or digits. Java is case-sensitive.more letters and/or digits. Java is case-sensitive.

Keywords cannot be used as user-identifiers. See text for a Keywords cannot be used as user-identifiers. See text for a list of keywords.list of keywords.

Style – recommended & preferred; consistency is a must!Style – recommended & preferred; consistency is a must! Class names begin with a capital letterClass names begin with a capital letter Variable names begin with a lower case letterVariable names begin with a lower case letter Function names begin with a verb which is lowercased.Function names begin with a verb which is lowercased. Constants are all upper case.Constants are all upper case. Multiple word names are lower case except for the beginning of each Multiple word names are lower case except for the beginning of each

word componentword component..

Page 23: Java Programming CIS 421 Web-Based Java Programming

ExamplesExamples

Request Request would be a class name would be a class name myRequestmyRequest would be a variable name would be a variable name getRequest()getRequest() would be a function would be a function

(method) name(method) name THE_REQUESTTHE_REQUEST would be a constant. would be a constant. The Java standard style convention The Java standard style convention

should be followed in our programming.should be followed in our programming.

Page 24: Java Programming CIS 421 Web-Based Java Programming

Standard TypesStandard Types

charchar – ascii or unicode – ascii or unicode booleanboolean – true or false – true or false Numerical types – various sizes of Numerical types – various sizes of

numbersnumbers

Page 25: Java Programming CIS 421 Web-Based Java Programming

Numerical TypesNumerical Types

Standard numerical types in Java areStandard numerical types in Java aretypetype sizesize least valueleast value greatest valuegreatest value________________________________________ ________________________________________ bytebyte 88 -128-128 127127shortshort 1616 -32768-32768 3276732767intint 3232 -2147483648-2147483648 21474836472147483647longlong 6464 -2-26363 226363-1-1float*float* 3232 ~ -3.4 x 10~ -3.4 x 103838 ~ 3.4 x 10~ 3.4 x 103838

double* double* 6464 ~ -1.7 x 10~ -1.7 x 10308308 ~ 1.7 x 10~ 1.7 x 10308308

* 7 and 15 digit accuracy respectively* 7 and 15 digit accuracy respectively

Page 26: Java Programming CIS 421 Web-Based Java Programming

Variables and ExpressionsVariables and Expressions

Java follows the syntax of C/C++ for Java follows the syntax of C/C++ for expressions and assignment.expressions and assignment.

The operators for the standard types are The operators for the standard types are the same as those for C/C++the same as those for C/C++

Remember that = is assignment andRemember that = is assignment and== is equal relational operator.== is equal relational operator.

You should NOT use = in a cascading You should NOT use = in a cascading manner.manner.

Page 27: Java Programming CIS 421 Web-Based Java Programming

Control StructuresControl Structures

The control structures are the same as C/C++The control structures are the same as C/C++ ifif switchswitch forfor whilewhile do – whiledo – while

Note: unlike C/C++, where the expression can Note: unlike C/C++, where the expression can evaluate to int, evaluate to int, the test expression MUST be of the test expression MUST be of type booleantype boolean

Page 28: Java Programming CIS 421 Web-Based Java Programming

Functions (Methods)Functions (Methods)

In Java there are no independent functions In Java there are no independent functions A function (method) is always a member A function (method) is always a member

function of some class.function of some class. The syntax is very similar.The syntax is very similar.

modifier(s) resulttype name( <params>)modifier(s) resulttype name( <params>)

{ { local declarationslocal declarations and statementsand statements }} // the modifier is // the modifier is publicpublic, , privateprivate, or , or protectedprotected, and can also , and can also

be prefaced be prefaced staticstatic

Page 29: Java Programming CIS 421 Web-Based Java Programming

System OutputSystem Output

Output is generated by using streams. The Output is generated by using streams. The stream classes are defined in the standard Java stream classes are defined in the standard Java package package java.iojava.io. .

The class The class SystemSystem in the package in the package java.langjava.lang contains three different streams for use in Java contains three different streams for use in Java programs:programs:

System.inSystem.in the keyboardthe keyboardSystem.outSystem.out the screenthe screenSystem.errSystem.err the screenthe screen

System.out.println( any string)System.out.println( any string)

Page 30: Java Programming CIS 421 Web-Based Java Programming

Examples of OutputExamples of Output

To print an object, the object should have To print an object, the object should have overloaded the method overloaded the method toString toString that is that is inherited from the Class Object.inherited from the Class Object.

Standard types have this method.Standard types have this method. System.out.println(“The value of x = “ + x );System.out.println(“The value of x = “ + x ); The + is the concatenation operator for The + is the concatenation operator for

strings.strings.

Page 31: Java Programming CIS 421 Web-Based Java Programming

System InputSystem Input

System input is quite complicated, so many System input is quite complicated, so many authors provide a package of IO functions for authors provide a package of IO functions for the standard types.the standard types.

We prefer to avoid these. A class InputReader We prefer to avoid these. A class InputReader is in the public java directory for text input.is in the public java directory for text input.

More fundamental IO will be discussed laterMore fundamental IO will be discussed later Java is made for GUIs, particularly components Java is made for GUIs, particularly components

such as TextFields, Menus. etc;such as TextFields, Menus. etc;

Page 32: Java Programming CIS 421 Web-Based Java Programming

Examples of inputExamples of input

helloYou.javahelloYou.java helloInt.javahelloInt.java

java/hello directory in public areajava/hello directory in public area

Page 33: Java Programming CIS 421 Web-Based Java Programming

Things that are differentThings that are different

String concatenation is the operator + String concatenation is the operator + It takes two operands which are It takes two operands which are

“stringable”, that is any operand that is a “stringable”, that is any operand that is a string or has the toString method string or has the toString method overloaded for that type.overloaded for that type.

System.out.println(76 + “trombones”);System.out.println(76 + “trombones”);

Page 34: Java Programming CIS 421 Web-Based Java Programming

PackagesPackages

Java organizes code into packages which Java organizes code into packages which correspond to directories in the file system.correspond to directories in the file system.

Each Java class is contained in a package.Each Java class is contained in a package. The default package is The default package is .. (the current (the current

directorydirectory)) The System class is found in java.langThe System class is found in java.lang The Applet class is found in java.appletThe Applet class is found in java.applet

Page 35: Java Programming CIS 421 Web-Based Java Programming

CommentsComments

When calling methods of the same class, we When calling methods of the same class, we do not need to use the class name as a do not need to use the class name as a prefix.prefix.

When calling methods of another class, we When calling methods of another class, we use the class name or object of that class as use the class name or object of that class as a prefix.a prefix.

Page 36: Java Programming CIS 421 Web-Based Java Programming

Objects Objects

Still declared as a classStill declared as a class No separate sectionsNo separate sections

Each declaration specified with accessEach declaration specified with access public, private, protectedpublic, private, protected

static declarations part of class, but not static declarations part of class, but not objectobject

non-static declarations part of instantiated non-static declarations part of instantiated objects onlyobjects only