Upload
oro
View
61
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
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 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
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;
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
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;
Java Elements 6
boolean
• true or false• Example:boolean done;done = true;
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.
Java Elements 8
char
• Examplechar letter;letter = 'A',
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
• 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
Java Elements 11
double
• Example:double price;double velocity;price = 10.6;velocity = 47.63555;
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
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
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
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
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
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
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
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
Java Elements 20
Combined Assignment Operators
• number = number + 5; number += 5;• number = number * 10; number *= 10;• +=• -=• *=• /=• %=
Java Elements 21
Increment and Decrement• Increment ++ x = x+ 1;
++x;x++;
• Decrement ‑‑--x; x--;
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
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
Java Elements 24
Java Operator Precedence
Description Operators
Unary operators +, -
Multiplicative operators *, /, %
Additive operators +, -
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
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
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
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
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;
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
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
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
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); }}
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
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;
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
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}
}
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
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