Tutorial 3: Unit tests and JUnit

Size: px
Start display at page:

Download "Tutorial 3: Unit tests and JUnit"

Transcription

1 Tutorial 3: Unit tests and JUnit Runtime logic errors, such as contract violations, are among the more frequent in a poorly debugged program. Logic error should be fixed. However, to fix an error we need to identify it first. Testing is one of the more powerful ways of identifying bugs. However, we should keep in mind that testing only reveals errors; it does not proof their absence. In this tutorial we will be exercising unit tests and the JUnit framework. In addition, we will see good examples of Java code. Unit testing allows us to check the correctness of a simple unit of code the smallest testable part of a program. Ideally unit tests should be simple enough for a fast running time, independent from each other, and should be independent of their execution order. With a Unit Testing framework, such as JUnit, unit test will run automatically each time the code is compiled. Tests should be written before the code. This is the basic principle of the test-driven approach to software development. In this approach, 1. First, we write the tests 2. Second we write the simplest code that passes the test 3. and then, we improve the quality of the written code. For the sake of introduction to JUnit and unit tests in software development we will be use the problem Pirates described in the appendix below. 0. Thoroughly read the problem description given in the appendix. Make sure you fully understand the problem. Simulate example 1 using pen and paper, if necessary. Repeat for example 2. Should you have any doubt about the problem, do not hesitate to ask; 1. To the best of our knowledge, there is no other way of solving this problem than simulate the procedure of the Machiavellian, and irascible captain. 2. One way of performing this simulation starts by converting the input into a list of elements representing the crew circle in the deck. For instance, the input 3151 would be converted into the following list of characters ('E','E','E','F','E','E','E','E','E','F'), where E refers to a enemy, and F to a friend. 3. Based on this list, we can develop a function that checks whether a given step n would kill any captain friend, let s call this function throwoverboardwithstep (int n). It returns true if the captain or one of his friends will be thrown overboard, false otherwise. 4. Now what we need to is call the above function, for n=1, 2, 3,, until a step is found such as no captain friend is killed. 5. The problem description states that all inputs have a solution, therefore the above sequence of calls will surely ends. POO Tutorial 3-1

2 6. No need to say that we are going to implement the above mentioned procedure within a class. Let that class be PirateSolver. 7. Once you got a clear picture of what needs to be done, and how code will be organized, we can move to (test driven) implementation. 8. Open eclipse, and create a new java project called Pirates; 9. Add to the project a new class, and call it Main. This class, the client, will read as: import java.util.scanner; public class Main { public static void main(string [] args) { Scanner sc = new Scanner (System.in); PirateSolver solver = new PirateSolver(sc.next()); System.out.println(solver.solution()); sc.close(); 10. We will now prepare the project for test-driven development. Add to the project a new JUnit Test Case (File -> New > Other > Java > JUnit JUnit Test Case). 11. At the top select New JUnit 4 test and name it PiratesUnitTests, then press Finnish. 12. A dialog may open asking this: JUnit 4 is not on the build path. Do you want to add it? If this appears press OK. 13. Now, within the file PiratesUnitTests.java we should have: import static org.junit.assert.*; import org.junit.test; public class PiratesUnitTests public void test() { fail("not yet implemented"); 14. Rigth after the last import, add: import java.util.*; 15. The first test we will develop will test the behaviour of the PirateSolver constructor A constructor can be seen as a special function, with the same name as the class and without return type, that will be called automatically each time a new class object is created It will be within this constructor that the process described in 2 will take place. For this, replace the function named test() above by the following test: POO Tutorial 3-2

3 @Test public void testconstructor() { PirateSolver p = new PirateSolver("3151"); List<Character> sa = new ArrayList<Character>(); // line 4 Collections.addAll(sa, 'E','E','E','F','E','E','E','E','E','F'); // line 5 assertequals(p.getcrew(), sa); PirateSolver q = new PirateSolver(" "); assertequals(q.getcrew().size(), 18); Later on this course we will fully understand line 4 and 5 above. For now it is enough to realize that, in line 4, we are creating a list of characters, named sa, implemented as an ArrayList. On the other hand, in line 5 we are adding a set of elements to the list sa. 16. In this test we are using assertequals using two integer arguments. See below, the many possible arguments that assertequals may run with. 17. Run the test just created as JUnit Test (Run -> Run As -> JUnit test). 18. At this time, we have just created the test, and run it before writing any program code. We can observe immediately that the test is doing its job by providing us with a red bar indicating that the test has failed it is the test job to fail whenever no source code for testing exists. 19. Now write the simplest code that passes this test. That is, add the class PirateSolver to the project and implement its constructor. That is complete the code bellow: import java.util.*; class PirateSolver { private List<Character> piratelist; private int noenemies; public PirateSolver(String s) { piratelist = new ArrayList<Character>(); int len = s.length(); noenemies = 0; // To be completed. //From String s form list piratelist as specified in step Also implement the public method getcrew() that returns the list representing the crew (i.e., the variable piratelist). 21. You are going to need to know the following. To assess the character at position i in the String s use Character c = s.charat(i); To convert a character c to its corresponding integer i use: int i = Character.digit(c, 10); POO Tutorial 3-3

4 To add a Character c to the piratelist use at position j; piratelist.add(j, c); or to add c at the end of the list use: piratelist.add(c); 22. Now run the test again. 23. If everything was ok, the JUnit offer you a magnificent green bar, denoting that the code has passed the test. 24. We can now refine your constructor code, if necessary. 25. Now, let s write the test for our function boolean throwoverboardwithstep (int n). This test can read public void testthrowoverboardwithstep() { PirateSolver p = new PirateSolver("3151"); asserttrue(p.throwoverboardwithstep(1)); assertfalse(p.throwoverboardwithstep(3)); 26. After writing this test, should we need to say anything else about the behaviour of throwoverboardwithstep? As you can see, sometimes, a test can be also a convenient way of documenting code. 27. Now and only now write the code for public boolean throwoverboardwithstep (int n), as described in Run all tests again. Did you get the green bar? Great! 29. Now write a test for the function public int solution(). 30. Write the simplest code that passes the test just written. Refine it. 31. Finally, submit your program (not the tests) to POO 2016/17 mooshak ( problem E, and get and an Accepted. Note: The file where unit tests are implemented: PiratesUnitTests.java, cannot be submitted to Mooshak. or a Compile Time Error will be issued. The Java environment currently installed in Mooshak does not have the classes required to support unit tests. Please copy, comment, and past the developed unit tests to the Main.java file. 32. There are many other things that we can do with the JUnit 4.0 framework. Here is a list of the available assertions in JUnit 4.0. Possible arguments are given within parenthesis. asserttrue POO Tutorial 3-4

5 (boolean) Reports an error if boolean is false (String, boolean) Adds error String to output assertfalse (bolean) Reports an error if boolean is true (String, boolean) Adds error String to output assertnull (Object) Reports an error if object is not null (String, Object) Adds error String to output assertnotnull (Object) Reports an error if object is null (String, Object) Adds error String to output assertsame (Object, Object) Reports error if two objects are not identical (String, Object, Object) Adds error String to output assertnotsame (Object, Object) Reports error if two objects are identical (Styring, Object, Object) Adds error String to output assertequals (Object, Object) Reports error if two objects are not equal (String, Object, Object) Adds error String to output (String, String) Reports delta between two strings if the two strings are not equal (String, String, String) Adds error String to output (boolean, boolean) Reports error if the two booleans are not equal (String, boolean, boolean) Adds error String to output (byte,byte) Reports error if the two bytes are not equal (String, byte, byte) Adds error String to output (char, char)reports error if two chars are not equal (String, char, char) Adds error String to output (short, short) Reports error if two shorts are not equal (String, short, short) Adds error String to output (int, int) Reports error if two ints are not equal (String, int, int) Adds error String to output (long, long) Reports error if two longs are not equal (String, long, long) Adds error String to output (float, float, float) Reports error if the first two floats are not within range specified by third float (String, float, float, float) Adds error String to output (double, double, double) Reports error if the first two doubles are not within range specified by third double (String, double, double, double) Adds error String to output (object[], object[]); Reports error if either the legnth or element of each array are not equal. New to JUnit 4 (String, object[], object[]) Adds error String to output. 33. [Advanced: Return here later] Besides that, you can use the arguments of for testing important behaviour of your code, such as Exception throwing, or code running time. POO Tutorial 3-5

6 34. Supposed that you want to avoid clonage in class PirateSolver. You can write a test for checking whether the appropriated Exception is actually being thrown each time the clone() method is invoked. Such a test can be given (expected=clonenotsupportedexception.class) public void testclonenotsupportedexception() throws CloneNotSupportedException { PirateSolver b1 = new PirateSolver("3151"); PirateSolver b2 = (PirateSolver) b1.clone(); 35. Also, we can make sure that your code does not take more than a certain amount of time to execute. For instance, you can make sure that solving a given instance of our problem does not take more than (timeout=3000) public void testeficientsolve() { PirateSolver p = new PirateSolver("4444"); assertequals(p.solution(), 5851); 36. Learn more on JUnit at POO Tutorial 3-6

7 Appendix: Pirates In a dreadful storm, Malbolge, the terrifying pirate ship raging the Algarve coast, can only be saved by lightening its cargo. The Machiavellian, irascible captain grabbed this opportunity to get rid of his enemies in the crew, whom, he believed, were plotting against him. To achieve this, he convinced all the men to form a circle on the deck and then, starting at one of them, every nth man will to be thrown overboard, in a way that appeared random to the crew, who are not particularly gifted mathematicians. Astutely, the captain managed to set up the sitting arrangement beforehand in such a way that all his enemies would be thrown out. However, the captain is thick as a brick and forgot the step number (the step number is the n, in the phrase every nth man above.) This is dangerous, because unless he is able to recall the right step immediately, some of his friends, and perhaps the captain himself, may end up feeding the sharks. Task Write a program that, given a sequence of numbers describing the sitting arrangement of friends and enemies around the circle, computes the step n by which all captain s enemies are cast overboard, before that happens to any of the captain s friends. The sequence is coded by a decimal number where the leftmost digit stands for the first few enemies, the next digit for the first few friends, then enemies again, and so on. The throw overboard counting starts at the first enemy. For example, the number 2251 represents a sequence starting with two enemies, followed by two friends, then five enemies and finally one friend. If n is 5, the first man to be thrown overboard is indeed one of the enemies, the first one in the second group. Input The input contains one line only with an integer number F representing the sequence of captain enemies and friends (including himself) in the circle, as explained. F is such that 10 < F < , has an even number of digits, and its decimal representation does not contain any zeros. Output The output shall contain only one line, in which there is one positive integer representing the smallest step n by which the captain and all his friends are saved and all the captain enemies are thrown overboard. More precisely, the smallest step such that all enemies are thrown overboard before that would happen to any of the friends. (We suppose that when all the enemies are gone, the captain will suspend the operation.) Remember, the captain holds a feasible sequence. Therefore, all inputs have a solution that will not be greater than Example of input 1 Example of output Example of input 2 Example of output Credits: Problem D from TIUP 2008, Stage 3, May 21, Universidade do Algarve POO Tutorial 3-7

Binghamton University. CS-140 Fall Unit Testing

Binghamton University. CS-140 Fall Unit Testing Unit Testing 1 Test Early, Test Often 2 Informal Unit Testing package lab05; import java.lang.illegalargumentexception; public class ProfTest { public static void main(string[] args) { System.out.println("Professor

More information

Binghamton University. CS-140 Fall Unit Testing

Binghamton University. CS-140 Fall Unit Testing Unit Testing 1 Test Early, Test Often 2 Informal Unit Testing public static void main(string[] args) { Rectangle rect = new Rectangle ( new Point(20,30), 20,40 ); System.out.println("Created " + rect);

More information

CSCE 747 Unit Testing Laboratory Name(s):

CSCE 747 Unit Testing Laboratory Name(s): CSCE 747 Unit Testing Laboratory Name(s): You have been hired to test our new calendar app! Congrats!(?) This program allows users to book meetings, adding those meetings to calendars maintained for rooms

More information

CS201 - Assignment 3, Part 1 Due: Friday February 28, at the beginning of class

CS201 - Assignment 3, Part 1 Due: Friday February 28, at the beginning of class CS201 - Assignment 3, Part 1 Due: Friday February 28, at the beginning of class One of the keys to writing good code is testing your code. This assignment is going to introduce you and get you setup to

More information

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle Boggle If you are not familiar with the game Boggle, the game is played with 16 dice that have letters on all faces. The dice are randomly deposited into a four-by-four grid so that the players see the

More information

Software-Architecture Unit Testing (JUnit)

Software-Architecture Unit Testing (JUnit) Software-Architecture Unit Testing (JUnit) Prof. Dr. Axel Böttcher 10. Oktober 2011 Objectives Understand the concept of unit testing Know how to write unit tests Know when to write unit tests Why Unit-Testing?

More information

Software Testing Prof. Meenakshi D Souza Department of Computer Science and Engineering International Institute of Information Technology, Bangalore

Software Testing Prof. Meenakshi D Souza Department of Computer Science and Engineering International Institute of Information Technology, Bangalore Software Testing Prof. Meenakshi D Souza Department of Computer Science and Engineering International Institute of Information Technology, Bangalore Lecture 04 Software Test Automation: JUnit as an example

More information

Video 2.1. Arvind Bhusnurmath. Property of Penn Engineering, Arvind Bhusnurmath. SD1x-2 1

Video 2.1. Arvind Bhusnurmath. Property of Penn Engineering, Arvind Bhusnurmath. SD1x-2 1 Video 2.1 Arvind Bhusnurmath SD1x-2 1 Topics Why is testing important? Different types of testing Unit testing SD1x-2 2 Software testing Integral part of development. If you ship a software with bugs,

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

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

11 Using JUnit with jgrasp

11 Using JUnit with jgrasp 11 Using JUnit with jgrasp jgrasp includes an easy to use plug-in for the JUnit testing framework. JUnit provides automated support for unit testing of Java source code, and its utility has made it a de

More information

Introduc)on to tes)ng with JUnit. Workshop 3

Introduc)on to tes)ng with JUnit. Workshop 3 Introduc)on to tes)ng with JUnit Workshop 3 We have to deal with errors Early errors are usually syntax errors. The compiler will spot these. Later errors are usually logic errors. The compiler cannot

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

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

Dynamic Analysis Techniques Part 2

Dynamic Analysis Techniques Part 2 oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 1 Software Design (F28SD2) Dynamic Analysis Techniques Part 2 Andrew Ireland School of Mathematical & Computer Sciences Heriot-Watt University

More information

CS159. Nathan Sprague. September 30, 2015

CS159. Nathan Sprague. September 30, 2015 CS159 Nathan Sprague September 30, 2015 Testing Happens at Multiple Levels Unit Testing - Test individual classes in isolation. Focus is on making sure that each method works according to specification.

More information

Testing on Steriods EECS /30

Testing on Steriods EECS /30 1/30 Testing on Steriods EECS 4315 www.eecs.yorku.ca/course/4315/ How to test code? 2/30 input code output Provide the input. Run the code. Compare the output with the expected output. White box testing

More information

Test-Driven Development (a.k.a. Design to Test) CSE260, Computer Science B: Honors Stony Brook University

Test-Driven Development (a.k.a. Design to Test) CSE260, Computer Science B: Honors Stony Brook University Test-Driven Development (a.k.a. Design to Test) CSE260, Computer Science B: Honors Stony Brook University http://www.cs.stonybrook.edu/~cse260 Person-hours Labor is sometimes measured in person-hours,

More information

Motivating Example: Two Types of Errors (2) Test-Driven Development (TDD) with JUnit. Motivating Example: Two Types of Errors (1)

Motivating Example: Two Types of Errors (2) Test-Driven Development (TDD) with JUnit. Motivating Example: Two Types of Errors (1) Motivating Example: Two Types of Errors (2) Test-Driven Development (TDD) with JUnit EECS2030 B: Advanced Object Oriented Programming Fall 2018 CHEN-WEI WANG Approach 1 Specify: Indicate in the method

More information

There are several files including the start of a unit test and the method stubs in MindNumber.java. Here is a preview of what you will do:

There are several files including the start of a unit test and the method stubs in MindNumber.java. Here is a preview of what you will do: Project MindNumber Collaboration: Solo. Complete this project by yourself with optional help from section leaders. Do not work with anyone else, do not copy any code directly, do not copy code indirectly

More information

Test-Driven Development (TDD) with JUnit

Test-Driven Development (TDD) with JUnit Test-Driven Development (TDD) with JUnit EECS2030 B: Advanced Object Oriented Programming Fall 2018 CHEN-WEI WANG Motivating Example: Two Types of Errors (1) Consider two kinds of exceptions for a counter:

More information

Announcements. Lab tomorrow. Quiz Thursday P3 due Friday. Exceptions and unit testing

Announcements. Lab tomorrow. Quiz Thursday P3 due Friday. Exceptions and unit testing Announcements Lab tomorrow Exceptions and unit testing Quiz Thursday P3 due Friday Follow-ups Exceptions and Try-catch Using try-catch with loops Comparison to switch vs. if-else if Realistic examples

More information

Design Patterns: State, Bridge, Visitor

Design Patterns: State, Bridge, Visitor Design Patterns: State, Bridge, Visitor State We ve been talking about bad uses of case statements in programs. What is one example? Another way in which case statements are sometimes used is to implement

More information

In this lab we will practice creating, throwing and handling exceptions.

In this lab we will practice creating, throwing and handling exceptions. Lab 5 Exceptions Exceptions indicate that a program has encountered an unforeseen problem. While some problems place programmers at fault (for example, using an index that is outside the boundaries of

More information

VARIABLES AND TYPES CITS1001

VARIABLES AND TYPES CITS1001 VARIABLES AND TYPES CITS1001 Scope of this lecture Types in Java the eight primitive types the unlimited number of object types Values and References The Golden Rule Primitive types Every piece of data

More information

CS-201 Introduction to Programming with Java

CS-201 Introduction to Programming with Java CS-201 Introduction to Programming with Java California State University, Los Angeles Computer Science Department Lecture X: Methods II Passing Arguments Passing Arguments methods can accept outside information

More information

Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Notes Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and

More information

COE318 Lecture Notes Week 9 (Oct 31, 2011)

COE318 Lecture Notes Week 9 (Oct 31, 2011) COE318 Software Systems Lecture Notes: Week 9 1 of 12 COE318 Lecture Notes Week 9 (Oct 31, 2011) Topics Casting reference variables equals() and hashcode() overloading Collections and ArrayList utilities

More information

Software Development Tools. COMP220/COMP285 Sebastian Coope Eclipse and JUnit: Creating and running a JUnit test case

Software Development Tools. COMP220/COMP285 Sebastian Coope Eclipse and JUnit: Creating and running a JUnit test case Software Development Tools COMP220/COMP285 Sebastian Coope Eclipse and JUnit: Creating and running a JUnit test case These slides are mainly based on Java Development with Eclipse D.Gallardo et al., Manning

More information

Tools for Unit Test - JUnit

Tools for Unit Test - JUnit Tools for Unit Test - JUnit Conrad Hughes School of Informatics Slides thanks to Stuart Anderson 15 January 2010 Software Testing: Lecture 2 1 JUnit JUnit is a framework for writing tests Written by Erich

More information

AP Computer Science Unit 1. Writing Programs Using BlueJ

AP Computer Science Unit 1. Writing Programs Using BlueJ AP Computer Science Unit 1. Writing Programs Using BlueJ 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

More information

INTRODUCTION TO JAVA PROGRAMMING JAVA FUNDAMENTALS PART 2

INTRODUCTION TO JAVA PROGRAMMING JAVA FUNDAMENTALS PART 2 INTRODUCTION TO JAVA PROGRAMMING JAVA FUNDAMENTALS PART 2 Table of Contents Introduction to JUnit 4 What is a Test Driven approach? 5 The benefits of a Test Driven Approach 6 What is Continuous Integration?

More information

Assertions, pre/postconditions

Assertions, pre/postconditions Programming as a contract Assertions, pre/postconditions Assertions: Section 4.2 in Savitch (p. 239) Specifying what each method does q Specify it in a comment before method's header Precondition q What

More information

Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Notes Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and

More information

print statements, debugger expressions, test scripts. Writing expressions in a debugger only that t a program works now. An application typically

print statements, debugger expressions, test scripts. Writing expressions in a debugger only that t a program works now. An application typically JUnit testing Current practice print statements, debugger expressions, test scripts. Writing expressions in a debugger only that t a program works now. An application typically undergoes many changes over

More information

COMP 110 Programming Exercise: Simulation of the Game of Craps

COMP 110 Programming Exercise: Simulation of the Game of Craps COMP 110 Programming Exercise: Simulation of the Game of Craps Craps is a game of chance played by rolling two dice for a series of rolls and placing bets on the outcomes. The background on probability,

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

Thinking Functionally

Thinking Functionally Thinking Functionally Dan S. Wallach and Mack Joyner, Rice University Copyright 2016 Dan S. Wallach, All Rights Reserved Reminder: Fill out our web form! Fill this out ASAP if you haven t already. http://goo.gl/forms/arykwbc0zy

More information

CS 101 Fall 2005 Midterm 2 Name: ID:

CS 101 Fall 2005 Midterm 2 Name:  ID: This exam is open text book but closed-notes, closed-calculator, closed-neighbor, etc. Questions are worth different amounts (in particular, the final two questions are worth substantially more than any

More information

public static boolean isoutside(int min, int max, int value)

public static boolean isoutside(int min, int max, int value) See the 2 APIs attached at the end of this worksheet. 1. Methods: Javadoc Complete the Javadoc comments for the following two methods from the API: (a) / @param @param @param @return @pre. / public static

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

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

AP Computer Science Unit 1. Writing Programs Using BlueJ

AP Computer Science Unit 1. Writing Programs Using BlueJ AP Computer Science Unit 1. Writing Programs Using BlueJ 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

More information

Introduction to Java Unit 1. Using BlueJ to Write Programs

Introduction to Java Unit 1. Using BlueJ to Write Programs Introduction to Java Unit 1. Using BlueJ to Write Programs 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

More information

COMP 111. Introduction to Computer Science and Object-Oriented Programming. Week 3

COMP 111. Introduction to Computer Science and Object-Oriented Programming. Week 3 COMP 111 Introduction to Computer Science and Object-Oriented Programming Tasks and Tools download submit edit Web-CAT compile unit test view results Working with Java Classes You Use You Complete public

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

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

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

Reading Input from Text File

Reading Input from Text File Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Lab 5 Reading Input from Text File Eng. Mohammed Alokshiya November 2, 2014 The simplest

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

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false. CS101, Mock Boolean Conditions, If-Then Boolean Expressions and Conditions The physical order of a program is the order in which the statements are listed. The logical order of a program is the order in

More information

16-Dec-10. Consider the following method:

16-Dec-10. Consider the following method: Boaz Kantor Introduction to Computer Science IDC Herzliya Exception is a class. Java comes with many, we can write our own. The Exception objects, along with some Java-specific structures, allow us to

More information

CSE 331 Final Exam 3/16/15 Sample Solution

CSE 331 Final Exam 3/16/15 Sample Solution Question 1. (12 points, 3 each) A short design exercise. Suppose Java did not include a Set class in the standard library and we need to store a set of Strings for an application. We know that the maximum

More information

Week 3 Classes and Objects

Week 3 Classes and Objects Week 3 Classes and Objects written by Alexandros Evangelidis, adapted from J. Gardiner et al. 13 October 2015 1 Last Week Last week, we looked at some of the different types available in Java, and the

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

Procedural Java. Procedures and Static Class Methods. Functions. COMP 210: Object-Oriented Programming Lecture Notes 2.

Procedural Java. Procedures and Static Class Methods. Functions. COMP 210: Object-Oriented Programming Lecture Notes 2. COMP 210: Object-Oriented Programming Lecture Notes 2 Procedural Java Logan Mayfield In these notes we look at designing, implementing, and testing basic procedures in Java. We will rarely, perhaps never,

More information

Oracle 1Z Java SE 8 Programmer I. Download Full Version :

Oracle 1Z Java SE 8 Programmer I. Download Full Version : Oracle 1Z0-808 Java SE 8 Programmer I Download Full Version : https://killexams.com/pass4sure/exam-detail/1z0-808 QUESTION: 121 And the commands: Javac Jump.java Java Jump crazy elephant is always What

More information

Java Programming. Atul Prakash

Java Programming. Atul Prakash Java Programming Atul Prakash Java Language Fundamentals The language syntax is similar to C/ C++ If you know C/C++, you will have no trouble understanding Java s syntax If you don't, it will be easier

More information

Tools for Unit Test JUnit

Tools for Unit Test JUnit Tools for Unit Test JUnit Stuart Anderson JUnit is a framework for writing tests JUnit 1 Written by Erich Gamma (Design Patterns) and Kent Beck (extreme Programming) JUnit uses Java s reflection capabilities

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

Principles of Software Construction: Objects, Design, and Concurrency (Part 2: Designing (Sub )Systems)

Principles of Software Construction: Objects, Design, and Concurrency (Part 2: Designing (Sub )Systems) Principles of Software Construction: Objects, Design, and Concurrency (Part 2: Designing (Sub )Systems) More Analysis for Functional Correctness Jonathan Aldrich Charlie Garrod School of Computer Science

More information

AP Computer Science Unit 1. Programs

AP Computer Science Unit 1. Programs AP Computer Science Unit 1. Programs Open DrJava. Under the File menu click on New Java Class and the window to the right should appear. Fill in the information as shown and click OK. This code is generated

More information

Computational Expression

Computational Expression Computational Expression Variables, Primitive Data Types, Expressions Janyl Jumadinova 28-30 January, 2019 Janyl Jumadinova Computational Expression 28-30 January, 2019 1 / 17 Variables Variable is a name

More information

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java

More information

6.005 Elements of Software Construction Fall 2008

6.005 Elements of Software Construction Fall 2008 MIT OpenCourseWare http://ocw.mit.edu 6.005 Elements of Software Construction Fall 2008 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. 6.005 elements

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

CSE 331 Summer 2016 Final Exam. Please wait to turn the page until everyone is told to begin.

CSE 331 Summer 2016 Final Exam. Please wait to turn the page until everyone is told to begin. Name The exam is closed book, closed notes, and closed electronics. Please wait to turn the page until everyone is told to begin. Score / 54 1. / 12 2. / 12 3. / 10 4. / 10 5. / 10 Bonus: 1. / 6 2. / 4

More information

Stage 11 Array Practice With. Zip Code Encoding

Stage 11 Array Practice With. Zip Code Encoding A Review of Strings You should now be proficient at using strings, but, as usual, there are a few more details you should know. First, remember these facts about strings: Array Practice With Strings are

More information

ASSIGNMENT 5 Data Structures, Files, Exceptions, and To-Do Lists

ASSIGNMENT 5 Data Structures, Files, Exceptions, and To-Do Lists ASSIGNMENT 5 Data Structures, Files, Exceptions, and To-Do Lists COMP-202B, Winter 2009, All Sections Due: Tuesday, April 14, 2009 (23:55) You MUST do this assignment individually and, unless otherwise

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

Learning objectives. Reading carefully. Managing your time. CS2110 Fall 2017 Assignment A1. PhD Genealogy. See CMS for the due date

Learning objectives. Reading carefully. Managing your time. CS2110 Fall 2017 Assignment A1. PhD Genealogy. See CMS for the due date 1 CS2110 Fall 2017 Assignment A1 PhD Genealogy Website http://genealogy.math.ndsu.nodak.edu contains the PhD genealogy of about 214,100 mathematicians and computer scientists, showing their PhD advisors

More information

CSE 143 SAMPLE MIDTERM

CSE 143 SAMPLE MIDTERM CSE 143 SAMPLE MIDTERM 1. (5 points) In some methods, you wrote code to check if a certain precondition was held. If the precondition did not hold, then you threw an exception. This leads to robust code

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

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

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

Unit Testing & Testability

Unit Testing & Testability CMPT 473 Software Quality Assurance Unit Testing & Testability Nick Sumner - Fall 2014 Levels of Testing Recall that we discussed different levels of testing for test planning: Unit Tests Integration Tests

More information

Test automation / JUnit. Building automatically repeatable test suites

Test automation / JUnit. Building automatically repeatable test suites Test automation / JUnit Building automatically repeatable test suites Test automation n Test automation is software that automates any aspect of testing n Generating test inputs and expected results n

More information

Test automation Test automation / JUnit

Test automation Test automation / JUnit Test automation Test automation / JUnit Building automatically repeatable test suites Test automation is software that automates any aspect of testing Generating test inputs and expected results Running

More information

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS These are sample pages from Kari Laitinen s book "A Natural Introduction to Computer Programming with Java". For more information, please visit http://www.naturalprogramming.com/javabook.html CHAPTER 5

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

CS11 Advanced Java. Winter Lecture 2

CS11 Advanced Java. Winter Lecture 2 CS11 Advanced Java Winter 2011-2012 Lecture 2 Today s Topics n Assertions n Java 1.5 Annotations n Classpaths n Unit Testing! n Lab 2 hints J Assertions! n Assertions are a very useful language feature

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/ OBJECT-ORIENTED PROGRAMMING IN JAVA 2 Programming

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

Test Execution and Automation. CSCE Lecture 15-03/20/2018

Test Execution and Automation. CSCE Lecture 15-03/20/2018 Test Execution and Automation CSCE 747 - Lecture 15-03/20/2018 Executing Tests We ve covered many techniques to derive test cases. How do you run them on the program? You could run the code and check results

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

Testing. Topics. Types of Testing. Types of Testing

Testing. Topics. Types of Testing. Types of Testing Topics 1) What are common types of testing? a) Testing like a user: through the UI. b) Testing like a dev: through the code. 2) What makes a good bug report? 3) How can we write code to test code (via

More information

Inheritance and Testing Spring 2018 Exam Prep 4: February 11, 2019

Inheritance and Testing Spring 2018 Exam Prep 4: February 11, 2019 CS 61B Inheritance and Testing Spring 2018 Exam Prep 4: February 11, 2019 1 Playing with Puppers Suppose we have the Dog and Corgi classes which are a defined below with a few methods but no implementation

More information

CSE 331 Final Exam 6/5/17. Name UW ID#

CSE 331 Final Exam 6/5/17. Name UW ID# Name UW ID# There are 10 questions worth a total of 100 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. The exam is closed book, closed notes,

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

Lecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning

Lecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning Lecture 1 Contracts 15-122: Principles of Imperative Computation (Fall 2018) Frank Pfenning In these notes we review contracts, which we use to collectively denote function contracts, loop invariants,

More information

Exception-Handling Overview

Exception-Handling Overview م.عبد الغني أبوجبل Exception Handling No matter how good a programmer you are, you cannot control everything. Things can go wrong. Very wrong. When you write a risky method, you need code to handle the

More information

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a Spring 2017 Name: TUID: Page Points Score 1 28 2 18 3 12 4 12 5 15 6 15 Total: 100 Instructions The exam is closed book, closed notes. You may not use a calculator, cell phone, etc. i Some API Reminders

More information

Lecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning

Lecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning Lecture 1 Contracts 15-122: Principles of Imperative Computation (Spring 2018) Frank Pfenning In these notes we review contracts, which we use to collectively denote function contracts, loop invariants,

More information

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal The ArrayList class CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Describe the ArrayList class Discuss important methods of this class Describe how it can be used in modeling Much of the information

More information

Introduction to JUnit

Introduction to JUnit Introduction to JUnit Minsoo Ryu Hanyang University History Kent Beck developed the first xunit automated test tool for Smalltalk in mid-90 s Beck and Gamma (of design patterns Gang of Four) developed

More information

Fundamentals of Programming Data Types & Methods

Fundamentals of Programming Data Types & Methods Fundamentals of Programming Data Types & Methods By Budditha Hettige Overview Summary (Previous Lesson) Java Data types Default values Variables Input data from keyboard Display results Methods Operators

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables COMP-202 Unit 2: Java Basics CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables Assignment 1 Assignment 1 posted on WebCt and course website.

More information

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

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