COP 2800 Lake Sumter State College Mark Wilson, Instructor

Slides:



Advertisements
Similar presentations
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
Advertisements

1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
CMT Programming Software Applications
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
C++ for Engineers and Scientists Third Edition
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
DAT602 Database Application Development Lecture 5 JAVA Review.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Chapter 3 Control Flow Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Expressions An expression is a series of variables, operators, and method calls (constructed according to the syntax of the language) that evaluates to.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Introduction to Java Java Translation Program Structure
Basic Java Syntax COMP 401, Spring 2014 Lecture 2 1/14/2014.
Copyright Curt Hill Variables What are they? Why do we need them?
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Reference Learning Java DDC publishing Herst, Yamauchi, Adler COP 3331 Object Oriented Analysis and Design Java Part I.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
1.  Algorithm: 1. Read in the radius 2. Compute the area using the following formula: area = radius x radius x PI 3. Display the area 2.
Information and Computer Sciences University of Hawaii, Manoa
Lecture 4b Repeating With Loops
Elementary Programming
Chap. 2. Types, Operators, and Expressions
Selections Java.
Yanal Alahmad Java Workshop Yanal Alahmad
Lecture 2: Data Types, Variables, Operators, and Expressions
CS180 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Variables and Arithmetic Operators in JavaScript
Selenium WebDriver Web Test Tool Training
University of Central Florida COP 3330 Object Oriented Programming
BY GAWARE S.R. COMPUTER SCI. DEPARTMENT
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 4: Making Decisions.
Chapter 5: Control Structures II
Java Programming: From Problem Analysis to Program Design, 4e
Introduction to C Programming
Introduction to Programming in Java
CET 3640 – Lecture 2 Java Syntax Chapters 2, 4, 5
Starting JavaProgramming
Outline Altering flow of control Boolean expressions
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Java - Data Types, Variables, and Arrays
Chapter 8 JavaScript: Control Statements, Part 2
Chapter 2: Basic Elements of Java
Chapter 1: Computer Systems
Java Tokens & Data types
Chapter 7 Conditional Statements
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
elementary programming
The System.exit() Method
Lecture Notes – Week 2 Lecture-2
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Unit 3: Variables in Java
Chap 2. Identifiers, Keywords, and Types
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
CprE 185: Intro to Problem Solving (using C)
Presentation transcript:

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.