Download presentation
Presentation is loading. Please wait.
1
Java basics
2
Programming Problem solving through the use of a computer system Maxim
You cannot make a computer do something if you do not know how to do it yourself
3
Software Program Sequence of instruction that tells a computer what to do Execution Performing the instruction sequence Programming language Language for writing instructions to a computer Major flavors Machine language or object code Assembly language High-level The instruction set for a machine is a set of binary codes that are unique to its CPU type. Consequently, different computers use different machine languages. The machine language understood by Intel’s Pentium processor is quite different from the machine language understood by IBM’s PowerPC® processor. A major problem with machine language programming is that it is very tedious and error prone to write directly in binary codes. Slightly less tedious is assembly language programming. An assembly language is a symbolic language for coding machine language instructions. Like machine language programmers, assembly language programmers must have a complete understanding of basic operations of the machine. Furthermore, because the corresponding machine operations are so primitive, for even very simple tasks, assembly language programs can be quite long and complicated. Program to which computer can respond directly. Each instruction is a binary code that corresponds to a native instruction
4
Symbolic language for coding machine language instructions
Software Program Sequence of instruction that tells a computer what to do Execution Performing the instruction sequence Programming language Language for writing instructions to a computer Major flavors Machine language or object code Assembly language High-level The instruction set for a machine is a set of binary codes that are unique to its CPU type. Consequently, different computers use different machine languages. The machine language understood by Intel’s Pentium processor is quite different from the machine language understood by IBM’s PowerPC® processor. A major problem with machine language programming is that it is very tedious and error prone to write directly in binary codes. Slightly less tedious is assembly language programming. An assembly language is a symbolic language for coding machine language instructions. Like machine language programmers, assembly language programmers must have a complete understanding of basic operations of the machine. Furthermore, because the corresponding machine operations are so primitive, for even very simple tasks, assembly language programs can be quite long and complicated. Symbolic language for coding machine language instructions
5
Software Program Sequence of instruction that tells a computer what to do Execution Performing the instruction sequence Programming language Language for writing instructions to a computer Major flavors Machine language or object code Assembly language High-level A distinguishing characteristic of a high-level programming language is that detailed knowledge of the machine being programmed is not required. Another characteristic is that a high-level programming language uses a vocabulary and structure that is close to the type of problem being solved. For example, the programming language FORTRAN, which is used to solve scientific and engineering problems, uses a notation that is mathematical. Indeed, the name FORTRAN is derived from the phrase formula translation. Because of the close coupling of a programming language to types of problems, there are literally hundreds of high-level programming languages. The commands in a high-level language program are not executed directly by a computer. A high-level language program has to be translated first. The conversion is accomplished by a specialized program called a translator. A translator accepts a program written in a one language and translates it to an equivalent program in another language. The input to the translator is the source program and the output of the translator is the target program. Most translators convert a high-level language program to a machine language program. For high-level languages, a translator normally is referred to as a compiler. Detailed knowledge of the machine is not required. Uses a vocabulary and structure closer to the problem being solved
6
Java is a high-level programming language
Software Program Sequence of instruction that tells a computer what to do Execution Performing the instruction sequence Programming language Language for writing instructions to a computer Major flavors Machine language or object code Assembly language High-level A distinguishing characteristic of a high-level programming language is that detailed knowledge of the machine being programmed is not required. Another characteristic is that a high-level programming language uses a vocabulary and structure that is close to the type of problem being solved. For example, the programming language FORTRAN, which is used to solve scientific and engineering problems, uses a notation that is mathematical. Indeed, the name FORTRAN is derived from the phrase formula translation. Because of the close coupling of a programming language to types of problems, there are literally hundreds of high-level programming languages. The commands in a high-level language program are not executed directly by a computer. A high-level language program has to be translated first. The conversion is accomplished by a specialized program called a translator. A translator accepts a program written in a one language and translates it to an equivalent program in another language. The input to the translator is the source program and the output of the translator is the target program. Most translators convert a high-level language program to a machine language program. For high-level languages, a translator normally is referred to as a compiler. Java is a high-level programming language
7
For program to be executed it must be translated
Software Program Sequence of instruction that tells a computer what to do Execution Performing the instruction sequence Programming language Language for writing instructions to a computer Major flavors Machine language or object code Assembly language High-level A distinguishing characteristic of a high-level programming language is that detailed knowledge of the machine being programmed is not required. Another characteristic is that a high-level programming language uses a vocabulary and structure that is close to the type of problem being solved. For example, the programming language FORTRAN, which is used to solve scientific and engineering problems, uses a notation that is mathematical. Indeed, the name FORTRAN is derived from the phrase formula translation. Because of the close coupling of a programming language to types of problems, there are literally hundreds of high-level programming languages. The commands in a high-level language program are not executed directly by a computer. A high-level language program has to be translated first. The conversion is accomplished by a specialized program called a translator. A translator accepts a program written in a one language and translates it to an equivalent program in another language. The input to the translator is the source program and the output of the translator is the target program. Most translators convert a high-level language program to a machine language program. For high-level languages, a translator normally is referred to as a compiler. For program to be executed it must be translated
8
Translation Translator
Accepts a program written in a source language and translates it to a program in a target language Compiler Standard name for a translator whose source language is a high-level language Interpreter A translator that both translates and executes a source program The commands in a high-level language program are not executed directly by a computer. A high-level language program has to be translated first. The conversion is accomplished by a specialized program called a translator. A translator accepts a program written in a one language and translates it to an equivalent program in another language. The input to the translator is the source program and the output of the translator is the target program. Most translators convert a high-level language program to a machine language program. For high-level languages, a translator normally is referred to as a compiler. A particular type of translator of interest to Java programmers is an interpreter. An interpreter is a translator that both translates and executes the source program.
9
Java translation Two-step process First step
Translation from Java to bytecodes Bytecodes are architecturally neutral object code Bytecodes are stored in a file with extension .class Second step An interpreter translates the bytecodes into machine instructions and executes them Interpreter is known a Java Virtual Machine or JVM At the beginning of this section, we mentioned that one of the key features of Java is that a Java program can run on a variety of different types of machines. This feature makes Java ideal for developing Internet applications where there are many different types of machines connected to the network. It is the Java interpreter that makes this happen. When we compile a Java program, the Java compiler does not produce a machine language program for a particular computer like the compilers for other programming languages such as C, C++, or FORTRAN do. Rather the Java compiler produces a program for an interpreter called the Java Virtual Machine (JVM). Essentially, the JVM is a program that mimics the operation of a real machine. The JVM reads the program produced by the Java compiler and executes the Java machine language instructions produced by the Java compiler. The Java machine language instructions are called Java bytecodes and can be viewed as architecturally neutral object code. The bytecodes are stored in a file with an extension of .class. For program DisplayForecast.java, a Java compiler produces a bytecode file named DisplayForecast.class.
10
Task Display the supposed forecast
I think there is a world market for maybe five computers. Thomas Watson, IBM, 1943.
11
Sample output
12
DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson
// Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); }
13
DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } Three statements make up the action of method main() Method main() is part of class DisplayForecast
14
DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } A method is a named piece of code that performs some action or implements a behavior
15
DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } An application program is required to have a public static void method named main().
16
DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } public, static, and void are keywords. They cannot be used as names public means the method is shareable
17
DisplayForecast.java Consider static and void later
// Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } Consider static and void later
18
DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } Java allows a statement to be made up of multiple lines of text Semicolons delimit one statement from the next
19
DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } A class defines an object form. An object can have methods and attributes Keyword class indicates a class definition follows
20
DisplayForecast.java The class has a name
// Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } The class has a name
21
DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } Programs are read by people – make sure they are readable. Use whitespace, comments, and indentation to aid understanding
22
DisplayForecast.java Whitespace Whitespace separates program elements
// Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } Whitespace Whitespace separates program elements Whitespace between program elements is ignored by Java
23
DisplayForecast.java Three comments
// Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } Three comments // indicates rest of the line is a comment Comments are used to document authors, purpose, and program elements
24
Method main() is part of DisplayForecast
Indentation // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } Method main() is part of DisplayForecast Statements are part of method main() Indentation indicates subcomponents
25
Method main() public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } Class System supplies objects that can print and read values System variable out references the standard printing object Known as the standard output stream Variable out provides access to printing methods print(): displays a value println(): displays a value and moves cursor to the next line
26
System.out
27
Selection
28
Method main() public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } Method print() and println() both take a string parameter The parameter specifies the value that is to be used in the invocation
29
Method main() The print() statement starts the program output
public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } The print() statement starts the program output I think there is a world market for░
30
Method main() public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } The first println() statement completes the first line of output I think there is a world market for maybe five computers ░
31
Method main() public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } The second println() statement starts and completes the second line of output I think there is a world market for maybe five computers Thomas Watson, IBM, 1943 ░
32
Experiment What does this method main() output?
public static void main(String[] args) { System.out.print("The real problem is not whether "); System.out.print("machines think but whether people "); System.out.println("do"); System.out.println(“-- B.F. Skinner (paraphrased)"); } What does this method main() output?
33
Computation Programmers frequently write small programs for computing useful things Example – body mass index (BMI) Measure of fitness Ratio of person’s weight to the square of the person’s height Weight in is kilograms, height is in meters Person of interest is 4.5 feet and weighs 75.5 pounds Metric conversions Kilograms per pound 0.454 Meters per foot
34
Common program elements
Type Set of values along with operators that can manipulate and create values from the set Primitive types support numeric, character, logical values double and float Values with decimals byte, short, int, long Integers char Characters (considered numeric) boolean Logical values Basic operators + addition - subtraction * multiplication / division
35
Common program elements
Constant Symbolic name for memory location whose value does not change KILOGRAMS_PER_POUND Variable Symbolic name for memory location whose value can change weightInPounds Good programmers prefer the systematic use of symbolic names over literal values—so-called “magic” numbers—because the names provide meaning and their use reduces the potential introduction of errant values through incorrect keyboarding. It is a Java programming convention that the identifier name of a constant be composed of uppercase letters with underscores separating the various words that make up a name. Thus, the use of KILOGRAMS_PER_POUND in BMI.java rather than kilogramsPerPound. It is a Java coding style convention that the identifier name of a variable be descriptive of the represented value and that it begin with a lowercase letter. If a variable name is composed of a single word, then the entire name is in lowercase. If a variable name is composed of multiple words, then the words are concatenated together and all letters are lowercase except for the letters that start successive words. Thus, the coding style calls for bodyTemperature rather than the nondescriptive bt or the underscore using body_temperature.
36
Program outline for BMI.java
// Purpose: Compute BMI for given weight and height public class BMI { // main(): application entry point public static void main(String[] args) { // define constants // set up person's characteristics // convert to metric equivalents // perform bmi calculation // display result }
37
public static void main(String[] args) {
// define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = ; // set up person's characteristics double weightInPounds = 75.5; // our person’s weight double heightInFeet = 4.5; // our person’s height // convert to metric equivalents double metricWeight = weightInPounds * KILOGRAMS_PER_POUND; double metricHeight = heightInFeet * METERS_PER_FOOT; // perform bmi calculation double bmi = metricWeight / (metricHeight * metricHeight); // display result System.out.println("A person with"); System.out.println(" weight " + weightInPounds + " lbs"); System.out.println(" height " + heightInFeet + " feet"); System.out.println("has a BMI of " + Math.round(bmi)); }
38
public static void main(String[] args) { // define constants
final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = ; // set up person's characteristics double weightInPounds = 75.5; // our person’s weight double heightInFeet = 4.5; // our person’s height // convert to metric equivalents double metricWeight = weightInPounds * KILOGRAMS_PER_POUND; double metricHeight = heightInFeet * METERS_PER_FOOT; // perform bmi calculation double bmi = metricWeight / (metricHeight * metricHeight); // display result System.out.println("A person with"); System.out.println(" weight " + weightInPounds + " lbs"); System.out.println(" height " + heightInFeet + " feet"); System.out.println("has a BMI of " + Math.round(bmi)); } Keyword final indicates a constant is being defined Keyword double indicates the constant holds a floating point value Rest of definition associates a value with symbolic name Java programmers use capital letters and underscores when naming constants Double Java representation of floating point numbers (numbers with decimals) Not always exact but generally very good Constants Names whose values cannot change
39
public static void main(String[] args) {
// define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = ; // set up person's characteristics double weightInPounds = 75.5; // our person’s weight double heightInFeet = 4.5; // our person’s height // convert to metric equivalents double metricWeight = weightInPounds * KILOGRAMS_PER_POUND; double metricHeight = heightInFeet * METERS_PER_FOOT; // perform bmi calculation double bmi = metricWeight / (metricHeight * metricHeight); // display result System.out.println("A person with"); System.out.println(" weight " + weightInPounds + " lbs"); System.out.println(" height " + heightInFeet + " feet"); System.out.println("has a BMI of " + Math.round(bmi)); }
40
public static void main(String[] args) {
// define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = ; // set up person's characteristics double weightInPounds = 75.5; // our person’s weight double heightInFeet = 4.5; // our person’s height // convert to metric equivalents double metricWeight = weightInPounds * KILOGRAMS_PER_POUND; double metricHeight = heightInFeet * METERS_PER_FOOT; // perform bmi calculation double bmi = metricWeight / (metricHeight * metricHeight); // display result System.out.println("A person with"); System.out.println(" weight " + weightInPounds + " lbs"); System.out.println(" height " + heightInFeet + " feet"); System.out.println("has a BMI of " + Math.round(bmi)); }
41
public static void main(String[] args) {
// define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = ; // set up person's characteristics double weightInPounds = 75.5; // our person’s weight double heightInFeet = 4.5; // our person’s height // convert to metric equivalents double metricWeight = weightInPounds * KILOGRAMS_PER_POUND; double metricHeight = heightInFeet * METERS_PER_FOOT; // perform bmi calculation double bmi = metricWeight / (metricHeight * metricHeight); // display result System.out.println("A person with"); System.out.println(" weight " + weightInPounds + " lbs"); System.out.println(" height " + heightInFeet + " feet"); System.out.println("has a BMI of " + Math.round(bmi)); }
42
public static void main(String[] args) {
// define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = ; // set up person's characteristics double weightInPounds = 75.5; // our person’s weight double heightInFeet = 4.5; // our person’s height // convert to metric equivalents double metricWeight = weightInPounds * KILOGRAMS_PER_POUND; double metricHeight = heightInFeet * METERS_PER_FOOT; // perform bmi calculation double bmi = metricWeight / (metricHeight * metricHeight); // display result System.out.println("A person with"); System.out.println(" weight " + weightInPounds + " lbs"); System.out.println(" height " + heightInFeet + " feet"); System.out.println("has a BMI of " + Math.round(bmi)); }
43
public static void main(String[] args) { // define constants
final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = ; // set up person's characteristics double weightInPounds = 75.5; // our person’s weight double heightInFeet = 4.5; // our person’s height // convert to metric equivalents double metricWeight = weightInPounds * KILOGRAMS_PER_POUND; double metricHeight = heightInFeet * METERS_PER_FOOT; // perform bmi calculation double bmi = metricWeight / (metricHeight * metricHeight); // display result System.out.println("A person with"); System.out.println(" weight " + weightInPounds + " lbs"); System.out.println(" height " + heightInFeet + " feet"); System.out.println("has a BMI of " + Math.round(bmi)); } When we depict double values, the values may be sometimes truncated (e.g., the actual value represented by metricHeight is ).
44
public static void main(String[] args) {
// define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = ; // set up person's characteristics double weightInPounds = 75.5; // our person’s weight double heightInFeet = 4.5; // our person’s height // convert to metric equivalents double metricWeight = weightInPounds * KILOGRAMS_PER_POUND; double metricHeight = heightInFeet * METERS_PER_FOOT; // perform bmi calculation double bmi = metricWeight / (metricHeight * metricHeight); // display result System.out.println("A person with"); System.out.println(" weight " + weightInPounds + " lbs"); System.out.println(" height " + heightInFeet + " feet"); System.out.println("has a BMI of " + Math.round(bmi)); }
45
Operator evaluation depend upon its operands
public static void main(String[] args) { // define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = ; // set up person's characteristics double weightInPounds = 75.5; // our person’s weight double heightInFeet = 4.5; // our person’s height // convert to metric equivalents double metricWeight = weightInPounds * KILOGRAMS_PER_POUND; double metricHeight = heightInFeet * METERS_PER_FOOT; // perform bmi calculation double bmi = metricWeight / (metricHeight * metricHeight); // display result System.out.println("A person with"); System.out.println(" weight " + weightInPounds + " lbs"); System.out.println(" height " + heightInFeet + " feet"); System.out.println("has a BMI of " + Math.round(bmi)); } Operator evaluation depend upon its operands The next invocation of println() System.out.println(" weight " + weightInPounds + " lbs"); supplies the value of the expression " weight " + weightInPounds + " lbs" to println(). Our use of the term expression is deliberate. " weight " + weightInPounds + " lbs" requires operator evaluation. The expression is composed of two String concatenation operations.
46
Math.round(bmi) is 18 public static void main(String[] args) {
// define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = ; // set up person's characteristics double weightInPounds = 75.5; // our person’s weight double heightInFeet = 4.5; // our person’s height // convert to metric equivalents double metricWeight = weightInPounds * KILOGRAMS_PER_POUND; double metricHeight = heightInFeet * METERS_PER_FOOT; // perform bmi calculation double bmi = metricWeight / (metricHeight * metricHeight); // display result System.out.println("A person with"); System.out.println(" weight " + weightInPounds + " lbs"); System.out.println(" height " + heightInFeet + " feet"); System.out.println("has a BMI of " + Math.round(bmi)); } Math.round(bmi) is 18 Method Math.round() is a class method of standard Java class java.lang.Math. As it is a class method, the method is a service provided by the class that does not require association with a particular class object. The method takes a double floating-point value as its parameter and returns the nearest integer value. Thus, the program outputs
47
// Purpose: Convert a Celsius temperature to Fahrenheit
public class CelsiusToFahrenheit { // main(): application entry point public static void main(String[] args) { // set Celsius temperature of interest int celsius = 28; // convert to Fahrenheit equivalent int fahrenheit = 32 + ((9 * celsius) / 5); // display result System.out.println("Celsius temperature"); System.out.println(" " + celsius); System.out.println("equals Fahrenheit temperature"); System.out.println(" " + fahrenheit); } The different primitive types have different representation capabilities. For example, the short uses 2 bytes to represent an integer value and an int uses 4 bytes. As a result, a short variable can store integer values only in the range –32,768 … 32,767, and an int variable can store integer values only in the range –2,147,483,648 … 2,147,483,647. Java’s motivation for having multiple numeric types is to give programmers full access to all the types supported by typical and specialized computer hardware (e.g, PCs, mobile telephones, PDAs). In the applications in this text, we generally use the primary primitive types int, char, and double.
48
// Purpose: Demonstrate char arithmetic public class LowerToUpper {
// main(): application entry point public static void main(String[] args) { // set lower case character of interest char lowerCaseLetter = 'c'; // convert to uppercase equivalent char upperCaseLetter = 'A' + (lowerCaseLetter - 'a'); // display result System.out.println("Uppercase equivalent of"); System.out.println(" " + lowerCaseLetter); System.out.println("is"); System.out.println(" " + upperCaseLetter); } When we depict double values, the values may be sometimes truncated (e.g., the actual value represented by metricHeight is ).
49
Expressions What is the value used to initialize expression
int expression = * 5; What value is displayed System.out.println(5 / 2.0); Java rules in a nutshell Each operator has a precedence level and an associativity Operators with higher precedence are done first * and / have higher precedence than + and - Associativity indicates how to handle ties When floating-point is used the result is floating point It seems that there are two possible values for expr. If the addition is performed first, then expr is initialized to 30; if instead, the multiplication is performed first, then expr is initialized to 14. N
50
Question Does the following statement compute the average of double variables a, b, and c? Why double average = a + b + c / 3.0;
51
Interactive programs Programs that interact with their users through statements performing input and output BMI.java Not interactive – weight and height are fixed It is important that programs tell the users what is expected of them. For example, BMICalculator.java tells the user to input the weight in pounds and the height in feet. These prompts may seem unnecessary: we know that two numbers are needed because we wrote the program. However in general, a user runs a program without seeing the source code, so it is important for a program to tell to the user what is expected. That is why the weight prompt of BMICalculator.java displays
52
Support for interactive console programs
Variable System.in Associated with the standard input stream – the keyboard Class Scanner Supports extraction of an input as a numbers, characters, and strings Scanner stdin = new Scanner(System.in); In the next section, the program becomes interesting. There, method main() defines and initializes a variable stdin of type BufferedReader. BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); With this variable the program has access to a BufferedReader object, which is an input stream. BufferedReader objects have a method readLine() that can extract character strings from an input stream. The BufferedReader object created in lines 17–18 can extract strings from the input stream System.in. By default, System.in is associated with the keyboard. Because BufferedReader is a class, its variables are not primitive type variables—they are reference type (object) variables. The syntax for defining and initializing a reference type variable such as stdin is different than the defining a primitive type variable. The stdin variable initialization process has two parts. First, the new expression constructs a new BufferedReader object. The value of that new expression is a reference (pointer) to the memory location that holds the new BufferedReader object. Thus, the value of an object variable is not an object but a reference to an object. Therefore, the definition in lines 17–18 sets aside a memory location for variable stdin. The value of this memory location is a reference to a memory location that holds a new BufferedReader object. The new BufferedReader referenced by stdin is built out of a new InputStreamReader, which is in turn built out of the standard input stream represented by System.in. Variable stdin references a BufferedReader.
53
Accessing the standard input stream
Set up Scanner stdin = new Scanner(System.in); A new operation constructs a new object. The value of the operation is a reference to the new object. This new operation constructs a BufferedReader object out of a new InputStreamReader object that was built using the object representing the standard input stream
54
Interactive program for bmi
Program outline // Purpose: Compute BMI for user-specified // weight and height import java.util.*; public class BMICalculator { // main(): application entry point public static void main(String[] args) { // defining constants // displaying legend // set up input stream // get person's characteristics // convert to metric equivalents // perform bmi calculation // display result } An import statement indicates that the program requires access to other Java resources. In creating and accessing the input stream object for getting input values, the program uses classes that are defined in standard Java software library java.io. In Java parlance, a software library is known as a package or application programming interface (API). Because only classes defined in package java.lang are available implicitly to a program, it is necessary to import the needed classes from the io API. The * in the import statement is a special character indicating that all resources of java.io are to be made available to the program. For this reason, it is sometimes called the wildcard character.
55
public static void main(String[] args) throws IOException {
final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = ; System.out.println("BMI Calculator\n"); Scanner stdin = new Scanner(System.in); System.out.print("Enter weight (lbs): "); double weight = stdin.nextDouble(); System.out.print("Enter height (feet): "); double height = stdin.nextDouble()); double metricWeight = weight * KILOGRAMS_PER_POUND; double metricHeight = height * METERS_PER_FOOT; double bmi = metricWeight / (metricHeight * metricHeight); System.out.println("A person with"); System.out.println(" weight " + weight + " (lbs)"); System.out.println(" height " + height + " (feet)"); System.out.println("has a BMI of " + bmi); } The initialization expression for variable weight is the result of the invocation Double.parseDouble(stdin.readLine()) The initialization expression has two parts that should be examined. The subexpression stdin.readLine() invokes the readLine() method of the BufferedReader object referenced by stdin, The invocation produces the parameter value supplied to Double.parseDouble(). More to come The nuances of classes in general and the particulars of BufferedReader are deferred until later chapters. For now only enough background is supplied so that you can make similar uses of the particular classes that BMICalculator.java employs. Interactive input and output It is important that programs tell the users what is expected of them. For example, BMICalculator.java tells the user to input the weight in pounds and the height in feet. These prompts may seem unnecessary: we know that two numbers are needed because we wrote the program. However in general, a user runs a program without seeing the source code, so it is important for a program to tell to the user what is expected. That is why the weight prompt of BMICalculator.java displays Enter weight (lbs): rather than displaying just Enter weight: The latter is insufficient—the user would not know what type of weight is wanted (e.g., carats, ounces, pounds, grams, kilograms, etc.) In addition to telling the user what form the input should take, another general principle is to echo the input supplied by the user whenever it is practical. This practice gives the user some assurance that the input was received and interpreted correctly. For example, in BMICalculator.java, the weight and height are displayed along with the BMI. Thus, the user can see whether the program correctly interpreted the input. Method readLine() waits for a line to be entered completely by the user. Once the line is entered, the whole line—whitespace and all except for the terminating newline character—is converted to string format and returned. For this application, the user should enter a single number in reaction to the prompt. Therefore, the invocation stdin.readLine() should return a string that consists of a single number in floating-point form.
56
Accessing the standard input stream
Extraction System.out.print("Enter weight (lbs): "); double weight = stdin.nextDouble(); System.out.print("Enter height (feet): "); double height = stdin.nextDouble();
57
Primitive variable assignment
Assignment operator = Allows the memory location for a variable to be updated Consider int j = 11; j = 1985; Besides signaling in a variable definition that the variable is to be initialized, the symbol = is also the Java assignment operator. The assignment operator takes two operands. The left operand is the target variable; the right operand is the modifying expression. When evaluated, the assignment operator updates the value in the memory location associated with a target variable based on the modifying expression. The assignment operator works in the following manner. First, the left operand is evaluated to make sure that its value can be modified (e.g., a non-final variable). The right operand then is evaluated and its value is used to update the memory location associated with the left operand. For our particular assignment, the memory location associated with variable j is reset to the int value The assignment expression is read as “j gets 1985” or “j is assigned 1985.”
58
Primitive variable assignment
Assignment operator = Allows the memory location for a variable to be updated Consider int j = 11; j = 1985; Besides signaling in a variable definition that the variable is to be initialized, the symbol = is also the Java assignment operator. The assignment operator takes two operands. The left operand is the target variable; the right operand is the modifying expression. When evaluated, the assignment operator updates the value in the memory location associated with a target variable based on the modifying expression. The assignment operator works in the following manner. First, the left operand is evaluated to make sure that its value can be modified (e.g., a non-final variable). The right operand then is evaluated and its value is used to update the memory location associated with the left operand. For our particular assignment, the memory location associated with variable j is reset to the int value The assignment expression is read as “j gets 1985” or “j is assigned 1985.”
59
Primitive variable assignment
Consider int a = 1; int aSquared = a * a; a = 5; aSquared = a * a; int i = 0; i = i + 1; int asaRating; asaRating = 400;
60
Primitive variable assignment
Consider int a = 1; int aSquared = a * a; a = 5; aSquared = a * a; int i = 0; i = i + 1; int asaRating; asaRating = 400;
61
Primitive variable assignment
Consider int a = 1; int aSquared = a * a; a = 5; aSquared = a * a; int i = 0; i = i + 1; int asaRating; asaRating = 400;
62
Primitive variable assignment
Consider int a = 1; int aSquared = a * a; a = 5; aSquared = a * a; int i = 0; i = i + 1; int asaRating; asaRating = 400;
63
Primitive variable assignment
Consider int a = 1; int aSquared = a * a; a = 5; aSquared = a * a; int i = 0; i = i + 1; int asaRating; asaRating = 400;
64
Primitive variable assignment
Consider int a = 1; int aSquared = a * a; a = 5; aSquared = a * a; int i = 0; i = i + 1; int asaRating; asaRating = 400;
65
Primitive variable assignment
Consider int a = 1; int aSquared = a * a; a = 5; aSquared = a * a; int i = 0; i = i + 1; int asaRating; asaRating = 400;
66
Primitive variable assignment
Consider double x = 5.12; double y = 19.28; double rememberX = x; x = y; y = rememberX;
67
Primitive variable assignment
Consider double x = 5.12; double y = 19.28; double rememberX = x; x = y; y = rememberX;
68
Primitive variable assignment
Consider double x = 5.12; double y = 19.28; double rememberX = x; x = y; y = rememberX;
69
Primitive variable assignment
Consider double x = 5.12; double y = 19.28; double rememberX = x; x = y; y = rememberX;
70
Primitive variable assignment
Consider double x = 5.12; double y = 19.28; double rememberX = x; x = y; y = rememberX;
71
Increment and decrement operators
++ Increments a number variable by 1 -- Decrements a numeric variable by 1 Consider int i = 4; ++i; System.out.println(i); System.out.print(++i); System.out.println(i++);
72
Increment and decrement operators
++ Increments a number variable by 1 -- Decrements a numeric variable by 1 Consider int i = 4; // define ++i; System.out.println(i); System.out.print(++i); System.out.println(i++);
73
Increment and decrement operators
++ Increments a number variable by 1 -- Decrements a numeric variable by 1 Consider int i = 4; ++i; // increment System.out.println(i); System.out.print(++i); System.out.println(i++);
74
Increment and decrement operators
++ Increments a number variable by 1 -- Decrements a numeric variable by 1 Consider int i = 4; ++i; System.out.println(i); // display System.out.print(++i); System.out.println(i++); System.out.println(i);
75
Increment and decrement operators
++ Increments a number variable by 1 -- Decrements a numeric variable by 1 Consider int i = 4; ++i; System.out.println(i); System.out.print(++i); // update then display System.out.println(i++);
76
Increment and decrement operators
++ Increments a number variable by 1 -- Decrements a numeric variable by 1 Consider int i = 4; ++i; System.out.println(i); System.out.print(++i); System.out.println(i++); // display then update
77
Increment and decrement operators
++ Increments a number variable by 1 -- Decrements a numeric variable by 1 Consider int i = 4; ++i; System.out.println(i); System.out.print(++i); System.out.println(i++); System.out.println(i); // display
78
Escape sequences Java provides escape sequences for printing special characters \b backspace \n newline \t tab \r carriage return \\ backslash \" double quote \' single quote
79
Escape sequences What do these statements output?
System.out.println("Person\tHeight\tShoe size"); System.out.println("========================="); System.out.println("Hannah\t5‘1\"\t7"); System.out.println("Jenna\t5'10\"\t9"); System.out.println("JJ\t6'1\"\t14"); Output Person Height Shoe size ========================= Hannah 5‘1" 7 Jenna 5'10" 9 JJ '1" 14
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.