Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Variables and Simple I/O zDeclare, scope, assign primitive datatypes. zUse simple I/O to Get and send data to/from the console.

Similar presentations


Presentation on theme: "1 Variables and Simple I/O zDeclare, scope, assign primitive datatypes. zUse simple I/O to Get and send data to/from the console."— Presentation transcript:

1 1 Variables and Simple I/O zDeclare, scope, assign primitive datatypes. zUse simple I/O to Get and send data to/from the console

2 2 GOALS... zThis lecture will teach us how to work with Javas primitive datatypes. We will declare, assign and understand the scope of these variables. We will also discuss escape sequences, constants and finally, we will learn simple console I/O processes.

3 3 Primitive Data Types: zJava provides containers in which you can maintain different types of information zThe data type you will use depends on the type of information you need to maintain

4 4 Primitive Data Types: zThe 8 primitive data types : DataTypeSizeRange boolean1true false char2Unicode Char Set(ASCII) int4+/- 2^31 -1 double8+/- 1.8 * 10^38 byte1-128 to 127 short2+/- 32,767 long8+/- 2 ^63 -1 float4+/- 3.4 * 10^38

5 5 Primitive Data Types: zPrimitive data types ARE NOT objects as they are not derived from Java classes zTherefore they do not have any associated methods (this concept is important as we will soon see that Java also provides Number classes for these data types) zEach datatype has a fixed size in memory (unlike C++) zFloat is precise to 7 significant digits zDouble is precise to 14 significant digits

6 6 Primitive Data Types: zEach datatype has a fixed size in memory (unlike C++) zFloat is precise to 7 significant digits zDouble is precise to 14 significant digits

7 7 zDeclaring Variables: zThere are several ways to declare variables zYou can declare variables as members of a class zPublic zPrivate zProtected

8 8 zDeclaring Variables: zThese variables are almost always declared Private and will only be modified by methods of the class zThese variables are typically initialized in the class constructor

9 9 zExamples: public class CalcIt { // variables available only to class "CalcIt" private int numGrades; private double grade1; private double grade2; private double grade3; private double grade4; private double grade5; z// set the initial values of the grades znumGrades = 5; zgrade1 = 90.0; zgrade2 = 97.0; zgrade3 = 98.0; zgrade4 = 80.0; zgrade5 = 92.0; zAssignment The variables are valued with the = zgrade2 = grade1 + 5; zthis example is evaluating the RVALUE of the equals sign which ztakes the value in variable grade1 adds 5 to it (in temporary zmemory) and ASSIGNS that result into the memory location znamed grade2 that holds space for a double number z zYou can declare variables as LOCAL to a specific method or specific to SPVM zThese variables scope is only within the method or function in which they are declared zThese variables end, are flushed from memory, when the method or function ends zLocal variables MUST be declared before they are used zLocal variables DO NOT get default values zLocal variables do not use Public, Private or Protected scope since they are always LOCAL in scope zExamples: zstatic public void main(String[] args) z{ znew dec1(); // calls the class constructor z z// LOCAL Primitave Double zdouble yourGrade = 0.0; z z// create instance of the CalcIt class z// LOCAL variable zCalcIt myCalc = new CalcIt(); zpublic double calcAvg() z{ zdouble avg = 0; // local variable to this z// method zLocal variables can only be declared ONCE in the same scope zint x; z zint x = 67; // SYNTAX ERROR !!! zNOTE:all variable declarations end in a semi-colon ; zThe declaration includes the primitave data type and the instance name zYou may list several variables of the same type on the same line: zint myInt, yourInt; zyou may initialize the variable at declaration zprivate double grade1 = 34; zprivate double grade2 = grade1 + 34; zdefault values are 0 for numbers and null for objects

10 10 zExamples: // set the initial values of the grades numGrades = 5; grade1 = 90.0; grade2 = 97.0; grade3 = 98.0; grade4 = 80.0; grade5 = 92.0; grade2 = grade1 + 5;

11 11 zExamples: zAssignment The variables are valued with the = grade2 = grade1 + 5; zthis example is evaluating the RVALUE of the equals sign which...

12 12 zExamples: z...takes the value in variable grade1 adds 5 to it (in temporary memory) and ASSIGNS that result into the memory location named grade2 that holds space for a double number

13 13 zYou can declare variables as LOCAL to a specific method or specific to SPVM zThese variables scope is only within the method or function in which they are declared zThese variables end, are flushed from memory, when the method or function ends

14 14 zLocal variables MUST be declared before they are used zLocal variables DO NOT get default values zLocal variables do not use Public, Private or Protected scope since they are always LOCAL in scope

15 15 zExamples: static public void main(String[] args) { new dec1(); double yourGrade = 0.0; CalcIt myCalc = new CalcIt();

16 16 zExamples: public double calcAvg() { double avg = 0; }

17 17 zLocal variables can only be declared ONCE in the same scope int x; int x = 67; // SYNTAX ERROR !!! zNOTE:all variable declarations end in a semi-colon ;

18 18 zThe declaration includes the primitave data type and the instance name zYou may list several variables of the same type on the same line: int myInt, yourInt;

19 19 zYou may initialize the variable at declaration private double grade1 = 34; private double grade2 = grade1 + 34; zDefault values are 0 for numbers and null for objects

20 20 zCHAR: zHolds 1 printable ACSII value zMostly contains a letter but can also contain an ACSII representation of a number (not for math) zReview ACSII table

21 21 zFor example: A B c F Yif added together has a value of 332 (sum of ACSII values) zY has an ACSII value of 89 zSo, adding chars that contain numbers will add their ACSII value and NOT their char representation zChars have an ASCII value and can be added

22 22 zConstants / Final: zSymbolic Constants: xA variable that once defined MAY not be modified by code Private final int numClasses = 5; z

23 23 zLocal variable constant: final double taxRate =.23; xYou can, however, set the initial value of a final variable in the classes Constructor (see code example for numgrades) z

24 24 zLiteral Constants: Charsyh Int2134 Double12.4.05 z

25 25 zEscape Sequences: zNon printable characters \n newline \r carriage return \t tab \f form feed \ single quote \ double quote \\ backslash

26 26 Example: System.out.print( \n Don \ t let me down \n Don \ t let me down \n ) zWill print out:Dont let me down Dont let me down

27 27 zScope of Variables: zThe scope of a variable is related to where in code that variable is defined zThe scope of a class level field (public, private or protected) extends throughout the class and Can be accessed by all of its methods

28 28 zThe scope of a local variable extends to the end of the code block in which it is declared zMethods that are in control go onto system stack and that sack is destroyed, along with any local variables that were declared

29 29 zYou can declare variables with the same name as class level attributes as long as they are in different scope levels zIn this case the variable in effect is the one most local (declared most closely) to the executing code block

30 30 zExample: (Remember private double grade1; is already declared) while (x > 0) { double grade1=0; grade1 = 10.0 * (double)x; x--; System.out.println(grade1); } avg = (grade1 + grade2 + grade3 + grade4 + grade5) / numGrades;

31 31 zLets Open the project Code & move the local variable around to demonstrate zExample: SEE CODE HANDOUT Run NET BEANS IDE and Open Declare Variables Project

32 32 zSimple I/O to and from Console: zWe need to be able to write programs that accept variable data from an external source(es) zWe should be able to accept simple data from a user, at application execution, and be able to display information (to a console or through a messagebox)

33 33 zSimple I/O to and from Console: zWe should be able to read in data and write out data to files (this topic will be discussed in a later lecture) zNOTE: Use the program Variables and Simple IO.java for illustrations on these options (copy of this code is Part of the lecture !!!)

34 34 zInput and Output with System: Java.lang.System zOutput is accomplished with System.out.print( ) or System.out.println( ) zYou can print out any primitave datatype or string representation of any object (.toString) System.out.println(Hello World)

35 35 zJava.util.Scanner zInput is accomplished by the Scanner Class zAn object of InputStream (only reads raw bytes) zWe need to wrap system.in with a class that provides easy and intuitive methods to access information entered by the user

36 36 zThe Scanner Class: zThis class represents an input (TEXT or CONSOLE) source and decomposes the input stream into numbers, strings or Booleans as TOKENS. zThe DEFAULT field delimiter is WHITESPACE Look at the methods of the Scanner class in Java.Util.Scanner

37 37 zMUST IMPORT THE FOLLOWING CLASSES: import java.util.Scanner;

38 38 Example:SEE CODE HANDOUT Run NET BEANS IDE and Open Variables and Simple IO Project

39 39 NOTE ABOUT SCANNER: zWhen using the numeric and string methods together to retrieve data, you have to be careful of the hidden line control character.

40 40 zThe numeric methods, like nextDouble ignore but DO NOT consume this character. Therefore ensuing nextLine method calls gobble up this character but not the string as intended.

41 41 zExample: Age = myScanner.nextInt(); Weight = myScanner.nextDouble(); Name = myScanner.nextLine(); Name will be empty FIX: After the line Weight = myScanner.nextDouble(); Add myScanner.nextLine(); // THIS consumes the newline character

42 42 zInput and Output using JOptionPane: Javax.swing.JOptionPane zUse the showInputDialog and showMessageDialog methods of the JoptionPane class To read in, processs and display data

43 43 zMUST IMPORT THE FOLLOWING CLASSES: import javax.swing.JOptionPane; zExample: SEE CODE HANDOUT Run NET BEANS IDE and Open Variables and Simple IO Project

44 44 zInput and Output with EasyReader: zUse a prepared class that does the inputstreamreader and bufferedreader wrapping for us zWe simply import and then use this class

45 45 zInput and Output with EasyReader: zMUST IMPORT THE FOLLOWING CLASSES: import EasyReader; zExample: SEE CODE HANDOUT..\Class Projects Code Solutions\Variables and Simple IO Example Code\SimpleIO\SimpleIO.mcp

46 46 zCASTING: zDiscuss casting in Java via the Casting Handout (Lambert Comp Appendix B)

47 47 zProject: zHandout contains: Several short programs to write *Library Fine *Stick Figure Characters * MUST code using BOTH I/O methods (JOptionPane & Scanner) Code Evaluation for syntax, logic & system errors Evaluate the output of code

48 48 TEST IS THE DAY AFTER THE PROJECT IS DUE !!!


Download ppt "1 Variables and Simple I/O zDeclare, scope, assign primitive datatypes. zUse simple I/O to Get and send data to/from the console."

Similar presentations


Ads by Google