CS 4812: Java - PowerPoint PPT Presentation

1 / 50
About This Presentation
Title:

CS 4812: Java

Description:

In Java, one must focus on the application and methods to manipulate data ... Java is simple--no pointers/stack concerns (for the most part) ... – PowerPoint PPT presentation

Number of Views:97
Avg rating:3.0/5.0
Slides: 51
Provided by: davidd1
Category:
Tags: java

less

Transcript and Presenter's Notes

Title: CS 4812: Java


1
CS 4812 Java
  • Summer 1998
  • Lecture 0
  • the null lecture

2
Welcome(Well, come . . .)
  • CS 4812 An course in advanced Java
  • Where does CS 4812 fit in to the overall CS
    curriculum?

3
The Role of CS4812
  • Three goals. Count em. Three

1. Develop Teaching Skills
  • Presentations

2. Develop Program Evaluation Skills
HOW?
  • Grading Programs

3. Develop Programming Skills
  • Coding Programs

All in Java(tm)
4
Heres the deal . . .
Grades
  • Dont worry about your grade.
  • Youll do just fine . . .
  • IF you
  • learn the material
  • write clean code
  • OR
  • are just damn good.

5
Grades You Decide
Gotta be 20-40
Sorry, 10 constant
You allocate weights among programs. YES, You
Decide! (Plan your quarter.)
6
The Troika o Code
  • Your programs include
  • A text-based, menu program to manipulate data for
    wire-frame objects (I/O and object serialization)
  • An applet/application for viewing 3D wire-frame
    models (graphics/events/threads)
  • An educational applet to teach CS1502 students
    about Java/Basic Programming

Good Design/Javadoc
O-O
Hack alert!
7
The Logic Behind CS4812
  • Students learn better when not focused on
    performance evaluation.
  • Access to good resources is key.
  • Letting people pursue their interests assures a
    quality return.

8
A Word on Text Books
  • Dont buy any new How-To Cookbooks
  • (JDK 1.2 is comin soon)
  • Drop 20.00 on the Nutshell, if youre full of
    cash. (Be sure to look for 2d edition.)
  • Get Bruce Eckels excellent online book
  • http//www.EckelObjects.com

9
A Word on IDEs
  • Use the latest JDK 1.1.x, currently 6.
  • Dont spend on a fancy IDE. It will be out of
    date soon.
  • Watch out for expensive upgrade policies, slow
    JDK support

Visual, smisual. Just use note pad
10
A Java Refresher
  • In the remaining time, lets review some Java
    basics.

Like, what is Java anyway . . .
11
Java What?
  • Sun describes Java as

"A simple, object-oriented, distributed,
interpreted, robust, secure, architecture
neutral, portable, high-performance,
multithreaded, and dynamic language"
What does that mean?
12
Object Oriented
  • In Java, one must focus on the application and
    methods to manipulate data
  • Less emphasis on procedures
  • Class system used a collection of data and
    methods
  • Objects instances of classes
  • Root class java.Object
  • 23 packages, or arrangements of classes
  • Never worked with packages before?

RTFM
13
Interpreted/Architecturally Neutral
  • A compiler used to generate byte-codes, not
    native binaries
  • JVM acts as interpreter for each platform
  • No "link" phase of code development, as in C/C
    (faster!)
  • Code is not merely portable but platform neutral

14
Dynamic/Distributed
  • Java is dynamic since classes can load at any
    point
  • Java is distributed, providing support for
    networking
  • java.net package
  • RMI (Remote Method Invocation)

15
Simple/Robust
  • Java is simple--no pointers/stack concerns (for
    the most part)
  • In-bound checking at runtime of array
    pointers--no memory corruption and cryptic error
    messages.
  • Exception handling try/catch/finally series
    allows for simplified error recovery

16
Secure
  • Byte-code verification on loading (not just
    compilation).
  • Applet code runs in 'sandbox', with significant
    restrictions on what it can do.
  • enforced by the SecurityManager class
  • Work-arounds for applet security restrictions
    include digitally signing code

17
Secure (cont'd)
  • Untrusted code cannot
  • Read files (except from host URL)
  • List Directories
  • Obtain file information (existence, size, date,
    etc.)
  • Write, Delete, Rename files or directories
  • Read or write from FileDescriptor objects
  • Listen/Accept on any privileged port
  • Call System.exit() or Runtime.ext()
  • Create new processes with Runtime.exec()
  • Start a print job, access clipboard or event queue

18
Secure (cont'd)
  • Untrusted code cannot
  • Get full access to System.getProperty(), but it
    can use getProperty() to find
  • java.version java.class.version
  • java.vendor java.vendor.url
  • os.name os.version
  • os.arch file.separator
  • path.separator, line.separator
  • Cannot load sun. package classes
  • Remaining weak-spot Denial of Service Attacks

19
High-Performance/ Multithreaded
  • The new dynamic compilers are matching and
    sometimes beating C benchmarks.
  • JITs are catching up to C-speeds.
  • Multi-threaded
  • Thread myThread new Thread (this)
  • Try that with C!

20
Java Syntax
  • All java programs contain (within one or more
    classes)
  • public static void main (String a)
  • ...
  • The Java interpreter runs until the main()
    returns, a System or Runtime exit is called, or
    until the end of main is found.
  • though only one main may be called in a process

So, lets write a Goodbye World program in Java
. . .
21
Exiting a Java program
  • import java.lang.Runtime / not necessary /
  • class test
  • public static void main (String arg)
  • Runtime.getRuntime().traceInstructions(true)
  • Runtime.getRuntime().traceMethodCalls(true)
  • System.out.println (Heres some stats")
  • System.out.println (Runtime.getRuntime().totalMem
    ory() " total memory\n Runtime.getRuntime().f
    reeMemory() " available")
  • if (true) return / 1 -- works /
  • System.exit(0) / 2 -- instant death/
  • Runtime.getRuntime().exit(0) / 3 -- only if
    the thread is running /
  • / 4 --end of main/
  • //test

22
Filenames and Directory Structure in Java
  • Source code features the ".java" extension. The
    file name should match the class
    name. This naming convention is enforced by most
    (but not all) compilers.
  • Thus, an improperly named java file, saved as
    "myTest.java"
  • class test ...
  • Compiled byte code has the ".class" extension.
  • The magic number for class files is

C A F E B A B E
23
The .java file
  • 1. Consists of the optional package statement,
  • 2. followed by any necessary import statements
  • 3. followed by the class name,
  • 4. followed by any inheritance and interface
    declarations.
  • 5. Note if the file defines more than one class
    or interface, only one can be declared public,
    and the source file name must match the public
    class name

Style don't declare more than one class in a
.java file!
24
The average .java file
  • Thus
  • package EDU.gatech.cc.dagon
  • import java.awt.event.
  • import java.awt.
  • public class MyApplet extends java.applet.Applet
    implements ActionListener ... //MyApplet
  • Note the globally unique package name.
  • Without a package specification, the code becomes
    part of an unnamed default package in the
    current directory.

25
That "import" Statement--What?
  • Comes in three flavors
  • import package.class //1
  • import package. // 2
  • import java.lang. //3 (Implicit)
  • What it does provides the Java interpreter with
    a reference to other classes necessary for the
    compilation of the present .java file
  • What it does NOT actually "import" or
    "include" the code-no overhead, in other words.

26
Why no "include"?
  • Java maps fully qualified class names to a
    directory path, and therefore does not need an
    include, fdef, etc. (and no preprocessor as
    well!)
  • Thus
  • java.awt.TextField
  • is mapped to
  • java/awt/TextField
  • and dynamically loaded, as needed.

27
Comments
  • Three flavors
  • 1. C-style comments with / /
  • 2. C style comments beginning //
  • 3. A unique "doc comment" starting with /
    /
  • Fun with comments
  • //
  • / // /
  • ///////////////////
  • / /

28
Javadocin
  • /
  • getName(int i) - returns the name at a
  • specified array location
  • _at_param int i - the index of the array to
  • be retrieved
  • _at_return String strName - the name
  • _at_see EmployeesisEmployed() - called to
  • verify employment
  • /
  • public String getName (int i)
  • if (myEmpl.isEmployed())
  • return myArrayi
  • else return "Nada"
  • // getName(int)

29
Still Javadocin
  • You may include HTML tags (but avoid structuring
    tags, like , etc.)
  • Javadoc comments should immediately preceed the
    declaration of the class, field or method. The
    first sentence should be a summary. Use the
    special javadoc tags--_at_. When '_at_' tags are used,
    the parsing continues until the doc compiler
    encounters the next '_at_' tag.

_at_author
_at_param
_at_return
_at_exception
_at_deprecated // 1.1

_at_since // 1.1
_at_ see _at_ see _at_
see _at_
version
30
Primitive Data Types
  • Although an O-O language, Java supports several
    primitive data types, including
  • Primitive Type Default Value
  • boolean false
  • char '\u0000' (null)
  • byte (byte) 0
  • short (short) 0
  • int 0
  • long 0L
  • float 0f
  • double 0d

31
The char Type
  • All char values are individual characters.
    Literals are expressed between single
    quotes
  • char a 't'
  • Escape characters and Unicode escapes are
    supported
  • char a '\n', apost '\'', delete
    '\377', aleph '\u05D0'

32
The Floating-Point Type
  • Two flavors float and double for 32-bit and
    64-bit values, respectively
  • A number may be expressed as a float by appending
    'f' to the end likewise a double with 'd'.
    Thus
  • float f 0f
  • double d 123123d
  • Note also
  • java.lang.Double.POSITIVE_INFINITY
  • /also float one divided by positive zero/
  • java.lang.Double.NEGATIVE_INFINITY
  • /also float one divided by negative zero/
  • java.lang.Double.NaN
  • / ditto an irrational number/

33
The boolean Type
  • The boolean type of course evaluates to either
    true/false.
  • Although you cant treat the boolean as an
    integer, you can perform some unary operations on
    it.
  • Thus

boolean b false b b true b !b
34
The Mechanics of Non-Primitives (Referenced
Data Types, Objects, Etc.)
  • Non-primitive data types are often called
    'referenced types', an allusion to the manner in
    which they are handled. Whereas primitives are
    referenced by value, objects are by reference.
  • One cannot dereference an object, as in C ( and
    -). Instead, primitives are always passed by
    value, and objects are always passed by
    reference.

35
Cautionary Note Watch Pass-by-Reference
  • Note that methods take in references to objects,
    not their actual values.
  • Thus, the following is an invalid swap function
  • public void swap (Object a, Object b)
  • Object temp a
  • a b
  • b temp
  • This merely works with the references to the two
    objects-the local variables in the method
    (Solution use some instance variables instead
    use Object.clone() method.)

36
Checking for Equalities
  • Objects and primitives evaluate differently
  • E.g., primitives

Expression Memory int d1 d1 -- 0 int
d2 d2 -- 0 d1 3 d1 -- 3
d2 3 d2 -- 3 if (d1 d2 )
// TRUE
37
Checking for Equalities
Why?
  • E.g., objects

Expression Memory String s1 s1 -- String
s2 s2 -- s1"Hello" s1--"Hello" s2"Hello"
s2--"Hello" if (s1s2) //FALSE?
38
Checking for EqualitiesThe Little-Known
Exception
  • Normally, we use .equals to compare objects if
    (Obj1.equals(Obj2)) etc.
  • There is one exception, however, in the case of
    String literals.

3.10.5 String Literals
String literals-or, more generally, strings that
are the values of constant expressions
(15.27)-are "interned" so as to share unique
instances, using the method String.intern
(20.12.47).
39
Creating Objectsthe new keyword
  • String s new String("This is a new String")
  • Also, two other special methods
  • 1. s "This is a new String"
  • 2. use the newInstance() method in Class
  • (used for dynamic loading)

40
Accessing Objects The . operator
  • class Data
  • String s
  • int quantity
  • //Data
  • Data myData new Data()
  • myData.s "Note the dot operator"
  • myData.quantity 5

41
Arrays - Creation
  • Declaration and instantiation
  • int myInts new int10
  • myInts0 3
  • int myInts new int10
  • Static initialization
  • int myInts
  • 1,2,5,6,7,4,3,23,4,4,3,3,5

42
Multi-Dimensional Arrays
  • int myTwoDimArray
  • myTwoDimArray new int105
  • Quiz yourself Valid?
  • String s
  • s new String10
  • Valid?
  • s new String10

//YES!
// NO!
43
Static multidimensional initialization
  • String s "Static", "multidimensional",
    "initialization", "of", "arrays", "requires",
    "the", "use", "of", "nested", "parens"
  • Creates
  • Static arrays of
  • multidimensional requires nested
  • initialization the parens
  • of use null

44
Operators
  • , --, , -, , ( ) !, ,
    /, , , , , , !, , , , , , ?, , , -, , ,
  • etc. etc.

No surprises here just look them up
45
Loops
  • Three flavors
  • 1. For loop
  • int count
  • for (count 0 count
  • for ( count
  • for ( count
  • for ( count
  • for (int count 10 count -- 0)
  • for ( ) // infinite
  • for (count 0 count
  • bNotDoneYet count , otherCount--)
  • for (count 0 count

46
Loops (contd)
  • 2. While Loops
  • while ()
  • . . .
  • 3. Do While Loops
  • do . . .
  • while ()

47
Minimum Loop Executions
  • for - for the duration of the expression
  • while - might not execute, depending
  • do -while - executes at least once
  • Use continue and break to skip cycles
    and leave loops return is also an option

48
Basic Streams (or, How to Print)
  • When starting Java, there are at least three
    streams created for you
  • System.in // for getting input
  • System.out // for output
  • System.err // for bad news output
  • These are InputStream and PrintStream objects
  • Note For Win95/NT System.out is "almost"
    identical to System.err - the both display to the
    screen (the one exception is when using DOS
    redirect, , where System.out is redirected,
    while System.err is still put to the screen )

49
Output streams
  • System.out.println ("This line is printed out")
  • System.err.println ("This is the error stream's
    output")
  • These are both instances of the PrintStream
    class.
  • There are other methods you might find useful in
    these classes
  • System.out.flush()
  • System..out.write(int)
  • System.out.write(byte buf, int offset, int
    length)

50
Streams (cont'd) -- An Example
  • class test
  • public static void main (String arg)
  • //System.out.close()
  • byte i new byte100
  • for (byte k100 k--0)
  • ik k
  • System.out.println("NOT CLOSED")
  • System.out.flush()
  • System.out.write(i,0,i.length)
  • //main
  • //class test
Write a Comment
User Comments (0)
About PowerShow.com