More Control Structures

Size: px
Start display at page:

Download "More Control Structures"

Transcription

1 Chapter 8 More Control Structures 1

2 8.1 Exceptions When a Java program performs an illegal operation, an exception happens. If a program has no special provisions for dealing with exceptions, it will behave badly if one occurs. In many cases, the program will terminate immediately. Java provides a way for a program to detect that an exception has occurred and execute statements that are designed to deal with the problem. This process is called exception handling. 2

3 Common Exceptions There are many kinds of exceptions, each with a different name. Common exceptions: ArithmeticException NullPointerException Trying to divide by zero causes an ArithmeticException: i = j / k; // ArithmeticException occurs if k = 0 3

4 Common Exceptions Using zero as the right operand in a remainder operation also causes an ArithmeticException: i = j % k; // ArithmeticException occurs if k = 0 Calling a method using an object variable whose value is null causes a NullPointerException: acct.deposit(100.00); // NullPointerException occurs if acct is null 4

5 Handling Exceptions When an exception occurs (is thrown), the program has the option of catching it. In order to catch an exception, the code in which the exception might occur must be enclosed in a try block. After the try block comes a catch block that catches the exception (if it occurs) and performs the desired action. 5

6 Handling Exceptions The try and catch blocks together form a single statement, which can be used anywhere in a program that a statement is allowed: try block catch (exception-type identifier) block exception-type specifies what kind of exception the catch block should handle. identifier is an arbitrary name. 6

7 Handling Exceptions If an exception is thrown within the try block, and the exception matches the one named in the catch block, the code in the catch block is executed. If the try block executes normally without an exception the catch block is ignored. An example of try and catch blocks: try { quotient = dividend / divisor; catch (ArithmeticException e) { System.out.println("Error: Division by zero"); 7

8 Variables and try Blocks Be careful when declaring variables inside a try (or catch) block. A variable declared inside a block is always local to that block. An example: try { int quotient = dividend / divisor; catch (ArithmeticException e) { System.out.println("Error: Division by zero"); quotient is local to the try block; it can t be used outside the try block. 8

9 Variables and try Blocks There s another trap associated with try blocks. Suppose that the quotient variable is declared immediately before the try block: int quotient; try { quotient = dividend / divisor; catch (ArithmeticException e) { System.out.println("Error: Division by zero"); The compiler won t allow the value of quotient to be accessed later in the program, because no value is assigned to quotient if the exception occurs. 9

10 Variables and try Blocks The solution is often to assign a default value to the variable: int quotient = 0; // Default value try { quotient = dividend / divisor; catch (ArithmeticException e) { System.out.println("Error: Division by zero"); 10

11 Accessing Information About an Exception When an exception occurs, Java creates an exception object that contains information about the error. The identifier in a catch block (typically e) represents this object. Every exception object contains a string. The getmessage method returns this string: e.getmessage() 11

12 Accessing Information About an Exception An example of printing the message inside an exception object: try { quotient = dividend / divisor; catch (ArithmeticException e) { System.out.println(e.getMessage()); If the exception is thrown, the message might be: / by zero Printing the value returned by getmessage can be useful if it s not clear what the error is or what caused it. 12

13 Terminating the Program After an Exception When an exception is thrown, it may be necessary to terminate the program. Ways to cause program termination: Execute a return statement in the main method. Call the System.exit method. 13

14 Terminating the Program After an Exception Adding a call of System.exit to a catch block will cause the program to terminate: try { quotient = dividend / divisor; catch (ArithmeticException e) { System.out.println("Error: Division by zero"); System.exit(-1); A program that terminates abnormally should supply a nonzero argument (typically 1) to System.exit. 14

15 Converting Strings to Integers Attempting to convert a string to an int value using Integer.parseInt may fail: Converting "123" will succeed. Converting "duh" will fail, causing a NumberFormatException to be thrown. A robust program should provide a catch block to handle the exception: try { n = Integer.parseInt(str); catch (NumberFormatException e) { // Handle exception 15

16 Converting Strings to Integers If the string contains user input, it s often a good idea to have the user re-enter the input. Putting the try and catch blocks in a loop allows the user multiple attempts to enter a valid number: while (true) { SimpleIO.prompt("Enter an integer: "); String userinput = SimpleIO.readLine(); try { n = Integer.parseInt(userInput); // Input was valid; exit the loop catch (NumberFormatException e) { System.out.println("Not an integer; try again."); 16

17 Converting Strings to Integers The loop could be put inside a class method that prompts the user to enter a number and then returns the user s input in integer form: private static int readint(string prompt) { while (true) { SimpleIO.prompt(prompt); String userinput = SimpleIO.readLine(); try { return Integer.parseInt(userInput); catch (NumberFormatException e) { System.out.println("Not an integer; try again."); 17

18 Multiple catch Blocks A try block can be followed by more than one catch block: try { quotient = Integer.parseInt(str1) / Integer.parseInt(str2); catch (NumberFormatException e) { System.out.println("Error: Not an integer"); catch (ArithmeticException e) { System.out.println("Error: Division by zero"); When an exception is thrown, the first matching catch block will handle the exception. 18

19 Exercise Write a program to demonstrate the divide by zero exception, and print out a message if dividing by zero. 19

20 8.2 The switch Statement A cascaded if statement can be used to test the value of an expression against a set of possible values: if (day == 1) System.out.println("Sunday"); else if (day == 2) System.out.println("Monday"); else if (day == 3) System.out.println("Tuesday"); else if (day == 4) System.out.println("Wednesday"); else if (day == 5) System.out.println("Thursday"); else if (day == 6) System.out.println("Friday"); else if (day == 7) System.out.println("Saturday"); 20

21 The switch Statement There s a better way to accomplish the same effect. Java s switch statement is designed specifically for comparing a variable (or, more generally, an expression) against a series of possible values. 21

22 The switch Statement An equivalent switch statement: switch (day) { case 1: System.out.println("Sunday"); case 2: System.out.println("Monday"); case 3: System.out.println("Tuesday"); case 4: System.out.println("Wednesday"); case 5: System.out.println("Thursday"); case 6: System.out.println("Friday"); case 7: System.out.println("Saturday"); 22

23 The switch Statement When a switch statement is executed, the expression in parentheses (the controlling expression) is evaluated. The value of the controlling expression is then compared with the values listed after the word case (the case labels). If a match is found, the statements after the matching case label are executed. 23

24 The switch Statement Each case ends with a break statement. Executing a break statement causes the switch statement to terminate. The program continues executing with the statement that follows the switch statement. 24

25 Combining Case Labels Several case labels may correspond to the same action: switch (day) { case 1: System.out.println("Weekend"); case 2: System.out.println("Weekday"); case 3: System.out.println("Weekday"); case 4: System.out.println("Weekday"); case 5: System.out.println("Weekday"); case 6: System.out.println("Weekday"); case 7: System.out.println("Weekend"); 25

26 Combining Case Labels This statement can be shortened by combining cases whose actions are identical: switch (day) { case 1: case 7: System.out.println("Weekend"); case 2: case 3: case 4: case 5: case 6: System.out.println("Weekday"); 26

27 Combining Case Labels To save space, several case labels can be put on the same line: switch (day) { case 1: case 7: System.out.println("Weekend"); case 2: case 3: case 4: case 5: case 6: System.out.println("Weekday"); 27

28 The default Case If the value of the controlling expression in a switch statement doesn t match any of the case labels, the switch statement is skipped entirely. To indicate a default action to occur whenever the controlling expression doesn t match any of the case labels, the word default: can be used as a label. 28

29 The default Case An example of a default case: switch (day) { case 1: case 7: System.out.println("Weekend"); case 2: case 3: case 4: case 5: case 6: System.out.println("Weekday"); default: System.out.println("Not a valid day"); 29

30 The General Form of the switch Statement In general, the switch statement has the following appearance: switch ( expression ) { case constant-expression : statements case constant-expression : statements default : statements A constant expression is an expression whose value can be determined by the compiler. 30

31 The General Form of the switch Statement Case labels don t have to go in any particular order, although it s good style to put the labels in a logical order. The default label doesn t have to go last, although that s where most programmers put it. It s illegal for the same value to appear in two case labels. Any number of statements (including none at all) can go after each case label. Normally, the last statement in each case is break. 31

32 Layout of the switch Statement There are at least two common ways to lay out a switch statement. One layout technique puts the first statement in each case on the same line as the case label: switch (year) { case 1992: olympicsite = "Barcelona"; case 1996: olympicsite = "Atlanta"; case 2000: olympicsite = "Sydney"; case 2004: olympicsite = "Athens"; 32

33 Layout of the switch Statement When there s only one statement per case (not counting break), programmers often save space by putting the break statement on the same line: switch (year) { case 1992: olympicsite = "Barcelona"; case 1996: olympicsite = "Atlanta"; case 2000: olympicsite = "Sydney"; case 2004: olympicsite = "Athens"; The other common layout involves putting the statements in each case under the case label, indenting them to make the case label stand out. 33

34 Layout of the switch Statement Example: switch (year) { case 1992: olympicsite = "Barcelona"; case 1996: olympicsite = "Atlanta"; case 2000: olympicsite = "Sydney"; case 2004: olympicsite = "Athens"; 34

35 Layout of the switch Statement Although this layout allows longer statements, it also increases the number of lines required for the switch statement. This layout is best used when there are many statements in each case or the statements are lengthy. 35

36 Advantages of the switch Statement The switch statement has two primary advantages over the cascaded if statement. Using switch statements instead of cascaded if statements can make a program easier to understand. Also, the switch statement is often faster than a cascaded if statement. As the number of cases increases, the speed advantage of the switch becomes more significant. 36

37 Limitations of the switch Statement The switch statement can t replace every cascaded if statement. To qualify for conversion to a switch, every test in a cascaded if must compare the same variable (or expression) for equality with a constant: if (x == constant-expression 1 ) statement 1 else if (x == constant-expression 2 ) statement 2 else if (x == constant-expression 3 ) statement 3 37

38 Limitations of the switch Statement If any value that x is being compared with isn t constant, a switch statement can t be used. If the cascaded if statement tests a variety of different conditions, it s not eligible for switch treatment. A switch statement s controlling expression must have type char, byte, short, or int. 38

39 The Role of the break Statement Each case in a switch statement normally ends with a break statement. If break isn t present, each case will fall through into the next case: switch (sign) { case -1: System.out.println("Negative"); case 0: System.out.println("Zero"); case +1: System.out.println("Positive"); If sign has the value 1, the statement will print "Negative", "Zero", and "Positive". 39

40 The Role of the break Statement The case labels in a switch statement are just markers that indicate possible places to enter the list of statements inside the braces. Omitting the break statement is sometimes a useful programming technique, but most of the time it s simply a mistake. Putting a break statement at the end of the last case makes it easier (and less risky) to add additional cases. 40

41 Exercise Implement the following method that returns the number of days in a month. public int numofdays(int year, int month) 41

42 Program: Determining the Number of Days in a Month The MonthLength program asks the user for a month (an integer between 1 and 12) and a year, then displays the number of days in that month: Enter a month (1-12): 4 Enter a year: 2003 There are 30 days in this month The program will use a switch statement to determine whether the month has 30 days or 31 days. If the month is February, an if statement will be needed to determine whether February has 28 days or 29 days. 42

43 MonthLength.java // Determines the number of days in a month import jpb.*; public class MonthLength { public static void main(string[] args) { // Prompt the user to enter a month SimpleIO.prompt("Enter a month (1-12): "); String userinput = SimpleIO.readLine(); int month = Integer.parseInt(userInput); // Terminate program if month is not between 1 and 12 if (month < 1 month > 12) { System.out.println("Month must be between 1 and 12"); return; // Prompt the user to enter a year SimpleIO.prompt("Enter a year: "); userinput = SimpleIO.readLine(); int year = Integer.parseInt(userInput); 43

44 // Determine the number of days in the month int numberofdays; switch (month) { case 2: // February numberofdays = 28; if (year % 4 == 0) { numberofdays = 29; if (year % 100 == 0 && year % 400!= 0) numberofdays = 28; case 4: // April case 6: // June case 9: // September case 11: // November numberofdays = 30; default: numberofdays = 31; 44

45 // Display the number of days in the month System.out.println("There are " + numberofdays + " days in this month"); 45

46 8.3 The continue Statement Java s continue statement is similar to the break statement. Unlike break, executing a continue statement doesn t cause a loop to terminate. Instead, it causes the program to jump to the end of the loop body. The break statement can be used in loops and switch statements; the use of continue is limited to loops. continue is used much less often than break. 46

47 Uses of the continue Statement Using continue can simplify the body of a loop by reducing the amount of nesting inside the loop. Consider the following loop: while (expr1) { if (expr2) { statements A version that uses continue: while (expr1) { if (!expr2) continue; statements 47

48 Uses of the continue Statement The continue statement is especially useful for subjecting input to a series of tests. If it fails any test, continue can be used to skip the remainder of the loop. Testing a Social Security number for validity includes checking that it contains three digits, a dash, two digits, a dash, and four digits. The following loop won t terminate until the user enters an 11-character string with dashes in the right positions. 48

49 while (true) { SimpleIO.prompt("Enter a Social Security number: "); ssn = SimpleIO.readLine(); if (ssn.length() < 11) { System.out.println("Error: Number is too short"); continue; if (ssn.length() > 11) { System.out.println("Error: Number is too long"); continue; if (ssn.charat(3)!= '-' ssn.charat(6)!= '-') { System.out.println( "Error: Number must have the form ddd-dd-dddd"); continue; // Input passed all the tests, so exit the loop 49

Java Programming: from the Beginning. Chapter 8 More Control Structures. CSc 2310: Principle of Programming g( (Java) Spring 2013

Java Programming: from the Beginning. Chapter 8 More Control Structures. CSc 2310: Principle of Programming g( (Java) Spring 2013 CSc 2310: Principle of Programming g( (Java) Spring 2013 Java Programming: from the Beginning Chapter 8 More Control Structures 1 Copyright 2000 W. W. Norton & Company. All rights reserved. 81 8.1 Exceptions

More information

Expression statements are formed by adding a semicolon to the end of certain types of expressions.

Expression statements are formed by adding a semicolon to the end of certain types of expressions. Expression statements are formed by adding a semicolon to the end of certain types of expressions. Variable declaration statements declare variables. int width, height, area; String hello = "Hello, world!";

More information

CSC Java Programming, Fall Java Data Types and Control Constructs

CSC Java Programming, Fall Java Data Types and Control Constructs CSC 243 - Java Programming, Fall 2016 Java Data Types and Control Constructs Java Types In general, a type is collection of possible values Main categories of Java types: Primitive/built-in Object/Reference

More information

Le L c e t c ur u e e 3 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Control Statements

Le L c e t c ur u e e 3 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Control Statements Course Name: Advanced Java Lecture 3 Topics to be covered Control Statements Introduction The control statement are used to control the flow of execution of the program. This execution order depends on

More information

Java Programming: from the Beginning

Java Programming: from the Beginning CSc 2310: Principle of Programming g( (Java) Spring 2013 Java Programming: from the Beginning Chapter 5 Arrays 1 Copyright 2000 W. W. Norton & Company. All rights reserved. Outline 5.1 Creating and Using

More information

Key Points. COSC 123 Computer Creativity. Java Decisions and Loops. Making Decisions Performing Comparisons. Making Decisions

Key Points. COSC 123 Computer Creativity. Java Decisions and Loops. Making Decisions Performing Comparisons. Making Decisions COSC 123 Computer Creativity Java Decisions and Loops Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) A decision is made by evaluating a condition in an if/

More information

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Java Decisions and Loops Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) A decision is made by evaluating a condition in an if/else

More information

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003 Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

More information

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception 22 November 2007 Ariel Shamir 1 Run-time Errors Sometimes

More information

Control Structures in Java if-else and switch

Control Structures in Java if-else and switch Control Structures in Java if-else and switch Lecture 4 CGS 3416 Spring 2017 January 23, 2017 Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 1 / 26 Control Flow Control flow refers to the specification

More information

C16b: Exception Handling

C16b: Exception Handling CISC 3120 C16b: Exception Handling Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/28/2018 CUNY Brooklyn College 1 Outline Exceptions Catch and handle exceptions (try/catch)

More information

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward.

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward. Introduction to Computation and Problem Solving Class 25: Error Handling in Java Prof. Steven R. Lerman and Dr. V. Judson Harward Goals In this session we are going to explore better and worse ways to

More information

Chapter 3. Selections

Chapter 3. Selections Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of

More information

Motivations. Chapter 3: Selections and Conditionals. Relational Operators 8/31/18. Objectives. Problem: A Simple Math Learning Tool

Motivations. Chapter 3: Selections and Conditionals. Relational Operators 8/31/18. Objectives. Problem: A Simple Math Learning Tool Chapter 3: Selections and Conditionals CS1: Java Programming Colorado State University Motivations If you assigned a negative value for radius in Listing 2.2, ComputeAreaWithConsoleInput.java, the program

More information

Exception in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.

Exception in thread main java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling. Exceptions 1 Handling exceptions A program will sometimes inadvertently ask the machine to do something which it cannot reasonably do, such as dividing by zero, or attempting to access a non-existent array

More information

Basic Control Structures

Basic Control Structures Chapter 4 Basic Control Structures 1 4.1 Performing Comparisons Most programs need the ability to test conditions and make decisions based on the outcomes of those tests. The primary tool for testing conditions

More information

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Third Look At Java Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Little Demo public class Test { public static void main(string[] args) { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]);

More information

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception Ariel Shamir 1 Run-time Errors Sometimes when the computer

More information

DM503 Programming B. Peter Schneider-Kamp.

DM503 Programming B. Peter Schneider-Kamp. DM503 Programming B Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm503/! VARIABLES, EXPRESSIONS & STATEMENTS 2 Values and Types Values = basic data objects 42 23.0 "Hello!" Types

More information

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp DM550 / DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ CALLING & DEFINING FUNCTIONS 2 Functions and

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions

More information

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Computer Programming, I. Laboratory Manual. Experiment #3. Selections Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #3

More information

Controls Structure for Repetition

Controls Structure for Repetition Controls Structure for Repetition So far we have looked at the if statement, a control structure that allows us to execute different pieces of code based on certain conditions. However, the true power

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions

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

Eng. Mohammed S. Abdualal

Eng. Mohammed S. Abdualal Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 3 Selections

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

Following is the general form of a typical decision making structure found in most of the programming languages:

Following is the general form of a typical decision making structure found in most of the programming languages: Decision Making Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined

More information

Full file at Chapter 2 - Inheritance and Exception Handling

Full file at   Chapter 2 - Inheritance and Exception Handling Chapter 2 - Inheritance and Exception Handling TRUE/FALSE 1. The superclass inherits all its properties from the subclass. ANS: F PTS: 1 REF: 76 2. Private members of a superclass can be accessed by a

More information

class objects instances Fields Constructors Methods static

class objects instances Fields Constructors Methods static Class Structure Classes A class describes a set of objects The objects are called instances of the class A class describes: Fields (instance variables)that hold the data for each object Constructors that

More information

PROGRAMMING FUNDAMENTALS

PROGRAMMING FUNDAMENTALS PROGRAMMING FUNDAMENTALS Q1. Name any two Object Oriented Programming languages? Q2. Why is java called a platform independent language? Q3. Elaborate the java Compilation process. Q4. Why do we write

More information

Programming - 2. Common Errors

Programming - 2. Common Errors Common Errors There are certain common errors and exceptions which beginners come across and find them very annoying. Here we will discuss these and give a little explanation of what s going wrong and

More information

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved. Chapter 4: Expressions Chapter 4 Expressions 1 Chapter 4: Expressions Operators Expressions are built from variables, constants, and operators. C has a rich collection of operators, including arithmetic

More information

Java Basic Programming Constructs

Java Basic Programming Constructs Java Basic Programming Constructs /* * This is your first java program. */ class HelloWorld{ public static void main(string[] args){ System.out.println( Hello World! ); A Closer Look at HelloWorld 2 This

More information

Control Structures in Java if-else and switch

Control Structures in Java if-else and switch Control Structures in Java if-else and switch Lecture 4 CGS 3416 Spring 2016 February 2, 2016 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful

More information

Statements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14

Statements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14 Statements Control Flow Statements Based on slides from K. N. King Bryn Mawr College CS246 Programming Paradigm So far, we ve used return statements and expression statements. Most of C s remaining statements

More information

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d. Chapter 4: Control Structures I (Selection) In this chapter, you will: Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba Exception handling Exception an indication of a problem that occurs during a program s execution. The name exception implies that the problem occurs infrequently. With exception

More information

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Chapter 8 Exception Handling CS 180 Sunil Prabhakar Department of Computer Science Purdue University Clarifications Auto cast from char to String does not happen. Cast between int and char happens automatically.

More information

Programmierpraktikum

Programmierpraktikum Programmierpraktikum Claudius Gros, SS2012 Institut für theoretische Physik Goethe-University Frankfurt a.m. 1 of 37 11/02/2012 05:24 PM Java - Control Flow 2 of 37 11/02/2012 05:24 PM controlling the

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and

More information

Chapter 3 Selection Statements

Chapter 3 Selection Statements Chapter 3 Selection Statements 3.1 Introduction Java provides selection statements that let you choose actions with two or more alternative courses. Selection statements use conditions. Conditions are

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

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

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15 Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions

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

Chapter 5. Exceptions. CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science. Dr. S.

Chapter 5. Exceptions. CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science. Dr. S. Chapter 5 Exceptions CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science Dr. S. HAMMAMI Objectives After you have read and studied this chapter, you

More information

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic BIT 3383 Java Programming Sem 1 Session 2011/12 Chapter 2 JAVA basic Objective: After this lesson, you should be able to: declare, initialize and use variables according to Java programming language guidelines

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

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

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages References Exceptions "Handling Errors with Exceptions", Java tutorial http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html CSE 413, Autumn 2005 Programming Languages http://www.cs.washington.edu/education/courses/413/05au/

More information

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017 Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 03: Control Flow Statements: Selection Instructor: AbuKhleif, Mohammad Noor Sep 2017 Instructor AbuKhleif, Mohammad Noor

More information

Exceptions. What exceptional things might our programs run in to?

Exceptions. What exceptional things might our programs run in to? Exceptions What exceptional things might our programs run in to? Exceptions do occur Whenever we deal with programs, we deal with computers and users. Whenever we deal with computers, we know things don

More information

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features: Lecture 28 Exceptions and Inner Classes Goals We are going to talk in more detail about two advanced Java features: Exceptions supply Java s error handling mechanism. Inner classes ease the overhead of

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

Std 12 Lesson-10 Exception Handling in Java ( 1

Std 12 Lesson-10 Exception Handling in Java (  1 Ch-10 : Exception Handling in Java 1) It is usually understood that a compiled program is error free and will always successfully. (a) complete (b) execute (c) perform (d) accomplish 2) In few cases a

More information

Fundamentals of Object Oriented Programming

Fundamentals of Object Oriented Programming INDIAN INSTITUTE OF TECHNOLOGY ROORKEE Fundamentals of Object Oriented Programming CSN- 103 Dr. R. Balasubramanian Associate Professor Department of Computer Science and Engineering Indian Institute of

More information

COMP-202: Foundations of Programming. Lecture 6: Conditionals Jackie Cheung, Winter 2016

COMP-202: Foundations of Programming. Lecture 6: Conditionals Jackie Cheung, Winter 2016 COMP-202: Foundations of Programming Lecture 6: Conditionals Jackie Cheung, Winter 2016 This Lecture Finish data types and order of operations Conditionals 2 Review Questions What is the difference between

More information

BBM 102 Introduction to Programming II Spring Exceptions

BBM 102 Introduction to Programming II Spring Exceptions BBM 102 Introduction to Programming II Spring 2018 Exceptions 1 Today What is an exception? What is exception handling? Keywords of exception handling try catch finally Throwing exceptions throw Custom

More information

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators Objectives Chapter 4: Control Structures I (Selection) In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.

Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops. Chapter 6 Loops 1 Iteration Statements C s iteration statements are used to set up loops. A loop is a statement whose job is to repeatedly execute some other statement (the loop body). In C, every loop

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

EXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) {

EXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) { EXCEPTION HANDLING We do our best to ensure program correctness through a rigorous testing and debugging process, but that is not enough. To ensure reliability, we must anticipate conditions that could

More information

Condi(onals and Loops

Condi(onals and Loops Condi(onals and Loops 1 Review Primi(ve Data Types & Variables int, long float, double boolean char String Mathema(cal operators: + - * / % Comparison: < > = == 2 A Founda(on for Programming any program

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Building Java Programs. Chapter 2: Primitive Data and Definite Loops Building Java Programs Chapter 2: Primitive Data and Definite Loops Copyright 2008 2006 by Pearson Education 1 Lecture outline data concepts Primitive types: int, double, char (for now) Expressions: operators,

More information

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. CSE 142, Summer 2002 Computer Programming 1. Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 1 Reading Readings and References»

More information

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1. Readings and References Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ Reading» Chapter 18, An Introduction to Programming and Object Oriented

More information

CMSC 202. Exceptions

CMSC 202. Exceptions CMSC 202 Exceptions Error Handling In the ideal world, all errors would occur when your code is compiled. That won t happen. Errors which occur when your code is running must be handled by some mechanism

More information

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 Motivations If you assigned a negative value for radius

More information

Chapter 4. Conditionals and recursion. 4.1 The modulus operator. 4.2 Conditional execution

Chapter 4. Conditionals and recursion. 4.1 The modulus operator. 4.2 Conditional execution Chapter 4 Conditionals and recursion 4.1 The modulus operator The modulus operator works on integers (and integer expressions) and yields the remainder when the first operand is divided by the second.

More information

Programming for Electrical and Computer Engineers. Loops

Programming for Electrical and Computer Engineers. Loops Programming for Electrical and Computer Engineers Loops Dr. D. J. Jackson Lecture 6-1 Iteration Statements C s iteration statements are used to set up loops. A loop is a statement whose job is to repeatedly

More information

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging Outline Computer programming Debugging Hints Gathering evidence Common C errors "Education is a progressive discovery of our own ignorance." Will Durant T.U. Cluj-Napoca - Computer Programming - lecture

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

CIS133J. Working with Numbers in Java

CIS133J. Working with Numbers in Java CIS133J Working with Numbers in Java Contents: Using variables with integral numbers Using variables with floating point numbers How to declare integral variables How to declare floating point variables

More information

Expressions & Flow Control

Expressions & Flow Control Objectives Distinguish between instance and local variables 4 Expressions & Flow Control Describe how instance variables are initialized Identify and correct a Possible reference before assignment compiler

More information

COE318 Lecture Notes Week 10 (Nov 7, 2011)

COE318 Lecture Notes Week 10 (Nov 7, 2011) COE318 Software Systems Lecture Notes: Week 10 1 of 5 COE318 Lecture Notes Week 10 (Nov 7, 2011) Topics More about exceptions References Head First Java: Chapter 11 (Risky Behavior) The Java Tutorial:

More information

Values in 2 s Complement

Values in 2 s Complement Values in 2 s Complement Java uses an encoding known as 2 s complement 1, which means that negative numbers are represented by inverting 2 all of the bits in a value, then adding 1 to the result. For example,

More information

Topics. Chapter 5. Equality Operators

Topics. Chapter 5. Equality Operators Topics Chapter 5 Flow of Control Part 1: Selection Forming Conditions if/ Statements Comparing Floating-Point Numbers Comparing Objects The equals Method String Comparison Methods The Conditional Operator

More information

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0 6 Statements 43 6 Statements The statements of C# do not differ very much from those of other programming languages. In addition to assignments and method calls there are various sorts of selections and

More information

09/08/2017 CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations.

09/08/2017 CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations. CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations. 1 RUNTIME ERRORS All of us have experienced syntax errors. This

More information

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA DECISION STRUCTURES: USING IF STATEMENTS IN JAVA S o far all the programs we have created run straight through from start to finish, without making any decisions along the way. Many times, however, you

More information

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time Tester vs. Controller Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG For effective illustrations, code examples will mostly be written in the form of a tester

More information

10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS

10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS JAVA CONTROL STATEMENTS Introduction to Control statements are used in programming languages to cause the flow of control to advance and branch based on changes to the state of a program. In Java, control

More information

Elementary Programming

Elementary Programming Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Learn ingredients of elementary programming: data types [numbers, characters, strings] literal

More information

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade; Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

More information

Basics of Java Programming

Basics of Java Programming Basics of Java Programming Lecture 2 COP 3252 Summer 2017 May 16, 2017 Components of a Java Program statements - A statement is some action or sequence of actions, given as a command in code. A statement

More information

When we reach the line "z = x / y" the program crashes with the message:

When we reach the line z = x / y the program crashes with the message: CSCE A201 Introduction to Exceptions and File I/O An exception is an abnormal condition that occurs during the execution of a program. For example, divisions by zero, accessing an invalid array index,

More information

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous Assignment 3 Methods Review CSC 123 Fall 2018 Notes: All homework must be submitted via e-mail. All parts of assignment must be submitted in a single e-mail with multiple attachments when required. Notes:

More information

CSCI Object Oriented Design: Java Review Errors George Blankenship. Java Review - Errors George Blankenship 1

CSCI Object Oriented Design: Java Review Errors George Blankenship. Java Review - Errors George Blankenship 1 CSCI 6234 Object Oriented Design: Java Review Errors George Blankenship Java Review - Errors George Blankenship 1 Errors Exceptions Debugging Java Review Topics Java Review - Errors George Blankenship

More information

Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY. Arithmetic Operators

Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY. Arithmetic Operators Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY Arithmetic Operators There are four basic arithmetic operations: OPERATOR USE DESCRIPTION + op1 + op2 Adds op1 and op2 - op1 + op2 Subtracts

More information

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved. Chapter 9 Exception Handling Copyright 2016 Pearson Inc. All rights reserved. Last modified 2015-10-02 by C Hoang 9-2 Introduction to Exception Handling Sometimes the best outcome can be when nothing unusual

More information

Exception Handling CSCI 201 Principles of Software Development

Exception Handling CSCI 201 Principles of Software Development Exception Handling CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Outline Program USC CSCI 201L 2/19 Exception Handling An exception is an indication of a problem

More information

CSCI Object-Oriented Design. Java Review Topics. Program Errors. George Blankenship 1. Java Review Errors George Blankenship

CSCI Object-Oriented Design. Java Review Topics. Program Errors. George Blankenship 1. Java Review Errors George Blankenship CSCI 6234 Object Oriented Design: Java Review Errors George Blankenship George Blankenship 1 Errors Exceptions Debugging Java Review Topics George Blankenship 2 Program Errors Types of errors Compile-time

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