BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages

Size: px
Start display at page:

Download "BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages"

Transcription

1 Topic 1: Basic Java Plan: this topic through next Friday (5 lectures) Required reading on web site I will not spell out all the details in lecture! BlueJ Demo BlueJ = Java IDE (Interactive Development Environment) Editor + Compiler + Interpreter + other tools Remember: no "run" button; just execute main function My goal: highlight differences between Java and Python mention things that often trip up Java newbies file I/O Information about 3 Java tools on web site: BlueJ JDK plus text editor Eclipse Other alternatives OK as long as based on standard Sun (Oracle) Java, version 6 or 7 (also known as 1.6 or 1.7) 1 2 Features of Structured Programming Languages basic statements: assignments, function calls... compound statements: 1. Sequencing: one statement after another 2. Selection: choosing among alternatives 3. Iteration: repeating a statement 4. Grouping: treating several statements as a unit abstraction: functions/methods/procedures with parameters & results 1. Sequencing Python: separate one statement from the next by going to the next line (or midline semicolon) a = 7 b = 8 c = 5; d = 6 e = \ Java: All simple statements end with a semicolon. a = 7; b = 5; c = ; d = 6; 3 4

2 Python: if a > b: c = 17 else: c = 5 2. Selection Python: if n > 10: a = 1 b = 2 c = 3 3. Grouping What statements are executed only when n > 10? How do you know? Java: if (a>b) c = 17; else c = 5; or (ugly but legal): if (a> b) c = 17; else c = 5; Java: if (n > 10) { a = 1; b = 2; c = 3; Green part is called a block. Combines a group of statements into a compond statement. Java also has a switch statement for multi-way branches. Optional for 124. Ugly but legal equivalent: if (n>10) {a = 1; b = 2; c = 3; 5 6 4A. Iteration: While loops 4B. Iteration: For loops Python: while i < n: total += i i += 1 Java: while (i < n) { total += i; i++; Python: for i in range(n): total += i Java: for (int i = 1; i < n; i++) { total += i; Java also has a third kind of loop: do/while Optional for 124. same as: int i = 1; while (i < n) { total += i; i++; 7 8

3 Dynamic vs. Static Typing Declaring Variables Python uses dynamic typing: must run program to determine the types of expressions if <some condition>: x = 14 else: x = "abc" # what is the type of x??? # is x/4 a legal expression??? Java uses static typing: the value of every expression can be determined at compile time. Every variable must be declared with a type. Or: Rules: int x = 14; String y = "abc"; int x; // later on in program X = 14; A variable must be declared before it is set (possibly on the same line) A variable must be set before it is used 9 10 Nuisance public static void main(string args[]) { int x;.. if (<some error condition>) { System.out.println("error!"); System.exit(1); // aborts program else {... x =...; int y = x + 17; WILL NOT COMPILE!... // end main volume of a cone = In Java: Mixed-Mode Arithmetic double height = 10.6; double radius = 5.24; final double PI = ; double volume = 1/3 * PI * radius * radius * height; System.out.println(volume); result? why? 1 3 π r 2 h 11 12

4 Strings The "+" Operator Strings are objects Not lists/arrays String literal: "abcd" Character literal 'a' 'a' and "a" are not the same thing! To access parts of strings, use special String methods: charat length substring int x = 1; int y = 2; // value of x + y? String x = "abc"; String y = "def"; // value of x + y? String x = "one"; int y = 2; // value of x + y? The "+" Operator (continued) Comparing Strings (equality) int a = 9; int b = 6; System.out.println("the total is " + a + b); // what is printed? int c = 9; int d = 6; System.out.println(c + d + " is the total"); // what is printed? String s1 = "abcd"; String t = "ab"; prints "not equal"! String u = "cd"; String s2 = t + u; if (s1 == s2) System.out.println("equal"); else System.out.println("not equal"); if (s1.equals(s2)) prints "equal" System.out.println("equal"); else System.out.println("not equal"); 15 16

5 Comparing Strings (inequality) String a = "apple"; String b = "banana"; int val = a.compareto(b); Output To The Console System.out.print(s) System.out.println(s) compareto returns: 0 if a and b are exactly equal positive int if a is greater than b negative int if a is less than b Input From the Keyboard Input, continued 1. Create a Scanner object: Scanner keyboard = new Scanner(System.in); keyboard.hasnextint() true if next token is an integer 2. Use one of the reading methods: keyboard.next(): next "token" as String keyboard.nextline(): rest of current line as String keyboard.nextint(): next token, converted to integer keyboard.nextdouble(): next token, converted to double Example programs: ScannerDemo: basic input of integers & strings; we will add checking ReadLines: reading tokens & whole lines can be tricky 19 20

6 Reading From a File Needs knowledge of exceptions later this term. For now: helper class FileOpen available on web site. To use FileOpen: add copy to the same folder as your program. (No import necessary.) Methods What is a method? Like a function in Python. Small piece of a program Performs small task Other names in different languages: function, procedure, subprogram, subroutine String inputname = "myfile.txt"; Scanner inputfile = FileOpen.openScanner(inputName); PrintWriter outputfile = FileOpen.openWriter("output.txt"); // use outputfile just like System.out Look at FileOpenDemo... Why do we use methods? avoid duplicated code modularize improve readability readability means: easier to debug easier to modify harder to goof Parameters & Return Results Abstraction parameter: information you give to the method return result: information it gives back method with no result is "void" example: leapyear method abstract view of leapyear method: what it does (interface) concrete/implementation view: how it works (implementation) Every method must have a header comment saying what it does Include parameters, return result, possible errors To learn how to call the method: just read the header comment To learn how the method works: read the body too 23 24

7 Ending Things Early 1. break statement ends the current (innermost) loop 2. return ends the current method Order Of Methods Common question: Does the order in which I declare my methods matter? Answer: For functionality, no. For style, maybe yes. 3. System.exit(n) ends the program convention: n = 0 means normal exit n 0 parameter means error abort Example: Endings.java Overloading Scope OK to have two methods with the same name. Call is resolved based on number and/or types of parameters public static double m(double a, double b) { public static String m(int a, int b) { return a + 2*b; return a + b.substring(1); public static double m(double a, double b, double c) { return (a+b+c)/3.0; Scope of variable = where it can be used Scope of a Java variable: from declaration to end of block public static int scope() { int a =...; while (a > 0) { int b =...; for (int i = 0; i < b; i++) { int c = b+i; a += c; while (...) { double c =...;... // end while // end while return a; // end scope 27 28

8 Scope (2) You can't hide a variable by declaring a variable with the same name in an inner loop. Global Variables You can declare variables outside of any methods -- "globally". Don't do it until we discuss it in the next topic! int a =...; while (a > 0) { int b =...; if (...) { int b =...; // illegal! // end while Right now: Arrays basics of one- and two-dimensional arrays lets us use arrays in examples, assignments and quizzes Caution to Python Programmers Arrays are not lists!!!! ignores some details After classes topic we'll fill in some missing details Python Lists: can grow & shrink can mix many types of values (heterogeneous) languages features for adding & deleting at any position Java Arrays: size is specified at creation time, never changes all values must have same type (homogeneous) more programming effort required to add & delete array elements 31 32

9 Definitions Creating An Array array: ordered collection of elements of the same type [homogeneous collection] Note: indexes go from 0 to length-1 index: position of element length: number of elements in array Size of array specified when created. size can never change! General form: <type>[] <name> = new <type>[<size>] or: <type> <name>[] = new <type>[<size>] Examples: int marks[] = new int[20]; String[] names = new String[10]; In each of above, there are two things happening: 1. Declaring the array variable 2. Creating a new array and assigning it to the variable Declaring an Array 2. Creating a New Array syntax: <type> <name>[]; or: <type>[] <name>; declaration int coursemarks[]; coursemarks has not been initialized use an array constructor to give it a value: coursemarks = new int[20]; Note: no length specified! examples: int coursemarks[]; String args[]; double[] data; now coursemarks is an array containing 20 integers: indexes 0 to 19 all elements automatically initialized to zero or combine declaration & initialization: int coursemarks[] = new int[20]; 35 36

10 Using an Array refer to an element of an array as <array name> [ <index> ] // read values into array int coursemarks[] = new int[20]; for (int i = 0; i < 20; i++) { System.out.print("enter next mark: "); coursemarks[i] = keyboard.nextint(); // end for Style problem: 20 used in several places. Why is that // average the values bad? int sum = 0; for (int i = 0; i < 20; i++) sum = sum + coursemarks[i]; System.out.println("average mark: " + (double) sum / 20); Using an Array: Improved Version // read values into array final int NUM_STUDENTS = 20; int coursemarks[] = new int[num_students]; for (int i = 0; i < NUM_STUDENTS; i++) { System.out.print("enter next mark: "); coursemarks[i] = keyboard.nextint(); // end for // average the values int sum = 0; for (int i = 0; i < NUM_STUDENTS; i++) sum = sum + coursemarks[i]; System.out.println("average mark: " + (double) sum / NUM_STUDENTS); Even Better Version every array object has length attribute <array name>.length gets the length of the array Bounds Checking Java throws an exception (aborts) if you try to access or change an array element that's out of bounds int coursemarks[] = new int[20]; for (int i = 0; i<coursemarks.length; i++){ System.out.print("enter next mark: "); coursemarks[i] = keyboard.nextint(); // end for int sum = 0; for (int i = 0; i < coursemarks.length; i++) sum = sum + coursemarks[i]; System.out.println("average mark: " + (double) sum / coursemarks.length); Example: int myarray[] = new int[10]; int x = myarray[0]; // OK myarray[9] = 42; // OK int z = myarray[10]; // exception! myarray[-1] = 7; // exception! java.lang.arrayindexoutofboundsexception at ArrayTest.main(ArrayTest.java:9) 39 40

11 Arrays As Parameters public class ArrayParm { public static void changearray(int numbers[]) { numbers[0]++; // end changearray Two-Dimensional Arrays assignment scores for 20 students, 9 assignments: int scores[][] = new int[20][9]; visualize as a table: 20 rows, 9 columns public static void main(string args[]) { int years[] = new int[3]; years[0] = 1987; years[1] = 1989; years[2] = 1994; changearray(years); for (int i = 0; i < years.length; i++) System.out.println(years[i]); // end main // end class student number 3, assignment 6: scores[3][6] D Arrays &.length Java treats a 2D array as an array of arrays. int scores[][] = new int[20][9]; scores is a 2D array of ints scores[4] is a 1D array of ints (the 5 th row) scores[4][7] is an int What does scores.length mean? number of rows (20) the height of the array Example: Total of 2D Array int numbers[][] =...; // initialize numbers... int total = 0; for (int row = 0; row < numbers.length; row++) { for (int col = 0; col < numbers[row].length; col++) { total += numbers[row][col]; // end for How would you ask for the number of columns (width)? scores[0].length 43 44

12 Using Java API Classes 1. Spell Out Full Name of Class API is divided into packages. Example Scanner class is in java.util package. Three ways to use Scanner. public class Import { public static void main(string args[]) { java.util.scanner keyboard = new java.util.scanner(system.in); System.out.print("Enter your name: "); String name = keyboard.nextline(); System.out.println("Hello, " + name + "!"); // end main // end class Import Class From Package 3. Import All Classes From Package import java.util.scanner; public class Import { public static void main(string args[]) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter your name: "); String name = keyboard.nextline(); System.out.println("Hello, " + name + "!"); // end main // end class import java.util.*; public class Import { public static void main(string args[]) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter your name: "); String name = keyboard.nextline(); System.out.println("Hello, " + name + "!"); // end main // end class This is no more expensive than importing just Scanner

13 Special Class: java.lang Caution Automatically imported into all Java programs. Includes standard useful classes including: Math In CISC 124 you may use any API class unless specifically asked not to (for assignments, quizzes, etc) System String You may NOT use non-standard classes & packages (downloaded from Internet, supplied with Eclipse, etc.) FAQ Programming Style What's the point of the parameter of the main method?? (Or the parameter to System.exit?) Both are for using Java with a command-line system (DOS, Linux, Mac terminal) Demo... To be useful, a program has to work correctly. Also must be readable by human beings. Examples... Some assignments will have style points. In-class exercises discussing examples of student assignments (anonymously) Not needed for CISC 124. Quizzes & Exams: time pressure, no style points BUT: I can't give you points if I can't understand what you write! Style can mean more partial credit for incorrect code 51 52

Chapter 5 Lab Methods

Chapter 5 Lab Methods Chapter 5 Lab Methods Lab Objectives Be able to write methods Be able to call methods Be able to write javadoc comments Be able to create HTML documentation using the javadoc utility Introduction Methods

More information

St. Edmund Preparatory High School Brooklyn, NY

St. Edmund Preparatory High School Brooklyn, NY AP Computer Science Mr. A. Pinnavaia Summer Assignment St. Edmund Preparatory High School Name: I know it has been about 7 months since you last thought about programming. It s ok. I wouldn t want to think

More information

Chapter 5 Lab Methods

Chapter 5 Lab Methods Chapter 5 Lab Methods Lab Objectives Be able to write methods Be able to call methods Be able to write javadoc comments Be able to create HTML documentation for our Java class using javadoc Introduction

More information

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software. CISC-124 20180129 20180130 20180201 This week we continued to look at some aspects of Java and how they relate to building reliable software. Multi-Dimensional Arrays Like most languages, Java permits

More information

Last Class. While loops Infinite loops Loop counters Iterations

Last Class. While loops Infinite loops Loop counters Iterations Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics WIT COMP1000 Java Basics Java Origins Java was developed by James Gosling at Sun Microsystems in the early 1990s It was derived largely from the C++ programming language with several enhancements Java

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

13 th Windsor Regional Secondary School Computer Programming Competition

13 th Windsor Regional Secondary School Computer Programming Competition SCHOOL OF COMPUTER SCIENCE 13 th Windsor Regional Secondary School Computer Programming Competition Hosted by The School of Computer Science, University of Windsor WORKSHOP I [ Overview of the Java/Eclipse

More information

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

CS 152: Data Structures with Java Hello World with the IntelliJ IDE CS 152: Data Structures with Java Hello World with the IntelliJ IDE Instructor: Joel Castellanos e-mail: joel.unm.edu Web: http://cs.unm.edu/~joel/ Office: Electrical and Computer Engineering building

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

1. What is the difference between a compiler and an interpreter? Also, discuss Java s method.

1. What is the difference between a compiler and an interpreter? Also, discuss Java s method. Name: Write all of your responses on these exam pages. 1 Short Answer (5 Points Each) 1. What is the difference between a compiler and an interpreter? Also, discuss Java s method. 2. Java is a platform-independent

More information

Over and Over Again GEEN163

Over and Over Again GEEN163 Over and Over Again GEEN163 There is no harm in repeating a good thing. Plato Homework A programming assignment has been posted on Blackboard You have to convert three flowcharts into programs Upload the

More information

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money

More information

1 Short Answer (10 Points Each)

1 Short Answer (10 Points Each) 1 Short Answer (10 Points Each) 1. Write a for loop that will calculate a factorial. Assume that the value n has been input by the user and have the loop create n! and store it in the variable fact. Recall

More information

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Introduction to Java Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) Introduce Java, a general-purpose programming language,

More information

ITI1120 Introduction to Computing I Exercise Workbook Fall 2012

ITI1120 Introduction to Computing I Exercise Workbook Fall 2012 ITI1120 Introduction to Computing I Exercise Workbook Fall 2012 1 Table of Contents 1 Introduction 3 2 Computer Programming Model 3 3 Pre-defined Algorithm Models 6 4 Summary of Program Structure, Algorithm

More information

COMP 202 Java in one week

COMP 202 Java in one week COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. Dec. 9 Loops Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. What is a loop? What are the three loops in Java? What do control structures do?

More information

Flow of Control: Loops. Chapter 4

Flow of Control: Loops. Chapter 4 Flow of Control: Loops Chapter 4 Java Loop Statements: Outline The while statement The do-while statement The for Statement Java Loop Statements A portion of a program that repeats a statement or a group

More information

Chapter 7: Arrays and the ArrayList Class

Chapter 7: Arrays and the ArrayList Class Chapter 7: Arrays and the ArrayList Class Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 7 discusses the following main topics: Introduction

More information

CS 302: Introduction to Programming in Java. Lecture 11 Yinggang Huang. CS302 Summer 2012

CS 302: Introduction to Programming in Java. Lecture 11 Yinggang Huang. CS302 Summer 2012 CS 302: Introduction to Programming in Java Lecture 11 Yinggang Huang 1 Review How do we call a method? What are method inputs called? How many values can be returned from a method? Write a method header

More information

Chapter 4: Conditionals and Recursion

Chapter 4: Conditionals and Recursion Chapter 4: Conditionals and Recursion Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Agenda The modulus operator Random Number Generation Conditional Execution Alternative

More information

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

BASIC INPUT/OUTPUT. Fundamentals of Computer Science BASIC INPUT/OUTPUT Fundamentals of Computer Science Outline: Basic Input/Output Screen Output Keyboard Input Simple Screen Output System.out.println("The count is " + count); Outputs the sting literal

More information

Text User Interfaces. Keyboard IO plus

Text User Interfaces. Keyboard IO plus Text User Interfaces Keyboard IO plus User Interface and Model Model: objects that solve problem at hand. User interface: interacts with user getting input from user giving output to user reporting on

More information

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasketEnhanced { public static void main(string[]

More information

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation. Chapter 4 Lab Loops and Files Lab Objectives Be able to convert an algorithm using control structures into Java Be able to write a while loop Be able to write an do-while loop Be able to write a for loop

More information

Chapter 1 Lab Algorithms, Errors, and Testing

Chapter 1 Lab Algorithms, Errors, and Testing Chapter 1 Lab Algorithms, Errors, and Testing Lab Objectives Be able to write an algorithm Be able to compile a Java program Be able to execute a Java program using the Sun JDK or a Java IDE Be able to

More information

Introduction to Computer Science I Spring 2010 Sample mid-term exam Answer key

Introduction to Computer Science I Spring 2010 Sample mid-term exam Answer key Introduction to Computer Science I Spring 2010 Sample mid-term exam Answer key 1. [Question:] (15 points) Consider the code fragment below. Mark each location where an automatic cast will occur. Also find

More information

Top-Down Program Development

Top-Down Program Development Top-Down Program Development Top-down development is a way of thinking when you try to solve a programming problem It involves starting with the entire problem, and breaking it down into more manageable

More information

Introduction to Software Development (ISD) David Weston and Igor Razgon

Introduction to Software Development (ISD) David Weston and Igor Razgon Introduction to Software Development (ISD) David Weston and Igor Razgon Autumn term 2013 Course book The primary book supporting the ISD module is: Java for Everyone, by Cay Horstmann, 2nd Edition, Wiley,

More information

Full file at

Full file at Chapter 1 Primitive Java Weiss 4 th Edition Solutions to Exercises (US Version) 1.1 Key Concepts and How To Teach Them This chapter introduces primitive features of Java found in all languages such as

More information

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

! definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. ! We often use language like Indefinite loops while loop! indefinite loop: A loop where it is not obvious in advance how many times it will execute.! We often use language like " "Keep looping as long as or while this condition is

More information

COMP 202 Java in one week

COMP 202 Java in one week CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language

More information

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements More Things We Can Do With It! More operators and expression types More s 11 October 2007 Ariel Shamir 1 Overview Variables and declaration More operators and expressions String type and getting input

More information

Date: Dr. Essam Halim

Date: Dr. Essam Halim Assignment (1) Date: 11-2-2013 Dr. Essam Halim Part 1: Chapter 2 Elementary Programming 1 Suppose a Scanner object is created as follows: Scanner input = new Scanner(System.in); What method do you use

More information

1 Short Answer (10 Points Each)

1 Short Answer (10 Points Each) Name: Write all of your responses on these exam pages. 1 Short Answer (10 Points Each) 1. What is the difference between a compiler and an interpreter? Also, discuss how Java accomplishes this task. 2.

More information

Input. Scanner keyboard = new Scanner(System.in); String name;

Input. Scanner keyboard = new Scanner(System.in); String name; Reading Resource Input Read chapter 4 (Variables and Constants) in the textbook A Guide to Programming in Java, pages 77 to 82. Key Concepts A stream is a data channel to or from the operating system.

More information

Oct Decision Structures cont d

Oct Decision Structures cont d Oct. 29 - Decision Structures cont d Programming Style and the if Statement Even though an if statement usually spans more than one line, it is really one statement. For instance, the following if statements

More information

Loops. CSE 114, Computer Science 1 Stony Brook University

Loops. CSE 114, Computer Science 1 Stony Brook University Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?

More information

Computer Science is...

Computer Science is... Computer Science is... Machine Learning Machine learning is the study of computer algorithms that improve automatically through experience. Example: develop adaptive strategies for the control of epileptic

More information

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods

More information

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods

More information

Chapter 4: Loops and Files

Chapter 4: Loops and Files Chapter 4: Loops and Files Chapter Topics Chapter 4 discusses the following main topics: The Increment and Decrement Operators The while Loop Using the while Loop for Input Validation The do-while Loop

More information

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to A PROGRAM IS A SEQUENCE of instructions that a computer can execute to perform some task. A simple enough idea, but for the computer to make any use of the instructions, they must be written in a form

More information

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

More information

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. Today! Build HelloWorld yourself in BlueJ and Eclipse. Look at all the Java keywords. Primitive Types. HelloWorld in BlueJ 1. Find BlueJ in the start menu, but start the Select VM program instead (you

More information

Array. Array Declaration:

Array. Array Declaration: Array Arrays are continuous memory locations having fixed size. Where we require storing multiple data elements under single name, there we can use arrays. Arrays are homogenous in nature. It means and

More information

What did we talk about last time? Examples switch statements

What did we talk about last time? Examples switch statements Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation

More information

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007 Name: Please fill in your Student Number and Name. Student Number : Student Number: University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ 2007 Final Examination Question Max

More information

Basic Computation. Chapter 2

Basic Computation. Chapter 2 Basic Computation Chapter 2 Increment and Decrement Operators Used to increase (or decrease) the value of a variable by 1 Easy to use, important to recognize The increment operator count++ or ++count The

More information

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8 CS 302: INTRODUCTION TO PROGRAMMING Lectures 7&8 Hopefully the Programming Assignment #1 released by tomorrow REVIEW The switch statement is an alternative way of writing what? How do you end a case in

More information

CSIS 10A Assignment 4 SOLUTIONS

CSIS 10A Assignment 4 SOLUTIONS CSIS 10A Assignment 4 SOLUTIONS Read: Chapter 4 Choose and complete any 10 points from the problems below, which are all included in the download file on the website. Use BlueJ to complete the assignment,

More information

Object-oriented programming in...

Object-oriented programming in... Programming Languages Week 12 Object-oriented programming in... College of Information Science and Engineering Ritsumeikan University plan this week intro to Java advantages and disadvantages language

More information

PROGRAMMING STYLE. Fundamentals of Computer Science I

PROGRAMMING STYLE. Fundamentals of Computer Science I PROGRAMMING STYLE Fundamentals of Computer Science I Documentation and Style: Outline Meaningful Names Comments Indentation Named Constants Whitespace Compound Statements Documentation and Style Most programs

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Chapter 4: Loops and Files

Chapter 4: Loops and Files Chapter 4: Loops and Files Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 4 discusses the following main topics: The Increment and Decrement

More information

Example Program. public class ComputeArea {

Example Program. public class ComputeArea { COMMENTS While most people think of computer programs as a tool for telling computers what to do, programs are actually much more than that. Computer programs are written in human readable language for

More information

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG Selections EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG Learning Outcomes The Boolean Data Type if Statement Compound vs. Primitive Statement Common Errors

More information

Basic Computation. Chapter 2

Basic Computation. Chapter 2 Walter Savitch Frank M. Carrano Basic Computation Chapter 2 Outline Variables and Expressions The Class String Keyboard and Screen I/O Documentation and Style Variables Variables store data such as numbers

More information

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.

More information

b. Suppose you enter input from the console, when you run the program. What is the output?

b. Suppose you enter input from the console, when you run the program. What is the output? Part I. Show the printout of the following code: (write the printout next to each println statement if the println statement is executed in the program). a. Show the output of the following code: public

More information

COMP 110 Project 1 Programming Project Warm-Up Exercise

COMP 110 Project 1 Programming Project Warm-Up Exercise COMP 110 Project 1 Programming Project Warm-Up Exercise Creating Java Source Files Over the semester, several text editors will be suggested for students to try out. Initially, I suggest you use JGrasp,

More information

Midterm Examination (MTA)

Midterm Examination (MTA) M105: Introduction to Programming with Java Midterm Examination (MTA) Spring 2013 / 2014 Question One: [6 marks] Choose the correct answer and write it on the external answer booklet. 1. Compilers and

More information

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process Entry Point of Execution: the main Method Elementary Programming EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG For now, all your programming exercises will

More information

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables

More information

Introduction to Java & Fundamental Data Types

Introduction to Java & Fundamental Data Types Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains

More information

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

More information

Chapter 11: Create Your Own Objects

Chapter 11: Create Your Own Objects Chapter 11: Create Your Own Objects Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Our usual text takes a fairly non-standard departure in this chapter. Instead, please refer

More information

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repe$$on CSC 121 Fall 2015 Howard Rosenthal Repe$$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

A+ Computer Science -

A+ Computer Science - import java.util.scanner; or just import java.util.*; reference variable Scanner keyboard = new Scanner(System.in); object instantiation Scanner frequently used methods Name nextint() nextdouble() nextfloat()

More information

Full file at

Full file at Chapter 3 Flow of Control Multiple Choice 1) An if selection statement executes if and only if: (a) the Boolean condition evaluates to false. (b) the Boolean condition evaluates to true. (c) the Boolean

More information

Object Oriented Programming. Java-Lecture 6 - Arrays

Object Oriented Programming. Java-Lecture 6 - Arrays Object Oriented Programming Java-Lecture 6 - Arrays Arrays Arrays are data structures consisting of related data items of the same type In Java arrays are objects -> they are considered reference types

More information

Basic Computation. Chapter 2

Basic Computation. Chapter 2 Basic Computation Chapter 2 Outline Variables and Expressions The Class String Keyboard and Screen I/O Documentation and Style Variables Variables store data such as numbers and letters. Think of them

More information

Intro to Programming in Java Practice Midterm

Intro to Programming in Java Practice Midterm 600.107 Intro to Programming in Java Practice Midterm This test is closed book/notes. SHORT ANSWER SECTION [18 points total] 1) TRUE/FALSE - Please circle your choice: Tr for true, Fa for false. [1 point

More information

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

More information

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Testing and Debugging

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Testing and Debugging WIT COMP1000 Testing and Debugging Testing Programs When testing your code, always test a variety of input values Never test only one or two values because those samples may not catch some errors Always

More information

4. Java language basics: Function. Minhaeng Lee

4. Java language basics: Function. Minhaeng Lee 4. Java language basics: Function Minhaeng Lee Review : loop Program print from 20 to 10 (reverse order) While/for Program print from 1, 3, 5, 7.. 21 (two interval) Make a condition that make true only

More information

H212 Introduction to Software Systems Honors

H212 Introduction to Software Systems Honors Introduction to Software Systems Honors Lecture #07: September 21, 2015 1/30 We explained last time that an array is an ordered list of values. Each value is stored at a specific, numbered position in

More information

Decisions (If Statements) And Boolean Expressions

Decisions (If Statements) And Boolean Expressions Decisions (If Statements) And Boolean Expressions CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Last updated: 2/15/16 1 Syntax if (boolean_expr)

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015 Announcements Midterm Exams on 4 th of June (12:35 14:35) Room allocation will be announced soon

More information

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1 Name SOLUTION Page Points Score 2 15 3 8 4 18 5 10 6 7 7 7 8 14 9 11 10 10 Total 100 1 P age 1. Program Traces (41 points, 50 minutes)

More information

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 Announcements Check the calendar on the course webpage regularly for updates on tutorials and office hours.

More information

Chapter 5 Lab Methods

Chapter 5 Lab Methods Gaddis_516907_Java 4/10/07 2:10 PM Page 41 Chapter 5 Lab Methods Objectives Be able to write methods Be able to call methods Be able to write javadoc comments Be able to create HTML documentation for our

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI Outline Chapter 3 Using APIs 3.1 Anatomy of an API 3.1.1 Overall Layout 3.1.2 Fields 3.1.3 Methods 3.2 A Development Walkthrough 3.2.1 3.2.2 The Mortgage Application 3.2.3 Output Formatting 3.2.4 Relational

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables

More information

CSE 114 Computer Science I

CSE 114 Computer Science I CSE 114 Computer Science I Iteration Cape Breton, Nova Scotia What is Iteration? Repeating a set of instructions a specified number of times or until a specific result is achieved How do we repeat steps?

More information

Java Coding 3. Over & over again!

Java Coding 3. Over & over again! Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java

More information

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs. Java SE11 Development Java is the most widely-used development language in the world today. It allows programmers to create objects that can interact with other objects to solve a problem. Explore Java

More information

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Loops EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Understand about Loops : Motivation: Repetition of similar actions Two common loops: for and while Primitive

More information

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Review what an array is Review how to declare arrays Review what reference variables are Review how to pass arrays to methods Review

More information

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

More information

Express Yourself. What is Eclipse?

Express Yourself. What is Eclipse? CS 170 Java Programming 1 Eclipse and the for Loop A Professional Integrated Development Environment Introducing Iteration Express Yourself Use OpenOffice or Word to create a new document Save the file

More information

CS61BL. Lecture 1: Welcome to CS61BL! Intro to Java and OOP Testing Error-handling

CS61BL. Lecture 1: Welcome to CS61BL! Intro to Java and OOP Testing Error-handling CS61BL Lecture 1: Welcome to CS61BL! Intro to Java and OOP Testing Error-handling About me Name: Edwin Liao Email: edliao@berkeley.edu Office hours: Thursday 3pm - 5pm Friday 11am - 1pm 611 Soda Or by

More information