Preparing a Java Program - PowerPoint PPT Presentation

1 / 90
About This Presentation
Title:

Preparing a Java Program

Description:

System.out.print('Roses are red,'); System.out.println(' violets are blue, ... Roses are red, violets are blue, This poem is as good as new. 6/8/09 ... – PowerPoint PPT presentation

Number of Views:24
Avg rating:3.0/5.0
Slides: 91
Provided by: IBMU362
Learn more at: http://www.cs.ucf.edu
Category:

less

Transcript and Presenter's Notes

Title: Preparing a Java Program


1
Preparing a Java Program
  • We are going to use JDK environment of Sun
    Microsystems.
  • JDK environment is simple to use and free.
  • You can JDK environment for your own computer
    from
  • the sun website http//java.sun.com/j2se/1.3
     
  • Editing
  • Create a file containing a Java program.
  • You may use any text editor.
  • This file will be .java extension (Ex
    Test1.java )
  • Compiling
  • Use Java compiler to compile the Java program. (
    javac Test1.java )
  • Java compiler will create a file with .class
    extension. This file will contain the Java
    byte-codes of your Java program ( Test1.class ).
    You can run this file in different platforms.
  • The other compilers produce executable files.

2
Preparing a Java Program (cont.)
  • Executing
  • Execute the byte-codes of your Java program by a
    Java interpreter.
  • We will see that there are two types of Java
    programs application, applet
  • If our program is an application, we will execute
    it as follows
  • java Test1 (will interpret Test1.class
    file )
  • If our program is an applet
  • First we will create a .html file containing
    a link to our .class
    file.
  • Then we will run our applet using
    appletviewer
    appletviewer Test1.html
  • We may run our applets under web-browsers
    too.

3
Simple IO
System.out.print(A simple sentence")   The
other version of this method is the println
method. The only difference between print and
println is that println advances the cursor to
the next line.   Thus, the following three
statements   System.out.print("Roses are
red,") System.out.println(" violets are
blue,") System.out.println("This poem is as good
as new.")   would produce the following
output   Roses are red, violets are blue, This
poem is as good as new.
4
Simple Operator Overloading
  • 32 (Integers)
  • 3.22.3 (Reals)
  • How does Java handle these expressions?
  • DogHouse???
  • 4Computers ???

5
Simple Output
System.out.println("Hello " "World!") Output H
ello World     System.out.println("Answer "
7) Output Answer 7     System.out.println(34)
Output 7   System.out.println(34"
7") Output 77
6
A Simple Console Application Program
  • // Author Ilyas Cicekli Date October 9,
    2001
  • //
  • // A simple application program which prints
    Hello, World
  •  
  • public class Test1
  •  
  • public static void main(String args)
  •  
  • // print Hello, World
  • System.out.println("Hello, World)
  •  
  • // end of main
  •  
  • // end of class

7
A Simple Console Application Program (cont.)
  • Every Java program (every application program)
    defines a class.
  • We use class keyword to declare a class.
  • The name of a class is an identifier. Uppercase
    and lowercase letters are different.
  • The name of the class must be same as the the
    file holding that class (Test1.java)
  • Our class contains only one method.
  • Every console application program should contain
    main method.
  • It may contain other methods too.
  • The method main should be declared using public
    and static keywords.
  • Our main method contains only one executable
    statement
  • This is a method invocation statement (print
    statement)
  • Comments
  • // single line comments
  • / ... / multi line comments
  • We can use as much as white spaces between words
    to make easier to read programs.

8
A Simple Console Application Program (cont.)
  • We put this application program into the file
    Test1.java using a text editor.
  • To compile javac Test1.java
  • creates Test1.class file (if there is no syntax
    errors)
  • To run java Test1
  • java interpreter will interpret the byte-codes in
    Test1.class file.
  • As a result, we will see Hello, World on the
    screen

9
Simple Java Program (cont.)
  • What do we have in our simple Java program?
  • Identifiers Test1,args,...
  • Reserved Words public, class, static, ...
  • Literals Hello, World
  • Operators -- .
  • Delimeters -- ( )
  • Comments -- // end of class
  • When these parts are combined according to the
    certain rules (the syntax of Java), a
    syntactically correct Java program is created.

10
Introduction to Objects
  • Initially, we can think of an object as a
    collection of services that we can tell it to
    perform for us
  • The services are defined by methods in a class
    that defines the object

System.out.println (Make the most of each day.")
11
The println and print Methods
  • The System.out object provides another service as
    well
  • The print method is similar to the println
    method, except that it does not advance to the
    next line
  • Therefore anything printed after a print
    statement will appear on the same line

12
Abstraction
  • An abstraction hides (or ignores) the right
    details at the right time
  • An object is abstract in that we don't really
    have to think about its internal details in order
    to use it
  • We don't have to know how the println method
    works in order to invoke it
  • A human being can only manage seven (plus or
    minus 2) pieces of information at one time
  • But if we group information into chunks (such as
    objects) we can manage many complicated pieces at
    once
  • Therefore, we can write complex software by
    organizing it carefully into classes and objects

13
Identifiers
  • We make up words for class names, method names,
    and variables.
  • These words are called identifiers.
  • For example,
  • Test1, main, System, out, println are
    identifiers in our simple program.
  • We made up Test1 and main(!) and others are
    defined in Java API (Application Programming
    Interface).
  • An identifier can be composed of any combination
    of letters, digits, the under score character,
    and the dollar sign but it cannot start with a
    digit.
  • We can use both upper case letters and lower case
    letters in identifiers. But Java is case
    sensitive. Identifiers Val, val and VAL are all
    different variables.
  • Some Legal Identifiers x val count_flag Test1
    amount val1 stockItem
  • Some Illegal Identifiers 1val x x-1 x
  • Although we can choose any legal identifier to be
    used, but it is nice to follow certain style
    guidelines when make up an identifier.
  • Choose meaningful names (not too long, not too
    short, descriptive words)
  • First character of a class name should be an
    uppercase letter.
  • First character of a method name and a variable
    should be a lower case letter.

14
  • Three types of identifiers
  • words that we make up ourselves.
  • words that are reserved for special purposes in
    the language
  • words that are not in the language, but were
    used by
  • other programmers to make the library.

15
  • Identifiers- different words used in a program
  • The rule an identifier may be composed of any
    number of
  • letters,
  • digits
  • (dollar sign)
  • _ (underscore).
  • but the first character can not be a digit.
  • A letter any English or foreign language
    alphabetic
  • symbol (both uppercase and lower case)

Java is case sensitive!
16
Variables
  • A variable is a name for a location in memory
  • A variable must be declared, specifying the
    variable's name and the type of information that
    will be held in it

int total
int count, temp, result
Multiple variables can be created in one
declaration
17
Variables
  • A variable can be given an initial value in the
    declaration

int sum 0 int base 32, max 149
  • When a variable is referenced in a program, its
    current value is used

18
Assignment
  • An assignment statement changes the value of a
    variable
  • The assignment operator is the sign

total 55
  • The expression on the right is evaluated and the
    result is stored in the variable on the left
  • The value that was in total is overwritten
  • You can only assign a value to a variable that is
    consistent with the variable's declared type

19
Variables
  • A variable is an identifier that represents a
    memory location which holds a particular type of
    data.
  • The type of a variable indicates the size of the
    memory location which will be reserved for that
    variable, and how its content will be
    interpreted.
  • Variables must be declared before they can be
    referenced.
  • The syntax of a variable declaration
  • data-type variable-name
  • Examples
  • int x (32 bits and it will be interpreted as
    an integer number)
  • double y (64 bits and it will be interpreted as
    a floating point number)
  • short z (16 bits and it will be interpreted as
    an integer number)
  • String s (big enough to hold a reference)
  • Contents of the allocated locations are not known
    (or we shouldnt assume it).

20
Variable Declarations
  • Multiple variables can be declared with same
    declaration statement.
  • data-type variable-name1,...,variable-namen
  • int a, b, c double x, y
  • Variables can be initialized in declarations.
  • int total0, count1
  • double price15.25
  • When a new value is placed in a memory location,
    this new value replaces the old value in that
    memory location.
  • int x1,y2
  • x 3
  • y x

21
Constants
  • A constant is an identifier that is similar to a
    variable except that it holds one value for its
    entire existence
  • The compiler will issue an error if you try to
    change a constant
  • In Java, we use the final modifier to declare a
    constant
  • final int MIN_HEIGHT 69
  • Constants
  • give names to otherwise unclear literal values
  • facilitate changes to the code
  • prevent inadvertent errors

22
Constants
  • A constant is similar to a variable except that
    they keep the same value through their existence.
  • Constants cannot be used in the left side of an
    assignment statement.
  • They are specified using the reserved word final
    in declarations.
  • Examples
  • final double PI 3.14159
  • final int NUMOFSTUDENTS 58
  • As a style, we choose upper case letter for
    identifiers representing constants.
  • Constants are better than literals because
  • they make code more readable by giving a name to
    a value.
  • they facilitate easy updates in the programs
    because the value is only specified in one place.

23
Assignment Statement
  • variable expression
  • The value of the expression is evaluated, and its
    result is stored in the memory location indicated
    by that variable overwriting the value stored in
    that location.
  • An expression is a sequence of operands (such as
    variables, literals, constants, method calls),
    and operators. It can be a single operand or a
    more complex expression.
  • The variable must be assignment compatible with
    the expression.

24
Java data types
  • Primitive data types
  • integers (byte, short, int, long)
  • floating point numbers (float, double)
  • boolean (true, false)
  • char (any symbol encoded by a 16-bit unicode)
  • Objects- everything else
  • An object is defined by a class. A class is the
    data type of the object.
  • You can define your own objects or
  • use predefined classes from library.

25
Data Types
  • Each value in memory is associated with a
    specific data type.
  • Data type of a value determines
  • size of the value (how many bits) and how these
    bits are interpreted.
  • what kind of operations we can perform on that
    data.
  • A data type is defined by a set of values and the
    operators you can perform on them.
  • Data Types in Java
  • Primitive Data Types
  • Object Data Types

26
Primitive Data
  • There are exactly eight primitive data types in
    Java
  • Four of them represent integers
  • byte, short, int, long
  • Two of them represent floating point numbers
  • float, double
  • One of them represents characters
  • char
  • And one of them represents boolean values
  • boolean

27
Primitive Data Types
  • There are eight primitive data types in Java
    programming language.
  • byte
  • short
  • int
  • long
  • float
  • double
  • char -- characters
  • boolean -- boolean values

integers
floating point numbers (real numbers0
28
Typing and Naming
What kind of things a program can
manipulate? Some of them are simple, like
numbers. Others may be complex. Those are called
objects.
What is a type?
A type specifies what a thing can do (or what
you can do with a thing). Names are ways to
refer to things that already exist. Every name
has a type, which tells you what you can expect
from the thing that the name refers to.
29
Java numerical primitive types
There are four separate integer primitive data
types They differ by the amount of the memory
used to store them. Internally, integers are
represented using twos complement representation
(discussed later).
30
boolean true or false
char x, 6, \, \, \u006A
16 bit unicode
Example
int a1, b0 boolean boolaltb // bool is
false char lettera
31
Literal Assigned type
6 int (default type) 6L long 6l long 1,000,0
00,000 int 2.5 (or 2.5e-2) double (default
type) 2.5F float 2.5f float x char \n
char (new line) \u0039 char represented by
unicode 0039 true boolean \tHello
World!\n String (not a primitive data type!)
32
Literals and identifiers
  • A literal is a thing itself. You can type it
    directly
  • in appropriate place of the program.
  • An identifier is a name that uniquely identifiers
    a thing.
  • Java is a strongly typed language.
  • Each thing (variable ) must be declared.
  • Appropriate storage space is allocated.
  • If no value is specified, the value is
    initialized to 0, 0.0,
  • \u0000 (null character) and false by default.

int myNumber double realNumber char
firstLetterOfMyName boolean isEmpty
33
Assignment actually assigns value to a
name myNumber4 firstLetterOfMyNameN isEmpty
true
Combination of declaration and assignment is
called definition boolean isHappytrue double
degree0.0 String s This is a string. float
x, y4.1, z2.2
34
int y4, z2 xy/z
Syntax error
35
Binary Numbers
  • Before we talk about primitive data types in Java
    programming language, let us review the binary
    numbers.
  • a sequence of 0s and 1s.
  • two bits 00 01 10 11 (four different
    values)
  • three bits 000 001 010 011 100 101 110 111
    (eight different values)
  • 8 bits (1 byte) 00000000 ... 11111111 (256
    different values)
  • n bits 2n different values

36
Internal Data Representation of Integers
  • Twos complement format is used to represent
    integer numbers.
  • Twos complement format representation makes
    internal arithmetic processing easier.
  • In Twos complement format
  • positive numbers are represented as a straight
    forward binary number.
  • a negative value is represented by inverting all
    the bits in the corresponding positive number,
    then adding 1.
  • (sign bit 0 for positive numbers, 1 for
    negative numbers)
  • Ex (byte)
  • 00000110 (6) ? 11111001 1 11111010
    (-6)
  • invert all the digits ones complement then
    add one

37
Internal Data Representation More Examples
  • 31 00011111 ? 11100000 1 11100001
    (-31)
  • 0 00000000
  • 127 01111111 ? 10000000 1 10000001
    (-127)
  • 1 00000001 ? 11111110 1 11111111 (-1)
  • 10000000 (which number?) ? -128
  • 12810000000 ? 01111111 1 10000000 (-128)
  • Addition 00000011 11111111 00000010 (2)
  • 3 -1

38
Overflow - Underflow
  • If a value grows so large that it cannot be
    stored in the space, this is called as OVERFLOW.
  • If a value grows so small that it cannot be
    stored in the space, this is called as
    UNDERFLOW.
  • If an overflow or an underflow occurs, we will
    get incorrect results (not error messages).
  • Overflow Underflow
  • byte x 127 byte x -128
  • x (byte) (x1) x (byte) (x-1)
  • ? value of x is 128 ? value of x is 127
  • 01111111 00000001 10000000 10000000
    11111111 01111111

39
Floating Point Numbers (Real Numbers)
  • There are two separate floating point primitive
    data types.
  • They differ by the amount of the memory used to
    store them.
  • Java treats any floating point literal as double.
  • If we want to force a literal to be float 1.2f
    1.2F
  • double literals 1.2 1.2d 1.2D

40
Internal Representation of Floating Point Numbers
  • Java uses the standard IEEE 754 floating point
    format to represent real numbers.
  • float
  • double
  • sign exponent mantissa
  • value sign mantissa 2exponent

41
Boolean
  • A boolean value represents a true or false
    condition.
  • The reserved words true and false are only valid
    values for a boolean type.
  • int i, j
  • boolean x, y
  • x true
  • y (i lt j)

42
Boolean
  • A boolean value represents a true or false
    condition
  • A boolean can also be used to represent any two
    states, such as a light bulb being on or off
  • The reserved words true and false are the only
    valid values for a boolean type
  • boolean done false

43
Characters
  • A char value stores a single character from
    Unicode character set.
  • A character set is an ordered list of characters.
    Each character is represented by a sequence of
    bits.
  • The Unicode character set uses 16 bits per
    character (65636 unique characters) and contains
    international character sets from different
    languages, numbers, symbols.
  • ASCII character set is a subset of the Unicode
    character set. It uses only 8 bits (256
    characters). In fact, the first 256 characters of
    the Unicode character set are ASCII characters.
  • 32 space
  • 48-57 0 to 9
  • 65-90 A to Z
  • 97-122 a to z
  • Character literals
  • a A 1 0
  • Note that 1 and 1 are different literals
    (character and integer)

44
Characters
  • A char variable stores a single character from
    the Unicode character set
  • A character set is an ordered list of characters,
    and each character corresponds to a unique number
  • The Unicode character set uses sixteen bits per
    character, allowing for 65,536 unique characters
  • It is an international character set, containing
    symbols and characters from many world languages
  • Character literals are delimited by single
    quotes
  • 'a' 'X' '7' '' ',' '\n'

45
Characters
  • The ASCII character set is older and smaller than
    Unicode, but is still quite popular
  • The ASCII characters are a subset of the Unicode
    character set, including

46
Reserved Words
  • Reserved words are identifiers that have a
    special meaning in a programming language.
  • For example,
  • public, void, class, static are reserved words
    in our simple programs.
  • In Java, all reserved words are lower case
    identifiers (Of course we can use just lower case
    letters for our own identifiers too)
  • We cannot use the reserved words as our own
    identifiers (i.e. we cannot use them as
    variables, class names, and method names).

47
Java reserved words
  • Data declaration boolean, float, int, char
  • Loop keywords for, while, continue
  • Conditional keywords if, else, switch
  • Exceptional keywords try, throw, catch
  • Structure keywords class, extends, implements
  • Modifier and access keywords public, private,
    protected
  • Miscellaneous true, null, super, this

48
/ HelloWorld application program / public
class HelloWorld // Class
header // Start class body public static
void main(String argv) //main method
System.out.println(HelloWorld!) //
end of main // end HelloWorld
words that we make up ourselves
49
/ HelloWorld application program / public
class HelloWorld // Class
header // Start class body public static
void main(String argv) //main method
System.out.println(HelloWorld!) //
end of main // end HelloWorld
words that are reserved for special purposes in
the language are called reserved words
50
words that are not in the language, but were used
by other programmers to make the library
/ HelloWorld application program / public
class HelloWorld // Class
header // Start class body public static
void main(String argv) //main method
System.out.println (HelloWorld!) //
end of main // end HelloWorld
51
Literals
  • Literals are explicit values used in a program.
  • Certain data types can have literals.
  • String literal Hello,World
  • integer literals -- 12 3 77
  • double literals 12.1 3.45
  • character literals a 1
  • boolean literals -- true false

52
Another Simple Console Application Program
  • public class Test2
  •  
  • public static void main(String args)
  • // print the city and its population.
  • System.out.println("The name of the city is
    Orlando)
  • System.out.println(Its population is
    1000000)
  •  
  • // Different usage of operator
  • System.out.println(Sum of 54 (54))
  •  
  • // Different output method print
  • System.out.print(one..)
  • System.out.print(two..)
  • System.out.println(three..)
  • System.out.print(four..)
  • // end of main
  • // end of class

53
Another Simple Application Program (cont.)
  • The operator is a string concatenation
    operator.
  • abcde ? abcde
  • 1000000 is converted to a String (1000000) ,
    and this string is concatenated with the string
    literal Its population is.
  • The operator is also a regular add operator
    for numeric values. in (54) is a
    regular add operator for numeric values.
  • In other words, the operator is overloaded.
  • println prints its argument and moves to the next
    line.
  • print prints its argument and it does not move to
    the next line.
  • The output of our program will be
  • The name of the city is Orlando
  • Its population is 1000000
  • Sum of 54 9
  • one..two..three..
  • four..

54
Applets
  • A Java application is a stand-alone program with
    a main method (like the ones we've seen so far)
  • An applet is a Java program that is intended to
    transported over the web and executed using a web
    browser
  • An applet can also be executed using the
    appletviewer tool of the Java Software
    Development Kit
  • An applet doesn't have a main method
  • Instead, there are several special methods that
    serve specific purposes
  • The paint method, for instance, is automatically
    executed and is used to draw the applets contents

55
Applets
  • The paint method accepts a parameter that is an
    object of the Graphics class
  • A Graphics object defines a graphics context on
    which we can draw shapes and text
  • The Graphics class has several methods for
    drawing shapes
  • The class that defines the applet extends the
    Applet class
  • This makes use of inheritance, an object-oriented
    concept explored in more detail in Chapter 7

56
Applets
  • An applet is embedded into an HTML file using a
    tag that references the bytecode file of the
    applet class
  • It is actually the bytecode version of the
    program that is transported across the web
  • The applet is executed by a Java interpreter that
    is part of the browser

57
Java Applets Fundamentals
Any applet
  • should be embedded into html file
  • lthtmlgt
  • ltapplet codeMyApplet.class width100
    height100gt
  • lt/appletgt
  • lt/htmlgt
  • is executed by appletviewer or by Web browser
  • you can run applet by the command
  • appletviewer file_name.html
  • extends Applet class from java.applet package

58
import java.applet.Applet public class MyApplet
extends Applet // applet body
extends keyword indicates that the class MyApplet
inherits from Applet class.
superclass
subclass
Inheritance relationship
59
A programmer can use all capabilities from
predefined class Applet in any subclass that
extends Applet.
public boolean equals(Object arg) public String
toString()
Object
java.lang
public void setSize(int w, int h) public void
setBackground(Color c)
java.awt
Component
public void paint (Graphics p) public void
add(Component item,)
Container
Panel
public void init() public void start() public
void showStatus(String message) public void
stop() public void destroy()
Applet
MyApplet
One branch of a Hierarchy tree
60
A Simple Applet Program
  • // Author Ilyas Cicekli Date October 9,
    1997
  • //
  • // A simple applet program which prints Hello,
    World
  •  
  • import java.awt.
  • import java.applet.Applet
  •  
  • public class Test1Applet extends Applet
  •  
  • public void paint (Graphics page)
  • page.drawString(Hello, World, 50,50)
  • // end of paint method
  •  
  • // end of class

61
A Simple Applet Program (cont.)
  • We import classes from packages java.awt and
    java.applet.
  • From java.awt package, we use Graphics class.
  • From java.applet package, we use Applet class
    (and its methods).
  • Our new class Test1Applet extends the already
    existing class Applet.
  • Our class will inherit all methods of Applet if
    they are not declared in our method
  • We declare only paint method
  • it is called after the initialization
  • it is also called automatically every time the
    applet needs to be repainted
  • Event-driven programming
  • methods are automatically called responding to
    certain events
  • drawString writes a string on the applet.
  • drawString(string, x, y)
  • top corner of an applet is 0,0

62
A Simple Applet Program (cont.)
  • To compile
  • javac Test1Applet.java
  • if there is a mistake in our code, the Java
    compiler will give an error message.
  • To run
  • appletviewer Test1Applet.html
  • It will print Hello, World in the applet window.
  • Test1Applet.html file should contain
  •  
  • lthtmlgt
  • ltapplet code"Test1Applet.class" width300
    height100gt
  • lt/appletgt
  • lt/htmlgt

63
A Simple Applet Program (cont.)
Output
64
Another Applet Program -- ManApplet.java
  • // A simple applet program which draws a man
  • import java.awt.
  • import java.applet.Applet
  •  
  • public class ManApplet extends Applet
  •  
  • public void paint (Graphics page)
  • page.drawString("A MAN", 100,30)
  • // Head
  • page.drawOval(100,50,50,50)
  • page.drawOval(115,65,5,5) // eyes
  • page.drawOval(130,65,5,5)
  • page.drawLine(125,70,125,80) // nose
  • page.drawLine(120,85,130,85) // mouth
  • // Body
  • page.drawLine(125,100,125,150)
  • // Legs
  • page.drawLine(125,150,100,200)
  • page.drawLine(125,150,150,200)

65
Another Applet Program (cont.)
  • ManApplet.html
  •  
  • lthtmlgt
  • ltapplet code"ManApplet.class" width300
    height300gt
  • lt/appletgt
  • lt/htmlgt
  • drawString(astring,x,y)
  • writes the given string starting from the ltx,ygt
    coordinate.
  •  
  • drawLine(x1,y1,x2,y2)
  • draws a line from ltx1,y1gt to ltx2,y2gt coordinate.
  •  
  • drawOval(x,y,width,height)
  • draws an oval with given width and height (if the
    oval were enclosed in a rectangle).
  • ltx,ygt gives the top left corner of the rectangle.

66
Output of ManApplet
67
JAVA API (Application Programming Interface)
  • The Java API is a set of a class libaries.
  •  
  • The classes of the Java API are grouped into
    packages.
  • Each package contains related classes.
  • A package may contain another packages too.
  •  
  • We can access a class explicitly
    java.lang.System (. seperates packages and
    classes). Or, we can access all classes in a
    package at the same time java.awt.
  •  
  • Some packages in the Java API.
  • java.lang general support, it is
    automatically imported into all Java programs
  • java.io perform a wide variety of input
    output functions
  • java.awt graphics relelated stuff
    (awt-Abstract Windowing Toolkit)
  • java.applet to create applets
  • java.math mathematical functions.
  • .

68
Class Libraries
  • A class library is a collection of classes that
    we can use when developing programs
  • There is a Java standard class library that is
    part of any Java development environment
  • These classes are not part of the Java language
    per se, but we rely on them heavily
  • The System class and the String class are part of
    the Java standard class library
  • Other class libraries can be obtained through
    third party vendors, or you can create them
    yourself

69
Packages
  • The classes of the Java standard class library
    are organized into packages
  • Some of the packages in the standard class
    library are

70
The import Declaration
  • All classes of the java.lang package are
    automatically imported into all programs
  • That's why we didn't have to explicitly import
    the System or String classes in earlier programs
  • The Random class is part of the java.util package
  • It provides methods that generate pseudo-random
    numbers
  • We often have to scale and shift a number into an
    appropriate range for a particular purpose

71
import Statement
  • We can access a class by giving its full name
    such as java.awt.Graphics. But we will
    repeat this over and over again in our programs.
  •  
  • The import statement identifies the packages and
    the classes of the Java API that will be
    referenced in our programs.
  •  
  • import package.class
  • identify the particular package that will be
    used in our program.
  • example import java.applet.Applet
  •  
  • import package.
  • we will be able to access all classes in that
    package.
  • example import java.awt.

72
Structure of a Console Application Program
  • imported classes
  • You should at least import classes in java.io
    package.
  • public class ltyour application namegt
  •  
  • public static void main (String args) throws
    IOException
  •    declarations of local variables and local
    objects (references)
  • executable statements
  • other methods if they exist
  • Remember the file name should be lt your
    application namegt.java

73
Structure of an Applet Program
  • imported classes
  • you should import at least Graphics and Applet
    classes
  • public class ltyour class namegt extends Applet
  • declarations
  • you should declare all variables which will be
    used in your methods
  • declarations of methods in your application
  • Declarations of your own methods and the methods
    responding to events.
  • If a required method is needed but it is not
    declared, it is inherited from Applet class.
    Normally the free versions we get from Applet
    class.

74
Some Methods for Events
  • ? Normally, you may declare following methods
    (or other methods) to respond to certain events
  •  
  • public void init()
  • it is called when your applet is started.
  • -- It performs initialization of an applet.
  • public void start()
  • it is called after init method and every time
    user returns to this applet.
  • public void paint (Graphics g)
  • -- it is called after the initialization.
  • -- it is also called automatically every time the
    applet needs to be repainted.
  • public void stop()
  • -- it is called when the applet should stop
  • public void destroy()
  • -- it is called when the applet is destroyed

75
Structure of a Method
  • public ltits typegt ltits namegt ( ltits argumentsgt
    )
  • declarations of local variables
  • executable statements

76
Wrapper Classes
  • For each primitive data type, there exists a
    wrapper class.
  • A wrapper class contains the same type of data as
    its corresponding primitive data type, but it
    represents the information as an object (an
    instance of that wrapper class).
  • A wrapper class is useful when we need an object
    instead of a primitive data type.
  • Wrapper classes contain useful methods. For
    example, Integer wrapper class contains a method
    to convert a string which contains a number into
    its corresponding value.
  • When we talk numeric input/output, we will use
    these wrapper classes.
  • Wrapper Classes
  • Byte Short Integer Long Float Double Character
    Boolean Void

77
An Object Data Type (String)
  • Each object value is an instance of a class.
  • The internal representation of an object can be
    more complex.
  • We will look at the object data types in detail
    later.
  • String literals my name 123
  • String s1, s2
  • s1 abc
  • s2 defg
  • System.out.println(s1s2)

an object of String
abc
s1
s2
defg
an object of String
78
The String Class
  • Every character string is an object in Java,
    defined by the String class
  • Every string literal, delimited by double
    quotation marks, represents a String object
  • The string concatenation operator () is used to
    append one string to the end of another
  • It can also be used to append a number to a
    string
  • A string literal cannot be broken across two
    lines in a program

79
String Class
String(String str) //constructor char charAt(int
index) int compareTo(String str) String
concat(String str) boolean equals(String
str) boolean equalsIgnoreCase(String str) int
length() String replace(char oldChar, char
newChar) String substring(int offset, int
endIndex) String toLowerCase() String
toUpperCase()
80
String Concatenation
  • The plus operator () is also used for arithmetic
    addition
  • The function that the operator performs depends
    on the type of the information on which it
    operates
  • If both operands are strings, or if one is a
    string and one is a number, it performs string
    concatenation
  • If both operands are numeric, it adds them
  • The operator is evaluated left to right
  • Parentheses can be used to force the operation
    order

81
Escape Sequences
  • What if we wanted to print a double quote
    character?
  • The following line would confuse the compiler
    because it would interpret the second quote as
    the end of the string
  • System.out.println ("I said "Hello" to you.")
  • An escape sequence is a series of characters that
    represents a special character
  • An escape sequence begins with a backslash
    character (\), which indicates that the
    character(s) that follow should be treated in a
    special way
  • System.out.println ("I said \"Hello\" to you.")

82
Escape Sequences
  • Some Java escape sequences

83
  • String type
  • The type for arbitrary text
  • Is not a primitive data type, but Java has
    String literals
  • Strings are objects, represented by String class
  • in java.lang pachage
  • String name
  • namenew String ( Hello World!)
  • String namenew String(Hello World!)

declaration
instantiation
name
Hello World!
constructor
84
public class StringClass public static void
main(String args) String
phrasenew String(This is a class)
String string1, string2, string3, string4
char letter int lengthphrase.length()
letter phrase.charAt(5)
string1phrase.concat(, which manipulates
strings) string2string1.toUpperCase()
string3string2.replace(E, X)
string4string3.substring(3, 30)
System.out.println(Original stringphrase)
System.out.println(letter)
System.out.println(lengh islength) .

85
Arithmetic Expressions
  • Simple Assignment Statements
  • x y z
  • x x 5
  • Some of Arithmetic Operators
  • addition
  • subtraction
  • multiplication
  • / division
  • mod operator (remainder)

86
Arithmetic operators
op1op2 addition op1-op2 subtraction op1op2 mu
ltiplication op1/op2 division op1op2 modulo
  • op1 and op2 can be of integer or floating-point
    data types
  • if op1 and op2 are of the same type, the type
    of result will be the same
  • mixed data types arithmetic promotion
    before evaluation
  • op1 or op2 is a string operator
    performs concatenation

87
Arithmetic Expressions
  • An expression is a combination of operators and
    operands
  • Arithmetic expressions compute numeric results
    and make use of the arithmetic operators

Addition Subtraction - Multiplication Divis
ion / Remainder
  • If either or both operands to an arithmetic
    operator are floating point, the result is a
    floating point

88
Division
  • If the operands of the / operator are both
    integers, the result is an integer (the
    fractional part is truncated).
  • If one or more operands of the / operator are
    floating point numbers, the result is a floating
    point number.
  • The remainder operator returns the integer
    remainder after dividing the first operand by
    the second one.
  • The operands of must be integers.
  • Examples
  • 13 / 5 ? 2
  • 13.0 / 5 ? 2.4
  • 13 / 5.0 ? 2.4
  • 2 / 4 ? 0
  • 2.0 / 4.0 ? 0.5
  • 6 2 ? 0
  • 145 ? 4
  • -145 ? -4

89

Quick Review of / and   Remember when both
operands are integers, / performs integer
division. This simply truncates your answer.
Thus, -11/3 is -3 and 5/4 is 1, for
example.   The operator simply computes the
remainder of dividing the first operand by the
second. If the first operand is negative then
the answer will also be negative (or zero). If
the first operand is positive, then the answer
will also be positive (or zero.) Here are a few
examples   113 is 2 11-3 is 2 -11 3 is
-2 -11 -3 is -2   If you are at all unsure how
these work, please try a few out on your own,
compile and run them. (This is as easy as
running a program with the statement
System.out.println(-11-3))
90
Operator Precedence
  • x x y 5 // what is the order of
    evaluation?
  • Operators in the expressions are evaluated
    according to the rules of precedence and
    association.
  • Operators with higher order precedence are
    evaluated first
  • If two operators have same precedence, they are
    evaluated according to association rules.
  • Parentheses can change the order of the
    evaluations.
  • Precedence Rules for some arithmetic operators
  • - (unary minus and plus) right to left higher
  • / left to right
  • - left to right lower
  • Examples
  • x a b c d ? x ((a(bc))-d)
  • x (a b) c d ? x (((ab)c)-d)
  • x a b c ? x ((ab)c)
Write a Comment
User Comments (0)
About PowerShow.com