Computing and the Humanities - PowerPoint PPT Presentation

About This Presentation
Title:

Computing and the Humanities

Description:

Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' 'n' 16. Characters ... Author: Ilyas Cicekli Date: October 9, 1997 ... – PowerPoint PPT presentation

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

less

Transcript and Presenter's Notes

Title: Computing and the Humanities


1
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.

2
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

3
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

4
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
5
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.
6
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).
7
boolean true or false
char x, 6, \, \, \u006A
16 bit unicode
Example
int a1, b0 boolean boolaltb // bool is
false char lettera
8
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!)
9
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
10
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
11
int y4, z2 xy/z
Syntax error
12
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

13
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

14
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)

15
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'

16
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

17
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).

18
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

19
/ 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
20
/ 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
21
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
22
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

23
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

24
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..

25
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

26
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

27
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

28
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

29
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
30
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
31
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

32
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

33
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

34
A Simple Applet Program (cont.)
Output
35
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)

36
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.

37
Output of ManApplet
38
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.
  • .

39
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

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

41
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

42
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.

43
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

44
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.

45
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

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

47
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

48
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
49
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

50
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()
51
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

52
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.")

53
Escape Sequences
  • Some Java escape sequences

54
  • 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
55
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) .

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

57
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

58
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

59
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

60

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))
61
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)

62
Data Conversion
  • Because Java is a strongly typed language, each
    data value is associated with a particular type.
  • Sometimes we may need to convert a data value of
    one type to another type.
  • In this conversion process, we may use loose
    important information.
  • A conversion between two primitive types falls
    into one of two categories
  • widening conversion widening conversions
    usually do not loose information
  • narrowing conversion narrowing conversions may
    loose information
  • A boolean value cannot be converted to any other
    primitive type.

63
Data Conversions
  • Sometimes it is convenient to convert data from
    one type to another
  • For example, we may want to treat an integer as a
    floating point value during a computation
  • Conversions must be handled carefully to avoid
    losing information
  • Widening conversions are safest because they tend
    to go from a small data type to a larger one
    (such as a short to an int)
  • Narrowing conversions can lose information
    because they tend to go from a large data type to
    a smaller one (such as an int to a short)

64
Java Widening Conversions
  • In widening conversions, they often go from one
    type to another type uses more space to store the
    value.
  • In most widening conversions, we do not loose
    information.
  • we may loose information in the following
    widening conversions
  • int ? float long ? float long ? double

65
Widening Conversions (cont.)
  • A widening conversion may automatically occur
  • int x long y double z
  • y x
  • z x 1 // the result of the addition is
    converted into double
  • z x 1.0 // the value of x is converted into
    double, then the addition is performed.
  • We may use information in some widening
    conversions
  • int x 1234567891 // int is 32-bit and float is
    32-bit
  • float y
  • y x // we will loose some precision (7 digit
    precision)

66
/ Testing data conversion / public class
DataConv public static void main(String
args) long i100000001 // 9 digits
float x xi System.out.println("x"x
)
Output
67
Java narrowing conversions
byte char short byte, char char byte,
short int byte, short, char long byte, short,
char, int float byte, short, char, int,
long double byte, short, char, int, long, float
16
16
64
32
Can lose both numeric magnitude and precision
Both short char and char short are narrowing
conversions!
68
  • In Java, data conversions can occur in three
    ways
  • assignment conversion
  • arithmetic promotion
  • casting
  • Assignment conversion occurs when a value of one
    type is assigned to a variable of another
  • Only widening conversions can happen via
    assignment

int dollars float money25.18 intmoney
compile-time error
69
  • Arithmetic promotion happens automatically when
  • operators in expressions convert their operands
  • When an integer and a floating-point number are
    used as operands to a single arithmetic
    operation, the result is floating point. The
    integer is implicitly converted to a
    floating-point number before the operation takes
    place.

int i37 double x27.475 System.out.println(ix
(ix))
Output
ix64.475l
70
Mixed-Type Arithmetic
byte short int long float double
Automatic (implicit) conversion
bytelong longlong floatint
floatfloat floatdouble doubledouble
71
Data Conversions
  • Casting is the most powerful, and dangerous,
    technique for conversion
  • Both widening and narrowing conversions can be
    accomplished by explicitly casting a value
  • To cast, the type is put in parentheses in front
    of the value being converted
  • For example, if total and count are integers, but
    we want a floating point result when dividing
    them, we can cast total.

72
Casting
import java.io. class Test public static
void main(String args) int a,b a
3 b 2 System.out.println(a/b)
System.out.println((float)(a/b))
System.out.println((float)a/b)
System.out.println((float)a/(float)b) eola
16 javac Test.java eola 17 java
Test 1 1.0 1.5 1.5 eola 18
73
int total1, count2 float result result
(float) total / count
Output
result0.5
int total1, count2 float result result
total / count
Output
result0.0
74
Operator Precedence
  • Operators can be combined into complex
    expressions
  • result total count / max - offset
  • Operators have a well-defined precedence which
    determines the order in which they are evaluated
  • Multiplication, division, and remainder are
    evaluated prior to addition, subtraction, and
    string concatenation
  • Arithmetic operators with the same precedence are
    evaluated from left to right
  • Parentheses can always be used to force the
    evaluation order

75
Operator Precedence
  • What is the order of evaluation in the following
    expressions?

a b c d e
a b c - d / e
1
4
3
2
3
2
4
1
a / (b c) - d e
2
3
4
1
a / (b (c (d - e)))
4
1
2
3
76
Assignment Revisited
  • The assignment operator has a lower precedence
    than the arithmetic operators

First the expression on the right hand side of
the operator is evaluated
answer sum / 4 MAX lowest
1
4
3
2
Then the result is stored in the variable on the
left hand side
77
Assignment Revisited
  • The right and left hand sides of an assignment
    statement can contain the same variable

First, one is added to the original value of count
count count 1
Then the result is stored back into
count (overwriting the original value)
78
Increment and Decrement Operators
ik kk1 kk1 ik ik kk-1 kk-1 ik
ik ik ik-- i--k
int i,j,k1 //initially ij0 ik // i2,
k2 jk-- // j2, k1
79
Assignment Operators
assignment addition, then assignment - subtr
action, then assignment multiplication, then
assignment / division, then assignment remaind
er, then assignment
80
Comparison (or relational ) Operators
Return type boolean
lt less than gt greater than lt less than or
equal gt greater or equal equal ! not
equal instanceof type comparison
When operator is used to compare two object
variables of the same type, the result of
comparison is true only if two variables refer
to the same object. equals() method is used to
compare objects.
81
Numeric operators precedence
1. ( ) Parenthesis 2. -- Increment,
Decrement 3. / Multiplication, Division,
Modulus 4. - Addition, Subtraction 5. lt gt
lt gt Relational Operatots 6. ! Equality
Operators 7. - / Assignment
Operators
82
What value will j and k have after each of the
following calculations? Assume j has the value 10
and k has the value 5 before each operation is
done.
kj k-j kj2 k/25j-- kj-3
83
Java Operators contd
Evaluate the following expression
96lt2542
1
3
2
4
96lt2542
2
1
3
4
int m10, k2, j3 mjk--
j4, k1, m60
jj1 mm(jk) kk-1
84
Increment and Decrement Operators
  • The increment operator and the decrement
    operator -- can be applied to all integer and
    floating point types.
  • The increment and decrement operators are unary
    operators, and their arguments must be variables.
  • The increment operator adds one to its argument,
    the decrement operator subtracts one from its
    argument.
  • They can be prefix or postfix operators.
  • pre-increment, post-increment, pre-decrement,
    post-decrement
  • In pre-increment and pre-decrement operations,
    first these operations are performed then the
    value of the variable is used in the expression.
  • In post-increment and post-decrement operations,
    first the value of the variable is used in the
    expression, then these operations are performed.
  • Examples
  • int x2 int y
  • y x 2 ? x is 3, y is 6
  • y x 3 ? x is 4, y is 9
  • y x-- 1 ? x is 3, y is 5
  • y --x 1 ? x is 2, y is 3

85
Operators and Precedence Rules

86
Input and Output (in Console Applications)
  • Java I/O is based on input and output streams
  • There are pre-defined standard streams
  • System.in reading input keyboard
    (InputStream object)
  • System.out writing output monitor
    (PrintStream object)
  • System.err writing output (for errors) monitor
    (PrintStream object)
  • print and println methods (defined in PrintStream
    class) are used to write to the the standard
    output stream (System.out).
  • We will get the inputs from the standard input
    stream (System.in).
  • To read character strings, we will create a more
    useful object of BufferedReader class from
    System.in.
  • BufferedReader stdin
  • new BufferedReader(new InputStreamReader(System.i
    n))

87
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()
88
s1new String(Hello!) s2new
String(Hello!) boolean b1s1s2 boolean
b2s1.equals(s2) s1s2 boolean b3s1s2
false
true

Hello!
s1
Hello!
s2
true

89
Creating Objects
  • We use the new operator to create an object

title new String ("Java Software Solutions")
This calls the String constructor, which is a
special method that sets up the object
  • Creating an object is called instantiation
  • An object (title ) is an instance of a particular
    class
  • (String)

90
Method invocation
  • Once an object has been instantiated, we can use
    the dot operator to invoke its methods
  • title.length()

91
Simple I/O Program
  • // This program reads your name and print it
    together with "Hi"
  • import java.io.
  • public class HiMessage
  • public static void main(String args) throws
    IOException
  • String yourName
  • // Create a BufferedReader object
  • ? BufferedReader stdin
  • new BufferedReader(new InputStreamReader(System
    .in))
  • // print the prompt
  • ? System.out.print("Enter your name and push
    enter key gt ")
  • System.out.flush()
  • // read the name
  • ? yourName stdin.readLine()

92
Numeric Input
  • We always read a string first, then we convert
    that string into a numeric value.
  • String astring
  • int num
  • astring stdin.readLine()
  • num Integer.parseInt(astring)
  • parseInt is a static method in the wrapper class
    Integer which converts a string into an int value
    (assuming that the string holds the digits of
    that integer).
  • If we put space before or after the integer
    number, the Java system will give an error
    message.

93
Numeric Input trim()
  • To able to put extra spaces before and after a
    numeric value during the input, we may use trim
    method of String class.
  • num Integer.parseInt(astring.trim())
  • trim method removes blanks in the front and the
    end of a string object (creates a new String
    object).
  • String s
  • s 123
  • s.trim() ? 123

94
To Read a double Value
  • We always read a string first, then we convert
    that string into a numeric value.
  • String astring
  • double num
  • astring stdin.readLine()
  • num Double.parseDouble(astring)
  • parseDouble is a static method in the wrapper
    class Double which converts a string into an
    double value (assuming that the string holds
    the digits of that double number).
  • To remove extra spaces before and after a numeric
    value during the input, we may use trim method of
    String class.
  • num Double.parseDouble(astring.trim())

95
String argv
  • Useful to pass parameters into program
  • public static void main(String argv)
  • use argv.length to see how many parameters were
    entered
  • argv0 gives first parameter (string)
  • argv1 gives second string
  • String s1 argv0

96
Simple I/O in Applets
  • import java.awt.
  • import java.applet.
  • import java.awt.event.
  • public class HiMessageApplet extends Applet
    implements ActionListener
  • Label prompt,greeting // Output areas
  • TextField input // Input area
  • // This method will be called when the applet
    starts,
  • // and creates the required parts of the
    applet.
  • public void init()
  • // Create prompt area and put it into the
    applet
  • prompt new Label("Enter your name and
    push return key ")
  • add(prompt)
  • // Create input area and put it into the
    applet
  • input new TextField(20)
  • add(input)
  • // Create greeting area and put it into the
    applet
  • greeting new Label("")
  • add(greeting)

97
Simple I/O in Applets (cont.)
  • // This method will be called when anytime a
    string is typed
  • // in input area and the return key is pushed.
  • public void actionPerformed(ActionEvent e)
  • greeting.setSize(300,20)
  • greeting.setText("Hi " input.getText())
  • input.setText("")

98
Simple I/O in Applets (Output)
At the beginning
Before we push the return key
After we pushed the return key
99
Simple I/O in Applets (Output-cont.)
Before we push the return key
After we pushed the return key
100
Another Applet with I/O Operations
  • import java.applet.Applet
  • import java.awt.
  • import java.awt.event.
  • public class SumAverageApplet extends Applet
    implements ActionListener
  • Label prompt // prompt area
  • TextField input // input area for positive
    integer
  • int number // value of positive integer
  • int sum // sum of all numbers
  • int count // number of positive integers
  • double average // average of all numbers
  • // Create the graphical components and
    initialize the variables
  • public void init()
  • // Create prompt and put it into the applet
  • prompt new Label( "Enter a positive
    integer and push the return key" )
  • add(prompt)
  • // Create input area and put it into the
    applet

101
Another Applet with I/O Operations (cont.)
  • // Respond to the events in input area
  • public void actionPerformed(ActionEvent e)
  • // Get the input and convert it into a number
  • number Integer.parseInt(e.getActionCommand()
    .trim())
  • // Evaluate the new values
  • sum sum number
  • count count 1
  • average (double) sum / count
  • input.setText("")
  • // show the results
  • repaint()
  • // Show the results
  • public void paint(Graphics g)
  • g.drawString("SUM " Integer.toString(sum),
    50, 50)
  • g.drawString("AVG " Double.toString(average
    ), 50, 70)

102
Another Applet with I/O Operations (output)
103
What happens when we type a real number?
104
Logical (Boolean) Operators
! Unary logical compliment (NOT) Evaluation
AND XOR Evaluation OR Short-circuit
AND Short-circuit OR
boolean
if isHighPresure is true, the second operand
will not be evaluated
Examples
if(!isHighPressure(temp1gttemp2)) boolean
b1(xlty)(agtb) boolean b2(10lt5)(5gt1)
both operands will always be evaluated
105
The Random Class (java.util)
see page 727
Methods
Random() class constructor float
nextFloat() returns a random float number
between 0.0 and 1.0 int nextInt() returns a
random integer number between -231 and 231-1
106
Example
import java.util.Random public class
RandomNumbers Random generatornew
Random() int num1 float num2
num1generator.nextInteger()
num2generator.nextFloat() .
an object of class Random is created
(instantiated)
Methods from class Random are called
107
Math Class (java.lang)
see page 710
Methods
static int abs(int num) static double acos(double
num) static double asin(double num) static double
cos(double angle) static double exp(double
num) static double pow(double num, int
power) static double sqrt(double num)
Methods that can be invoked through the class
name (without having to instantiate an object
first) are called static (or class) methods
108
import java.util.Random public class
RandomNumbers public static void main
(String args) Random generator new
Random() int num1 float num2
num1 generator.nextInt() num1 Math.abs
(generator.nextInt()) 10
the method abs(int) from class Math is called
without instantiation of an object (via class
name)
num1 now is an integer from 0 to 9.
109
contd
num1 Math.abs (generator.nextInt()) 10
1 System.out.println ("1 to 10 " num1)
num1 Math.abs (generator.nextInt()) 20 10
System.out.println ("10 to 29 " num1)
num2 generator.nextFloat()
System.out.println ("A random float"num2)
num2 generator.nextFloat() 6 num1
(int) num2 1 System.out.println ("1 to 6 "
num1)
110
println() is a method declared in the class
PrintStream.
java.io.PrintStream class is Javas printing
expert
public class PrintStream extends
FilterOutputStream public print (String s)
public print (int i) public print
(boolesn b) public println (String s)

So, different print() and println( ) methods
belong to PrintStream class
111
System.out is a variable from class System and is
of type PrintStream
public final class System ... public
static PrintStream out // Standart output
stream public static PrintStream err //
Standart error stream public static
InputStream in // Standart input stream ...
System class is part of java.lang package.
112
System.out.println(Hello World!)
  • A method println(...) is a service that the
    System.out
  • object can perform . This is the object of type
    PrintStream,
  • declared in java.lang.System class.
  • Method println(...) is invoked ( or called )
  • The method println() is called by sending the
    message
  • to the System.out object, requesting the
    service.

113
NumberFormat Class (java.text)
page 720
This class is abstract that means that an object
can not be instantiated using a new operator.
You request an object from one of the methods
invoked through class itself
String format(double number) returns a string
containing the number in the format
specified by the object
converts double_n into string in accordance with
objNumberFormat
Example
String sobjNumberFormat.format(double_n)
an instance of NumberFormat object
114
Methods of NumberFormat class that return an
object
static NumberFormat getCurrencyInstance()
returns an instance of NumberFormat object,
that represents currency format static
NumberFormat getPercentInstance() returns an
instance of NumberFormat object, that
represents percentage format
115
Example
import java.text.NumberFormat public class
Price double total19.35 double
tax_rate0.06 NumberFormat money
NumberFormat.getCurrencyInstance() String
formated_total money.format(total)
NumberFormat percent NumberFormat.getPercentIns
tance() String formated_taxpercent.format(tax_
rate)
116
DecimalFormat Class (java.txt)
DecimalFormat (String pattern) constructor
creates a DecimalFormat object with
specified pattern
argument of String type is sent to constructor
name of object
DecimalFormat fmtnew DecimalFormat(0.)
constructor is called
an object is created
type of object
117
void applyPattern (String pattern) applies
the specified pattern to the DecimalFormat object
fmt.applyPattern(0.)
118
String format (double number) returns a string
containing the number, formated in
accordance with the NumberFormat object
int radius5 double areaMath.PIMath.pow(radius,
2) System.out.println(fmt.format(area))
Output 78.5398
Write a Comment
User Comments (0)
About PowerShow.com