©Silberschatz, Korth and Sudarshan1.1 Primitive Types, Strings, and Console I/O n Variables and Expressions The Class String n Keyboard and Screen I/O.

Slides:



Advertisements
Similar presentations
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Advertisements

Slides prepared by Rose Williams, Binghamton University Chapter 1 Getting Started 1.2 Expressions and Assignment Statement.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Chapter 21 Primitive Types, Strings, and Console I/O Chapter 2.
String Escape Sequences
Primitive Types, Strings, and Console I/O Chapter 2.
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
1 Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Primitive Types, Strings, and Console I/O Chapter 2.1 Variables and Values Declaration of Variables Primitive Types Assignment Statement Arithmetic Operators.
©Silberschatz, Korth and Sudarshan1 Primitive Types, Strings, and Console I/O n Variables and Expressions The Class String n Keyboard and Screen I/O n.
Basic Computation Module 2. Objectives Describe the Java data types used for simple data Write Java statements to declare variables, define named constants.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
1 Primitive Types and Strings n Variables, Values, and Expressions The Class String Reading: => Section 1.2.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Input, Output, and Processing
CPS120: Introduction to Computer Science
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 2: Java Fundamentals
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
November 1, 2015ICS102: Expressions & Assignment 1 Expressions and Assignment.
SE-1010 Dr. Mark L. Hornick 1 Variables & Datatypes.
Primitive Types, Strings, and Console I/O Chapter 2.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank M. Carrano. ISBN © 2008 Pearson Education, Inc.,
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank M. Carrano. ISBN © 2009 Pearson Education, Inc.,
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
©Silberschatz, Korth and Sudarshan1.1 Chapter 2: Primitive Types, Strings, and Console I/O n Variables and Expressions The Class String n Keyboard and.
Computer Programming with Java Chapter 2 Primitive Types, Assignment, and Expressions.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
1 Primitive Types n Four integer types:  byte  short  int (most common)  long n Two floating-point types:  float  double (most common) n One character.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Chapter 21 Primitive Types, Strings, and Console I/O Recitation Week 2.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank M. Carrano. ISBN © 2008 Pearson Education, Inc.,
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Chapter 21 Primitive Types, Strings, and Console I/O Chapter 2.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Primitive Types Four integer types: Two floating-point types:
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Variables and Arithmetic Operators in JavaScript
Java Programming: From Problem Analysis to Program Design, 4e
IDENTIFIERS CSC 111.
Starting JavaProgramming
Chapter 2: Primitive Types, Strings, and Console I/O
Primitive Types, Strings, and Console I/O
Chapter 2 Edited by JJ Shepherd
Chapter 2: Basic Elements of Java
Chapter 2 Part 2 Edited by JJ Shepherd
Expressions and Assignment
Basic Computation Chapter 2.
Introduction to Java Applications
Primitive Types and Expressions
Chap 2. Identifiers, Keywords, and Types
Chapter 2 Primitive Data Types and Operations
Presentation transcript:

©Silberschatz, Korth and Sudarshan1.1 Primitive Types, Strings, and Console I/O n Variables and Expressions The Class String n Keyboard and Screen I/O n Documentation and Style Reading => Section 1.2

©Silberschatz, Korth and Sudarshan1.2 Variables and Values n Variables are memory locations that store data such as numbers and letters. n The data stored by a variable is called its value.  The value is stored in the memory location. n A variables value can be changed.

©Silberschatz, Korth and Sudarshan1.3 Variables and Values public class EggBasket { public static void main (String[] args) { int numberOfBaskets, eggsPerBasket, totalEggs; numberOfBaskets = 10; eggsPerBasket = 6; totalEggs = numberOfBaskets * eggsPerBasket; System.out.println ("If you have"); System.out.println (eggsPerBasket + " eggs per basket and"); System.out.println (numberOfBaskets + " baskets, then"); System.out.println ("the total number of eggs is " + totalEggs); } Output: If you have 6 eggs per basket and 10 baskets, then the total number of eggs is 60

©Silberschatz, Korth and Sudarshan1.4 Variables and Values Variables: numberOfBaskets eggsPerBasket totalEggs Assigning values: numberOfBaskets = 10; eggsPerBasket = 6; totalEggs = numberOfBaskets * eggsPerBasket; n A variable must be declared before it is used. n When you declare a variable, you provide its name and type. int numberOfBaskets, eggsPerBasket, totalEggs; A variable’s type determines what kinds of values it can hold, e.g., integers, real numbers, characters.

©Silberschatz, Korth and Sudarshan1.5 Syntax and Examples n Variable declaration syntax: type variable_1, variable_2, … ; Examples: int styleChoice, numberOfChecks; double balance, interestRate; char jointOrIndividual; A variable is declared just before it is used or at the beginning of a “block” enclosed in { }: public static void main(String[] args) { /* declare variables here */ : }

©Silberschatz, Korth and Sudarshan1.6 Types in Java n In most programming languages, a type implies several things:  A set of values  A (hardware) representation for those values  A set of operations on those values n Example - type int:  Values – integers in the range to  Representation – 4 bytes, binary, “two’s complement”  Operations – addition (+), subtraction (-), multiplication (*), division (/), etc. n Two kinds of types:  Primitive types  Class types

©Silberschatz, Korth and Sudarshan1.7 Types in Java n A primitive type:  values are “simple,” non-decomposable values such as an individual number or individual character  int, double, char n A class type:  values are “complex” objects  a class of objects has both data and methods  “ Think WHIRLED peas. ” is a value of class type String  ‘ November 10, 1989 ’ is a value of class type date (non-Java)

©Silberschatz, Korth and Sudarshan1.8 Java Identifiers n An identifier:  a name given to something in a program  name of a variable, name of a method, name of a class, etc.  created by the programmer, generally n Identifiers may contain only:  letters  digits (0 through 9)  the underscore character (_)  and the dollar sign symbol ($) which has a special meaning  the first character cannot be a digit. Identifiers may not contain any spaces, dots (. ), asterisks ( * ), or other characters not mentioned above: 7-11netscape.comutil.* (not allowed)

©Silberschatz, Korth and Sudarshan1.9 Java Identifiers, cont. Java is case sensitive i.e., stuff, Stuff, and STUFF are different identifiers. n keywords or reserved words have special, predefined meanings: abstract assert boolean break byte case catch char class const continue default do double else enum extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while n Keywords cannot be used as identifiers n Identifiers can be arbitrarily long.

©Silberschatz, Korth and Sudarshan1.10 Naming Conventions Choose names that are helpful, or rather readable, such as count or speed, but not c or s. n Class types:  begin with an uppercase letter (e.g. String ). n Primitive types:  begin with a lowercase letter (e.g. int ). n Variables of both class and primitive types:  begin with a lowercase letters (e.g. myName, myBalance ).  multiword names are “punctuated” using uppercase letters.

©Silberschatz, Korth and Sudarshan1.11 Primitive Types n Four integer types:  byte  short  int (most common)  long n Two floating-point types:  float  double (most common) n One character type:  char n One boolean type:  boolean

©Silberschatz, Korth and Sudarshan1.12 Primitive Types, cont.

©Silberschatz, Korth and Sudarshan1.13 Examples of Primitive Values n Integer values: n Floating-point values: n Character values: `a` `A` `#` ` ` n Boolean values: true false

©Silberschatz, Korth and Sudarshan1.14 Motivation for Primitive Types n Why are there several different integer types?  storage space  operator efficiency n More generally, why are there different types at all?  reflects how people understand different kinds of data, e.g., letter vs. numeric grades.  helps prevent programmer errors.

©Silberschatz, Korth and Sudarshan1.15 Assignment Statements n An assignment statement is used to assign a value to a variable: int answer; answer = 42; The “equal sign” is called the assignment operator. In the above example, the variable named answer is assigned a value of 42, or more simply, answer is assigned 42.

©Silberschatz, Korth and Sudarshan1.16 Assignment Statements, cont. n Assignment syntax: variable = expression ; where expression can be  a literal or constant (such as a number),  another variable, or  an expression which combines variables and literals using operators

©Silberschatz, Korth and Sudarshan1.17 Assignment Examples n Examples: int amount; int score, numberOfCards, handicap; int eggsPerBasket; char firstInitial; : amount = 3; firstInitial = ‘ W ’ ; score = numberOfCards + handicap; eggsPerBasket = eggsPerBasket - 2; => last line looks weird in mathematics, why?

©Silberschatz, Korth and Sudarshan1.18 Assignment Evaluation n The expression on the right-hand side of the assignment operator ( = ) is evaluated first. n The result is used to set the value of the variable on the left-hand side of the assignment operator. score = numberOfCards + handicap; eggsPerBasket = eggsPerBasket - 2;

©Silberschatz, Korth and Sudarshan1.19 Simple Screen Output The following outputs the String literal “ The count is “ followed by the current value of the variable count. System.out.println( “ The count is “ + count); “ + ” means concatenation if at least one argument is a string

©Silberschatz, Korth and Sudarshan1.20 Simple Input n Sometimes data is needed and obtained from the user at run time. n Simple keyboard input requires: import java.util.*; or import java.util.Scanner; at the beginning of the file.

©Silberschatz, Korth and Sudarshan1.21 Simple Input, cont. A “Scanner” object must be initialized before inputting data: Scanner keyboard = new Scanner(System.in); n To input data: eggsPerBasket = keyboard.nextInt(); which reads one int value from the keyboard and assigns it to the variable eggsPerBasket.

©Silberschatz, Korth and Sudarshan1.22 Simple Input, cont. n class EggBasket2

©Silberschatz, Korth and Sudarshan1.23 Command-Line Arguments Frequently input is provided to a program at the command-line. public class UseArgument { public static void main(String[] args) { System.out.print(“Hi, ”); System.out.print(args[0]); System.out.println(“. How are you?”); } Sample interaction: % javac UseArgument.java % java UseArgument Alice Hi, Alice. How are you? % java UseArgument Bob Hi, Bob. How are you?

©Silberschatz, Korth and Sudarshan1.24 Command-Line Arguments Frequently multiple values are provided at the command-line. public class Use3Arguments { public static void main(String[] args) { System.out.print(“The first word is ”); System.out.print(args[0]); System.out.print(“, the second is ”); System.out.print(args[1]); System.out.print(“, and the third is ”); System.out.println(args[2]); } Sample interaction: % javac Use3Arguments.java % java Use3Arguments dog cat cow The first word is dog, the second is cat, and the third is cow

©Silberschatz, Korth and Sudarshan1.25 Command-Line Arguments Command-line arguments can be numeric. public class IntOps { public static void main(String[] args) { int a = Integer.parseInt(args[0]);// Notice the variable declaration int b = Integer.parseInt(args[1]);// Notice the comments…lol int sum = a + b; int prod = a * b; int quot = a / b; int rem = a % b; System.out.println(a + " + " + b + " = " + sum); System.out.println(a + " * " + b + " = " + prod); System.out.println(a + " / " + b + " = " + quot); System.out.println(a + " % " + b + " = " + rem); } Sample interaction: % javac IntOps.java % java IntOps = * 99 = / 99 = % 99 = 46

©Silberschatz, Korth and Sudarshan1.26 Literals Values such as 2, 3.7, or ’ y ’ are called constants or literals. Integer literals can be preceded by a + or - sign, but cannot contain commas. n There are two distinct properties that every integer literal has:  format – either decimal, hexadecimal or octal, and  type – either long or int Both the format and the type of an integer literal can be determined by…looking at it!

©Silberschatz, Korth and Sudarshan1.27 Integer Literal Formats n Decimal:  0, 10, 37, 643, 829, etc.  first digit must NOT be zero, for any non-zero integer n Hexadecimal:  consists of the leading characters 0x or 0X followed by one or more hexadecimal digits, i.e., 0 through F (lower and upper case equivalent)  each letter may be either upper case or lower case  0xA (decimal 10), 0x0 (decimal 0), 0xFF (decimal 255), 0xf0 (decimal 240), 0x34A2, 0Xff decimal (255), etc. n Octal:  Consists of the leading digit 0 followed by one or more octal digits, i.e., 0 through 7  010 (decimal 8), 023 (decimal 19), 037 (decimal 31)

©Silberschatz, Korth and Sudarshan1.28 Integer Literal Formats n What is the format?  0  2  0372  0xDadaCafe  1996  0x00FF00FF  0A3C  0945  450xA

©Silberschatz, Korth and Sudarshan1.29 Integer Literal Formats The format used to specify an integer literal has no impact on its corresponding internal value. All of the following println statements output the same thing: int x; x = 16; System.out.println("Value:" + x); x = 020; System.out.println("Value:" + x); x = 0x10; System.out.println("Value:" + x);

©Silberschatz, Korth and Sudarshan1.30 Integer Literal Type An integer literal is of type long if it is suffixed with an letter L or l; otherwise it is of type int.  note that capital L is preferred n Integer literals of type long:  2L  0372L  0xDadaCafeL  1996L  0x00FF00FFL  0l  0777L  0x l  L  0xC0B0L

©Silberschatz, Korth and Sudarshan1.31 Integer Literal Type See the program: 

©Silberschatz, Korth and Sudarshan1.32 Floating Point Literals n Just like with integer literals… Floating point literals can also be preceded by a + or - sign, but cannot contain commas. n There are two distinct properties that every floating point literal has:  format – either fully expanded notation or scientific notation  type – either float or double Both the format and the type of a floating point literal can be determined by…looking at it!

©Silberschatz, Korth and Sudarshan1.33 Floating Point Literal Formats n Floating-point constants can be written:  with digits after a decimal point, as in 3.5 or  using scientific notation n Examples:  can be written as 8.65e8  can be written as 4.83e-4 The number in front of the “e” does not need to contain a decimal point, e.g. 4e-4

©Silberschatz, Korth and Sudarshan1.34 Floating Point Literal Type An floating point literal is of type float if it is suffixed with an letter F or f; otherwise it is of type double. n Floating point literals of type float:  2.5F  0.0f  8.65e8f  4e-4 F  3f  +35.4f  -16F

©Silberschatz, Korth and Sudarshan1.35 Assignment Compatibilities n Java is said to be strongly typed, which means that there are limitations on mixing variables and values in expressions and assignments. int x = 0; long y = 0; float z = 0.0f; x = y;// illegal x = z;// illegal y = z;// illegal z = 3.6;// illegal (3.6 is of type double) y = 25;// legal, but interesting…

©Silberschatz, Korth and Sudarshan1.36 Assignment Compatibilities n Sometimes automatic conversions between types do take place: short s; int x; s = 83; x = s; double doubleVariable; int intVariable; intVariable = 7; doubleVariable = intVariable;

©Silberschatz, Korth and Sudarshan1.37 Assignment Compatibilities, cont. n A value of one numeric type can be assigned to a variable of any type further to the right, as follows: byte --> short --> int --> long --> float --> double but not to a variable of any type further to the left. Makes sense intuitively because, for example, any legal byte value is a legal short value. On the other hand, many legal short values are not legal byte values.

©Silberschatz, Korth and Sudarshan1.38 Assignment Compatibilities, cont. Example – all of the following are legal, and will compile: byte b; short s; int i; long l; float f; double d; b = 10; s = b; i = b; l = i; f = l;// This one is interesting, why? d = f;

©Silberschatz, Korth and Sudarshan1.39 Assignment Compatibilities, cont. Example – NONE (except the first) of the following will compile: byte b; short s; int i; long l; float f; double d; d = 1.0; f = d; l = f; i = l; s = i; b = s;

©Silberschatz, Korth and Sudarshan1.40 Type Casting n A type cast creates a value in a new type from an original type. n A type cast can be used to force an assignment when otherwise it would be illegal (thereby over-riding the compiler, in a sense). n Example: double distance; distance = 9.0; int points; points = (int)distance; n The above would be illegal without (int).

©Silberschatz, Korth and Sudarshan1.41 Type Casting, cont. The value of (int)distance is 9, but the value of distance, both before and after the cast, is 9.0. The type of distance does NOT change and remains double. What happens if distance contains 9.7?  Any nonzero value to the right of the decimal point is truncated (as oppossed to rounded). n Remember the rule – “cast with care,” because the results can be unpredictable.

©Silberschatz, Korth and Sudarshan1.42 Characters as Integers n Like everything else, each character is represented by a binary sequence. n The binary sequence corresponding to a character is a positive integer. n Which integer corresponds to each character is dictated by a standardized character encoding.  each character is assigned a unique integer code  the codes are different for upper and lower case letters, e.g., 97 may be the integer value for ‘a’ and 65 for ‘A’  some characters are printable, others are not n Why should different computers use the same code? n ASCII and Unicode are common character codes

©Silberschatz, Korth and Sudarshan1.43 Unicode Character Set n Most programming languages use the ASCII character encoding.  American Standard Code for Information Interchange (ASCII)  (only) encodes characters from the north American keyboard  uses one byte of storage n Java uses the Unicode character encoding which includes ASCII. n The Unicode character set:  uses two bytes of storage  includes characters from many different alphabets other than English (in contrast to ASCII)  codes characters from the North American keyboard the same way that ASCII does

©Silberschatz, Korth and Sudarshan1.44 ASCII/Unicode !“#$%&‘() 48…57…65…90…97…122 09AZaz

©Silberschatz, Korth and Sudarshan1.45 Assigning a char to an int A value of type char can be assigned to a variable of type int to obtain its Unicode value. n Example: char answer = ’y’; System.out.println(answer); System.out.println((int)answer); >y >121 n See the program at:

©Silberschatz, Korth and Sudarshan1.46 Initializing Variables n A variable that has been declared, but not yet given a value is said to be uninitialized. int x, y, z; x = y; x = z + 1; n Some languages automatically initialize a variable when it’s declared, other languages don’t. n Others (Java) initialize in some circumstances, but not in others.  Variables declared to be of a primitive type are NOT automatically initialized.  In other cases Java will initialize variables; this will be discussed later.

©Silberschatz, Korth and Sudarshan1.47 Initializing Variables n Some languages report an error when a variable is used prior to initialization by the program.  Sometimes at compile time, other times at run-time. n Some languages won’t report an error, and will even let you use an uninitialized variable.  In such cases the initial value of the variable is arbitrary!  The program might appear to run correctly sometimes, but give errors on others. n Java:  The compiler will (try) to catch uninitialized variables. => Always make sure your variables are initialized prior to use!

©Silberschatz, Korth and Sudarshan1.48 Initializing Variables, cont. n In Java, a variable can be assigned an initial value in it’s declaration. n Examples: int count = 0; char grade = ’ A ’ ; // default is an A n Syntax: type variable1 = expression1, variable2 = expression2, … ;

©Silberschatz, Korth and Sudarshan1.49 Arithmetic Operations n Arithmetic expressions:  are formed using the +, -, *, / and % operators  operators have operands, which are literals, variables or sub-expressions. n Expressions with two or more operators can be viewed as a series of steps, each involving only two operands.  The result of one step produces an operand which is used in the next step.  Note that Java is left-associative. n Example: int x = 0, y = 50, z = 20; double balance = 50.25, rate = 0.05; x = x + y + z; balance = balance + (balance * rate)

©Silberschatz, Korth and Sudarshan1.50 Expression Type n An arithmetic expression can have operands of different numeric types.  x + (y * z) / w  Note that this does not contradict our rules for assignment. n Every arithmetic expression has a (resulting) type. n Given an arithmetic expression:  If any operand in the expression is of type double, then the expression has type double.  Otherwise, if any operand in the expression is of type float, then the expression has type float.  Otherwise, if any operand in the expression is of type long, then the expression has type long.  Otherwise the expression has type int.

©Silberschatz, Korth and Sudarshan1.51 Expression Type, cont. n Example: int hoursWorked = 40; double payRate = 8.25; double totalPay; Then the expression in the assignment: totalPay = hoursWorked * payRate is a double with a value of

©Silberschatz, Korth and Sudarshan1.52 Operators with integer and floating point numbers n See the program:  

©Silberschatz, Korth and Sudarshan1.53 The Division Operator The division operator ( / ) behaves as expected. n If one of the operands is a floating-point type then the result is of the same floating point type.  9.0 / 2 = 4.5  9 / 2.0 = 4.5 n If both operands are integer types then the result is truncated, not rounded.  9 / 2 = 4  99 / 100 = 0

©Silberschatz, Korth and Sudarshan1.54 The mod Operator The mod ( % ) operator is used with operands of integer type to obtain the remainder after integer division. n 14 divided by 4 is 3 with a remainder of 2.  Hence, 14 % 4 is equal to 2. n The mod operator has many uses, including determining:  If an integer is odd or even ( x % 2 = 0 )  If one integer is evenly divisible by another integer ( a % b = 0 )

©Silberschatz, Korth and Sudarshan1.55 Case Study: Vending Machine Change n Program Requirements:  The user enters an amount between 1 cent and 99 cents.  The program determines a combination of coins equal to that amount.  For example, 55 cents can be two quarters and one nickel. => What are “requirements” anyway? n Sample dialog: Enter a whole number from 1 to 99. The machine will determine a combination of coins cents in coins: 3 quarters 1 dime 0 nickels 2 pennies

©Silberschatz, Korth and Sudarshan1.56 Case Study, cont. n Algorithm (version #1, in pseudo-code): 1. Read the amount. 2. Find the maximum number of quarters in the amount. 3. Subtract the value of the quarters from the amount. 4. Repeat the last two steps for dimes, nickels, and pennies. 5. Print the amount and the quantities of each coin. => What is an “algorithm” anyway? => What is “pseudo-code” also? n Program Variables Needed: int amount, quarters, dimes, nickels, pennies;

©Silberschatz, Korth and Sudarshan1.57 Case Study,cont. Interpreted literally, the algorithm doesn’t work properly, because the original amount is changed by the intermediate steps.  The original value of amount is lost. n Add an additional variable: int amount, originalAmount, quarters, dimes, nickles, pennies; and update the algorithm.

©Silberschatz, Korth and Sudarshan1.58 Case Study, cont. n Algorithm (version #2): 1. Read the amount. 2. Make a copy of the amount. 3. Find the maximum number of quarters in the amount. 4. Subtract the value of the quarters from the amount. 5. Repeat the last two steps for dimes, nickels, and pennies. 6. Print the original amount and the quantities of each coin. n Typically pseudo-code is iteratively embellished or enhanced.

©Silberschatz, Korth and Sudarshan1.59 Case Study, cont. n How do we determine the number of quarters in an amount?  There are 2 quarters in 55 cents, but there are also 2 quarters in 65 cents.  That’s because 55 / 25 = 2 and 65 / 25 = 2. n How do we determine the remaining amount?  Using the mod operator: 55 % 25 = 5 and 65 % 25 = 15 n Similarly for dimes, nickels and pennies  Pennies are simply amount % 5.

©Silberschatz, Korth and Sudarshan1.60 Case Study, cont.

©Silberschatz, Korth and Sudarshan1.61 Case Study—testing the implementation n The program should be tested with several different amounts. n Test with values that give zero values for each possible coin denomination. n Test with amounts close to:  “Extreme” or “boundary condition” values such as 0, 1, 98 and 99.  Coin denominations such as 24, 25, and 26.

©Silberschatz, Korth and Sudarshan1.62 Increment (and Decrement) Operators n Used to increase (or decrease) the value of a variable by 1.  count = count +1  count = count -1 n Easy to use, important to recognize. n The increment operator:  count++  ++count n The decrement operator:  count--  --count

©Silberschatz, Korth and Sudarshan1.63 Increment (and Decrement) Operators “Mostly” equivalent operations: count++; ++count; count = count + 1; count--; --count; count = count - 1;

©Silberschatz, Korth and Sudarshan1.64 Increment (and Decrement) Operators in Expressions n After executing: int m = 4; int result = 3 * (++m); result has a value of 15 and m has a value of 5 n After executing: int m = 4; int result = 3 * (m++); result has a value of 12 and m has a value of 5

©Silberschatz, Korth and Sudarshan1.65 Increment and Decrement Operator, Cont. n Common code: int n = 3; int m = 4; int result; What will be the value of m and result after each of these executes? (a) result = n * ++m; (b) result = n * m++; (c) result = n * --m; (d) result = n * m--;

©Silberschatz, Korth and Sudarshan1.66 Precedence Rules—Binary Operators n An expression (without parenthesis) is evaluated according to the (basic) rules of precedence:  Highest precedence – unary operators +, -, ++, -- and !  Intermediate precedence – binary arithmetic operators *, / and %  Lowest precedence – binary arithmetic operators + and - n Binary operators in Java are “left-associative:”  When binary operators have equal precedence the operator on the left has higher precedence than the operator(s) on the right. n Unary operators in Java are “right-associative:”  When unary operators have equal precedence the operator on the right has higher precedence  if x contains x is -11 and x is 11 afterwards; same as – (++x) -x++ is -10 and x is 11 afterwards; same as – (x++)

©Silberschatz, Korth and Sudarshan1.67 Use Parentheses n Parentheses can be used to over-ride the rules of precedence: (cost + tax) * discount n Parenthesis can also be used to clarify code, even when precedence is not over-ridden: balance + (interestRate * balance) n Spaces also clarify code: balance + interestRate*balance but spaces do not dictate precedence.

©Silberschatz, Korth and Sudarshan1.68 Sample Expressions

©Silberschatz, Korth and Sudarshan1.69 The Class String As we already have seen, a String is a sequence of characters. We’ve used constants, or rather, literals of type String : “Enter a whole number from 1 to 99.” “Number of quarters:” “I will output a combination of coins”

©Silberschatz, Korth and Sudarshan1.70 Declaring and Printing Strings n Variables of type String can be declared and Initialized: String greeting; greeting = “ Hello! ” ; n Equivalent to the above: String greeting = “ Hello! ” ; String greeting = new String( “ Hello! ” ); n Printing: System.out.println(greeting);

©Silberschatz, Korth and Sudarshan1.71 Concatenation of Strings Two strings can be concatenated using the + operator: String greeting = “Hello”; String name = “Smith”; String sentence; sentence = greeting + “ officer ”; sentence = sentence + name; System.out.println(sentence); Any number of strings can be concatenated using the + operator.

©Silberschatz, Korth and Sudarshan1.72 Concatenating Strings and Integers n Strings can be concatenated with other types: String solution; solution = “The temperature is “ + 72; System.out.println (solution); Output: The temperature is 72

©Silberschatz, Korth and Sudarshan1.73 Positions in a String n Each character in a String has its own position. n Positions are numbered starting at 0.  ‘ J ’ in “ Java is fun. ” is in position 0  ‘ f ’ in “ Java is fun. ” is in position 8 n The position of a character is also referred to as its index.

©Silberschatz, Korth and Sudarshan1.74 Positions in a String, cont.

©Silberschatz, Korth and Sudarshan1.75 Classes n Recall that Java has primitive types and class types:  primitive types  class types n Primitive types have:  simple, “atomic,” non-decomposable values  Operations (built-in) n Class types have:  complex values, with structure  Methods (some built-in, others user-defined)

©Silberschatz, Korth and Sudarshan1.76 Objects, Methods, and Data n A primitive type is use to create variables. n A class type is used to produce “objects.” n An object is an entity that:  stores data  can take actions defined by methods  basically a complex variable. n The data and methods applicable to an object are defined by its class.

©Silberschatz, Korth and Sudarshan1.77 The Class String String is a class type The length() method returns an int, which is the number of characters in a particular String object. int howMany = solution.length(); You can use a call to method length() anywhere an int can be used. int X = 10; int count = solution.length(); System.out.println(solution.length()); X = X * solution.length() + 3;

©Silberschatz, Korth and Sudarshan1.78 Indexing Characters within a String using Methods n charAt(position)  returns the char at the specified position Example: String greeting = "Hi, there!"; char ch1 = greeting.charAt(0); // Stores ‘H’ in ch1 char ch2 = greeting.charAt(2); // Stores ‘,’ in ch2 n substring(start, end)  returns the string from start up to, but not including, end String myWord; myWord = greeting.substring(4,7) // Stores the in myWord

©Silberschatz, Korth and Sudarshan1.79 Example of Class String

©Silberschatz, Korth and Sudarshan1.80 String Methods n See the Java on-line documentation for more details!

©Silberschatz, Korth and Sudarshan1.81 Escape Characters n How would you print the following? “Java” refers to a language. n The following don’t work: System.out.println(“Java refers to a language.”); System.out.println(““Java” refers to a language.”); The compiler needs to be told that the quotation marks ( “ ) do not signal the start or end of a string, but instead are to be printed. System.out.println(“\”Java\” refers to a language.”);

©Silberschatz, Korth and Sudarshan1.82 Escape Characters n “Escape sequences” are used to print problematic characters. n Each escape sequence is a single character even though it is written with two symbols.

©Silberschatz, Korth and Sudarshan1.83 Examples n Examples: System.out.println( “ abc\\def ” );=>abc\def System.out.println( “ new\nline ” );=>new line char singleQuote = ‘ \ ’’ ; System.out.println(singleQuote); => ‘

©Silberschatz, Korth and Sudarshan1.84 Keyboard and Screen I/O: Outline n Screen Output n Keyboard Input

©Silberschatz, Korth and Sudarshan1.85 Screen Output We’ve seen several examples of screen output already. System.out is an object that is part of Java. println() is one of the methods available to the System.out object.

©Silberschatz, Korth and Sudarshan1.86 Screen Output, cont. The concatenation operator ( + ) is useful when everything does not fit on one line.: System.out.println( “ When everything “ + “ does not fit on one line, use the ” + “ concatenation operator (\ ’ +\ ’ ) ” ); => Do not break the line except immediately before or after the concatenation operator ( + ).

©Silberschatz, Korth and Sudarshan1.87 Screen Output, cont. Alternatively, use print() System.out.print( “ When everything “ ); System.out.print( “ does not fit on “ ); System.out.print( “ one line, use the “ ); System.out.print( “ \ ” print\ ” ” ); System.out.println( “ statement ” ); ending with a println().

©Silberschatz, Korth and Sudarshan1.88 Screen Output, cont. n Syntax: System.out.println(output_1 + output_ output_n); n Example: System.out.println ( “ “ + “ Oldsmobile ” + “ “ + 442); 1967 Oldsmobile 442

©Silberschatz, Korth and Sudarshan1.89 printf (or format ) Method for Output Formatting Heavily influenced by C outputStream.printf(formatString, args … )  System.out.printf( … )  smileyOutStream.printf( … ) formatString specifies how to format args System.out.printf( “ %s %d %f%n ”, name, id, gpa);  System.out.println(name + “ “ + id + “ “ + gpa); Useful for “right justified” numbers Numbers in println and print are “left justified”

©Silberschatz, Korth and Sudarshan1.90 Formatting String % width conversion width specifies how many slots are available for output If width > number of characters, spaces are printed first before the characters— “right justified” printf( “ %5d ”, count)  Count  32901:  2004:  22:  : all digits are printed, width is ignored

©Silberschatz, Korth and Sudarshan1.91 Conversion Characters ConversionArgumentDescription d integerDecimal integer f floating pointDecimal float s general (String, Boolean, …)String n New line c characterCharacter (unicode) e floating pointDecimal scientific notation o integerOctal integer x integerHexadecimal integer % % (% to output %)

©Silberschatz, Korth and Sudarshan1.92 Imprecision in Floating-Point Numbers n Floating-point numbers often are only approximations since they are stored with a finite number of bits. Hence 1.0/3.0 is slightly less than 1/3. 1.0/ / /3.0 could be less than 1. n See the program: 

©Silberschatz, Korth and Sudarshan1.93 Floating-point Precision width.precision conversion printf( “ %5.2f ”, PI) printf( “ %7.4f ”, PI)

©Silberschatz, Korth and Sudarshan1.94 Left Justified Spaces are added (padded) on the right Minus ( - ) sign before the width … printf( “ %-7s %-4d ”, name, age) Why are there 4 spaces after “John” instead of 3? John20

©Silberschatz, Korth and Sudarshan1.95 Example

©Silberschatz, Korth and Sudarshan1.96 Keyboard Input n Starting from Java 5.0  Java has reasonable facilities for handling keyboard input. Scanner class in the java.util package  A package is a library of classes.

©Silberschatz, Korth and Sudarshan1.97 Using the Scanner Class n Near the beginning of your program, insert import java.util.* Create an object of the Scanner class Scanner keyboard = new Scanner(System.in) Read data (an int or a double, for example) int n1 = keyboard.nextInt(); double d1 = keyboard.nextDouble();

©Silberschatz, Korth and Sudarshan1.98 Some Scanner Class Methods n Syntax: Int_Variable = Object_Name.nextInt(); Double_Variable = Object_Name.nextDouble(); Float_Variable = Object_Name.nextFloat(); String_Variable = Object_Name.next(); String_Variable = Object_Name.nextLine(); Boolean_Variable = Object_Name.nextBoolean(); nextByte(), nextShort(), nextLong()

©Silberschatz, Korth and Sudarshan1.99 Some Scanner Class Methods, cont. n Examples: int count = keyboard.nextInt(); double distance = keyboard.nextDouble(); String word = keyboard.next(); String wholeLine = keyboard.nextLine(); n Remember to prompt the user for input: System.out.print( “ Enter an integer: “ );

©Silberschatz, Korth and Sudarshan1.100 Keyboard Input Demonstration n class ScannerDemo

©Silberschatz, Korth and Sudarshan1.101 nextLine() Method Caution The nextLine() method reads the remainder of the current line, even if it is empty.

©Silberschatz, Korth and Sudarshan1.102 nextLine() Method Caution, cont. n Example: int n; String s1, s2; n = keyboard.nextInt(); s1 = keyboard.nextLine(); s2 = keyboard.nextLine(); 5440 or bust n is set to 5440 but s1 is set to the empty string.

©Silberschatz, Korth and Sudarshan1.103 The Empty String n String with zero characters String s3 = “” ; Good for String initialization

©Silberschatz, Korth and Sudarshan1.104 Other Input Delimiters, cont. n class DelimitersDemo

©Silberschatz, Korth and Sudarshan1.105 Documentation and Style: Outline n Meaningful Names n Self-Documentation and Comments n Indentation n Named Constants Grading  10% on documentation and comments  10% on style (variable naming, indentation)

©Silberschatz, Korth and Sudarshan1.106 Documentation and Style n Most programs are modified over time to respond to new requirements. n Programs which are easy to read and understand are easy to modify. n Even if it will be used only once, you have to read it in order to debug it.

©Silberschatz, Korth and Sudarshan1.107 Meaningful Names for Variables A variable’s name should suggest its use. n Observe conventions in choosing names for variables.  Use only letters and digits.  Use more than one character.  “Punctuate” using uppercase letters at word boundaries (e.g. taxRate ).  Start variables with lowercase letters.  Start class names with uppercase letters.

©Silberschatz, Korth and Sudarshan1.108 Documentation and Comments n The best programs are self-documenting.  clean style  well-chosen names n Comments are written into a program as needed explain the program.  They are useful to the programmer, but they are ignored by the compiler.

©Silberschatz, Korth and Sudarshan1.109 When to Use Comments n Begin each program file with an explanatory comment  what the program does  the name of the author  contact information for the author  date of the last modification. n Provide only those comments which the expected reader of the program file will need in order to understand it.

©Silberschatz, Korth and Sudarshan1.110 Comments Example n class CircleCalculation

©Silberschatz, Korth and Sudarshan1.111 Template for CSE 1001 /** Name: address: Course: cse1001 Section: Assignment: Date: Description: */ import java.util.*; public class { public static void main(String[] args) { // input from the keyboard Scanner keyboard = new Scanner(System.in); }

©Silberschatz, Korth and Sudarshan1.112 Comments A program can usually be broken into segments/blocks based on the algorithm, e.g. in HW2:  Prompt the user for input  Input from the keyboard  Calculation  Output to the screen Blank line between two segments A description (comment) before each segment

©Silberschatz, Korth and Sudarshan1.113 Pseudocode and Comments Solving a problem 1. Devise an algorithm (steps to solve the problem) 2. Write the algorithm in pseudocode (semi English, semi Java) 3. English part of pseudocode becomes comments in your program Tip: 1. type the English part of pesudocode as comments into your program first 2. write the detailed Java instructions to satisfy/implement the pesudocode Advantages: 1. Each line of pseudocode helps you focus on a small task 2. Pseudocode tells you what steps you want to achieve 3. No need to add comments later on

©Silberschatz, Korth and Sudarshan1.114 Comments n A comment can begin with //.  Everything after these symbols and to the end of the line is treated as a comment and is ignored by the compiler. double radius; //in centimeters

©Silberschatz, Korth and Sudarshan1.115 Comments, cont. n A comment can begin with /* and end with */  Everything between these symbols is treated as a comment and is ignored by the compiler. /* the simplex method is used to calculate the answer*/

©Silberschatz, Korth and Sudarshan1.116 Comments, cont. n A javadoc comment, begins with /** and ends with */.  It can be extracted automatically from Java software. /** method change requires the number of coins to be nonnegative */

©Silberschatz, Korth and Sudarshan1.117 Indentation n Indentation should communicate nesting clearly. n A good choice is four spaces for each level of indentation. n Indentation should be consistent. n Indentation should be used for second and subsequent lines of statements which do not fit on a single line.

©Silberschatz, Korth and Sudarshan1.118 Indentation, cont. n Indentation does not change the behavior of the program. n Improper indentation can miscommunicate the behavior of the program.

©Silberschatz, Korth and Sudarshan1.119 Named Constants n To avoid confusion, always name constants (and variables). circumference = PI * radius; is clearer than circumference = * 6.023; n Place constants near the beginning of the program.

©Silberschatz, Korth and Sudarshan1.120 Named Constants, cont. n The value of a constant cannot be changed once it is initialized public static final double INTEREST_RATE = 6.65; n Consider the interest rate is used many times in the program:  What if you type 6.65 in some places, but 6.56 in others?  What if the interested rate has changed to 7.3?  Is balance * INTEREST_RATE easier to read than balance * 6.65 ?

©Silberschatz, Korth and Sudarshan1.121 Declaring Constants n syntax public static final Type Name = Constant; n examples public static final double PI = ; public static final String MOTTO = “ The customer is always right. ” ;  By convention, uppercase letters are used for constants.

©Silberschatz, Korth and Sudarshan1.122 Named Constants n class CircleCalculation2

©Silberschatz, Korth and Sudarshan1.123 Summary n You have become familiar with Java primitive types (numbers, characters, etc.). n You have learned about assignment statements and expressions. n You have learned about stings. n You have become familiar with the basics of classes, methods, and objects. n You have learned about simple keyboard input and screen output.

©Silberschatz, Korth and Sudarshan1.124 Number Constants DecimalBinaryOctalHexidecimal A B C D E F A B C D E F

©Silberschatz, Korth and Sudarshan1.125 Binary Representation n Assume an 8-bit type n 5 as an integer  ‘5’ as a character  (53 decimal, ASCII) n 5.0 as a floating point number  How?  What about 5.5?

©Silberschatz, Korth and Sudarshan1.126 Binary Real Numbers n 5.5  n 5.25  n  n 5.75  … …

©Silberschatz, Korth and Sudarshan bits only n 5.5  > n 5.25  > n  > ?? n With only 2 places after the point, the precision is.25 n What if the point is allowed to move around?

©Silberschatz, Korth and Sudarshan1.128 Floating-point Numbers n Decimal  54.3  5.43 x 10 1 [scientific notation] n Binary   x 2 1 [more correctly: x 10 1 ]  x 2 2 [more correctly: x ]  What can we say about the most significant bit?

©Silberschatz, Korth and Sudarshan1.129 Floating-point Numbers n General form: sign 1.mantissa x 2 exponent  the most significant digit is right before the dot  Always 1 [no need to represent it]  (more details are not discussed here: mantissa has no sign, but sign is embedded in exponent…) n x 2 2  Sign: positive (0)  Mantissa:  Exponent: 10 (decimal 2)  [IEEE standard: “biased exponent” exponent + 2 numBits Example: – 1 = 3 => 11 in binary]

©Silberschatz, Korth and Sudarshan1.130 Java Floating-point Numbers n Sign:  1 bit [0 is positive] n Mantissa:  23 bits in float  52 bits in double n Exponent:  8 bits in float  11 bits in double signexponentmantissa