730 likes | 857 Views
Chapter 3 Java Basics. Introduction Primitive Types Constants Input Conversion between Types Ethics in Computing. Introduction: Skeleton Programs. Skeleton Program for turtle graphics program // Comment that describes the program import turtlegraphics.*; public class className {
E N D
Chapter 3Java Basics Introduction Primitive Types Constants Input Conversion between Types Ethics in Computing
Introduction: Skeleton Programs • Skeleton Program for turtle graphics program • // Comment that describes the program • import turtlegraphics.*; • public class className • { • public static void main(String[] args) • throws TurtleException • { • // Put your Java statements here • } • } Programming and Problem Solving With Java
Introduction: Skeleton Programs • Skeleton Program for non-turtle graphics program • // Comment that describes the program • public class className • { • public static void main(String[] args) • { • // Put your Java statements here • } • } Programming and Problem Solving With Java
Introduction: Keywords • Keyword is reserved -- can’t use for identifier names • Keywords in Java Programming and Problem Solving With Java
Introduction: Identifier Names • Programmer must make up names for new classes, methods, variables • Rules for forming identifier names • Must start with letter, underscore (_), or dollar sign ($) • Other characters must be letters, digits, underscores, or dollar signs • No spaces! • No keywords Programming and Problem Solving With Java
Introduction: Identifier Names • Identifiers should also be meaningful to human readers • Part of good programming style Programming and Problem Solving With Java
Introduction: Identifier Names • Many identifiers use more than one word • Examples: SmartTurtle, turnRight • Java conventions • After the first word, begin each word with a capital letter • Class names start with capital letter (SmartTurtle) • Other names start with lower-case letter (turnRight) Programming and Problem Solving With Java
Introduction: The main() Method • The main() method is the one that starts with • public static void main(String[] args) … • Write executable instructions between braces • Executable instruction: makes computer do something • Examples of executable instructions • System.out.println("Hello!"); • myTurtle.turnRight(90); • Examples of non-executable instructions • public static void main(String[] args) • import turtlegraphics.*; • Computer starts executing the first statement in main() Programming and Problem Solving With Java
Introduction: Flow of Control • Write executable statements like a list • Write first instruction you want the computer to do • Then write second, and so on • Sequential execution • Computer executes each instruction in turn, in order they appear in program • Computer stops after executing last instruction • "Control" • When computer executing instruction, control is at that instruction Programming and Problem Solving With Java
Introduction: Semicolons • Semicolon required after each executable instruction • myTurtle.move(100); • myTurtle.turnRight(90); • Free-form input • Compiler ignores indentation, ends of lines (as long as words & other tokens not split) • Example of valid program • // (This program has poor formatting) • import turtlegraphics.*; public class DrawSimpleDesign { public static void main(String[] arguments) throws TurtleException { Turtle myTurtle = • new Turtle(); myTurtle.move(400); myTurtle.turnRight(90); myTurtle.move(200); } } Programming and Problem Solving With Java
Introduction: Letter Case • Java is case-sensitive • Compiler treats upper and lower case letters differently • A different from a • B different from b • public static void different from PUBLIC STATIC VOID • Some languages (Pascal) are case-insensitive public static void main(String args[]) Programming and Problem Solving With Java
Introduction: Comments • Comment starts with // and continues to end of line • // This program draws a square • myTurtle.move(100); // Position turtle for next figure • Compiler ignores comments • Programmer should include comments • Describe what the program does • Describe (in higher-level terms than the code) how the program works • Usually unnecessary to comment each line -- makes program too wordy • myTurtle.move(100); // Move 100 units • myTurtle.turnRight(90); // Turn 90 degrees Programming and Problem Solving With Java
Introduction: Streams • Stream • A sequence of characters • Has a reader (consumer of information)at one end • Has a writer (producer of information) at the other • Program's input and output are streams • Output stream is the textual output of the program • Input stream is the textual input of the program Stream Writer Reader Programming and Problem Solving With Java
Introduction: System.out Stream • System.out is the standard Java output stream • System is the name of a standard Java class • out is the output stream object in the System class • Refer to this output stream as System.out • Allows displaying text output on the console • System.out.println("Hello!"); • println() is method of out stream • Syntax for method use • object.method(arguments); • Action of println() • Display message on consoleat cursor's position Hello! Programming and Problem Solving With Java
Introduction: println() vs. print() • System.out.println() • Displays message, then moves cursor to beginning of next line • System.out.println("First message"); • System.out.println("Second message"); • First message • Second message • _ • System.out.print() • Just displays message (leaves cursor after) • System.out.print("First message"); • System.out.print("Second message"); • First messageSecond message_ Cursor Cursor Programming and Problem Solving With Java
Introduction: Use of print() • Use System.out.print() to display several values on same line • // Displays the message, because there's a println() • // after the print(). • public class DisplayMessage • { • public static void main(String[] args) • { • System.out.print("This"); • System.out.print(" will"); • System.out.println(" display"); • } • } Programming and Problem Solving With Java
Introduction: Use of flush() • Message from System.out.print doesn't display right away -- stored in buffer • Use System.out.flush() to force display of output from System.out.print() System.out.print("Hello!"); Hello! Hello System.out.flush(); Buffer Programming and Problem Solving With Java
Here is a small test_ Here is _ Introduction: The Output Buffer • Output goes to the output buffer before the screen System.out.println("Here is"); System.out.print("a small"); System.out.print(" test"); System.out.flush(); Here is a small a small test Buffer Programming and Problem Solving With Java
Displaying String Literals • Display string literals between quotes • System.out.println("This is a string literal"); • Three ways display a long string literal • Let the literal go past the edge of the editor screen • System.out.println("This is a very very very very very ver • Break the string into two strings, use print() on first, println() on second • System.out.print("This is a very very very very very "); • System.out.println("very very very long message"); • Use concatenation • System.out.println("This is a very very very very very " • + "very very very long message"); Programming and Problem Solving With Java
Introduction: Escape Sequences • Can't display double quote " directly • This statement doesn't compile • System.out.println("She said, "Hi!""); • Compiler can't find end of the string • Use escape character \ before " in string • System.out.println("She said, \"Hi!\""); • Other escape sequences • \b Backspace • \\ Backslash • \a Bell • \n End of line • \t Tab Programming and Problem Solving With Java
Primitive Types • Type is a kind of information • Must define the type of information in a program • Three common types of information • Textual • Numeric • Multimedia • Two kinds of numeric types • Integer: whole numbers (4, 99, -123) • Floating point (4.35, -33.4, 3.0) 2 43 18.6 Programming and Problem Solving With Java
Primitive Type: Integers • Display integer • System.out.println(123); • Display result of integer arithmetic • System.out.println(123 + 456); • Display a message with an integer • System.out.println("The answer is " + 123); • Display a message with integer arithmetic (wrong) • System.out.println("The sum is " + 123 + 456); • Compiler treats + as concatenation! • Display a message with integer arithmetic (correct) • System.out.println("The sum is " + (123 + 456)); 123579The answer is 123The sum is 123456The sum is 579 Programming and Problem Solving With Java
Primitive Types: Integer Operators Programming and Problem Solving With Java
Primitive Types: Integer Operators • Operator precedence: order of execution of operators • Example • System.out.println(30 + 10 / 2); • Possible interpretations correct! Programming and Problem Solving With Java
Primitive Types: Integer Operators • Evaluation of some sample expressions Programming and Problem Solving With Java
Primitive Types: Integer Types Programming and Problem Solving With Java
Primitive Types: Floating Point • Floating-point number has • Decimal point, or • Exponent, or both • Examples • 5.0, 12.34, 0.0, -45.8, 12. • Scientific notation • 5.6 x 1027 • = 5,600,000,000,000,000,000,000,000,000.0 • In Java • 5.6E27 Programming and Problem Solving With Java
Primitive Types: Floating Point • Display floating point number • System.out.println(18.7856); • Display a message, too • System.out.println("F.P. # is " + 18.7856); • Display a large floating point number • System.out.println("F.P. # is " + 123456789.0); • Large number display rule • If more than 6 digits display in scientific notationElse display in conventional notation 18.7856F.P. # is 18.7856F.P. # is 1.23457e008 Programming and Problem Solving With Java
Primitive Types: Floating Point Highlightedrowsrounded Programming and Problem Solving With Java
Primitive Types: Floating Point • Floating Point Operators Programming and Problem Solving With Java
Primitive Types: Floating Point • Floating point precedence Programming and Problem Solving With Java
Primitive Types: Floating Point • Floating point types • Float point ranges Programming and Problem Solving With Java
Use integers for counting Use floating-point numbers for measuring Primitive Types: Integer vs floating Programming and Problem Solving With Java
Using Strings • String is a sequence of characters • Literal value: "This is a string" • Java strings • Not primitive (built-in) type • Standard class • String operations • Many operations: length, substring, search, etc. • Example • // Display the length of a string literal • public class FindLength • { • public static void main(String[] args) • { • System.out.println("This is a string literal".length()); • } • } Programming and Problem Solving With Java
Variables • Variable: named location in memory • Can hold one value Programming and Problem Solving With Java
Variables • Each variable like a calculator memory • Holds one value • Can retrieve value many times • Storing a new value erases old • Differences from calculator memory • Can have many variables • Variable can be one of many types • Each variable has a name Programming and Problem Solving With Java
Variables Variable, schmariable • Kinds of variables • Local • Instance • Class (static) • Variable definitions • int count; • int sum, limit; • Example • public class IllustrateVariables • { • String anInstanceVariable; • static int aStaticVariable; • public static void main(String[] args) • { • int aLocalVariable; • } • } Programming and Problem Solving With Java
Variables: Parameters • Parameters are like local variables • Difference: initial value of parameter passed in • class SmartTurtle • { • // drawSquare: Draws a square of the given size • public void drawSquare(int size) • { • for (int i = 1; i <= 4; i++) • { • this.move(size); • this.turnRight(90); • } • } • … • } • Counting variable of for statement is local variable • Scope restricted to for statement Parameter size Local variable i Programming and Problem Solving With Java
Variables: Assignment • Assignment operator = • Stores value in a variable • Read as "becomes", not "equals" • Examples • int count; • count = 25; • count = sum; • count = sum + 15; • count = count + 1; • Syntax • Variable = Expression = Variable Expression Programming and Problem Solving With Java
Variables: Initialization • Initialization symbol = • Optional • Gives variable its first value • Examples • int count = 0; • double weight = 10.2; • String firstName = "John", lastName = "Smith"; • Only one variable initialized per value • int first, second, third = 25; • Uninitialized variables don't have a value • int count; • System.out.println(count); // Wrong • Compiler output Test.java:7: Variable count may not have been initialized. System.out.println(count); // Wrong Programming and Problem Solving With Java
Variables: Assign vs Initialize • Assignment & initialization use same symbol • Different operations • // Demonstrates assignment and initialization • public class StringDemonstration • { • public static void main(String[] args) • { • String firstName = "Linda"; // Initialize firstName • String lastName; // No initial value • String name; // No initial value • lastName = "Smith"; // Assign to lastName • name = firstName; // Assign to name • name = name + " " + lastName; // Assign to name again • System.out.println("Name is " + name); • } • } Name is Linda Smith Programming and Problem Solving With Java
Variables: Assign & Initialize • Assignment and initialization are operators • Not statements or commands • Part of expression • Very low precedence • = inside expressions • x = y = 0; • Same as • x = (y = 0); • Both x and y get 0 • Associativity • Two of same operators in expression • Tells which the computer executes first Programming and Problem Solving With Java
Variables: Increment & Decrement • Can use assignment to increment • count = count + 1; • Or use increment operator • count++; // Postfix version • ++count; // Prefix version • Difference between post- and pre- • Postfix: increment after evaluating expression • int x = 0, y = 1; • x = y++; // y is 2, x is 1 • Prefix: increment before evaluating expression • int x = 0, y = 1; • x = ++y; // y is 2, x is 2 • Also post- and prefix decrement operators -- • count--; • --count; ++ Programming and Problem Solving With Java
Variables: Displaying Values • // Displays the average of four floating • // point numbers • public class DisplayAverage • { • public static void main(String[] args) • { • double firstNum = 10.0; • double secondNum = 12.3; • double thirdNum = 15.4; • double fourthNum = 18.9; • double average; • average = (firstNum + secondNum + thirdNum + fourthNum) • / 4; • System.out.println("The average is " + average); • } • } Programming and Problem Solving With Java
Constants • Constant is like a variable • Has name • Has value • Constant is unlike a variable • Value can't change • Defining • Must define as a class (static) variable • Defined in the class, outside of any method • static final double TARGET_SALES = 350000.0; • Makes program more readable • System.out.println("Widget have sold " • + (sales / TARGET_SALES * 100) • + " percent of target sales"); Programming and Problem Solving With Java
Constants: Uses • Give meaning to meaningless literal value • static final double TARGET_SALES = 350000.0; • Makes program easier to read • Convention: ALL_CAPITAL_LETTERS for constants • Values that occur several times in a program • Names of companies, departments, etc. • static final String BANK_NAME = "First National Bank"; • static final String BRANCH_NAME = "Springfield Branch"; • Makes it easier to update the program • How about constants for 0 and 1? • static final int ONE = 1; • … • count = count + ONE; • No more readable than using literal value 1 0 1 Programming and Problem Solving With Java
Constants: Numeric Limits • Predefined constants for largest and smallest numbers • System.out.println("Range of int: " + Integer.MIN_VALUE • + " to " + Integer.MAX_VALUE); • System.out.println("Range of long: " + Long.MIN_VALUE • + " to " + Long.MAX_VALUE); • System.out.println("Range of float: " + Float.MIN_VALUE • + " to " + Float.MAX_VALUE); • System.out.println("Range of double: " + Double.MIN_VALUE • + " to " + Double.MAX_VALUE); • Output • Range of int: -2147483648 to 2147483647 • Range of long: -9223372036854775808 to 9223372036854775807 • Range of float: 1.4013e-045 to 3.40282e+038 • Range of double: 2.22507e-308 to 1.79769e+308 Programming and Problem Solving With Java
Input • Many programs require input from user • Input devices • Keyboard • Mouse • Stylus • Scanner • Keyboard input is complex in Java • Will use Keyboard class for now • Will learn other techniques later Programming and Problem Solving With Java
Input: Keyboard Class • import Keyboard; • public class DemonstrateKeyboardInput • { • public static void main(String[] args) • throws java.io.IOException • { • int height, width; • System.out.print("Enter height of rectangle: "); • System.out.flush(); • height = Keyboard.readInt(); • System.out.print("Enter width of rectangle: "); • System.out.flush(); • width = Keyboard.readInt(); • System.out.println("The area of the rectangle is " • + (width * height)); • } • } Enter height of rectangle: 4 Enter height of rectangle: 4 Enter width of rectangle: Enter height of rectangle: 4 Enter width of rectangle: 3 The area of the rectangle is 12 Enter height of rectangle: Enter height of rectangle: 4 Enter width of rectangle: 3 Note use of exception Programming and Problem Solving With Java
Input: Keyboard Class • Methods in Keyboard class • readInt() • readByte() • readShort() • readLong() • readFloat() • readDouble() • readString() • When control reaches Keyboard method • Computer waits for user to enter value • Method returns value user typed Programming and Problem Solving With Java