1 java basics chapter 2 cs 101-e. 2 displayforecast.java // authors: j. p. cohoon and j. w. davidson...

58
1 Java basics Chapter 2 CS 101-E

Post on 20-Dec-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

1

Java basics

Chapter 2

CS 101-E

Page 2: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

2

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.");

}}

// 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

// 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

// 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().

// 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

// 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.");

}} We will discuss 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.");

}} Java allows a statement to be made up of

multiple lines of text

Semicolons delimit one statement from the next

// 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

// 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 like a method must have 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.");

}} A class like a method must have 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.");

}} Programs are read by people – make sure they are

readable.

Use whitespace, comments, and indentation to aid understanding

// 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.");

}} // indicates rest of the line is a comment

Comments are used to document authors, purpose, and program elements

Three comments

Page 3: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

3

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.");

}}

Indentation indicates subcomponents

Method main() is part of DisplayForecast

Statements are part of method main()

Page 4: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

4

Good whitespacing

// 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 separates program elements

Whitespace between program elements is ignored by Java

Whitespace

Page 5: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

5

Bad whitespacing The same program without any whitespacing or comments:

public class DisplayForecast2 { 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."); } }

Page 6: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

6

An aside: IOCCC The International Obfuscated C Code Contest

Online at http://www.ioccc.org

C has very terse syntax So the contest tries to make it terser!

One common method is by modifying the whitespace

Page 7: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

7

An aside: IOCCC

#define _ -F<00||--F-OO--;int F=00,OO=00;main(){F_OO();printf("%1.3f\n",4.*-F/OO/OO);}F_OO(){ _-_-_-_ _-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-__-_-_-_-_-_-_-_-_-_-_-_-_-_-_-__-_-_-_-_-_-_-_-_-_-_-_-_-_-_-__-_-_-_-_-_-_-_-_-_-_-_-_-_-_-__-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_ _-_-_-_}

#define X#define XX#define XXX#define XXXX#define XXXXX#define XXXXXX#define XXXXXXX#define orfa for#define XXXXXXXXX#define archa char#define ainma main#define etcharga getchar#define utcharpa putchar

#include <stdio.h>#define Q r=R[*p++-'0'];while(#define B ;break;casechar*s="Qjou!s\\311^-g\\311^-n\\311^-c\\::^-q-ma%mO1JBHm%BQ-aP1J[O1HB%[Q<nbj\o)*|gps)<<*txjudi)m*|aQdbtf!::::;sfuvso<aQefgbvmu;aQ<m,,a%CQ<csfbla%bQ<aN2!Q\\ndbtf!aP2Q;m>aP2Q<a%!D12J!JGJHJOJQJFJSJJJMHS%HD12D12N3!N4\nJUJT%UQm>aP4HC%T\Qs\\q,,^>m,2<m>aP4HC%SD12N1\nJNQm>s\\..q^aHC%NHb%GN1!D32P3%RN1UP1D12JPQUaP1H\R%PN4\nQ<g\\(aP3Q(^>aP2Q,2<n\\(aP3Q(^>aP4Hb%OD12D12N2!N3\nJVP3Q,,<jg)aP3Q=>n\\\(aP3Q(^*m>g\\(aP3Q(^<fmtf!m,,aHC%QN1!N1\nJ#Qqsjoug)#&e]o#-aP1Q*aHb%#Qqvut)\aP1Q*aHb%FN1\nQm>::::aHC%VP3Q>bupj)hfut)c**aHb%JD12JON1!Qjg)a%LN1UP1D12JIQUa\P1HL%IQ*m>aN2!N2\nP2Q<fmtf!m,,aHC%MN1!N2>P2Q>aN2\nP2Hbdd!b/d";k;char R[4][99];main(c,v)char**v;{char*p,*r,*q;for(q=s;*q;q++)*q>' '&&(*q)--;{FILE*i=fopen(v[1],"r"),*o=fopen(q-3,"w");for(p=s;;p++)switch(*p++){B'M':Q(k=fgetc(i))!=EOF&&k!=*p)*r++=k;if(k==EOF){fputs("}}\n",o);fclose(o);return system(q-6);}*r=0B'P':while(*p!='`')fputc(*p++,o)B'O':Q*r)fputc(*r++,o);p--B'C':k=0;Q k<*p-'0')(*r++=fgetc(i),k++);*r=0 B'I':k= *p;if(**R==k)goto G B'G':k= *p;G:p=s;while(*p!='$'||p[1]!= k)p++;p++B'N':R[*p-'0'][0]++;}}}

X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X XX X X XX XX XXX X XXXXXXXXX X XXX XX XXX X XXXX XXXX X XXX XX XXXX X XX ainma(){ archa XX X XXXX XX XXXX X oink[9],*igpa, X XXXX XX XXXXXX atinla=etcharga(),iocccwa XXXXXX XX XXXX ,apca='A',owla='a',umna=26 XXXX XX XXX ; orfa(; (atinla+1)&&(!((( XXX XX XX atinla-apca)*(apca+umna-atinla) XX X X X >=0)+((atinla-owla)*(owla+umna- X X X atinla)>=0))); utcharpa(atinla), X X X atinla=etcharga()); orfa(; atinla+1; X X X X ){ orfa( igpa=oink ,iocccwa=( X X X X (atinla- XXX apca)*( XXX apca+umna- X X X atinla)>=0) XXX XXX ; (((( X X atinla-apca XXXXX XXXXXXX XXXXX )*(apca+ X X umna-atinla XXXXXX )>=0) XXXXXX +((atinla- X X owla)*(owla+ XXXX umna- XXXX atinla)>=0)) X X &&"-Pig-" XX "Lat-in" XX "COb-fus" X X "ca-tion!!"[ X (((atinla- X apca)*(apca+ X X umna-atinla) X >=0)?atinla- X apca+owla: XX atinla)-owla X ]-'-')||((igpa== X oink)&&!(*( XX igpa++)='w') X )||! X (*( X igpa X ++)=owla); * XX (igpa++)=(( X ( XXX XXX X atinla-apca XX )*(apca+ X umna XXX - XXX X atinla)>=0) XX ?atinla- X apca XXX + XXX owla X :atinla), X X atinla= X X X X etcharga()) X X ; orfa( X atinla=iocccwa?(( X (atinla- X X owla)*(owla+ X umna-atinla)>=0 X )?atinla- X X owla+apca: X atinla): X atinla; ((( X X atinla-apca)* X (apca+umna- X atinla)>=0)+( X X (atinla-owla)* X (owla+ X umna-atinla)>= X X 0)); utcharpa( XX XX atinla),atinla X X =etcharga()); XXXXXXX orfa(*igpa=0, X X igpa=oink; * igpa; utcharpa( X X *(igpa++))); orfa(; (atinla+1)&&(!((( X X atinla-apca )*(apca+ X X umna- XXXXX XXXXX atinla)>=0 X X )+(( XXXXX atinla- X XX owla)*( owla+umna- XX XX atinla)>=0))); utcharpa XX XX (atinla),atinla= XX XX etcharga()); } XX XXXX } XXXX XXXXXXXXX

a(X){/*/X=- a(X){/*/X=--1;F;X=- -1;F;X=--1;F;}/*/ -1;F;}/*/

char*z[]={"char*z[]={","a(X){/*/X=-","-1;F;X=-","-1;F;}/*/","9999999999 :-| ","int q,i,j,k,X,O=0,H;S(x)int*x;{X+=X;O+=O;*x+1?*x+2||X++:O++;*x=1;}L(n){for(*","z[i=1]=n+97;i<4;i++)M(256),s(i),M(128),s(i),M(64),N;X*=8;O*=8;}s(R){char*r=z","[R];for(q&&Q;*r;)P(*r++);q&&(Q,P(44));}M(m){P(9);i-2||P(X&m?88:O&m?48:32);P(","9);}y(A){for(j=8;j;)~A&w[--j]||(q=0);}e(W,Z){for(i-=i*q;i<9&&q;)y(W|(1<<i++&","~Z));}R(){for(k=J[*J-48]-40;k;)e(w[k--],X|O);}main(u,v)char**v;{a(q=1);b(1);","c(1);*J=--u?O?*J:*v[1]:53;X|=u<<57-*v[u];y(X);K=40+q;q?e(O,X),q&&(K='|'),e(X",",O),R(),O|=1<<--i:J[*J-48+(X=O=0)]--;L(q=0);for(s(i=0);q=i<12;)s(i++),i>4&&N",";s(q=12);P(48);P('}');P(59);N;q=0;L(1);for(i=5;i<13;)s(i++),N;L(2);}",0};

b(X){/*/X=- b(X){/*/X=--1;F;X=- -1;F;X=--1;F;}/*/ -1;F;}/*/

int q,i,j,k,X,O=0,H;S(x)int*x;{X+=X;O+=O;*x+1?*x+2||X++:O++;*x=1;}L(n){for(*z[i=1]=n+97;i<4;i++)M(256),s(i),M(128),s(i),M(64),N;X*=8;O*=8;}s(R){char*r=z[R];for(q&&Q;*r;)P(*r++);q&&(Q,P(44));}M(m){P(9);i-2||P(X&m?88:O&m?48:32);P(9);}y(A){for(j=8;j;)~A&w[--j]||(q=0);}e(W,Z){for(i-=i*q;i<9&&q;)y(W|(1<<i++&~Z));}R(){for(k=J[*J-48]-40;k;)e(w[k--],X|O);}main(u,v)char**v;{a(q=1);b(1);c(1);*J=--u?O?*J:*v[1]:53;X|=u<<57-*v[u];y(X);K=40+q;q?e(O,X),q&&(K='|'),e(X,O),R(),O|=1<<--i:J[*J-48+(X=O=0)]--;L(q=0);for(s(i=0);q=i<12;)s(i++),i>4&&N;s(q=12);P(48);P('}');P(59);N;q=0;L(1);for(i=5;i<13;)s(i++),N;L(2);}

c(X){/*/X=- c(X){/*/X=--1;F;X=- -1;F;X=--1;F;}/*/ -1;F;}/*/

Page 8: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

8

Identifiers Identifiers are names for variables, classes, etc.

Good ones are compact, but inidicate what they stand for radius, width, height, length

Bad ones are either too long theRadiusOfTheCircle theWidthOfTheBoxThatIsBeingUsed the_width_of_the_box_that_is_being_used

Or too short a, b, c, d, e

Good identifiers will help the graders understand your program!

Page 9: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

9

Keywords

// 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.");

}}

// 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.");

}}

// 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.");

}}

Some words are reserved, and can’t be used as identifiers

Page 10: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

10

Capitalization Case matters!

public ≠ Public ≠ PUBLIC This is different that FORTRAN and BASIC This is the same as C/C++

You can use Public as a identifier Not recommended, though!

Page 11: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

11

Defining a method All methods have the following syntax:

modifers type name ( parameters ) { statements }

Propertiesof the

method

Typethat itreturns

A namefor themethod

Any number(including zero)of parameters

The body ofthe method

(can be empty)

public static void main (String[] args) { ... }

Page 12: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

12

Escape sequences Java provides escape sequences for printing special

characters \b backspace \n newline \t tab \r carriage return \\ backslash \" double quote \' single quote

Page 13: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

13

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" 7Jenna 5'10" 9JJ 6'1" 14

Page 14: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

14

Assignment operator = Allows the memory location for a variable to be updated

Considerint j = 11;j = 1985;

Primitive variable assignment Assignment operator =

Allows the memory location for a variable to be updated

Considerint j = 11;j = 1985;

11j

Expression to beevaluated

Name of previouslydefined object

target = expression ;

1985j

Page 15: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

15

Considerint a = 1;int aSquared = a * a;a = 5;aSquared = a * a;

Considerint i = 0;i = i + 1;

Considerint asaRating;asaRating = 400;

Primitive variable assignment

5a

1aSquared

5a

25aSquared

0i

Considerint a = 1;int aSquared = a * a;a = 5;aSquared = a * a;

Considerint i = 0;i = i + 1;

Considerint asaRating;asaRating = 400;

Considerint a = 1;int aSquared = a * a;a = 5;aSquared = a * a;

Considerint i = 0;i = i + 1;

Considerint asaRating;asaRating = 400;

Considerint a = 1;int aSquared = a * a;a = 5;aSquared = a * a;

Considerint i = 0;i = i + 1;

Considerint asaRating;asaRating = 400;

Considerint a = 1;int aSquared = a * a;a = 5;aSquared = a * a;

Considerint i = 0;i = i + 1;

Considerint asaRating;asaRating = 400;

1i

Considerint a = 1;int aSquared = a * a;a = 5;aSquared = a * a;

Considerint i = 0;i = i + 1;

Considerint asaRating;asaRating = 400;

Considerint a = 1;int aSquared = a * a;a = 5;aSquared = a * a;

Considerint i = 0;i = i + 1;

Considerint asaRating;asaRating = 400;

Considerint a = 1;int aSquared = a * a;a = 5;aSquared = a * a;

Considerint i = 0;i = i + 1;

Considerint asaRating;asaRating = 400;

-asaRating 400asaRating

1a

1aSquared

Page 16: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

16

19.28x

5.12y

5.12rememberX

5.12x

Primitive variable assignment

5.12x

19.28y

5.12x

19.28y

5.12rememberX

19.28x

19.28y

5.12rememberX

Considerdouble x = 5.12;double y = 19.28;double rememberX = x; x = y; y = rememberX;

Considerdouble x = 5.12;double y = 19.28;double rememberX = x; x = y; y = rememberX;

Considerdouble x = 5.12;double y = 19.28;double rememberX = x; x = y; y = rememberX;

Considerdouble x = 5.12;double y = 19.28;double rememberX = x; x = y; y = rememberX;

Considerdouble x = 5.12;double y = 19.28;double rememberX = x; x = y; y = rememberX;

Considerdouble x = 5.12;double y = 19.28;double rememberX = x; x = y; y = rememberX;

Page 17: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

17

Primitive variable types Java has 8 (or so) primitive types:

float double boolean char byte short int long

real numbers

integer numbers

two values: true and falsea

a single character

Also the void “type”

Page 18: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

18

Primitive real (floating-point) types A float takes up 4 bytes of space

Has 6 decimal places of accuracy: 3.14159

A double takes up 8 bytes of space Has 15 decimal places of accuracy: 3.14159265358979

Always use doubles It will save you quite a headache!

Page 19: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

19

Primitive integer types Consider a byte:

0 1 0 0 0 1 0 1

1 byte = 8 bits Each bit has two possibilities: 0 or 1

28 = 256 Thus, a byte can have any one of 256 values

A Java byte can have values from -128 to 127 From -27 to 27-1

C/C++ has unsigned versions; Java does not

Page 20: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

20

Primitive integer types

Type Bytes Minimum value Maximum value

byte 1 -27=-128 27-1=127

short 2 -215=-32,768

215-1=32,767

int 4 -231=-2,147,483,648 231-1=2,147,483,647

long 8 -263=-9,223,372,036,854,775,808

263-1=9,223,372,036,854,775,807

Page 21: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

21

Increment and decrement operators ++

Increments a number variable by 1 --

Decrements a numeric variable by 1

Considerint i = 4; // define++i;System.out.println(i);System.out.print(++i);System.out.println(i++);System.out.println(i);

++ Increments a number variable by 1

-- Decrements a numeric variable by 1

Considerint i = 4;++i; // incrementSystem.out.println(i);System.out.print(++i);System.out.println(i++);System.out.println(i);

++ Increments a number variable by 1

-- Decrements a numeric variable by 1

Considerint i = 4;++i;System.out.println(i); // displaySystem.out.print(++i);System.out.println(i++);System.out.println(i);

++ Increments a number variable by 1

-- Decrements a numeric variable by 1

Considerint i = 4;++i;System.out.println(i);System.out.print(++i); // update then displaySystem.out.println(i++); System.out.println(i);

++ Increments a number variable by 1

-- Decrements a numeric variable by 1

Considerint i = 4;++i;System.out.println(i);System.out.print(++i); System.out.println(i++); // display then update System.out.println(i);

++ Increments a number variable by 1

-- Decrements a numeric variable by 1

Considerint i = 4;++i;System.out.println(i);System.out.print(++i);System.out.println(i++);System.out.println(i); // display

++ Increments a number variable by 1

-- Decrements a numeric variable by 1

Considerint i = 4;++i;System.out.println(i);System.out.print(++i);System.out.println(i++);System.out.println(i);

4i 5i 6i 7i

Page 22: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

22

Why you should get the extended warranty

Page 23: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

23

Primitive character type All characters have a integer equivalent

‘0’ = 48 ‘1’ = 49 ‘A’ = 65 ‘a’ = 97

Thus, you can refer to ‘B’ as ‘A’+1

Page 24: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

24

Primitive character typepublic class LowerToUpper {

// main(): application entry pointpublic 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);}

}

Page 25: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

25

Primitive boolean type When is the following program valid in Java?

Assume a and b have been properly declared...if ( a && b ) {

// do something interesting}...

Answer: ONLY when a and b are boolean variables

In C/C++, a and b would be ints (or int variants) If you try making a and b ints in Java, you get the

following: operator && cannot be applied to int,int

Page 26: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

26

Primitive void “type” In Java, you can ONLY use void to specify that a method does

not return a value

You cannot use it to specify that there are no parameters to a method:

...

int foo (void) {

... This is different from C/C++

You cannot use it to declare a void “variable”, as in C/C++:void *foo;

Page 27: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

27

Variable initialization Consider the following code:

int x;System.out.println(x);

What happens?

Error message: variable x might not have been initialized

Page 28: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

28

Constants Consider the following:

final int x = 5;

The value of x can NEVER be changed! The value assigned to it is “final”

This is how Java defines constants

Page 29: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

29

Expressions What is the value used to initialize expression

int expression = 4 + 2 * 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

Page 30: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

30

Question on expressions Does the following statement compute the average of double

variables a, b, and c? Why

double average = a + b + c / 3.0;

Page 31: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

31

System.out.println()

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

Page 32: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

32

System.out

+ println(String s) : void+ print(String s) : void

+ ...

System.out : PrintStream

- destination =- ...

Variable System.out givesaccess to an output stream

of type PrintStream

The printing destination attributefor this PrintStream object is the

console window

The behaviors of a PrintStreamobject support a high-level view of

printing

Page 33: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

33

Selection

System . out . print ( "string " )

Literal character string that isthe parameter to print().

Member out of System is an outputstream object automatically

associated with the console windowrunning the application

Class System is definedin the standard

package java.lang

The period indicates that we want to select anindividual class member of System

The period indicates that we want toselect an individual class member of out

Method member of out. The execution of member print()causes its parameter to be displayed to the output stream

The method we are calling

Page 34: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

34

I/O streams System.out

Prints to standard output Equivalent to cout in C++, and print() in C

System.err Prints to standard error Equivalent to cerr in C++, and fprintf(stderr) in C

System.in Reads from standard input Equivalent to cin in C++, and scanf() in C

Page 35: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

35

Beware!!!

Page 36: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

36

Example program: temperature conversion// Purpose: Convert a Celsius temperature to Fahrenheit

public class CelsiusToFahrenheit {

// main(): application entry pointpublic 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);}

}

Page 37: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

37

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 0.3046

Page 38: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

38

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 } }

Page 39: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

39

// define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = 0.3046;

// define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = 0.3046;

// define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = 0.3046;

BMI.java: define constants

0.454KILOGRAMS_PER_POUND

0.3046METERS_PER_FOOT

Page 40: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

40

BMI.java: personal characteristics

75.5weightInPounds

// set up person's characteristics double weightInPounds = 75.5; // our person’s weight double heightInFeet = 4.5; // our person’s height

// set up person's characteristics double weightInPounds = 75.5; // our person’s weight double heightInFeet = 4.5; // our person’s height

// set up person's characteristics double weightInPounds = 75.5; // our person’s weight double heightInFeet = 4.5; // our person’s height

4.5heightInFeet

Page 41: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

41

BMI.java: convert to metric equivalents

34.2770metricWeight

// convert to metric equivalents

double metricWeight = weightInPounds * KILOGRAMS_PER_POUND;

double metricHeight = heightInFeet * METERS_PER_FOOT;

// convert to metric equivalents

double metricWeight = weightInPounds * KILOGRAMS_PER_POUND;

double metricHeight = heightInFeet * METERS_PER_FOOT;

// convert to metric equivalents

double metricWeight = weightInPounds * KILOGRAMS_PER_POUND;

double metricHeight = heightInFeet * METERS_PER_FOOT; 1.3706metricHeight

Page 42: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

42

BMI.java: perform BMI calculation

// perform bmi calculation double bmi = metricWeight / (metricHeight *

metricHeight);

18.2439bmi

Page 43: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

43

// 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));

BMI.java: display result

// 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

Math.round(bmi) is 18

18.2439bmi

Page 44: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

public static void main(String[] args) { // define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = 0.3046; // 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)); }

Page 45: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

45

Pentium math error 1 Intel’s Pentiums

(60Mhz – 100 Mhz) had a floating point error

Graph of z = y/x

Intel reluctantlyagreed to replace them in 1994

Graph from http://kuhttp.cc.ukans.edu/cwis/units/IPPBR/pentium_fdiv/pentgrph.html

Page 46: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

46

Pentium math error 2 Top 10 reasons to buy a Pentium:

10 Your old PC is too accurate 8.9999163362 Provides a good alibi when the IRS calls 7.9999414610 Attracted by Intel's new "You don't need to know

what's inside" campaign

6.9999831538 It redefines computing--and mathematics!5.9999835137 You've always wondered what it would be like to be

a plaintiff

4.9999999021 Current paperweight not big enough 3.9998245917 Takes concept of "floating point" to a new level 2.9991523619 You always round off to the nearest hundred anyway 1.9999103517 Got a great deal from the Jet Propulsion Laboratory 0.9999999998 It'll probably work!!

Page 47: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

47

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

Page 48: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

48

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

Page 49: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

49

Interactive programs Programs that interact with their users through statements

performing input and output

Temperature conversion Not interactive – Celsius temperature is fixed

BMI.java Not interactive – weight and height are fixed

Page 50: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

50

Un-reliable computers…

Page 51: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

51

Interactive programs Programs that interact with their users through statements

performing input and output

BMI.java Not interactive – weight and height are fixed

Page 52: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

52

Support for interactive console programs Variable System.in

Associated with the standard input stream – the keyboard

Class Scanner Makes obtaining input from the keyboard easy

Scanner stdin = Scanner.create(System.in);

+ nextDouble() : double+ ...

stdin : Scanner

- source =- ...

Variable stdin gives Scanneraccess to an input stream

Input source attribute for thisScanner is the keyboard

Behaviors of a Scanner supporthigh-level view of inputting text

Page 53: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

53

How to make Java work with the Scanner class In Java 1.5, do a:

import java.util.*;

In Java 1.4 (what we are using) Copy the Scanner.class file to the classes subdirectory for

the JCreator project

Page 54: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

54

Interactive program for BMI Program outline

// Purpose: Compute BMI for user-specified// weight and height

public class BMICalculator {

// main(): application entry pointpublic 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

}}

Program outline// Purpose: Compute BMI for user-specified// weight and height

public class BMICalculator {

// main(): application entry pointpublic 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

}}

Page 55: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

public static void main(String[] args) { // define constants //...

// displaying legend System.out.println ("BMI Calculator\n");

// set up input stream Scanner stdin = Scanner.create(System.in);

// get person's characteristics System.out.print("Enter weight (lbs): "); double weight = stdin.nextDouble();

System.out.print("Enter height (feet): "); double height = stdin.nextDouble();

// convert to metric equivalents double metricWeight = weight * KILOGRAMS_PER_POUND; double metricHeight = height * METERS_PER_FOOT;

// perform bmi calculation double bmi = metricWeight / (metricHeight * metricHeight);

// display result //...}

Page 56: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

class BMICalculator {

public static void main(String[] args) { // define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = 0.3046;

// displaying legend System.out.println ("BMI Calculator\n");

// set up input stream Scanner stdin = Scanner.create(System.in);

// get person's characteristics System.out.print("Enter weight (lbs): "); double weight = stdin.nextDouble();

System.out.print("Enter height (feet): "); double height = stdin.nextDouble(); // convert to metric equivalents double metricWeight = weight * KILOGRAMS_PER_POUND; double metricHeight = height * METERS_PER_FOOT; // perform bmi calculation double bmi = metricWeight / (metricHeight * metricHeight); // display result 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 " + Math.round(bmi)); }}

Page 57: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

57

Scanner APIpublic Scanner(InputStream in) // Scanner(): convenience constructor for an

// InputStream

public Scanner(File s) // Scanner(): convenience constructor for a filename

public create(InputStream in) // create(): convenience construction from an // InputStream

public static Scanner create(File s) // Scanner(): convenience construction from a filename

public int nextInt() // nextInt(): next input value as an int

public short nextShort() // nextShort(): next input value as a short

public long nextLong() // nextLong(): next input value as a long

public double nextDouble() // nextDouble(): next next input value as a double

public float nextFloat() // nextFloat(): next next input value as a float

public String next() // next(): get next whitespace-free string

public String nextLine() // nextLine(): return contents of input line buffer

public boolean hasNext() // hasNext(): is there a value to next

Page 58: 1 Java basics Chapter 2 CS 101-E. 2 DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window

58

Class fields

class BMICalculator {

// define constants final static double KILOGRAMS_PER_POUND = 0.454; final static double METERS_PER_FOOT = 0.3046;

public static void main(String[] args) {

// displaying legend System.out.println ("BMI Calculator\n");

//... }}

class BMICalculator {

// define constants final static double KILOGRAMS_PER_POUND = 0.454; final static double METERS_PER_FOOT = 0.3046;

public static void main(String[] args) {

// displaying legend System.out.println ("BMI Calculator\n");

//... }}

class BMICalculator {

public static void main(String[] args) {

// define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = 0.3046;

// displaying legend System.out.println ("BMI Calculator\n");

//... }}