1 / 56

Lecture 3 Variables Primitive Data Types calculations & arithmetic operators Readings: Chapter 2

Lecture 3 Variables Primitive Data Types calculations & arithmetic operators Readings: Chapter 2. Review. What’s wrong with this line of code? system.out.println ( " He said "H ello "" ); What’s wrong with this program? public class Welcome1 {

Download Presentation

Lecture 3 Variables Primitive Data Types calculations & arithmetic operators Readings: Chapter 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 3VariablesPrimitive Data Types calculations&arithmetic operatorsReadings: Chapter 2

  2. Review • What’s wrong with this line of code? system.out.println ("He said "Hello""); • What’s wrong with this program? public class Welcome1 { // main method begins execution of Java application public static void main( String args[] ) System.out.println( "Welcome to Java" ) } // end method main } // end class Welcome1

  3. VariablesPrimitive Data Types and mathematical Operations • Introduce Programming with an Example • Identifiers, Variables, and Constants • Primitive Data Types • byte, short, int, long, float, double, char, Boolean • Expressions • Mathematical Operators • Syntax Errors, Runtime Errors, and Logic Errors

  4. Lets review • Key words • Identifiers • Style • Errors

  5. Reserved words: • Certain words have special meaning in Java and cannot be used as identifiers. These words are called reserved words. • So far we have seen the following reserved words: • int • public • import • static • void • class • We will see a complete list of reserved words soon. • Use of the words null, true and false is also prohibited.

  6. Lets review Identifiers • An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($). • An identifier must start with: • a letter • an underscore (_) • or a dollar sign ($). • It cannot start with a digit. • An identifier cannot be a reserved word. • (See Appendix A, “Java Keywords,” for a list of reserved words). • An identifier cannot betrue, false, or null. • An identifier can be of any length.

  7. Programming Style and Documentation • Appropriate Comments • Naming Conventions • Proper Indentation and Spacing Lines • Block Styles

  8. Appropriate Comments Include a comment at the beginning of the program: • to explain what the program does • its key features • its supporting data structures • and any unique techniques it uses. • Include your name • class section • instruction • date • and a brief description at the beginning of the program.

  9. Proper Indentation and Spacing • Indentation • Indent 3 spaces. • Spacing • Use blank line to separate segments of the code.

  10. Block Styles Use end-of-line style for braces.

  11. Programming Errors • Syntax Errors • Detected by the compiler • Runtime Errors • Causes the program to abort (when you divide a number by 0) • Logic Errors • Produces incorrect result

  12. Syntax Errors • Caused when the compiler cannot recognize a statement. • These are violations of the language • The compiler normally issues an error message to help the programmer locate and fix it • Also called compile errors or compile-time errors. • For example, if you forget a semi-colon, you will get a syntax error. public class SyntaxErrors { public static void main(String[] args) { i = 30; System.out.println(i + 4) } }

  13. Run-time Errors • Other major kind of error you’ll see • Happens when a program is running • The compiler cannot identify these errors at compile time. • Will talk more about these later public class RuntimeErrors { Public static void main(String[] args) { int i = 1 / 0; } }

  14. Logic Errors • Logic Errors • Produces incorrect result public class LogicalErrors { Public static void main(String[] args) { double average = 80.0 + 90.0 / 2; } } This program produces in correct answer of 90.0/2 + 80.0 = 45 + 80.0 = 125.0 Answer should be (80.0 + 90.0)/2 170.0/2 = 85.0

  15. Naming Conventionschoosing identifiers for variables and classes names • Choose meaningful and descriptive names. • For Variables, class names and methods: • Use lowercase. • If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. • For example, the variables radius and area, and the method computeArea.

  16. Naming Conventions, cont. • Class names: • Capitalize the first letter of each word in the name. • For example, the class name ComputeArea. • Constants: • Capitalize all letters in constants. • For example, the constant PI.

  17. Variables

  18. Memory Concepts • Variable names correspond to locations in the computer’s primary memory. • Every variable has: • a name • a type • and a value. • When a value is placed in a memory location the value replaces the previous value in that location (called destructive read-in) • A variable’s value can just be used and not destroyed (called non-destructive read-out)

  19. Bucket Analogy • It is useful to think of a variable as a bucket of data. • The bucket has a unique name, and can only hold certain kinds of data. balance is a variable containing the value 200, and can contain only integers. 200 balance Note: variables are not persistent. When you exit your program, the data is deleted. To create persistent data, you must store it to a file system.

  20. sum 0 Number1 sum number2 3 ? 2 Memory Concepts • Visual Representation sum = 0; number1 = 3; number2 = 2; Sum = number1 + number2; What is the value of Sum after execution of the above statement?

  21. Variable Declaration • Before you use a variable, you must declare it. (Not all languages require this, but Java certainly does.) • Examples: /* Creates an integer variable */ int number; /* Creates a double variable */ double price; /* Creates a string variable */ Sting name; /* Creates a character variable */ char letter; Semi-colon Data type identifier

  22. Declaring Variables int x; // Declare x to be an // integer variable; double radius; // Declare radius to // be a double variable; char a; // Declare a to be a // character variable; String name; // String variable “Bano”

  23. Important Point about Declarations • In Java you can declare variables at many different places in the program. They have different meaning and scope depending on where they are declared. For now, all our variables shall be declared at the beginning of a block of code within main(). public class Sample { public static void main(String args[]) { declare variables here { or inside a nested block } } // end method main } // end class Sample

  24. Good Programming Practices • Choose meaningful variable names to make your program more readable. For example, use income, instead of num. • Stick to lower-case variable names. For example, use income, instead of INCOME. Variables that are all capitals usually indicate a constant (more on this soon.) • Use proper case for all words after the first in a variable name. For example, instead of totalcommissions, use totalCommissions. • Avoid redefining identifiers previously defined in the Java API.

  25. DATA TYPE • integers: • the simplest data type in Java. • Used to hold positive and negative whole numbers, e.g. 5, 25, -777, 1. • floats: • Used to hold fractional or decimal values, e.g. 3.14, 10.25. • chars: Used to hold individual characters, e.g. ‘c’, ‘e’, ‘1’, ‘\n’ • We will explore each one in detail later this semester. • String: holds one or more character, e.g. “Dream Girls”, “NYU ROCKS!”, “C”

  26. Declaring and Initializingin One Step • int x = 1; • double d = 1.4; • float f = 1.4; Is this statement correct?

  27. Numerical Data Types Whole numbers: • byte8 bits • short16 bits • int32 bits • long64 bits Floating point or Decimal numbers: • float32 bits • double64 bits

  28. Assignment Statements x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a;

  29. Arithmetic

  30. Arithmetic • Arithmetic calculations used in most programs • Usage • *for multiplication • / for division • +, - • No operator for exponentiation • Integer division truncates remainder 7 / 5 evaluates to 1 5 / 2 yields an integer 2. 5.0 / 2 yields a double value 2.5 5 % 2 yields 1 (the remainder of the division) • Remainder operator % returns the remainder 7 % 5 evaluates to 2

  31. Arithmetic • Operator precedence • Some arithmetic operators act before others (i.e., multiplication before addition) • Use parenthesis when needed • Example: Find the average of three variablesa,b and c • Do not use: a + b + c / 3 • Use: ( a + b + c ) / 3 • Follows PEMDAS • Parentheses, Exponents, Multiplication, Division, Addition, Subtraction

  32. Important Point about Declarations • You must make a declaration immediately following the left brace following the main method. • at the beginning of a function and before any executable statements or else you get a syntax error. {declaration section … statement section …}

  33. Example 1: Basic Arithmetic • /* Illustrates Integer Variables */ • public class addition • { • public static void main(String[] args) • { • int x, y, z; • // Specify values of x and y • x = 2; • y = 3; • // add x and y and place the result in z variable • z = x + y; • System.out.println("x has a value of " + x); • System.out.println("y has a value of " + y); • System.out.println("The sum of x + y is " + z); • System.exit(0); • } • } Variable Declaration Variable Names Data Type Assignment Statements

  34. Printing Variables • To print a variable, use the System.out.print or System.out.println statement as you would for a string. • System.out.print (x); • System.out.println (x); • System.out.println ("x: " + x); Here the “addition” that is performed is string concatenation.

  35. Assignment Statements • Assignments statements enable one to initialize variables or perform basic arithmetic. x = 2; y = 3; z = x + y; • Here, we simply initialize x and y and store their sum within the variable z.

  36. Assignment Operator • = • Read the assignment operator as “GETS” not “EQUALS!” • This is an assignment of what’s on the right side of = to a variable on the left • egsum = integer1 + integer2; • Read this as, “sum gets integer1 + integer2” • integer1 and integer2 are added together and stored in sum

  37. Displaying Text in a Dialog Box • Display • Most Java applications use windows or a dialog box • We have used command window • Class JOptionPane allows us to use dialog boxes • Packages • Set of predefined classes for us to use • Groups of related classes called packages • Group of all packages known as Java class library or Java applications programming interface (Java API) • JOptionPane is in the javax.swing package • Package has classes for using Graphical User Interfaces (GUIs)

  38. Displaying Text in a Dialog Box • Upcoming program • Application that uses dialog boxes • Explanation will come afterwards • Demonstrate another way to display output • Packages, methods and GUI

  39. 1 // Fig. 2.6: Welcome4.java 2 // Printing multiple lines in a dialog box 3 import javax.swing.JOptionPane; // import class JOptionPane 4 5 public class Welcome4 { 6 public static void main( String args] ) 7 { 8 JOptionPane.showMessageDialog( 9 null, "Welcome\nto\nJava\nProgramming!" ); 10 11 System.exit( 0 ); // terminate the program 12 } 1 // Welcome4.java 2 // Printing multiple lines in a dialog box. 3 4 // Java packages 5 import javax.swing.JOptionPane; // program uses JOptionPane 6 7 public class Welcome4 { 8 9 // main method begins execution of Java application 10 public static void main( String args[] ) 11 { 12 JOptionPane.showMessageDialog( 13 null, "Welcome\nto\nJava\nProgramming!" ); 14 15 System.exit( 0 ); // terminate application with window 16 17 } // end method main 18 19 } // end class Welcome4 Welcome4.java1. import declaration2. Class Welcome42.1main2.2showMessageDialog2.3 System.exitProgram Output

  40. 4 // Java packages 5 import javax.swing.JOptionPane; // program uses OptionPane Displaying Text in a Dialog Box • Lines 1-2: comments as before • Two groups of packages in Java API • Core packages • Begin with java • Included with Java 2 Software Development Kit • Extension packages • Begin with javax • New Java packages • import declarations • Used by compiler to identify and locate classes used in Java programs • Tells compiler to load class JOptionPane from javax.swing package

  41. 12 JOptionPane.showMessageDialog( 13 null, "Welcome\nto\nJava\nProgramming!" ); 2.4 Displaying Text in a Dialog Box • Lines 6-11: Blank line, begin class Welcome4 and main • Call method showMessageDialog of class JOptionPane • Requires two arguments • Multiple arguments separated by commas (,) • For now, first argument always null • Second argument is string to display • showMessageDialog is a static method of class JOptionPane • static methods called using class name, dot (.) then method name

  42. 2.4 Displaying Text in a Dialog Box • All statements end with ; • A single statement can span multiple lines • Cannot split statement in middle of identifier or string • Executing lines 12 and 13 displays the dialog box • Automatically includes an OK button • Hides or dismisses dialog box • Title bar has string Message

  43. 15 System.exit( 0 ); // terminate application with window Displaying Text in a Dialog Box • Calls static method exit of class System • Terminates application • Use with any application displaying a GUI • Because method is static, needs class name and dot (.) • Identifiers starting with capital letters usually class names • Argument of 0 means application ended successfully • Non-zero usually means an error occurred • Class System part of package java.lang • No import declaration needed • java.lang automatically imported in every Java program • Lines 17-19: Braces to end Welcome4 and main

  44. Another Java Application: Adding Integers • Upcoming program • Use input dialogs to input two values from user • Use message dialog to display sum of the two values

  45. Declare variables: name and type. Input first integer as a String, assign to firstNumber. Convert strings to integers. Add, place result in sum. 1 // Addition.java 2 // Addition program that displays the sum of two numbers. 3 4 // Java packages 5 import javax.swing.JOptionPane; // program uses JOptionPane 6 7 public class Addition { 8 9 // main method begins execution of Java application 10 public static void main( String args[] ) 11 { 12 String firstNumber; // first string entered by user 13 String secondNumber; // second string entered by user 14 15 int number1; // first number to add 16 int number2; // second number to add 17 int sum; // sum of number1 and number2 18 19 // read in first number from user as a String 20 firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); 21 22 // read in second number from user as a String 23 secondNumber = 24 JOptionPane.showInputDialog( "Enter second integer" ); 25 26 // convert numbers from type String to type int 27 number1 = Integer.parseInt( firstNumber ); 28 number2 = Integer.parseInt( secondNumber ); 29 30 // add numbers 31 sum = number1 + number2; 32 Addition.java1. import2. class Addition2.1 Declare variables (name and type)3. showInputDialog4. parseInt5. Add numbers, put result in sum

  46. 33 // display result 34 JOptionPane.showMessageDialog( null, "The sum is " + sum, 35 "Results", JOptionPane.PLAIN_MESSAGE ); 36 37 System.exit( 0 ); // terminate application with window 38 39 } // end method main 40 41 } // end class Addition Program output

  47. 5 import javax.swing.JOptionPane; // program uses JOptionPane 7 public class Addition { 12 String firstNumber; // first string entered by user 13 String secondNumber; // second string entered by user 2.5 Another Java Application: Adding Integers • Location of JOptionPane for use in the program • Begins public class Addition • Recall that file name must be Addition.java • Lines 10-11: main • Declaration • firstNumber and secondNumber are variables

  48. String firstNumber, secondNumber; 12 String firstNumber; // first string entered by user 13 String secondNumber; // second string entered by user 2.5 Another Java Application: Adding Integers • Variables • Location in memory that stores a value • Declare with name and type before use • firstNumber and secondNumber are of type String (package java.lang) • Hold strings • Variable name: any valid identifier • Declarations end with semicolons ; • Can declare multiple variables of the same type at a time • Use comma separated list • Can add comments to describe purpose of variables

  49. 15 int number1; // first number to add 16 int number2; // second number to add 17 int sum; // sum of number1 and number2 2.5 Another Java Application: Adding Integers • Declares variables number1, number2, and sum of type int • int holds integer values (whole numbers): i.e., 0, -4, 97 • Types float and double can hold decimal numbers • Type char can hold a single character: i.e., x, $, \n, 7 • Primitive types - more in Chapter 4

  50. 20 firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); 2.5 Another Java Application: Adding Integers • Reads String from the user, representing the first number to be added • Method JOptionPane.showInputDialog displays the following: • Message called a prompt - directs user to perform an action • Argument appears as prompt text • If wrong type of data entered (non-integer) or click Cancel, error occurs

More Related