39
Java Elements 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 Program Structure

  • Upload
    oro

  • View
    59

  • Download
    2

Embed Size (px)

DESCRIPTION

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 - PowerPoint PPT Presentation

Citation preview

Page 1: Java Program Structure

Java Elements 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) { …}

Page 2: Java Program Structure

Java Elements 2

Data and Data Types• all data must have a data type • data type determines:

– internal representation and storage size. – Range of values – processing/operations

Page 3: Java Program Structure

Java Elements 3

Variables

• 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;– int a,b;– int a; // preferable– int b;

Page 4: Java Program Structure

Java Elements 4

Primitive Types

Type Description Exampleint Integers

(whole numbers)

45, -6, 0, 29987

double Real numbers 7.86, -19.234

char Single characters

'a', 'X', '?'

boolean Logical values True, false

Page 5: Java Program Structure

Java Elements 5

integer data type• 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;

Page 6: Java Program Structure

Java Elements 6

boolean

• true or false• Example:boolean done;done = true;

Page 7: Java Program Structure

Java Elements 7

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.

Page 8: Java Program Structure

Java Elements 8

char

• Examplechar letter;letter = 'A',

Page 9: Java Program Structure

Java Elements 9

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

Page 10: Java Program Structure

• 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 10

Page 11: Java Program Structure

Java Elements 11

double

• Example:double price;double velocity;price = 10.6;velocity = 47.63555;

Page 12: Java Program Structure

Java Elements 12

Initialization

• give a variable a value to start with• can initialize in declaration

int a = 1;int alpha = 32;int stars = 15;int count = 0;// the following example is legal in java, but// violates security guidelinesint length, width = 5; // only width is initialized// and now we see why

Page 13: Java Program Structure

Java Elements 13

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

Page 14: Java Program Structure

Java Elements 14

Declaring constants

• final type name = value; //local

• public static final type name = value; //globalpublic static final double PI = 3.14159;public static final char BLANK = ' ';public static final double INT_RATE = 0.12;

• use all caps and underscore

Page 15: Java Program Structure

Java Elements 15

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

Page 16: Java Program Structure

Java Elements 16

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

Page 17: Java Program Structure

Java Elements 17

Arithmetic operators

Operator Meaning Example Result

+ addition 2 + 2 4

- Subtraction 53 - 18 35

* Multiplication 3 * 8 24

/ Division 4.8 / 2.0 2.4

% Remainder 25 % 6 1

Page 18: Java Program Structure

Java Elements 18

Integer division

=> Rounds towards 03 /4 => 019 / 5 => 35/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

Page 19: Java Program Structure

Java Elements 19

ModulusÞ Remainder28 % 7 => 019 % 5 => 425 % 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

Page 20: Java Program Structure

Java Elements 20

Combined Assignment Operators

• number = number + 5; number += 5;• number = number * 10; number *= 10;• +=• -=• *=• /=• %=

Page 21: Java Program Structure

Java Elements 21

Increment and Decrement• Increment ++ x = x+ 1;

++x;x++;

• Decrement ‑‑--x; x--;

Page 22: Java Program Structure

Java Elements 22

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 expressionsx = 5;y = 5;System.out.println(++x + “ “ + y++); //outputs 6 and 5// final value of x and y is 6

Page 23: Java Program Structure

Java Elements 23

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

Page 24: Java Program Structure

Java Elements 24

Java Operator Precedence

Description Operators

Unary operators +, -

Multiplicative operators *, /, %

Additive operators +, -

Page 25: Java Program Structure

Java Elements 25

Precedence

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

Page 26: Java Program Structure

Java Elements 26

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

Page 27: Java Program Structure

Java Elements 27

Assignment examplesint stamp;int answer;Int widget;char letter;

stamp = 14; // valid14 = stamp; // invalidanswer = stamp;widget = stamp * 3;letter = 'a';letter = "alpha"; // invalid

Page 28: Java Program Structure

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 28

Page 29: Java Program Structure

Java Elements 29

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;

Page 30: Java Program Structure

Java Elements 30

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!";– length(); - returns length of string– System.out.println("Length of s1 = " + s1.length()); Length of s1 = 5• Index – integer used to indicate location

• Zero-based-

– charAt(0) => returns 1st character

Page 31: Java Program Structure

Java Elements 31

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

Page 32: Java Program Structure

Java Elements 32

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

Page 33: Java Program Structure

Java Elements 33

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

Page 34: Java Program Structure

Java Elements 34

Output

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

Page 35: Java Program Structure

Java Elements 35

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 classesimport java.util.Scanner;

Page 36: Java Program Structure

Java Elements 36

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

Page 37: Java Program Structure

Java Elements 37

Java application programimport statements if anypublic class ClassName{ declare names constants and/or stream objects

public static void main(String[] args) {

variable declarations

executable statements}

}

Page 38: Java Program Structure

Java Elements 38

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

Page 39: Java Program Structure

Java Elements 39

Programming Style and Form, cont’d

• Use clearly written prompt linesSystem.out.println(“Please enter a number between 1 and 10 and “ + “press Enter”);

• Use comments to document• Use proper indentation and formatting