Presentation is loading. Please wait.

Presentation is loading. Please wait.

Workshop on Java Programming

Similar presentations


Presentation on theme: "Workshop on Java Programming"— Presentation transcript:

1 Workshop on Java Programming
September 29, October 13, October 20 YANPING CHEN

2 Introduction to Object-Oriented Programming Concepts

3 Software Life Cycle Steps in software development
Problem specification Algorithm development Coding Testing Debugging Maintenance Documenting is an activity that occurs throughout the cycle

4 Problem Specification
The goal – use computer to solve problems Problems are usually stated in natural language Software designer extracts the exact problem specification from the informal problem -- requirements analysis

5 Understand the Problem
Clarify What data is given (available for use when the problem-solving takes place) What results are required What assumptions are safe to make What constraints must be obeyed

6 Example 1 Informal statement
John wants to know the total and average cost of the three books he just bought. Givens: descriptions and names of the values that are know A, B, C numbers representing the cost of each of John’s books Results: descriptions and names of the values to be computed from the givens SUM, the sum of A, B and C AVG, the average of A, B, C

7 Example 2 Informal statement
Write an algorithm that takes four scores (each out of 25) and computes their average (out of 100) Givens: descriptions and names of the values that are know A, B, C, D numbers representing the four scores Results: descriptions and names of the values to be computed from the givens AVG, the average of A, B, C, D out of 100

8 Algorithm An algorithm is a solution for a problem
An algorithm’s HEADER specifies the name of the algorithm, an order for the givens and an order for the results An algorithm’s BODY is a sequence of instructions which, when executed, computes the desired results from the givens. Algorithms are written in “pseudocode”. A precise notation convenient for people but not executable by computers.

9 Intermediate Variables
Often it is useful within an algorithm to use a variable that is neither a given nor a result to temporarily hold a value. Intermediate variables’ values are not returned to the calling statement, nor are they remembered from one call to the next.

10 Algorithm for Example1 GIVENS: numbers A, B, C RESULTS: HEADER
SUM, the sum of A, B and C AVG, the average of A, B and C HEADER Alg1(A, B, C) Return: (Sum, Avg) BODY Sum = A+B+C Avg = Sum /3

11 Algorithm for Example2 GIVENS: numbers A, B, C, D RESULTS: HEADER
AVG, the average of A, B, C and D out of 100 HEADER Alg2(A, B, C, D) Return: (Avg) BODY Sum = A + B + C + D //an Intermediate Variable Avg = Sum /4/25*100

12 Tracing an Algorithm To TRACE an algorithm is to execute it by hand, one statement at a time, keeping track of the value of each variable. The aim is either to see what results the algorithm produces or to locate “bugs” in the algorithm.

13 Tracing Example Example 1 Example 2 Avg Alg1 (18, 25, 20)

14 Invoking an Algorithm To invoke an algorithm you use a “call” statement which is identical to the header except for the names of the givens and results. (X,Y) Alg1(10, 7, -2) invokes algorithm Alg1 with givens A=10, B=7, C=-2 and returns the results in X(Sum) and Y(Avg) Information is passed between the call statement and the algorithm based on the ORDER of the givens and results, not their names.

15 Coding Coding = translating an algorithm into a particular programming language so it can be executed on a computer Be sure your algorithm is correct before coding it by tracing it on test data. Coding is largely a mechanical process, not a creative one. Both algorithm development and coding require very careful attention to detail

16 Translating to Code To program is to first develop and test algorithms in pseudocode and then TRANSLATE them into code in a programming language Translating algorithms into code is very much a mechanical process, involving only a few decisions. For each pseudocode block we will see one foolproof way of translating it to code. Algorithms are then translated block by block.

17 Using Algorithms When developing an algorithm, it is a good idea to make as much use as possible of existing algorithms (ones you have written or that are available in a library) You can put a CALL statement to any existing algorithm wherever it is needed in the algorithm you are developing. Be sure you get the ORDER of the givens and results correctly. To call an algorithm you need to know its header but not how it works – you must just trust that it works correctly.

18 Information Passing When calling an algorithm the call statement and the header must be identical except for the names of the givens and results. These are matched one-to-one in the order they appear. CALL: (T, AvgOutOf25) Alg1(X,Y,Z) HEADER: (Sum, Avg) Alg1(A,B,C) The arrow show how information is passed.

19 Testing, Debugging and Maintenance
Testing = looking for errors (“bugs”) in an algorithm or program by executing it on test data (givens) and checking the correctness of the results. Debugging = locating and correcting an error in an algorithm or program Maintenance = changing an algorithm or program that is in use.

20 What is an Object? An object is a software bundle of variables and related methods Software objects are used to model real-world objects Real-world objects share two characteristics: They all have state and behavior. Software objects also have state and behavior. A software object maintains its state in one or more variables. And implements its behavior with methods. A variable is an item of data named by an identifier. A method is a function (subroutine) associated with an object

21 Examples of Object Bicycles: Dogs:
States: current gear, current pedal cadence, two wheels, number of gears Behaviors: braking, accelerating, slowing down, changing gears Dogs: States: name, color, breed, hungry Behaviors: barking, fetching, wagging tail

22 What is a Message? Software objects interact and communicate with each other using messages A single object alone is generally not very useful. Instead, an object usually appears as a component of a larger program or application that contains many other objects. Through the interaction of these objects, programmers achieve higher-order functionality and more complex behavior.

23 What is a Message? (2) Messages provide two important benefits.
An object's behavior is expressed through its methods, so message passing supports all possible interactions between objects. Objects don't need to be in the same process or even on the same machine to send and receive messages back and forth to each other.

24 Components of Message (1)
When object A wants object B to perform one of B's methods, object A sends a message to object B Sometimes, the receiving object needs more information so that it knows exactly what to do when you want to change gears on your bicycle, you have to indicate which gear you want. This information is passed along with the message as parameters

25 Components of Message (2)
Three components that comprise a message: The object to which the message is addressed (YourBicycle) The name of the method to perform (changeGears) Any parameters needed by the method (lowerGear)

26 What is a Class? (1) A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind. In the real world, you often have many objects of the same kind. For example, your bicycle is just one of many bicycles in the world. Bicycles have some state and behavior in common. However, each bicycle's state is independent of and can be different from that of other bicycles. Using o-o terminology, we say that your bicycle object is an instance of the class of objects known as bicycles.

27 What is a Class? (2) In object-oriented software, it's also possible to have many objects of the same kind that share characteristics: rectangles, employee records, video clips, and so on. Objects of the same kind are similar and you can create a blueprint for those objects.

28 Class and Instance (1) After create the bicycle class, you can create any number of bicycle objects from the class. When create an instance of a class, the system allocates enough memory for the object and all its instance variables. Each instance gets its own copy of all the instance variables defined in the class.

29 Class and Instance (2) Variables: Methods
Class variable: contains information that is shared by all instances of the class Instance variable: contains information for one specific instance Methods Class methods: invoked directly from the class. Instance methods: invoked on a particular instance

30 Example for Class Variables
Suppose that all bicycles had the same number of gears. Defining an instance variable to hold the number of gears is inefficient: each instance would have its own copy of the variable, but the value would be the same for every instance. Define a class variable that contains the number of gears. All instances share this variable. If one object changes the variable, it changes for all other objects of that type.

31 Objects vs. Classes The difference between classes and objects is confusing. In software, the term "object" is sometimes used to refer to both classes and instances. Class is not shaded. It represents a blueprint of an object rather than an object itself. A blueprint of a bicycle is not a bicycle. An object is shaded, indicating that the object exists and that you can use it.

32 What is Inheritance? A class inherits state and behavior from its superclass. Inheritance provides a powerful and natural mechanism for organizing and structuring software programs. You know a lot about an object by knowing its class. Even if you don't know what a penny-farthing is, if I told you it was a bicycle, you would know that it had two wheels, handle bars, and pedals. Object-oriented systems allow classes to be defined in terms of other classes.

33 Example for Inheritance
Mountain bikes, racing bikes, and tandems are all kinds of bicycles. In object-oriented terminology, they are all subclasses of the bicycle class. Similarly, the bicycle class is the superclass

34 How does Inheritance work? (1)
Each subclass inherits state (in the form of variable declarations) and methods from the superclass. e.g. Mountain bikes, racing bikes, and tandems share some states: cadence, speed, and some behaviors: braking and changing pedaling speed Subclasses are not limited to the state and behaviors provided to them by their superclass. Subclasses can add variables and methods to the ones they inherit from the superclass. e.g. Some mountain bikes have an extra set of gears with a lower gear ratio.

35 How does Inheritance work? (2)
Subclasses can also override inherited methods and provide specialized implementations for those methods. e.g You had a mountain bike with an extra set of gears, you would override the "change gears" method so that the rider could use those new gears. Not just one layer of inheritance: the inheritance tree, or class hierarchy, can be as deep as needed. -- The farther down in the hierarchy a class appears, the more specialized its behavior.

36 How does Inheritance work? (3)
In JAVA, the Object class is at the top of class hierarchy, and each class is its descendant (directly or indirectly). Object provides behaviors that are required of all objects running in the Java Virtual Machine. e.g. All classes inherit Object's toString method, which returns a string representation of the object.

37 Benefits of Inheritance
Reuse the code in the superclass: Subclasses provide specialized behaviors from the basis of common elements provided by the superclass. Programmers can implement superclasses called abstract classes that define "generic" behaviors. The abstract superclass defines and may partially implement the behavior, but much of the class is undefined and unimplemented. Other programmers fill in the details with specialized subclasses.

38 Why Abstract Class Abstract class: The methods can not be specified at that moment. e.g. TextMessage, VoiceMessage, FaxMessage all have a method called play(), how can you implement play() in the superclass Message? Message TextMessage VoiceMessage FaxMessage

39 What is an Interface? (1) An interface is a contract in the form of a collection of method and constant declarations. An interface is probably most analogous to a protocol (an agreed on behavior). When a class implements an interface, it promises to implement all of the methods declared in that interface

40 What is an Interface? (2) Interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. Capturing similarities among unrelated classes without artificially forcing a class relationship. Declaring methods that one or more classes are expected to implement. Revealing an object's programming interface without revealing its class.

41 Example of Interface An inventory program for bicycle doesn't care what class of items it manages as long as each item provides certain information, such as price and tracking number. The inventory program sets up a protocol of communication. This protocol comes in the form of a set of constant and method definitions contained within an interface. The inventory interface would define, but not implement, methods that set and get the retail price, assign a tracking number, and so on.

42 Summary Class is a prototype for objects
Objects are created from classes An object's class is its type How to create an object from a class What constructors are What class variables and methods are What instance variables and methods are How to find out what a class's superclass is Interface is a protocol of behavior

43 Exercises Define classes based on the following scenario: (make reasonable assumption) Your use an bank card to do some transaction from a bank machine. There are three type of transaction: withdraw, deposit and pay bill. You need input a 4 digits PIN before you can do any transaction Bank machine will give you a record after each transaction

44 First Cup of JAVA

45 Concise History of Java
1991: Group of Sun engineers design a small portable computer language for consumer devices 1992: First product delivered by the group 1995: Hotjava – a WWW browser written in Java with a built-in interpreter of intermediate bytecodes starts Java hype 1996: First official version of Java is released 1999: Professional-looking applications start to appear using the new Swing GUI API

46 About Java Java technology is both a programming language and a platform The Java programming language is a high-level language: Simple Architecture neutral Object oriented Portable Distributed High performance Interpreted Multithreaded Robust Dynamic Secure

47 Overview of Java (1) Object-Orientation (OO)
Programs describe interactions between a collection of objects which are designed to model some aspect of the real world. For example, an airline reservation system would involve Airplanes, Seats, Passengers, Tickets and so on. Syntax is borrowed from C++, while object model from Smalltalk.

48 Overview of Java (2) Portability
As in some version of Pascal, source code is first compiled into platform-independent intermediate code – bytecode. Unlike Pascal, this intermediate compilation stage is explicit Once in the form of bytecodes, programs can be executed by platform-dependent virtual machines. Java is often advertised as an interpreter. In reality, Java source code is always compiled into bytecodes first. Bytecodes themselves are interpreted by Java virtual machine (Java VM)

49 How Java works? The Java programming language is unusual both compiled and interpreted. With the compiler, first you translate a program into an intermediate language called Java bytecodes The platform-independent codes interpreted by the interpreter on the Java platform. The interpreter parses and runs each Java bytecode instruction on the computer. Compilation happens just once; interpretation occurs each time the program is executed.

50

51 Why Java Platform-independent
Java bytecodes help make "write once, run anywhere" possible. You can compile your program into bytecodes on any platform that has a Java compiler. The bytecodes can then be run on any implementation of the Java VM. As long as a computer has a Java VM, the same program written in the Java programming language can run on Windows 2000, a Solaris workstation, or on an iMac.

52

53 Java Programming Environment
Official address for download: SDK: JavaTM 2 Platform, Standard Edition v 1.2 or v1.3 Document: JavaTM 2 Platform, Standard Edition, v 1.2 or v1.3 Documentation Java 2 Runtime Environment: browser plug-in (not necessary)

54 Java Directory Tree \jdk
docs library documentation in HTML format is here bin the compiler and tools demo look here for demo include files for native methods lib library files src various subdirectories for the library source

55 Before using Java Update the PATH variable
e.g. In Autoexec.bat SET PATH=d:\Jdk1.2.2\bin; Set the CLASSPATH if necessary e.g. in Autoexec.bat SET CLASSPATH=.; e:\myJava

56 A Simple Java Program Everything in Java Access modifier
lives in a class Access modifier Name of class Public class FirstSample { public static void main(String[] args) //Do nothing System.out.println("Hello World!"); } Entrance from command line Command-line argument Comments Semicolon at the end of every statement A block of code Call the method println of System.out object

57 Several Rules for Start (1)
Naming rules for classes, methods, variables, etc.: Begin with a letter: ‘A’-’Z’, ‘a’-’z’, ‘-’ or any Unicode character that denotes a letter in a language Symbols like ‘+’ or can not be used, nor can spaces All characters are case sensitive Following with any combination of letters and digits Unlimited in length Can not use Java reserved words

58 Several Rules for Start (2)
File name must be exactly the same with class name Must have a main method for execution Braces (opening brace and close brace) are used to delineate the parts. Syntax for call method: object.method(parameters)

59 Your First Cup of Java (for Win32)
/*The HelloWorldApp class implements an application that displays "Hello World!" to the standard output. */ public class HelloWorldApp { public static void main(String[] args) // Display "Hello World!" System.out.println("Hello World!"); System.out.print("Hello World!"); System.out.println(“ I am learning Java!"); }

60 Step by Step (1) Create a source file – programmer understand
You can use any text editor to create and edit source files. Be Careful When You Type Type all code, commands, and file names exactly as shown. The Java compiler and interpreter are case-sensitive, so you must capitalize consistently. Save as HelloWorldApp.java

61 Step by Step (2) Compile the source file into a bytecode file - Java Virtual Machine (Java VM) understand. Open MS-DOS Prompt Go to the directory that you save your source file Enter: Javac HelloWorldApp.java  Get a class file HelloWorldApp.class

62 Step by Step (3) Run the program contained in the bytecode file - computer understand. Enter Java HelloWorldApp Have you got the greeting words?

63 Algorithm to Program Program = a Java class with a “main” method that is the translation of the algorithm. Givens, Results and intermediates all get translated to LOCAL VARIABLES They all must be declared and given a type. Program template

64 Exercises Define turnEngineOff() and decelerate() methods for Car class Translate the Example 2 of algorithm into Java code

65 Fundamental Programming Structures in Java - Data

66 Data Type Eight primitive types
Six number types (4 integer and two floating-point type) int short long byte bloat double One character type: char One Boolean type: boolean

67 Integers (1) Numbers without fractional parts
Negative values are allowed Long integer numbers have a suffix L. Hexadecimal numbers have a prefix 0x Type Storage requirement Range (inclusive) int 4 bytes -2,147,483,648 to 2,147,483,647 (just over 2 billion) short 2 bytes -32,768 to 32,767 long 8 bytes -9,223,372,036,854,775,808L to 9,223,372,036,854,775,807L byte 1 bytes -128 to 127

68 Integers (2) Under Java, the ranges of the integer types do not depend on the machine on which you will run your Java code. Platform-independent integer type brings a small performance penalty (not the worst one).

69 Floating-Point Types Denote numbers with fractional parts.
double means the numbers have twice the precision of the float type Without a suffix F, a number is always considered to be of type double. Type Storage requirement Range float 4 bytes approximately ± E+38F (6 ~ 7 significant decimal digits) double 8 bytes approximately ± E +308F (15 significant decimal digits)

70 The Character Type Denotes characters in the Unicode encoding scheme.
Designed to handle all characters in all written languages -- 35,000 are in use \u prefix with four hexadecimal digits indicates a Unicode value Single quotes are used to denote char constants. ‘H’ is a character “H” is a string

71 Special characters Escape Sequence Name Unicode Value \b backspace
tab \u0009 \n linefeed \u000a \r carriage return \u000d \” double quote \u0022 \’ single quote \u0027 \\ backslash \u005c

72 Boolean Type Used for logic testing Only two values: TRUE or FALSE
Not numbers

73 Variables (1) Java requests declaring the type of a variable
Declare a variable by placing the type first, followed by the name of the variable e.g. byte b; //for space-sensitive //considerations int anIntegerVariable; long aLongVariable; char ch;

74 Variables (2) Multiple declaration:
int i, j; //both are integers recommend to declare one variable per line You can put declaration anywhere in your code, but you can only declare a variable once in any block in a method.

75 Expressions An expression is a series of variables, operators, and method calls (constructed according to the syntax of the language) that evaluates to a single value The job of an expression To perform the computation indicated by the elements of the expression To return a value that is the result of the computation e.g. System.out.println("The largest byte value is " + largestByte);

76 Assignments and Initializations
After you declare a variable, you should initialize it by means of an assignment statement Never have un-initialized variables Assignment: Previously declared variable on the left an equal sign (=) some Java expression with an appropriate value on the right

77 Example of Assignments and Initializations
Correct assignments: int foo; //this is a declaration foo = 37; //this is an assignment char yesChar; yesChar = ‘Y’ int i = 10; //this is an initialization

78 Conversions Between Numeric Types (1)
A binary operations on numeric values of different types will be treated in the following fashion: If any of the operands is of type double, the other one will be converted to a double; Otherwise, if any of the operands is of type float, the other one will be converted to a float; Otherwise, if any of the operands is of type long, the other one will be converted to a long.

79 Conversions Between Numeric Types (2)
Numeric conversion – loss of information casts: give the target type in parentheses, followed by the variable name. e.g. double x = 9.997; int nx = (int) x; Value of nx is 9. Round: use the Math.round method. int nx = (int)Math.round(x); Value of nx is 10. Return type is long

80 Conversions Between Numeric Types (3)
Certain assignment conversion by assigning the value of a variable of one type to another without an explicit cast: byte short int long double float

81 Constants Use keyword final to denote a constant
final indicates that you can only assign to the variable once e.g. public class UsesConstants { public static void main(String args) final double CM_PER_INCH = 2.54; double paperWidth = 8.5; double paperHeight = 11; System.out.println(“Paper size in centimeter: ” + paperWidth * CM_PER_INCH + “ by ” + paperHeight * CM_PER_INCH ); }

82 Class Constants Use static final for class constants
Appear outside method e.g. public class UserConstants2 { public static final double G = 9.81; // gravitation in meters/second squared public static void main(String[] args) System.out.println(G + “meters per second squared”); }

83 Arithmetic Operators (1)
Arithmetic operators + - * / are used in Java for addition, subtraction, multiplication and division The / operator denotes integer division if both arguments are integers, and floating-point division otherwise. % denoted integer remainder. e.g. 15 / 6 is 2 15 % 6 is 3 11.0 / 4 is 2.75

84 Arithmetic Operators (2)
You can use arithmetic operators in your variable initialization e.g. int n = 5; int a = 2 * n; // a is 10 Shortcut for using binary arithmetic operators x += 4; equal to x = x + 4 y %= 3; equal to y = y % 3

85 Exponentiation Java has no operator for raising a quantity to a power
Use Math.pow method. e.g. double y = Math.pow(x, n); y is set to x raised to the power n, which is xⁿ The return type of Math.pow is double.

86 Increment and Decrement Operators (1)
Increment operator: ++ adds 1 to the current value of the variable e.g. int n = 12; n++; Value of n is 13 Decrement operator: -- subtracts 1 to the current value of the variable int m = 7; m--; Value of m is 6.

87 Increment and Decrement Operators (2)
Not be applied to number. e.g 4++ is error Two forms make difference in expressions – recommend against using ++ and -- inside other expressions: “postfix”: evaluate to the old value of the variable “prefix”: does addition or subtraction first e.g int m = 7; int n = 7; int a = 2 * ++m; // a is 16, m is 8 int b = 2 * n++; //b is 14, n is 8

88 Rational and Boolean Operators
Results of rational and Boolean operators are of type boolean Test for equality: == Test for inequality: != Less than: < Greater than: > Less than or equal: <= Greater than or equal: >= Logic and: && Logic or: || e.g. (3 != 7) is true

89 Bitwise Operators (1) Work with any of the integer types
Work directly with the bits that make up the integers – use masking techniques to get a individual bits in a number “and”: & “or”: | “xor”: ^ “not”: ~ e.g. if foo is an integer, int fouthBitFromRight = (foo & 8) / 8 gives the fourth bit from the right in the binary representation of foo is one, and a zero if not

90 Bitwise Operators (2) >> and << operators shift a bit pattern to the right or left >> operator fills the top bits with the sign bit >>> operator fills the top bits with zero There is no <<< operator

91 Parentheses and Operator Hierarchy
Use parentheses to indicate the order in which you want operations to be carried out If no parentheses are used, operations are performed in the hierarchical order indicated Operators on the same level are processed from left to right, except for those that are right associative

92 Operator Precedence Operators Associativity [] . ()(method call)
left to right ! ~ (unary) – (unary) ()(cast) new right to left * / % + - << >> >>> < <= > >= instanceof == != & ^ | && || ?: = += -= *= /= %= &= |= ^= <<= >>= >>>=

93 Strings Denotes a sequences of Unicode characters
Java has not a built-in string type Use methods in String class, each quoted string is an instance of the String class e.g. String e = “”; //and empty string String greeting = “Hello”;

94 Concatenation of Strings
Java allows to use the + sign to join(concatenate) two strings together e.g. String expletive = “Expletive”; String PG13 = “deleted”; String message = expletive + PG13; The + sign join two strings together in the order received, exactly as they are given When you concatenate a string with a value that is not a string, the value is converted to a string String fating = “PG” + 13 is “PG13”

95 Substrings Exact a substring from a larger string with the substring method of the String class. e.g String greeting = “Hello”; String s = greeting.substring(0, 4); s is “Hell” The first character in a string has position 0. The length of string s.substring(a, b) is always b - a

96 String Editing To find out the length of a string, use length():
e.g. String greeting = “Hello”; int n = greeting.length(); //is 5 To get at individual characters of a string: s.charAt(n), n is between 0 and s.length() - 1 char ch = greeting.charAt(1); // is ‘e’ No direct way to change a character in strings – use substring() and concatenation to do that

97 Testing Strings for Equality (1)
To test if or not two strings are equal: s.equals(t). -- Return true if the strings and t are equal, false otherwise e.g. “Hello”.equals(command); To test if two strings are identical except for the upper/lower case letter distinction: s.equalsIgnoreCase(t) “Hello”.equalsIgnoreCase(“hello”); is true

98 Testing Strings for Equality (2)
Do not use == to test if strings are equal, it only determines whether or not the strings are stored in the same location e.g. String greeting = “Hello”; if (greeting == “Hello”) //probably true if (greeting.substring(0,4) == “Hell”) . //probably false Never use == to compare strings Go to the Java document to find API of String

99 Input from a Command Line Parameter
public class Test { public static void main(String[] args) double x = args[0];  double y = args[1]; System.out.println(“I got ” + x +“ and ” + y + “ from command line); } C:\>java Test 3.02

100 Formatting Output (1) System.out.print(x) print x with the maximum number of non-zero digits for that type e.g. x = / 3.0; System.out.print(x); prints To arrange your output neatly: NumberFormat class in java.txt package offers formatters for numbers, currency values and percentage values e.g. for United States locale should print 3, $3,333.33 333,333%

101 Formatting Output (2) To obtain a formatter for the default locale:
NumberFormat.getNumberInstance() NumberFormat.getCurrencyInstance() NumberFormat.getPercentInstance() Customize output Set minimum or maximum number of integer digits: setMinimumIntegerDigits() setMaximumIntegerDigits() Set minimum or maximum number of fractional digits: setMinimumFractionDigits() default 0 setMaximumFractionDigits()

102 Example of formatting Output
1.double x = / 3.0; NumberFormat nf = NumberFormat.getNumberInstance(); String fx = nf.format(x); //the string is “3,333.33” 2. double x = / 3.0; nf.setMaximumFractionDigits(4); nf.setMinimumIntegerDigits(6); //the string is “003, ”

103 Formatter for different locales
Object Locale.GERMAN is the local for German number formatting rules e.g. double x = / 3.0; NumberFormat nf = NumberFormat.getNumberInstance( Locale.GERMAN); Sysetm.out.println(nf.format(x)); NumberForamt cf = NumberFormat.getCurrencyInstance( Locale.GERMAN); Sysetm.out.println(cf.format(x)); Prints: 3.333,333 3.333,33 DM

104 Create your own format e.g To define a format that shows number with six digits after the decimal point, but no thousands separator DecimalFormat df = new decimalFormat(“0.######”); System.out.println(df.format(x));

105 Formatting characters for DecimalFormat class
Symbol Meaning A digit # A digit; don’t show if it is a leading or trailing zero . Location of decimal separator , Location of grouping separator ; Separates formats for positive and negative numbers - Negative prefix % Divide by 100 and show as percentage Any other symbols Include symbol in output string

106 Excises Write a program that tests whether a floating point number is zero. (Hint: You shouldn't generally use the equality operator == with floating point numbers, since floating point numbers by nature are hard to match exactly. Instead, test whether the number is close to zero.) Change the code for Algorithm 1 and 2 to get parameter from command line. Write a program that calculates the number of US dollars equivalent to a given number of French francs. Assume an exchange rate of francs per dollar. If you want to control the format of the numbers your program displays, you can use the DecimalFormat class, which is discussed in Customizing Formats

107 4. Write a program that uses the bits in a single integer to represent the true/false data shown in the following figure: Include in the program a variable named status, and have the program print the meaning of status. For example, if status is 1 (only bit 0 is set) the program should print something like this: Ready to receive requests Show your code. What is the output when status is 8? What is the output when status is 7?

108 Fundamental Programming Structures in Java - Control

109 Statements (1) Statements are roughly equivalent to sentences in natural languages. It forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;): Assignment expressions Any use of ++ or -- Method calls Object creation expressions e.g aValue = ; aValue++; System.out.println(aValue); Integer integerObject = new Integer(4);

110 Statements (2) Two other kinds of statements.
declaration statement declares a variable. e.g. double aValue = ; control flow statement regulates the order in which statements get executed.

111 Know more about blocks (1)
Block is any number of simple Java statements that are surrounded by a pair of braces Blocks define the scope of variables Blocks can be nested inside another e.g. public static void main(String[] args) { int n;   { int k; // k local to block and //defines only until the //end of the block }

112 Know more about blocks (2)
It is not possible to declare identically named variables in two nested blocks e.g. public static void main(String[] args) { int n;   { int k; int n; // error – can’t redefine n // in inner block }

113 Conditional Statements (1) – if Statement
Syntax: if (condition) statement; if (condition) { block } e.g. if (yourSales >= target) { performance = “Satisfactory”; bonus = 100; } NO youSales >= target YES performance = “Satisfactory” bonus = 100

114 Conditional Statements (2) – if-else Statement
Syntax: if (condition) statement1 else statement2; if (condition) {block1} else {block2} e.g. if (yourSales >= target) { performance = “Satisfactory”; bonus = 100; } else performance = “Unsatisfactory”; bonus = 0;

115 Use else groups with the closest if
e.g.if (yourSales >= 2 * target) { performance = “Excellent”; bonus = 1000; } else if (yourSales >= 1.5 * target) performance = “Fine”; bonus = 500; else if (yourSales >= target) performance = “Satisfactory”; bonus = 100; else System.out.println(“You are fired!”);

116 ? Operator Java supports the ternary ? operator The expression
condition ? e1 : e2 evaluates to e1 if the condition is true, to e2 otherwise. e.g. (x < y) ? x:y give the smaller of x and y int x = 1; int y = 3; int z = (x < y) ? x:y; // z is 1

117 Multiple Selections - switch Statement
Conditionally perform statements based on an integer or char expression Select only against a char or against all the integer types but long. Can not use a range of values Each break statement terminates the enclosing switch statement, and the flow of control continues with the first statement following the switch block. Use the default statement at the end of the switch to handle all values that aren't explicitly handled by one of the case statements

118 public class SwitchDemo
{ public static void main(String[] args) { int day = 3; switch (month) { case 1: System.out.println(“Monday"); break; case 2:System.out.println(“Tuesday"); break; case 3: System.out.println(“Wednesday"); break; case 4: System.out.println(“Thursday"); break; …… case 7: System.out.println("June"); break; }

119 public class SwitchDemo2
{ public static void main(String[] args) { int month = 2; int year = 2000; int numDays = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 31; break; case 4: case 6: case 9: case 11: numDays = 30; break; case 2: if ( ((year % 4 == 0) && !(year % == 0)) || (year % 400 == 0) ) numDays = 29; else numDays = 28; break; } System.out.println("Number of Days = " + numDays);

120 int month = 8; . . . switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; …… case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: System.out.println("Hey, that's not a valid month!"); break; }

121 Breaks break statement is used to resume program execution at the statement immediately following the current statement. e.g. while (years <= 100) { balance = ( balance + payment ) * ( 1 + interest ); if ( balance > goal ) break; years++; }

122 Labeled Breaks If followed by a label, the program resumes execution at the labeled statement. e.g. next_client: …… while (years <= 100) { balance = ( balance + payment ) * ( 1 + interest ); if ( balance > goal ) break next_client; years++; }

123 Indeterminate Loops (1) - while loop
Syntax: while (condition) { block } The while loop only executes the body of the loop while a condition is true NO condition YES Statemets

124 public class WhileDemo
{ public static void main(String[] args) String copyFromMe = "Copy this string until you " + "encounter the letter 'g'."; StringBuffer copyToMe = new StringBuffer(); int i = 0; char c = copyFromMe.charAt(i); while (c != 'g') copyToMe.append(c); c = copyFromMe.charAt(++i); } System.out.println(copyToMe); }

125 Indeterminate Loops (2) - do-while loop
Syntax: do { block } while (condition) Instead of evaluating the expression at the top of the loop, do-while evaluates the expression at the bottom. The statements are executed at least once Statemets condition YES NO

126 public class DoWhileDemo
{ public static void main(String[] args) String copyFromMe = "Copy this string until you " + "encounter the letter 'g'."; StringBuffer copyToMe = new StringBuffer(); int i = 0; char c = copyFromMe.charAt(i); do copyToMe.append(c); c = copyFromMe.charAt(++i); } while (c != 'g'); System.out.println(copyToMe); }

127 Determinate Loops – for loop
Syntax: for (initialization; termination; increment ) {block} Equal to { initialization; while (termination) { block; increment; }

128 /*Adds the numbers from 1 to 10 and displays the result
*/ public class ForDemo { public static void main(String[] args) int sum = 0; for (int current = 1; current <= 10; current++) sum += current; } System.out.println("Sum = " + sum);

129 continue Statement Skip the current iteration of a for, while , or do-while loop The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop, basically skipping the remainder of this iteration of the loop. The labeled form skips the current iteration of an outer loop marked with the given label.

130 public class ContinueDemo
{ public static void main(String[] args) StringBuffer searchMe = new StringBuffer( "peter piper picked a peck of pickled peppers"); int max = searchMe.length(); int numPs = 0; for (int i = 0; i < max; i++) { //interested only in p's if (searchMe.charAt(i) != 'p') continue; //process p's numPs++; searchMe.setCharAt(i, 'P'); } System.out.println("Found " + numPs + " p's in the string."); System.out.println(searchMe);

131 public class ContinueWithLabelDemo
{ public static void main(String[] args) { String searchMe = "Look for a substring in me"; String substring = "sub"; boolean foundIt = false; int max = searchMe.length() - substring.length(); test: for (int i = 0; i <= max; i++) { int n = substring.length(); int j = i; int k = 0; while (n-- != 0) { if (searchMe.charAt(j++) != substring.charAt(k++)) { continue test; } } foundIt = true; break test; System.out.println(foundIt ? "Found it" : "Didn't find it");

132 return Statement Exit from the current method.
The flow of control returns to the statement that follows the original method call. Two forms Returns a value: put the value (or an expression that calculates the value) after the return keyword. The data type of the value returned by return must match the type of the method's declared return value. e.g. return ++count Doesn't return a value. When a method is declared void, e.g. return;

133 Excises 1. What's wrong with the following code snippet: if (i = 1)
{ /*do something */ } 2. Consider the following code snippet. if (aNumber >= 0) if (aNumber == 0) System.out.println("first string"); else System.out.println("second string"); System.out.println("third string");

134 What output do you think the code will produce if aNumber is 3?
Write a test program containing the code snippet; make aNumber 3. What is the output of the program? Is it what you predicted? Explain why the output is what it is. In other words, what is the control flow for the code snippet? Using only spaces and line breaks, reformat the code snippet to make the control flow easier to understand. Use braces { and } to further clarify the code and reduce the possibility of errors by future maintainers of the code.


Download ppt "Workshop on Java Programming"

Similar presentations


Ads by Google