1.04k likes | 2.6k Views
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
E N D
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
Identifiers • Letters, digits, underscore, $ • Must begin with letter, underscore, or $ • Case sensitive • No spaces Java Elements
Identifiers • Legal: • Hello numPeople person2 • Illegal • Hello! One+two employee salary • Self documenting Java Elements
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
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
Primitive Types Java Elements
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
boolean • true or false • Example: boolean done; done = true; Java Elements
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
char • Example char letter; letter = 'A', Java Elements
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
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
double • Example: double price; double velocity; price = 10.6; velocity = 47.63555; Java Elements
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
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
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
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
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
Literals • int • 0 2 0372 0xDadaCafe 1996 0x00FF00FF • double 28.43 -.98 208. 2.3e4 • char 'a' 'X' '?' '\\' '\'' • bool true false Java Elements
Arithmetic operators Java Elements
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
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
Combined Assignment Operators • number = number + 5; number += 5; • number = number * 10; number *= 10; • += • -= • *= • /= • %= Java Elements
Increment and Decrement • Increment ++ x = x+ 1; ++x; x++; • Decrement ‑‑ --x; x--; Java Elements
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
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
Java Operator Precedence Java Elements
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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