1 / 44

Java Program Structure

Java Program Structure. Execution begins with first statement in main() Every Java program MUST have a static method called main( )! public static void main(String[] args ) { … }. Identifiers. Letters, digits, underscore, $ Must begin with letter, underscore, or $ Case sensitive

oro
Download Presentation

Java Program Structure

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. Java Program Structure • Execution begins with first statement in main() • Every Java program MUST have a static method called main( )! public static void main(String[] args) { … } Java Elements

  2. Identifiers • Letters, digits, underscore, $ • Must begin with letter, underscore, or $ • Case sensitive • No spaces Java Elements

  3. Identifiers • Legal: • Hello numPeople person2 • Illegal • Hello! One+two employee salary • Self documenting Java Elements

  4. Data and Data Types • all data must have a data type • data type determines: • internal representation and storage size. • Range of values • processing/operations Java Elements

  5. All Java identifiers must be declared before they are used Declarations - create and labels storage Memory location assigned Declare one variable per line type name; int a; inta,b; int a; // preferable int b; Variables Java Elements

  6. Primitive Types Java Elements

  7. int whole numbers and their negatives in the range allowed by your computer, no decimal point 5,-99,3456 examples: int x; int y; int total; int keys; integer data type Java Elements

  8. boolean • true or false • Example: boolean done; done = true; Java Elements

  9. char • one character • a letter, a digit, or a special symbol • sample values:  • 'A',  'B',  'a',  'b',  '1',  '2', '+', '-', '$', '#', '?', '*', etc • Unicode • Each character is enclosed in single quotes. • The character '0' is different than the integer 0. Java Elements

  10. char • Example char letter; letter = 'A', Java Elements

  11. Real numbers • Numbers with decimals • For very large numbers or very small fractions 3.67 * 1017  = 367000000000000000.0 = 3.67E17 5.89 * 10-6 = 0.00000589 = 5.89E-6 • Scientific notation/floating point notation • e stands for exponent and means "multiply by 10 to the power that follows“ • Examples: 5.274  .95  550. 9521e-3   -95e-1 95.213e2 Java Elements

  12. float • 4 bytes • -3.4E+38 – 3.4E+38 • 6- 7 significant digits • Single precision • Use if size is an issue • double • 8 bytes • -1.7E+308 – 1.7E+308 • 15 significant digits • Double precision • Use if precision is an issue, i.e currency Java Elements

  13. double • Example: double price; double velocity; price = 10.6; velocity = 47.63555; Java Elements

  14. Initialization • give a variable a value to start with • can initialize in declaration int a = 1; int alpha = 32; int stars = 15; intcount = 0; // the following example is legal in java, but // violates security guidelines int length, width = 5; // only width is initialized // and now we see why Java Elements

  15. Constants • cannot be changed • class constant – can be accessed anywhere in the class • Make programs easier to read • Makes value easier to change • Generally declare outside of method Java Elements

  16. Declaring constants • final type name = value; //local • public static final type name = value; //global public static final double PI = 3.14159; public static final char BLANK = ' '; public static final double INT_RATE = 0.12; • use all caps and underscore Java Elements

  17. Assignment • variable = expression; • different than equality • How it works: First the expression on the right-hand side is evaluated and then the resulting value is stored in the variable (in memory) on the left-hand side of the assignment operator. • variable is the name of a physical location in computer memory • an expression may be • a constant, or • a variable • a formula to be evaluated Java Elements

  18. Expressions • Simple value or set of operations that produces a value • literal • 24 or -3.67 • Evaluation – obtain value of expression • Operator • A symbol used to indicate an operation to be performed on one or more values Java Elements

  19. Literals • int • 0 2 0372 0xDadaCafe 1996 0x00FF00FF • double 28.43 -.98 208. 2.3e4 • char 'a' 'X' '?' '\\' '\'' • bool true false Java Elements

  20. Arithmetic operators Java Elements

  21. Integer division => Rounds towards 0 3 /4 => 0 19 / 5 => 3 5/3 => 1 • Division by zero is illegal and an ArithmeticException is thrown • Security issue • If the dividend is the negative integer of largest possible magnitude for its type, and the divisor is -1, then integer overflow occurs and the result is equal to the dividend. • No exception is thrown in this case Java Elements

  22. Modulus • Remainder 28 % 7 => 0 19 % 5 => 4 25 % 2 => 1 • Testing for even or odd • Number % 2 = 0 for evens • Finding individual digits of a number • Number % 10 is the final digit • Also works for floats Java Elements

  23. Combined Assignment Operators • number = number + 5;  number += 5; • number = number * 10;  number *= 10; • += • -= • *= • /= • %= Java Elements

  24. Increment and Decrement • Increment ++ x = x+ 1; ++x; x++; • Decrement ‑‑ --x; x--; Java Elements

  25. Increment and Decrement • Prefix: ++x => increment x before using it • Generally more efficient than postfix • Postfix: x++ => increment x after using value • Standalone, result is the same • ++x; • x++; • You see the behavior when used in expressions x = 5; y = 5; System.out.println(++x + “ “ + y++); //outputs 6 and 5 // final value of x and y is 6 Java Elements

  26. Precedence • Orders of operation • "who goes first" when expressions have multiple operators • rules are similar to rules used in algebra • () parentheses will override the precedence rules • When operators have same precedence, operations are performed left to right Java Elements

  27. Java Operator Precedence Java Elements

  28. Precedence • 3 + 5 + 6 / 2 => 11 • (3 + 5 + 6)/2 => 14 • Left to right • 40 – 25 - 9 => (40-25) – 9 => 15 – 9 => 6 EXAMPLE: 13 * 2 + 239 / 10 % 5 – 2 * 2 => 25 Java Elements

  29. Mixing Types and Casting • explicit conversion of a value from one data type to another. • (type) variable • Example: • (int) 2.5 /.15 //converts 2.5 to int • (int) (2.5 /.15) //converts result to int Java Elements

  30. Assignment notes • Cannot switch variable and expression • left side cannot be constant or formula • Only one variable can be on the left-hand side • Note: Make sure you initialize variables before using them in right-hand side of an assignment statement. An uninitialized variable will have some "garbage value" Java Elements

  31. int stamp; intanswer; Intwidget; char letter; stamp = 14; // valid 14 = stamp; // invalid answer = stamp; widget = stamp * 3; letter = 'a'; letter = "alpha"; // invalid Assignment examples Java Elements

  32. Intro to Strings • String not built into Java • String is a class • Part of java.lang class • Automatically imported • Declare: • String object; // note caps • String name = "Tom Jones"; • String s1 = "Hello”; • String s2 = "World!"; Java Elements

  33. Strings • Strings can be created implicitly by using a quoted string • String s1 = "Hello”; • String s2 = "World!"; • or, by using + on two String objects to create a new one • String combo = s1 + " " + s2; Java Elements

  34. String methods • <variable>.<method name>(<expression>,<expression>,…,<expression>) • any String method requiring an index will throw an IndexOutOfBoundsException if 0 > index > length()-1 • String s1 = "Hello”; • String s2 = "World!"; • System.out.println("Length of s1 = " + s1.length()); • Length of s1 = 5 • Index – integer used to indicate location • Zero-based Java Elements

  35. Java Elements

  36. Console Input • Scanner is a class • Need to import java.util import java.util.*; //allows use of Scanner class Scanner console = new Scanner (System.in); • Creates object console (can use any identifier name) • Associates console with standard input device • System.in – standard input device Java Elements

  37. Console input • console.nextInt() // retrieves next item as an integer • console.nextDouble() //retrieves next item as double • console.next() //retrieves next item as string • console.nextLine() // retrieves next item as string up to newline • ch = console.next().charAt(0); // reads a single character • Inappropriate type -> exception Java Elements

  38. import java.util.*; public class BMICalculator { public static void main(String [] args) { double height; double weight; double bmi; Scanner console = new Scanner(System.in); System.out.println("Enter height"); height = console.nextDouble(); System.out.println("Enter weight"); weight = console.nextDouble(); bmi = weight/(height * height) * 703; System.out.println("Current BMI:"); System.out.println(bmi); } } Java Elements

  39. Output • System.out – standard output device • System.out.print(expression); • System.out.println(expression);//goes to next line • System.out.println();//blank line Java Elements

  40. Packages, Classes, Methods, import • Few operations defined in Java • Many methods & identifiers are defined in packages • Class – set of related operations, allows users to create own type • Method – set of instructions designed to accomplish a specific task • Package – collection of related classes • java.util, contains class Scanner and methods nextInt, etc. import packageName.*; Import java.util.*; // compiler determines relevant classes import java.util.Scanner; Java Elements

  41. Creating a Java Application program • Program consists of one or more classes • Declare variables inside method • Declare named constants and input stream objects outside of main Java Elements

  42. Java application program import statements if any publicclassClassName { declare names constants and/or stream objects public static void main(String[] args) { variable declarations executable statements } } Java Elements

  43. Programming Style and Form • Use of blanks • Separate numbers when data is input • Use blank lines to separate data and code • All Java statements must end with a semicolon • Use uppercase for constants • Begin variables with lowercase • For run-together-words, capitalize each new word Java Elements

  44. Programming Style and Form, cont’d • Use clearly written prompt lines System.out.println(“Please enter a number between 1 and 10 and “ + “press Enter”); • Use comments to document • Use proper indentation and formatting Java Elements

More Related