Java Fundamentals - PowerPoint PPT Presentation

1 / 46
About This Presentation
Title:

Java Fundamentals

Description:

... in turn is part of the fruit class, which is under the larger class ... in autoexec.bat or another DOS batch file. Invoke compiler. javac HelloWorld.java ... – PowerPoint PPT presentation

Number of Views:113
Avg rating:3.0/5.0
Slides: 47
Provided by: davidt
Category:

less

Transcript and Presenter's Notes

Title: Java Fundamentals


1
Java Fundamentals intro to the environment
Duke is the mascot of the Java language see a lot
of Duke at the official Java web site
http//www.java.sun.com/
2
Java History
  • Designed for computers embedded in consumer
    appliances
  • Small, distributed, robust programs
  • Which made it ideal for computing
  • Wide variety of platforms
  • Object oriented
  • Multi-tasking
  • Good memory management
  • Basic syntax of C and C
  • But, more object-oriented, excludes complex
    features
  • James Gosling, (Canadian works at Sun
    Microsystems in 1999) developer still alive _at_
  • http//java.sun.com/people/jag/

3
Why Bytecode is Cool "write once, run
anywhere." when you compile your program, you
don't generate instructions for one specific
platform. generate Java bytecode, which are
instructions for the Java Virtual Machine (JVM).
Regardless of whether platform is Windows,
UNIX, Macros, or an Internet browser--has the JVM
it can understand those bytecodes.
Javas MagicThe Bytecode
4
(No Transcript)
5
Object-Oriented Programming
  • Code is organized in two ways
  • around the code
  • (what is happening)
  • Around its data
  • (who is being affected).OOPS

6
Encapsulation
  • Programming mechanism that binds together code
    and the data it manipulates
  • Keeps both safe from outside interference and
    misuse
  • When code and data are linked together in this
    fashion, an object is created, that supports
    encapsulation

7
Encapsulation contd
  • Javas basic unit of encapsulation is the class
  • A class defines the form of an object
  • Specifics both the data and the code that
    operates on that data
  • Java uses a class specification to construct
    objects

8
Encapsulation contd
  • Code and data that constitute a class are called
    members of that class
  • The data defined by the class are referred to as
    member variables
  • Code that operates on that data is referred to as
    member methods or methods

9
Polymorphismone interface, multiple methods
  • Is the quality that allows one interface to
    access a general class of actions
  • i.e. A steering wheel in a car, no matter what
    type of mechanism is used
  • manual steering
  • power steering
  • rack-and-pinion steering
  • steering wheel works the same

10
Inheritance
  • Which one object can acquire the properties of
    another object
  • Red Delicious apple is part of the classification
    apple, which in turn is part of the fruit class,
    which is under the larger class food.
  • A Red Delicious apple or MAC would in turn
    inherit its general attributes from its parents

food
fruit
meat
vegetables
apple
pear
orange
MAC
Red Delicious
11
Multi-threaded, memory management
  • Multi-threaded
  • One program execs multiple threads
  • Appear to run at same time
  • Computing
  • Reading disks
  • Formatting display
  • Transmitting over network
  • Automatic memory recycling
  • Lisp Smalltalk contribution
  • Garbage collector
  • Frees memory when finished with elements like
    class instances
  • Avoid memory leaks

12
Software Developers Kit (SDK)(older version
named JDK - Java Developers Kit )with JRE (Java
Runtime Environment)
  • For home use must have a Java development system
    installed on your home computer
  • Downloaded free of charge from www.java.sun.com
  • Instructions for downloading and installing at
    home can be found on the course web page under
  • General, Resources, Java..

13
Using TextPad as your editor for entering java
code
  • May use any editor (Notepad, TextPad, etc.)
  • TextPad handy because can recognize java syntax
    colour coded statements, brackets, etc.
  • Configure TextPad with links to SDK for easy
    access to java compile and run commands
  • Instructions for downloading TextPad and
    installing at home can be found on the course web
    page under
  • General, Resources, Java..

14
Creating a Java Program
  • Use TextPad, Notepad or another text editor
  • not dependent on one-vendor environment
  • Programs consist of
  • One or more classes
  • Programs name same as primary class
  • Primary class has a main() method.
  • The Java virtual machine (JVM) will execute main
    calls whatever else is needed.

15
The Java 2 SDK on Disk
  • Note that the Java SDK "home" directory is
    j2sdk1.4.?
  •     It is common to store this location in an
    environment variable named java_home        
  • set java_homej2sdk1.4.?
  • Note these important subdirectories
  • j2sdk1.4.?/bin
  • j2sdk1.4.?/jre
  • j2sdk1.4.?/lib

16
SDK Tools
  • In j2sdk1.4.?\bin on a Windows computer you will
    find
  • javac.exe
  • The Java compiler
  • java.exe
  • The Java interpreter
  • More formally the Java Virtual Machine (JVM)
  • javadoc.exe
  • The Java documentation utility

17
Hello World!
Use camel notation one exception Standard Class
names begin with a capital
  • public class HelloWorld
  • public static void main(String arg)
  • System.out.println("Hello World!")
  • Saved as "HelloWorld.java"

H
h
Be Careful When You Type Type all code,
commands, and file names exactly as shown. The
Java compiler and interpreter are case-sensitive,
so you must capitalize consistently. HelloWorld
?  helloworld
18
Hello World!
Keyword class to declare that a new class is
being defined
main() method, line at which execution starts
  • public class HelloWorld
  • public static void main(String arg)
  • System.out.println("Hello World!")
  • Saved as "HelloWorld.java.page 18 in book

members of the class
19
Compile/Run a Java program at DOS (command)
prompt
  • Ensure JDK is on path
  • set pathj2sdk1.4.?\binpath
  • in autoexec.bat or another DOS batch file
  • Invoke compiler
  • javac HelloWorld.java
  • produces file HelloWorld.class
  • Invoke Java virtual machine
  • java HelloWorld
  • executes HelloWorld.class

20
Compiling a Java program using TextPad
Missing "t in print.out
21
Executing a Java Program using TextPad (after
fixing error)
22
Comments in Java
  • Same as JavaScript
  • // everything in the line after this is ignored
  • / this is a multi-line
  • comment. Everything is
  • ignored until /

23
Javadoc - http//java.sun.com/j2se/javadoc/index.h
tmljavadocdocuments
  • Javadoc is the tool from Sun Microsystems for
    generating API documentation in HTML format from
    doc comments in source code.
  • For a sample of Javadoc-generated HTML, see J2SE
    1.4 API Documentation and
  • J2SE 1.3 API Documentation.

24
Javadoc from within TextPadTextPad in 2A206
will likely be configured with the following
tools already installed
  • Add javadoc to the tools list
  • Also handy if you add a tool to TextPad to make a
    .doc directory in the current directory. The
    javadoc tool puts the documentation in the .docs
    directory
  • User may then run the mkdir tool once before
    running javadoc
  • Instructions for configuring TextPad tools can be
    found on the course web page under
  • General, Resources, Java..

25
Javadoc comments(Appendix B page 551)
  • The javadoc program takes as input your Java
    programs source file and outputs several HTML
    files that contain the programs documentation.
  • Information about each class will be in its own
    HTML file.
  • Javadoc will also output an index and a hierarchy
    tree.

26
An Example that uses Documentation Commentspage
558
  • After the beginning /, the first line or lines
    become the main description of your class,
    variable, or method.
  • After that, you can include one or more of the
    various _at_ tags.
  • Each _at_ tag must start at the beginning of a new
    line or follow an asterisk() that is at the
    start of a line.
  • Multiple tags of the same type should be grouped
    together.

27
Declaring Variables
  • Identifier rules
  • Names start with a letter
  • Can contain letters or numbers
  • _ and are "letters"
  • Use Camel notation
  • userName
  • Variables are "typed"
  • Fixed allocation of memory
  • Value can change
  • Type cannot change
  • i.e. int cannot change to float
  • declare variables before using

28
Integer Declarations
  • public class IntDeclares
  • public static void main(String arg)
  • int textCounter
  • int wordCounter, lineCounter
  • int docCounter0
  • int fileCounter 0, driveCounter 0
  • System.out.println("variable declared "
    driveCounter)
  • One or more variables per declaration
  • Must initialize value(s)
  • Cannot use variables until initialized
  • Even though default value is 0
  • Note "" at end of every statement

29
Java Keywords
30
Primitive Variable Typesall others (string,
array, etc.) are reference types
  • byte 1 byte integer (-128 to 127)
  • char 2 bytes 1 character, can view as integer
  • short 2 bytes integer (-32,768 to 32,767)
  • Int(default) 4 bytes integer (2.147B)
  • long 8 bytes integer (9,223,372T)
  • float 4 bytes floating-point (9 sig digits,
    1045)
  • Double(default) 8 bytes floating-point (18 sig
    digits, 10324)
  • boolean logical true/false
  • Note all are signed, except char and boolean

31
Arithmetic Expressions
  • Add x 1
  • Subtract y 1
  • Multiply x y
  • Divide 15 / 6 produces 2
  • 15.0 / 6.0 produces 2.5
  • Modulus 15 6 produces 3
  • (remainder in integer math)
  • Expressions can contain multiple operators

32
Arithmetic Precedence
  • Brackets ()
  • unary negation -3
  • multiplication/division/modulus
  • addition/subtraction
  • assignment ()
  • Note assignment has a "value"
  • y (x 3) 2 // y has value 5
  • All evaluated left-to-right
  • Except assignment

33
Relational Operators pg 63
  • !
  • gt
  • lt
  • gt
  • lt

34
Logical Operators pg 64
  • Operator Meaning
  • AND
  • OR
  • XOR (exclusive OR)
  • Short-circuit OR
  • Short-circuit AND
  • ! Not

35
Literals(constants or fixed values)
  • By default, integer literals are of type int
  • If you want to specify a long literal, append an
    l or an L.
  • For example, 12 is an int, but 12L is a long
  • By default, floating-point literals are of type
    double
  • If you want to specify a float literal, append an
    f or an F to the constant.
  • For example, 10.19F is of type float

36
Character Escape Sequence
ch \t // this assigns ch the tab
character ch \ // assigns a single quote
to ch
37
Demonstrate escape sequences in strings
class StrDemo public static void main(String
args) System.out.println(First
line\nSecond line System.out.println(A\tB\tC
) System.out.println(D\tE\tF)
use (new line) \n to generate a new line
use tabs(\t) to align output
Output First line Second line A B C D E F
38
Initializing a Variable
  • In general, you must give a variable a value
    prior to using it
  • type var value
  • Value is the value that is given to var when var
    is created
  • int count 10 // give count an initial of 10
  • char ch X // initialize ch with the
    letter X
  • float f 1.25 // f is initialized with 1.2
  • int a, b 8, c 19, d // b and c have
    initializations

39
Type Conversion in Assignments
  • When compatible types are mixed in an assignment,
    the value of the right side is automatically
    converted to the type of the left side as long as
    they are compatible which means
  • The two types are compatible
  • The destination type is larger that the source
    type
  • int i
  • float f
  • i 10
  • f i // OK to assign an int to a float
  • For example boolean and int are not compatible
  • double to long is not a widening conversion

40
Casting Incompatible non-widening" Types
Casts (or "converts") a value to the specified
type.
  • // Demonstrate casting
  • class CastDemo
  • public static void main(String args)
  • double x, y
  • byte b
  • int i
  • char ch
  • x 10.0
  • y 3.0
  • i (int) (x / y) //cast double to int
  • System.out.println("integer outcome of x / y
    " i)
  • i 100
  • b (byte) i
  • System.out.println("Value of b " b)
  • i 257
  • b (byte) i
  • System.out.println("Value of b " b)
  • b 88
  • Force value to a another type
  • Example below (cast involves a narrowing
    conversion)
  • double x, y
  • (int) (x / y)
  • Casting from double to int
  • cast "i" to a correct type, then do math

41
MaxVariablesDemo Programhttp//java.sun.com/docs
/books/tutorial/java/nutsandbolts/example-1dot1/Ma
xVariablesDemo.java
public class MaxVariablesDemo public static
void main(String args) // integers
byte largestByte Byte.MAX_VALUE
short largestShort Short.MAX_VALUE int
largestInteger Integer.MAX_VALUE long
largestLong Long.MAX_VALUE // real
numbers float largestFloat
Float.MAX_VALUE double largestDouble
Double.MAX_VALUE // other primitive
types char aChar 'S' boolean
aBoolean true // display them all
System.out.println("The largest byte value is
" largestByte) System.out.println("The
largest short value is " largestShort)
System.out.println("The largest integer value is
" largestInteger) System.out.println("T
he largest long value is " largestLong)
System.out.println("The largest float value is
" largestFloat) System.out.println("The
largest double value is " largestDouble)
if (Character.isUpperCase(aChar))
System.out.println("The character " aChar "
is upper case.") else
System.out.println("The character " aChar "
is lower case.")
System.out.println("The value of aBoolean is "
aBoolean)
42
Results from MaxVariablesDemo Program
43
Java Exercise
  • There is an extensive online tutorial
    http//java.sun.com/docs/books/tutorial/index.html
    for Java. Follow the instructions in
  • Your First Cup of Java (for Win32)
  • Part 2 "Creating Your First Application" to
    create a simple "Hello, World" program. Work in a
    directory named g\WD1\exercise8.
  • http//java.sun.com/docs/books/tutorial/getStarte
    d/index.html
  • Follow the set of instructions from
  • Getting Started
  • Use TextPad or Notepad as instructed, pay careful
    attention to how the Java compiler (javac) and
    the Java Virtual Machine (java) are used.
  • When done, open your "Hello, World" program with
    the TextPad editor. Use Tools gt Compile Java to
    compile your program. Note how TextPad calls
    javac for you. Next, use Tools gt Run Java
    Application to run your program. Note how TextPad
    calls java for you. For the rest of the course we
    will use TextPad, but you should know how to
    compile and run Java programs from the command
    line.

44
Hello World - Applet
  • http//java.sun.com/docs/books/tutorial/getStarted
    /cupojava/win32.html1

45
Tutorial Questions and Answers
  • http//java.sun.com/docs/books/tutorial/java/nutsa
    ndbolts/QandE/questions_operators.html

46
To Do
  • Read Module 1,2 and 3
  • To My First Cup of Java HelloWorld exercise
  • Do Assignment 1
Write a Comment
User Comments (0)
About PowerShow.com