COP 2800 Lake Sumter State College Mark Wilson, Instructor Programming with Java COP 2800 Lake Sumter State College Mark Wilson, Instructor
Programming with Java Classes and Objects
What is a Class? A class is a blueprint or prototype from which objects are created. The term ‘class’ derives from ‘classification’.
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
UML Representation What the class knows What the class does
Variables and Constants Programming with Java Variables and Constants
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
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
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
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;
Programming with Java Expressions
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: = += -= *= /= %= &= ^= |= <<= >>= >>>=
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
Statement Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. Ends with a semicolon (;) aValue = 8933.234; // assignment statement aValue++; // increment statement System.out.println("Hello World!"); // method invocation statement Bicycle myBike = new Bicycle(); // object creation statement double aValue = 8933.234; // declaration statement
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 }
Programming with Java Branching
Structured Constructs Sequence Branching If If – Else Else – If Switch Looping Leading Decision Trailing Decision Counting (For) Enhanced For
If Construct Selection control structure with one alternative Sequence executes if the expression evaluates to true
If in Java General if (expression) { one or more statements; } if (expression) statement;
If in Java General if (expression) { one or more statements; } if (expression) statement; Examples if (a == b) { counter++; } if (counter > 5) limit = TRUE; // problematic
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
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’!”); } } }
If – Else Construct Selection control structure with two alternatives One sequence executes when the expression evaluates true Otherwise the other sequence executes
If – Else in Java General if (expression) { one or more statements; }
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;
Using If - Else Write a program to report whether a number entered by user is even or odd
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);
Nested Branches Any structured construct may contain one or more other structured constructs
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++;
Else – If Construct Selection control structure with any number of alternatives Simplified nesting of Ifs
Else – If in Java General if (expression) { one or more statements; } else if (expression) { else { if (expression) statement; else if (expression) else
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++; }
Using Else – If Write a program that compares two input numbers and reports the result
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);
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);
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.
Switch in Java General switch (expression) { case constant: statements; break; /* optional */ /* any number of cases */ default: /* optional */ }
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; }
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;
Using Switch Write a program that accepts two numbers, applies a user provided operator and displays the result as an equation.
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(); }
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);
Branching Summary Keywords Concepts if else else if switch case break default Concepts Branching If If – Else Else – If Switch Nesting
Introduction to Java Looping
Structured Constructs Sequence Branching If If – Else Else – If Switch Looping Leading Decision Trailing Decision Counting (For) Enhanced For
While Construct Sequence executes as long as the expression evaluates true. Sequence may never execute.
While in Java General while (expression) { statement(s) }
While in Java Example General while (count < 11) { System.out.println( "Count is: " + count); count++; } while (expression) { statement(s) }
Using While Write a program that computes the average of an array of integers.
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);
Until Construct Sequence executes as long as expression evaluates true. Sequence will always execute at least once.
Do – While in Java Example General do { System.out.println( "Count is: " + count); count++; } while (count < 11); do { statement(s) } while (expression)
Using Until Write a program that computes the average of an array of integers.
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); }
For Construct Special case of While Loop Responds to a frequent loop form
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) }
Using For Write a program that computes the average of an array of integers.
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);
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); }
Using Enhanced For Write a program that computes the average of an array of integers.
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);
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) {
Looping Summary Keywords Concepts while do for Leading decisions Trailing decisions Counting loops (For) Enhanced For
Programming Assignment Due 23:59, 20 Jan 2014 Coding Conventions: http://www.oracle.com/technetwork/java/codeconv-138413.html 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.