Download presentation
Presentation is loading. Please wait.
Published byNathan Henry Lane Modified over 6 years ago
1
COP 2800 Lake Sumter State College Mark Wilson, Instructor
Programming with Java COP 2800 Lake Sumter State College Mark Wilson, Instructor
2
Programming with Java Classes and Objects
3
What is a Class? A class is a blueprint or prototype from which objects are created. The term ‘class’ derives from ‘classification’.
4
What is an Object? An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life. An object is an instance of a class. State = Attributes = Instance Variables Behaviors = Methods
5
UML Representation What the class knows What the class does
6
Variables and Constants
Programming with Java Variables and Constants
7
Variable Types byte – 8 bit integer short – 16 bit integer
int – 32 bit integer long – 64 bit integer float – 32 bit floating point double – 64 bit floating point boolean – size varies, true or false char – 16 bit character
8
Variable Names Case sensitive Start with:
Letter (A-Z, a-z), Underscore (_), Dollar sign ($) Subsequent characters may include digits (0-9) Not a keyword Styles Lower case – averagescore Camel case – averageScore Underscore – average_score All caps – PI, reserve for constants Initial caps – AverageScore, reserve for methods
9
Variable Scope public - the field is accessible from all classes.
private - the field is accessible only within its own class. Variables declared within a block are only available within that block
10
Constants Only meaningful at the class level
Must be either primitive values or immutable objects Declared as: public static final type VARIABLE_NAME = value; private static final type VARIABLE_NAME = value;
11
Programming with Java Expressions
12
Operators Postfix: expr++ expr-- Unary: ++expr --expr +expr -expr ~ !
Multiplicative: * / % Additive: + - Shift: << >> >>> Relational: < > <= >= instanceof Equality: == != Bitwise AND: & Bitwise exclusive OR: ^ Bitwise inclusive OR: | Logical AND: && Logical OR: || Ternary: ? : Assignment: = += -= *= /= %= &= ^= |= <<= >>= >>>=
13
Expression A construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. int cadence = 0; anArray[0] = 100; System.out.println("Element 1 at index 0: " + anArray[0]); int result = 1 + 2; // result is now 3 if (value1 == value2) System.out.println("value1 == value2"); Force precedent with parentheses: x + y / 100 // ambiguous (x + y) / 100 // unambiguous, recommended
14
Statement Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. Ends with a semicolon (;) aValue = ; // assignment statement aValue++; // increment statement System.out.println("Hello World!"); // method invocation statement Bicycle myBike = new Bicycle(); // object creation statement double aValue = ; // declaration statement
15
Block A block is a group of zero or more statements between balanced (curly) braces ({}) and can be used anywhere a single statement is allowed. Can be used to define scope. Structured construct: Sequence class BlockDemo { public static void main(String[] args) { boolean condition = true; if (condition) { // begin block 1 System.out.println("Condition is true."); } // end block one else { // begin block 2 System.out.println("Condition is false."); } // end block 2 }
16
Programming with Java Branching
17
Structured Constructs
Sequence Branching If If – Else Else – If Switch Looping Leading Decision Trailing Decision Counting (For) Enhanced For
18
If Construct Selection control structure with one alternative
Sequence executes if the expression evaluates to true
19
If in Java General if (expression) { one or more statements; }
if (expression) statement;
20
If in Java General if (expression) { one or more statements; }
if (expression) statement; Examples if (a == b) { counter++; } if (counter > 5) limit = TRUE; // problematic
21
Using If Write Java code that:
Accepts a temperature in degrees Fahrenheit Converts that temperature to degrees Celsius Displays the result Identifies the temperature as hot when it is above 50 Identifies the temperature as cold when it is below 10
22
Using If class TempConvert { public static void main(String[] args) {
int temperatureF; int temperatureC; if (args.length > 0) { try { temperatureF = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Argument" + " must be an integer"); System.exit(1); } } /* Convert to Celsius */ temperatureC = int(double(temperatureF – 32) * (5.0 / 9.0)); System.out.format (“%d degrees Fahrenheit is %d degrees Celsius.%n”, temperatureF, temperatureC); if (temperatureC > 50) { System.out.println(“Wow that’s hot!”); } if (temperatureC < 10) { System.out.println(“Now that’s really chillin’!”); } } }
23
If – Else Construct Selection control structure with two alternatives
One sequence executes when the expression evaluates true Otherwise the other sequence executes
24
If – Else in Java General if (expression) { one or more statements; }
25
If – Else in Java General if (expression) { one or more statements; }
Examples if (expression) { one or more statements; } else { if (expression) statement; if (a == b) { counter++; } else { counter--; if (counter > 5) limit = TRUE; else limit = FALSE; if (counter > 5) limit = TRUE; else limit = FALSE;
26
Using If - Else Write a program to report whether a number entered by user is even or odd
27
Using If - Else class OddOrEven{
public static void main(String[] args) { int numberToCheck; if (args.length > 0) { try { numberToCheck = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Argument" + " must be an integer"); System.exit(1); } /* checking whether remainder is 0 or not */ if ((numberToCheck % 2) == 0) { System.out.format("%d is even.%n",numberToCheck); } else { System.out.format("%d is odd.%n",numberToCheck);
28
Nested Branches Any structured construct may contain one or more other structured constructs
29
Nesting Branches if (x > 0) positives++; if (x < 0) negatives++; if (x == 0) zeros++; if (x > 0) positives++; else if (x < 0) negatives++; else /* x equals 0 */ zeros++; if (x > 0) positives++; else if (x < 0) negatives++; else /* x equals 0 */ zeros++;
30
Else – If Construct Selection control structure with any number of alternatives Simplified nesting of Ifs
31
Else – If in Java General if (expression) { one or more statements; }
else if (expression) { else { if (expression) statement; else if (expression) else
32
Else – If in Java General Example if (expression) { if (a < b) {
one or more statements; } else if (expression) { } else { } if (expression) statement; else if (expression) else if (a < b) { lower++; } else if (a > b) { higher++; } else { same++; }
33
Using Else – If Write a program that compares two input numbers and reports the result
34
Using Else – If class OddOrEven{
public static void main(String[] args) { int firstNumber; int secondNumber; if (args.length > 1) { try { firstNumber = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Argument" + " must be an integer"); System.exit(1); } secondNumber = Integer.parseInt(args[1]); if (firstNumber == secondNumber) { System.out.format("Result: %d = %d %n", firstNumber, secondNumber); } else if (firstNumber > secondNumber) System.out.format("Result: %d > %d %n", firstNumber, secondNumber); } else { System.out.format("Result: %d < %d %n", firstNumber, secondNumber);
35
Using Else – If Revisited
class CompareInts{ public static void main(String[] args) { int firstNumber; int secondNumber; char relation; if (args.length > 1) { try { firstNumber = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Argument" + " must be an integer"); System.exit(1); } secondNumber = Integer.parseInt(args[1]); if (firstNumber == secondNumber) { relation = ‘=‘; } else if (firstNumber > secondNumber) { relation = ‘>’; } else { relation = ‘<‘; System.out.format("Result: %d %c %d %n", firstNumber, relation, secondNumber);
36
Switch Construct Selection control structure with any number of alternatives Works with byte, short, int, long, char, enumerated types, String class, classes that wrap char, byte, short and int.
37
Switch in Java General switch (expression) { case constant:
statements; break; /* optional */ /* any number of cases */ default: /* optional */ }
38
Switch in Java General Example switch (expression) { case constant:
expressions; break; /* optional */ /* any number of cases */ default: /* optional */ } switch (dayOfWeek) { case ‘Monday’: daysToWeekend = 5; break; case ‘Tuesday’: daysToWeekend = 4; case ‘Wednesday’: daysToWeekend = 3; case ‘Thursday’: daysToWeekend = 2; case ‘Friday’: daysToWeekend = 1; default: daysToWeekend = 0; }
39
Nesting Branches Revisited
daysToWeekend = 0; if (dayOfWeek == ‘Monday’) daysToWeekend = 5; if (dayOfWeek == ‘Tuesday’) daysToWeekend = 4; if (dayOfWeek == ‘Wednesday’) daysToWeekend = 3; if (dayOfWeek == ‘Thursday’) daysToWeekend = 2; if (dayOfWeek == ‘Friday’) daysToWeekend = 1; switch (dayOfWeek) { case ‘Monday’: daysToWeekend = 5; break; case ‘Tuesday’: daysToWeekend = 4; case ‘Wednesday’: daysToWeekend = 3; case ‘Thursday’: daysToWeekend = 2; case ‘Friday’: daysToWeekend = 1; default: daysToWeekend = 0; } if (dayOfWeek == ‘Monday’) daysToWeekend = 5; else if (dayOfWeek == ‘Tuesday’) daysToWeekend = 4; else if (dayOfWeek == ‘Wednesday’) daysToWeekend = 3; else if (dayOfWeek == ‘Thursday’) daysToWeekend = 2; else if (dayOfWeek == ‘Friday’) daysToWeekend = 1; else daysToWeekend = 0;
40
Using Switch Write a program that accepts two numbers, applies a user provided operator and displays the result as an equation.
41
Using Switch class Calculate{ public static void main(String[] args) {
float firstNumber; float secondNumber; char operator; firstNumber = Float.parseInt(args[0]); operator = args[1].charAt(0); secondNumber = Float.parseInt(args[2]); switch (operator) { case ‘+’: System.out.format( “%.2f + %.2f = %.2f %n”, number1, number2, (number1 + number2)); break; case ‘-’: “%.2f - %.2f = %.2f %n”, number1, number2, (number1 - number2)); case ‘*’: “%.2f * %.2f = %.2f %n”, number1, number2, (number1 * number2)); case ‘/’: “%.2f / %.2f = %.2f %n”, number1, number2, (number1 / number2)); default: System.out.format(“%c is not a valid operator.%n”, operator); System.exit(); }
42
Using Switch Revisited
class Calculate{ public static void main(String[] args) { float firstNumber; float secondNumber; char operator; float result; firstNumber = Float.parseInt(args[0]); operator = args[1].charAt(0); secondNumber = Float.parseInt(args[2]); switch (operator) { case ‘+’: result = number1 + number2; break; case ‘-’: result = number1 - number2; case ‘*’: result = number1 * number2; case ‘/’: result = number1 / number2; default: printf (“%c is not a valid operator.%n”, operator); System.exit(); } system.out.format(“%.2f %c %.2f = %.2f %n”, number1, operator, number2, result);
43
Branching Summary Keywords Concepts if else else if switch case break
default Concepts Branching If If – Else Else – If Switch Nesting
44
Introduction to Java Looping
45
Structured Constructs
Sequence Branching If If – Else Else – If Switch Looping Leading Decision Trailing Decision Counting (For) Enhanced For
46
While Construct Sequence executes as long as the expression evaluates true. Sequence may never execute.
47
While in Java General while (expression) { statement(s) }
48
While in Java Example General while (count < 11) {
System.out.println( "Count is: " + count); count++; } while (expression) { statement(s) }
49
Using While Write a program that computes the average of an array of integers.
50
Using While class Average{ public static void main(String[] args) {
int sum; int count; double average; int[] numbers = {1,2,3,4,5,6,7,8,9,10}; int i = 0; while (i < numbers.length) { sum += numbers[i++]; count++; } average = double(sum) / double(count); System.out.println ( “Average of the list is: “ + average);
51
Until Construct Sequence executes as long as expression evaluates true. Sequence will always execute at least once.
52
Do – While in Java Example General do { System.out.println(
"Count is: " + count); count++; } while (count < 11); do { statement(s) } while (expression)
53
Using Until Write a program that computes the average of an array of integers.
54
Using Until class Average{ public static void main(String[] args) {
int sum; int count; double average; int[] numbers = {1,2,3,4,5,6,7,8,9,10}; int i = 0; do { sum += numbers[i++]; count++; } while ( i < numbers.length); average = double(sum) / double(count); System.out.println ( “Average of the list is: “ + average); }
55
For Construct Special case of While Loop
Responds to a frequent loop form
56
For in Java Example General /* as a while loop */ i = 1;
while (i < 11) { System.out.println( "Count is: " + i); i++ } /* as a for loop */ for(int i=1; i<11; i++) { General for (initialization; termination; increment) { statement(s) }
57
Using For Write a program that computes the average of an array of integers.
58
Using For class Average{ public static void main(String[] args) {
int sum; int count; double average; int[] numbers = {1,2,3,4,5,6,7,8,9,10}; for (int i = 0; i < numbers.length; i++) { sum += numbers[i]; count++; } average = double(sum) / double(count); System.out.println (“Average of the list is: “ + average);
59
Enhanced For Works for collections and arrays
Item hold the current value from numbers array Automatically steps through the list Example class EnhancedForDemo { public static void main(String[] args){ int[] numbers = {1,2,3,4,5,6,7,8,9,10}; for (int item : numbers) { System.out.println( "Count is: " + item); }
60
Using Enhanced For Write a program that computes the average of an array of integers.
61
Using Enhanced For class Average{
public static void main(String[] args) { int sum; int count; double average; int[] numbers = {1,2,3,4,5,6,7,8,9,10}; for (int value: numbers) { sum += value; count++; } average = double(sum) / double(count); System.out.println (“Average of the list is: “ + average);
62
Infinite Loops Expressions in the For Loop are optional
Can be used for infinite loops While loop is preferred Example /* one idiomatic form */ for ( ; ; ) { statements; } /* preferred form */ while (true) {
63
Looping Summary Keywords Concepts while do for Leading decisions
Trailing decisions Counting loops (For) Enhanced For
64
Programming Assignment
Due 23:59, 20 Jan 2014 Coding Conventions: File Header Your name File name Assignment name and number short description or purpose of the program/ object/ code in the file Describe each function and class. At a minimum, briefly describe the purpose and usage. Comment obscure or difficult code.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.