Download presentation
Presentation is loading. Please wait.
1
Chapter 2: Objects and Primitive Data
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
2
Objects and Primitive Data
We can now explore some more fundamental programming concepts Chapter 2 focuses on: predefined objects primitive data the declaration and use of variables expressions and operator precedence class libraries Java applets drawing shapes Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Software Engineering Goal to make software reliable and maintainable As the complexity of a program increases, its cost to develop and revise grows exponentially cost complexity Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Software Components Programs are easier to construct and modify if they are made up of separate components A software component can be thought of any program element that transforms input into output Input Component Output 16 Compute average 22 Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
5
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Software Components Components can be combined to make larger components Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
6
Object-Oriented Programming
Java is object-oriented language Programs are made from software components called objects Initially, we can think of an object as data for it and a collection of services Object contains data and methods to provide the service Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
7
Object-Oriented Programming
Class A class represents a concept An object is defined by a class Multiple objects can be created from the same class Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
8
Object-Oriented Programming
A class represents a concept and an object represents the realization of that concept Objects Class My first car John's car Dad's car Car Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
9
Introduction to Objects
Recall the Lincoln program, We invoked the println method of the System.out object: System.out.println ("Whatever you are, be a good one."); method object Information provided to the method (parameters) Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
10
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Input and Output Java I/O is based on input streams and output streams There are three predefined standard streams: The print and println methods write to standard output Stream System.in System.out System.err Purpose reading input writing output writing errors Default Device keyboard monitor Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
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 See Countdown.java (page 53) Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
12
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Countdown.java class Countdown { public static void main (String[] args) { System.out.print ("Three... "); System.out.print ("Two... "); System.out.print ("One... "); System.out.print ("Zero... "); System.out.println ("Liftoff!"); System.out.println ("Houston, we have a problem."); } // method main } // class Countdown Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
13
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
The String Class Every character string is an object in Java, defined by the String class Every string literal represents a String object A string literal cannot be broken across two lines in a program Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
14
String Concatenation and Addition
The + operator serves two purposes When applied to two strings, they are combined into one (string concatenation) When applied to a string and a number, that value is converted to a string and concatenated When applied to two numeric types, they are added together arithmetically See Antarctica.java and Sum.java Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
15
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Antarctica.java class Antarctica { public static void main (String[] args) { System.out.print ("The international " + "dialing code "); System.out.println ("for Antarctica is " + 672); } // method main } // class Antarctica Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
16
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Sum.java class Sum { public static void main (String[] args) { System.out.println ("The sum of 16 and 9 is " + (16+9)); System.out.println (“16 and 9 concatenated" ); } // method main } // class Sum Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
17
Multiple variables can be created in one declaration
A variable is a name for a location in memory A variable must be declared before use its name and the type of information that will be held in it data type variable name int total; int count, temp, result; Multiple variables can be created in one declaration Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
18
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
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 See PianoKeys.java (page 60) Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
19
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Piano_Keys.java class Piano_Keys { public static void main (String[] args) { int keys = 88; System.out.println ("The number of piano keys: " + keys); } // method main } // class Piano_Keys Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
20
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
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 Assigned values must be consistent with the variable's declared type Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
21
Assignment Statements
class United_States { public static void main (String[] args) { int states = 13; System.out.println ("States in 1776: " + states); states = 50; System.out.println ("States in 1959: " + states); } // method main } // class United_States Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
22
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Primitive Data Types Data type A set of values and the operators you can perform on them Each value stored in memory is associated with a particular data type Primitive data types The Java language has 8 predefined data types Reserved words for primitive types: byte, short, int, long, float, double, boolean, char Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
23
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Primitive Data 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 Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
24
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Integers There are four separate integer primitive data types They differ by the amount of memory used to store them Type byte short int long Storage 8 bits 16 bits 32 bits 64 bits Min Value -128 -32,768 -2,147,483,648 < -9 x 1018 Max Value 127 32,767 2,147,483,647 > 9 x 1018 Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
25
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Floating Point There are two floating point types: The float type stores 7 significant digits The double type stores 15 significant digits Approximate Min Value -3.4 x 1038 -1.7 x 10308 Approximate Max Value 3.4 x 1038 1.7 x 10308 Type float double Storage 32 bits 64 bits Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
26
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Characters A char value stores a single character from the Unicode character set A character set is an ordered list of characters The Unicode character set uses sixteen bits per character, allowing for 65,536 unique characters Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n' Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
27
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Characters The ASCII character set is still the basis for many other programming languages ASCII is a subset of Unicode, including: uppercase letters lowercase letters punctuation digits special symbols control characters A, B, C, … a, b, c, … period, semi-colon, … 0, 1, 2, … &, |, \, … carriage return, tab, ... Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
28
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Boolean A boolean value represents a true or false condition The reserved words true and false are the only valid values for a boolean type boolean done = false; Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
29
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Wrappers Wrapper class(포장 클래스) for each primitive type Wrapper classes are useful in situations where you need an object instead of a primitive type They also contain some useful methods Primitive Type int double char boolean Wrapper Class Integer Double Character Boolean Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
30
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Constants A constant is similar to a variable except that they keep the same value throughout their existence They are specified using the reserved word final For example: final double PI = ; final int STUDENTS = 25; Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
31
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Constants When appropriate, constants are better than variables they prevent inadvertent errors because their value cannot change They are better than literal values because: they make code more readable by giving meaning to a value they facilitate change because the value is only specified in one place Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
32
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Expressions An expression is a combination of operators and operands every expression has its result value. The arithmetic operators +, -, *, /, %, ... Operands literal values, variables, or other sources of data The programmer usually store or print the result of an expression. Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
33
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Division Division A/B If A and B are both integers, the result is an integer (the fractional part is truncated) If one or more operands are floating point values, the result is a floating point value The remainder operator A%B returns the integer remainder after dividing The operands to the % operator must be integers The remainder result takes the sign of the numerator See Division.java Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
34
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Division.java class Division { public static void main (String[] args) { int oper1 = 9, oper2 = 4; double oper3 = 4.0; System.out.println ("Integer division: " + oper1/oper2); System.out.println ("Floating division: " + oper1/oper3); System.out.println ("Modulus division: " + oper1%oper2); } // method main } // class Division Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
35
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Division Expression 17 / 5 17.0 / 5 17 / 5.0 9 / 12 9.0 / 12.0 6 % 2 14 % 5 -14 % 5 Result 3 3.4 0.75 4 -4 Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
36
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Operator Precedence Operator precedence The order in which operands are evaluated in an expression Associativity Operators at the same level of precedence are evaluated (left to right ) or (right to left) Parentheses can be used to force precedence See Appendix D Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
37
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Operator Precedence Multiplication, division, and remainder have a higher precedence than addition and subtraction Both groups associate left to right Expression: Order of evaluation: Result: / % 3 6 3 1 4 2 Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
38
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Operator Precedence What is the order of evaluation in the following expressions? a + b + c + d + e a + b * c - d / e 1 2 3 4 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1 Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
39
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Operator Precedence Expression 2 + 3 * 4 / 2 3 * (3 * 13) + 2 3 * (13 + 2) 4 * (11 - 6) * ( ) (5 * (4 - 1)) / 2 Result 8 41 45 40 7 Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
40
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; 4 1 3 2 Then the result is stored in the variable on the left hand side Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
41
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) Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
42
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
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 Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
43
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Data Conversions Widening conversions are safest 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 they tend to go from a large data type to a smaller one (such as an int to a short) Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
44
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Data Conversions In Java, data conversions can occur in three ways: assignment conversion(ONLY WIDENING) arithmetic promotion(ONLY WIDENING) casting Assignment conversion occurs when a value of one type is assigned to a variable of another Arithmetic promotion happens automatically when operators in expressions convert their operands Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
45
Data Conversions Casting is the most powerful, and dangerous, technique for conversion Both widening and narrowing conversions To cast, the type is put in parentheses in front of the value being converted. result = (float) total / count; Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
46
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Creating Objects A variable either holds a primitive type, or it holds a reference to an object A class name can be used as a type to declare an object reference variable String title; No object has been created with this declaration An object reference variable holds the address of an object The object itself must be created separately Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
47
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 is an instance of a particular class Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
48
Creating Objects Because strings are so common, we don't have to use the new operator to create a String object title = "Java Software Solutions"; This is special syntax that only works for strings Once an object has been instantiated, we can use the dot operator to invoke its methods title.length() Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
49
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
String Methods The String class has several methods that are useful for manipulating strings Many of the methods return a value, such as an integer or a new String object See the list of String methods on page 75 and in Appendix M See StringMutation.java (page 77) Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
50
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
StringMutation.java public class StringMutation { public static void main (String[] args) String phrase = new String ("Change is inevitable"); String mutation1, mutation2, mutation3, mutation4; System.out.println ("Original string: \"" + phrase + "\""); System.out.println ("Length of string: " + phrase.length()); mutation1 = phrase.concat (", except from vending machines."); mutation2 = mutation1.toUpperCase(); mutation3 = mutation2.replace ('E', 'X'); mutation4 = mutation3.substring (3, 30); Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
51
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
StringMutation.java // Print each mutated string System.out.println ("Mutation #1: " + mutation1); System.out.println ("Mutation #2: " + mutation2); System.out.println ("Mutation #3: " + mutation3); System.out.println ("Mutation #4: " + mutation4); System.out.println ("Mutated length: " + mutation4.length()); } Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
52
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Class Libraries The Java API is a class library, a group of classes that support program development The classes in the Java API is separated into packages The System class, for example, is in package java.lang Each package contains a set of classes that relate in some way Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
53
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Packages The classes of the Java standard class library are organized into packages Package java.lang java.applet java.awt javax.swing java.net java.util Purpose General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities and components Network communication Utilities Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
54
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
The Java API Packages Other packages in the Java API: java.applet java.awt java.beans java.io java.lang java.math java.net java.rmi java.security java.sql java.text java.util Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
55
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Importing Packages (1) Using a class from Java API by a fully qualified name java.lang.System.out.println (); (2) Package can be imported using an import statement import java.applet.*; import java.util.Random; * to import all classes in a particular package Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
56
The import Declaration
All classes of the java.lang package are automatically imported into all programs System or String classes The Random class is part of the java.util package It provides methods for pseudo-random numbers scale and shift a number into an appropriate range See RandomNumbers.java (page 82) Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
57
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
RandomNumbers.java import java.util.Random; public class RandomNumbers { public static void main (String[] args) Random generator = new Random(); int num1; float num2; num1 = generator.nextInt(); System.out.println ("A random integer: " + num1); num1 = Math.abs (generator.nextInt()) % 10; System.out.println ("0 to 9: " + num1); Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
58
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
RandomNumbers.java num1 = Math.abs (generator.nextInt()) % ; System.out.println ("10 to 29: " + num1); num2 = generator.nextFloat(); System.out.println ("A random float [between 0-1]: " + num2); num2 = generator.nextFloat() * 6; // 0 to 5 num1 = (int) num2 + 1; System.out.println ("1 to 6: " + num1); } Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
59
Class Methods class methods or static methods
can be invoked through the class name, instead of through an object of the class The Math class contains many static methods, absolute value, trigonometry functions, square root, etc. temp = Math.cos(90) + Math.sqrt(delta); Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
60
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
The Keyboard Class The Keyboard class is NOT part of the Java API by the authors to make reading input from the keyboard easy contains several static methods for reading particular types of data The Keyboard class is part of a package called cs1 For now we will simply make use of it Details of the Keyboard class are explored in Chapter 8 See Echo.java (pp 86) and Quadratic.java (pp 87) Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
61
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Echo.java import cs1.Keyboard; public class Echo { public static void main (String[] args) String message; System.out.println ("Enter a line of text:"); message = Keyboard.readString(); System.out.println ("You entered: \"" + message + "\""); } Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
62
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Quadratic.java import cs1.Keyboard; public class Quadratic { public static void main (String[] args) int a, b, c; // ax^2 + bx + c System.out.print ("Enter the coefficient of x squared: "); a = Keyboard.readInt(); System.out.print ("Enter the coefficient of x: "); b = Keyboard.readInt(); System.out.print ("Enter the constant: "); c = Keyboard.readInt(); double discriminant = Math.pow(b, 2) - (4 * a * c); double root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a); double root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a); System.out.println ("Root #1: " + root1); System.out.println ("Root #2: " + root2); } Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
63
Formatting Output The NumberFormat class has static methods that return a formatter object getCurrencyInstance() getPercentInstance() Each formatter object has a method called format that returns a string with the specified information in the appropriate format See Price.java (page 89) Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
64
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Price.java import cs1.Keyboard; import java.text.NumberFormat; public class Price { public static void main (String[] args) final double TAX_RATE = 0.06; // 6% sales tax int quantity; double subtotal, tax, totalCost, unitPrice; System.out.print ("Enter the quantity: "); quantity = Keyboard.readInt(); System.out.print ("Enter the unit price: "); unitPrice = Keyboard.readDouble(); Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
65
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Price.java subtotal = quantity * unitPrice; tax = subtotal * TAX_RATE; totalCost = subtotal + tax; // Print output with appropriate formatting NumberFormat money = NumberFormat.getCurrencyInstance(); NumberFormat percent = NumberFormat.getPercentInstance(); System.out.println ("Subtotal: " + money.format(subtotal)); System.out.println ("Tax: " + money.format(tax) + " at " + percent.format(TAX_RATE)); System.out.println ("Total: " + money.format(totalCost)); } Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
66
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Formatting Output The DecimalFormat class can be used to format a floating point value in generic ways For example, you can specify that the number be printed to three decimal places The constructor of the DecimalFormat class takes a string that represents a pattern for the formatted number See CircleStats.java (page 91) Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
67
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
CircleStats.java import cs1.Keyboard; import java.text.DecimalFormat; public class CircleStats { public static void main (String[] args) int radius; double area, circumference; System.out.print ("Enter the circle's radius: "); radius = Keyboard.readInt(); area = Math.PI * Math.pow(radius, 2); circumference = 2 * Math.PI * radius; Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
68
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
CircleStats.java // Round the output to three decimal places DecimalFormat fmt = new DecimalFormat ("0.###"); System.out.println ("The circle's area: " + fmt.format(area)); System.out.println ("The circle's circumference: " + fmt.format(circumference)); } Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
69
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Input and Output The Java API allows you to create many kinds of streams to perform various kinds of I/O To read character strings, we will convert the System.in stream to another kind of stream using: BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); This declaration creates a new stream called stdin We will discuss object creation in more detail later Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
70
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Numeric Input Converting a string that holds an integer into the integer value using Integer wrapper class: value = Integer.parseInt (my_string); A value can be read and converted in one line: num = Integer.parseInt (stdin.readLine()); See Addition.java and Addition2.java Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
71
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Escape Sequences See Echo.java An escape sequence is a special sequence of characters preceded by a backslash (\) They indicate some special purpose, such as: Escape Sequence \t \n \" \' \\ Meaning tab new line double quote single quote backslash Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
72
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Echo.java import java.io.*; class Echo { public static void main (String[] args) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); String message; System.out.println ("Enter a line of text:"); message = stdin.readLine(); System.out.println ("You entered: \"" + message + "\""); } // method main } // class Echo Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
73
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Java Applets A Java applet a Java program that is intended to be sent across a network and executed using a Web browser A Java application is a stand alone program Applications have a main method, but applets do not Special methods of applets The paint method, for instance, is automatically executed and is used to draw the applets contents Applets are derived from the java.applet.Applet Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
74
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Java Applets Links to applets can be embedded in HTML documents 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(Netscape or Explorer) Appletviewer in JDK appletviewer xxx.html Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
75
Execution of Java Applets
local computer Java source code Java compiler Java bytecode Web browser remote computer Java interpreter Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
76
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
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 See Einstein.java (page 93) Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
77
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Einstein.java import java.applet.Applet; import java.awt.*; public class Einstein extends Applet { // Draws a quotation by Albert Einstein among some shapes. public void paint (Graphics page) page.drawRect (50, 50, 40, 40); // square page.drawRect (60, 80, 225, 30); // rectangle page.drawOval (75, 65, 20, 20); // circle page.drawLine (35, 60, 100, 120); // line page.drawString ("Out of clutter, find simplicity.", 110, 70); page.drawString ("-- Albert Einstein", 130, 100); } Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
78
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Drawing Shapes A shape can be filled or unfilled, depending on which method is invoked fillArc( ), fillOval( ), fillRect( ) The method parameters specify coordinates and sizes Java coordinate system has the origin in the upper left corner Many shapes with curves, like an oval, are drawn by specifying its bounding rectangle An arc can be thought of as a section of an oval Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
79
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Drawing a Line X Y 10 150 20 45 page.drawLine (10, 20, 150, 45); page.drawLine (150, 45, 10, 20); or Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
80
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Drawing a Rectangle X Y 50 20 40 100 page.drawRect (50, 20, 100, 40); Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
81
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Drawing an Oval X Y 175 20 80 bounding rectangle 50 page.drawOval (175, 20, 50, 80); Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
82
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
The Color Class A color is defined in a Java program using an object created from the Color class The Color class also contains several static predefined colors Every graphics context has a current foreground color Every drawing surface has a background color See Snowman.java (page ) Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
83
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Snowman.java import java.applet.Applet; import java.awt.*; public class Snowman extends Applet { public void paint (Graphics page) final int MID = 150; final int TOP = 50; setBackground (Color.cyan); page.setColor (Color.blue); page.fillRect (0, 175, 300, 50); // ground page.setColor (Color.yellow); page.fillOval (-40, -40, 80, 80); // sun Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
84
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Snowman.java page.setColor (Color.white); page.fillOval (MID-20, TOP, 40, 40); // head page.fillOval (MID-35, TOP+35, 70, 50); // upper torso page.fillOval (MID-50, TOP+80, 100, 60); // lower torso page.setColor (Color.black); page.fillOval (MID-10, TOP+10, 5, 5); // left eye page.fillOval (MID+5, TOP+10, 5, 5); // right eye page.drawArc (MID-10, TOP+20, 20, 10, 190, 160); // smile page.drawLine (MID-25, TOP+60, MID-50, TOP+40); // left arm page.drawLine (MID+25, TOP+60, MID+55, TOP+60); // right arm page.drawLine (MID-20, TOP+5, MID+20, TOP+5); // brim of page.fillRect (MID-15, TOP-20, 30, 25); // top of hat } Chapter 3 Copyright 1997 by John Lewis and William Loftus. All rights reserved.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.