LAB 7. Objectives: Navin Sridhar D 8 54

Size: px
Start display at page:

Download "LAB 7. Objectives: Navin Sridhar D 8 54"

Transcription

1 LAB 7 Objectives: 1. Learn to create and define constructors. 2. Understand the use and application of constructors & instance variables. 3. Experiment with the various properties of arrays. 4. Learn to create complex programs dealing with arrays and integrate all previously learnt knowledge with it. Navin Sridhar D 8 54

2 Chapter 11 Create your own objects Section 11.3: Constructors Constructors initialize instance variables. Rules to define a constructor: The name of the constructor is the same as the name of the class. Constructors have no return type and no return value. The keyword static is omitted. public Time() { this.hour = 0; this.minute = 0; this.second = 0.0; Section 11.5: Creating a new object class Time { int hour, minute; double second; public Time() { this.hour = 0; this.minute = 0; this.second = 0.0; public Time(int hour, int minute, double second) { this.hour = hour; this.minute = minute; this.second = second; public static void main(string[] args) { // one way to create and initialize a Time object Time t1 = new Time(); t1.hour = 11; t1.minute = 8; t1.second = ; System.out.println(t1); // another way to do the same thing Time t2 = new Time(11, 8, ); System.out.println(t2); OUTPUT:

3 Section 11.8: Pure Functions Result depends only on the arguments, and it has no side effects like modifying an argument or printing something. public static boolean isafter(time time1, Time time2) { if (time1.hour > time2.hour) return true; if (time1.hour < time2.hour) return false; if (time1.minute > time2.minute) return true; if (time1.minute < time2.minute) return false; if (time1.second > time2.second) return true; return false; public static Time addtime(time t1, Time t2) { Time sum = new Time(); sum.hour = t1.hour + t2.hour; sum.minute = t1.minute + t2.minute; sum.second = t1.second + t2.second; return sum; The problem is that this method does not deal with cases where the number of seconds or minutes adds up to more than 60. In that case, we have to carry the extra seconds into the minutes column, or extra minutes into the hours column. Let s do that using the conditional statement if : public static Time addtime(time t1, Time t2) { Time sum = new Time(); sum.hour = t1.hour + t2.hour; sum.minute = t1.minute + t2.minute; sum.second = t1.second + t2.second; if (sum.second >= 60.0) { sum.second -= 60.0; sum.minute += 1; if (sum.minute >= 60) { sum.minute -= 60; sum.hour += 1; return sum;

4 Section 11.9: Modifiers As an example of a modifier, consider increment, which adds a given number of seconds to a Time object. public static void increment(time time, double secs) { time.second += secs; if (time.second >= 60.0) { time.second -= 60.0; time.minute += 1; if (time.minute >= 60) { time.minute -= 60; time.hour += 1; What happens if the argument secs is much greater than 60? Corrected example: public static void increment(time time, double secs) { time.second += secs; while (time.second >= 60.0) { time.second -= 60.0; time.minute += 1; while (time.minute >= 60) { time.minute -= 60; time.hour += 1; Replacing the if statements with while statements solves this problem.

5 Section 11.10: Fill-in methods public static void addtimefill(time t1, Time t2, Time sum) { sum.hour = t1.hour + t2.hour; sum.minute = t1.minute + t2.minute; sum.second = t1.second + t2.second; if (sum.second >= 60.0) { sum.second -= 60.0; sum.minute += 1; if (sum.minute >= 60) { sum.minute -= 60; sum.hour += 1; Modifiers and fill-in methods are efficient because they don t have to create new objects. Pure functions help manage the complexity of large projects, in part by making certain kinds of errors impossible. Section 11.11: Incremental development and planning Here is a method that converts Time into seconds (with datatype double). public static double converttoseconds(time t) { int minutes = t.hour * 60 + t.minute; double seconds = minutes * 60 + t.second; return seconds; Here is a constructor that converts back seconds into Time. public Time(double secs) { this.hour =(int)(secs / ); secs -= this.hour * ; this.minute =(int)(secs / 60.0); secs -= this.minute * 60; this.second = secs;

6 Now, to add two times, public static Time addtime(time t1, Time t2) { double seconds = converttoseconds(t1) + converttoseconds(t2); return new Time(seconds); Exercises Exercise 11.1: Q. Write a definition for a class named Tile that represents Scrabble tiles. The instance variables should be a character named letter and an integer named value. Write a method named printtile that takes a Tile object as a parameter and prints the instance variables in a reader-friendly format. Write a method named testtile that creates a Tile object with the letter Z and the value 10, and then uses printtile to print the state of the object. public class Tile { char letter; int value; // Constructor public Tile(char letter, int value) { this.letter = letter; this.value = value; // Prints a tile public static void printtile(tile tile) { System.out.println("Tile['" + tile.letter + "' " + tile.value + "]"); // Tests the constructor and printtile functions public static void testtile() { Tile tile = new Tile('Z', 10); printtile(tile); public static void main(string[] args) { testtile();

7 Exercise 11.2: Q. Write a class definition for Date, an object type that contains three integers, year, month and day. This class should provide two constructors. The first should take no parameters. The second should take parameters named year, month and day, and use them to initialize the instance variables. Write a main method that creates a new Date object named birthday. The new object should contain your birthdate. You can use either constructor. class Date { int year, month, day; public Date() { this.year = 0; this.month = 0; this.day = 0; public Date(int year, int month, int day) { this.year = year; this.month = month; this.day = day; public static void main(string[] args) { Date date = new Date(1965, 01, 11); Exercise 11.3: Q. Create a new program called Rational.java that defines a class named Rational. A Rational object should have two integer instance variables to store the numerator and denominator. Write a constructor that takes no arguments and that sets the numerator to 0 and denominator to 1. Write a method called printrational that takes a Rational object as an argument and prints it in some reasonable format. Write a main method that creates a new object with type Rational, sets its instance variables to some values, and prints the object. Write a second constructor for your class that takes two arguments and that uses them to initalize the instance variables. Write a method called negate that reverses the sign of a rational number. This method should be a modifier, so it should return void. Add lines to main to test the new method. Write a method called invert that inverts the number by swapping the numerator and denominator. Add lines to main to test the new method. Write a method called todouble that converts the rational number to a double (floating-point number) and returns the result. This method is a pure function; it does not modify the object. As always, test the new method.

8 Write a modifier named reduce that reduces a rational number to its lowest terms by finding the greatest common divisor (GCD) of the numerator and denominator and dividing through. This method should be a pure function; it should not modify the instance variables of the object on which it is invoked. Write a method called add that takes two Rational numbers as arguments and returns a new Rational object. The return object should contain the sum of the arguments. public class Rational { int numerator, denominator; // simple constructor that sets the numerator to 0 // and denominator to 1 public Rational() { this.numerator = 0; this.denominator = 1; public static void printrational(rational rational) { System.out.println(rational.numerator + "/" + rational.denominator); public static void main(string[] args) { // Create a new rational number -1/3 Rational rational1 = new Rational(); rational1.numerator = -1; rational1.denominator = 3; printrational(rational1); constructor // Create a rational number using the second Rational rational2 = new Rational(8, 2); printrational(rational2); // Negate the rational number negate(rational1); printrational(rational1); // Invert the numerator and denominator invert(rational1); printrational(rational1); // Convert the rational number to a double double floatingpoint = todouble(rational1); System.out.println(floatingpoint);

9 // Reduce a rational number to its lowest terms Rational rational3 = new Rational(8, 64); printrational(rational3); reduce(rational3); printrational(rational3); // Sum two rationals printrational(add(rational2, rational3)); public Rational(int numerator, int denominator) { this.numerator = numerator; this.denominator = denominator; // negate is a modifier that reverses the sign of the rational number public static void negate(rational rational) { int numerator = rational.numerator; int negatednumerator = -1 * numerator; rational.numerator = negatednumerator; // invert is a modifier that swaps the numerator and denominator // of the rational number public static void invert(rational rational) { int oldnumerator = rational.numerator; int olddenominator = rational.denominator; rational.numerator = olddenominator; rational.denominator = oldnumerator; // todouble is a pure function that returns the rational number // expressed as a decimal public static double todouble(rational rational) { double numerator = rational.numerator; double denominator = rational.denominator; return (numerator / denominator); // returning the gcd of two integers public static int gcd(int a, int b) { if (b == 0) { return a; int rem = a % b; return gcd(b, rem);

10 // reduce is a modifier that reduces a rational number to its // lowest terms public static void reduce(rational rational) { int gcd = gcd(rational.numerator, rational.denominator); rational.numerator = rational.numerator / gcd; rational.denominator = rational.denominator / gcd; // returns the sum of the two rational numbers (lcm) public static Rational add(rational rational1, Rational rational2) { int newnumerator = rational1.numerator * rational2.denominator + rational1.denominator * rational2.numerator; int newdenominator = rational1.denominator * rational2.denominator; Rational newrational = new Rational(newNumerator, newdenominator); reduce(newrational); return newrational;

11 Chapter 12 Arrays An array is a set of values where each value is identified by an index. One of the most common ways to index an array is with a loop variable. Section 12.1: Accessing elements public static void count (int i) { int i = 0; while (i < 4) { System.out.println(count[i]); i++; The body of this loop is only executed when i is 0, 1, 2 and 3. Section 12.2: Copying arrays public static void main (String[] args) { double[] a = new double [3]; double[] b = new double [3]; int i = 0; while (i < 4) { b[i] = a[i]; i++; Section 12.4: for loops The general syntax looks like this: for (INITIALIZER; CONDITION; INCREMENTOR) { BODY It is more concise and, since it puts all the loop-related statements in one place, it is easier to read. for (int i = 0; i < 4; i++) { System.out.println(count[i]);

12 Section 12.5: Array length All arrays have one named instance variable: length. for (int i = 0; i < a.length; i++) { b[i] = a[i]; This code assumes that the array b contains at least as many elements as a. Section 12.6: Random numbers Java provides a method called random() that generates pseudorandom numbers from 0.0 to 1.0 (not including 1.0). for (int i = 0; i < 10; i++) { double x = Math.random(); System.out.println(x); NOTE: The method random() was also used in GridWorld to make the bug perform random walk. Section 12.7: Array of random numbers public static int[] randomarray(int n) { int[] a = new int[n]; for (int i = 0; i<a.length; i++) { a[i] = randomint(0, 100); return a; The above method takes a single argument, the size of the array. It allocates a new array of integers, fills it with random values, and returns a reference to the new array. To print this array, public static void printarray(int[] a) { for (int i = 0; i<a.length; i++) { System.out.println(a[i]);

13 Section 12.8: Counting The following is a method called inrange that counts the number of elements in an array that fall in a given range. public static int inrange(int[] a, int low, int high) { int count = 0; for (int i = 0; i < a.length; i++) { if (a[i] >= low && a[i] < high) count++; return count; Section 12.9: The histogram The counting pattern is the same whether we use a single counter or an array of counters. In this case, we initialize the array outside the loop; then, inside the loop, we invoke inrange and store the result. int[] counts = new int[100]; for (int i = 0; i < counts.length; i++) { counts[i] = inrange(scores, i, i+1); Section 12.10: A single-pass solution As the number of ranges increases, that gets to be a lot of traversals. It would be better to make a single pass through the array, and for each value, compute which range it falls in. Then we could increment the appropriate counter. int[] counts = new int[100]; for (int i = 0; i < scores.length; i++) { int index = scores[i]; //changes with each execution counts[index]++;

14 Exercises Exercise 12.1: Q. Write a method called clonearray that takes an array of integers as a parameter, creates a new array that is the same size, copies the elements from the first array into the new one, and then returns a reference to the new array. class clonearray { public static void main (String[] args) { int[] a = {2,4,4,4,2,22; System.out.println("Array A is: "); printarray(a); System.out.println(); int[] b = clonearray(a); System.out.println("Array B is: "); System.out.println(); printarray(b); public static int[] clonearray (int[] a) { int len = a.length; double[] b = new double [len]; int i = 0; while (i < len) { b[i] = a[i]; i++; return a; public static void printarray(int[] a) { for (int i = 0; i<a.length; i++) { System.out.println(a[i]);

15 Exercise 12.2: Q. Write a method called randomdouble that takes two doubles, low and high, and that returns a random double x so that low x < high. public static double randomdouble(double low, double high) { double difference = high - low; return Math.random()*difference + low; Exercise 12.3: Q. Write a method called randomint that takes two arguments, low and high, and that returns a random integer between low and high, not including high. public static double randomint(double low, double high) { double difference = high - low; return (int)(math.random()*difference + low); Exercise 12.4: Q. Write a method called makehist that takes an array of scores and returns a histogram of the values in the array. public static int[] makehist(int[] scores) { int[] count = new int[10]; Exercise 12.5: for (int i = 0; i < scores.length; i++) { int index = scores[i]; count[index]++; return count; Q. Write a method named arefactors that takes an integer n and an array of integers, and that returns true if the numbers in the array are all factors of n. public static boolean arefactors(int n, int[] a) { for (int i = 0; i < a.length; i++) { if (a [i] % n == 0) {continue; else {return false; return true;

16 Exercise 12.6: Q. Write a method that takes an array of integers and an integer named target as arguments, and that returns the first index where target appears in the array, if it does, and -1 otherwise. public static int find(int[] arr, int target) { for (int i = 0; i < arr.length; i++) { if (arr[i] == target) { return i; return -1; Exercise 12.10: Q. Write a method called indexofmaxinrange that takes an array of integers, finds the largest element in the given range, and returns its index. public static int indexofmaxinrange(int[] arr) { int max = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] >= max) { max = arr[i]; return max; Q. Write a method called swapelement that takes an array of integers and two indices, and that swaps the elements at the given indices. public static int[] swapelement(int[] arr, int x, int y) { int z = arr[y-1]; //temp variable arr[y-1] = arr[x-1]; arr[x-1] = z; System.out.println("Element at position " + x + " was swapped with element at position " + y); return arr;

17 Q. Write a method called selectionsort that takes an array of integers and that uses indexofmaxinrange and swapelement to sort the array from largest to smallest. public static int[] swapelement(int[] arr, int x, int y) { int z = arr[y-1]; arr[y-1] = arr[x-1]; arr[x-1] = z; return arr; public static int[] selectionsort(int[] a) { for (int i = 1; i < a.length; i++) { if (a[i] > a[i-1]) { swapelement(a,i,i+1); return a; Exercise 12.12: Q. A word is said to be a doubloon if every letter that appears in the word appears exactly twice. Write a method called isdoubloon that returns true if the given word is a doubloon and false otherwise. public static boolean isdubloon(string s) { int[] histo = new int[26]; for(int i = 0; i < s.length(); i++) { char curchar = s.tolowercase().charat(i); if ('a' <= curchar && curchar <= 'z') { histo[curchar-'a']++; for (int i = 0; i < histo.length; i++) { if (histo[i]!= 0 && histo[i]!= 2) { return false; return true;

18 CONCLUSION i) Constructors: Constructors are used to initialize the instances of our classes. A constructor can be visualized as a template of the program. All objects created using the new keyword will be given the parameters as defined in the constructor. ii) Encapsulation: Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. Encapsulation is also known as data hiding. The instance variables are almost every time declared as private. Instance variables are made private to force the users of that class to use methods to access them. iii) Using the this keyword: Within an instance method or a constructor, this is a reference to the current object the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. iv) Syntaxes related to Arrays: The index of any array always starts from 0. Built-in methods in Java can be used effectively for various applications. Array is a powerful concept which can be used for manipulation (sorting, deleting an element, etc.) very effortlessly for further processing. v) Array methods: An array may be passed to a method which may either be a modifier method (void) or return an array to the calling method (pure). The most preferable method to go through an array is by using the for loop.

8.14 Exercises 101. // if n is even, the result is t squared // if n is odd, the result is t squared times x

8.14 Exercises 101. // if n is even, the result is t squared // if n is odd, the result is t squared times x 8.14 Exercises 101 Type in this code and try out a few simple cases like creating a BigInteger and printing it. Notice that println knows how to print BigIntegers! Don t forget to add import java.math.biginteger

More information

Classes and functions

Classes and functions Classes and functions 14.1. Time As another example of a user-defined type, we ll define a class called Time that records the time of day. The class definition looks like this: class Time: pass We can

More information

Chapter 12: Arrays Think Java: How to Think Like a Computer Scientist by Allen B. Downey

Chapter 12: Arrays Think Java: How to Think Like a Computer Scientist by Allen B. Downey Chapter 12: Arrays Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Current Options for Storing Data 1) You need to store the room temperature, such as 62.5, in a variable. What

More information

Programming Language Concepts: Lecture 2

Programming Language Concepts: Lecture 2 Programming Language Concepts: Lecture 2 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in http://www.cmi.ac.in/~madhavan/courses/pl2011 PLC 2011, Lecture 2, 6 January 2011 Classes and

More information

Programming Language Concepts: Lecture 2

Programming Language Concepts: Lecture 2 Programming Language Concepts: Lecture 2 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in http://www.cmi.ac.in/~madhavan/courses/pl2009 PLC 2009, Lecture 2, 19 January 2009 Classes and

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

ITI 1120 Lab #9. Slides by: Diana Inkpen, Alan Williams, Daniel Amyot Some original material by Romelia Plesa

ITI 1120 Lab #9. Slides by: Diana Inkpen, Alan Williams, Daniel Amyot Some original material by Romelia Plesa ITI 1120 Lab #9 Slides by: Diana Inkpen, Alan Williams, Daniel Amyot Some original material by Romelia Plesa 1 Objectives Review fundamental concepts Example: the Time class Exercises Modify the Time class

More information

Chapter 15: Object Oriented Programming

Chapter 15: Object Oriented Programming Chapter 15: Object Oriented Programming Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey How do Software Developers use OOP? Defining classes to create objects UML diagrams to

More information

It is a constructor and is called using the new statement, for example, MyStuff m = new MyStuff();

It is a constructor and is called using the new statement, for example, MyStuff m = new MyStuff(); COSC 117 Exam 3 Key Fall 2012 Part 1: Definitions & Short Answer (3 Points Each) 1. A method in a class that has no return type and the same name as the class is called what? How is this type of method

More information

Types in Java. 8 Primitive Types. What if we want to store lots of items e.g. midsem marks?

Types in Java. 8 Primitive Types. What if we want to store lots of items e.g. midsem marks? Types in Java 8 Primitive Types byte, short, int, long float, double boolean Char Object types: predefined e.g. String ; User-defined via class and constructors What if we want to store lots of items e.g.

More information

Chapter 11: Create Your Own Objects

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

More information

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 January 21, 2013 Abstract Review of object-oriented programming concepts: Implementing

More information

Object Oriented Modeling

Object Oriented Modeling Object Oriented Modeling Object oriented modeling is a method that models the characteristics of real or abstract objects from application domain using classes and objects. Objects Software objects are

More information

Chapter 5: Arrays. Chapter 5. Arrays. Java Programming FROM THE BEGINNING. Copyright 2000 W. W. Norton & Company. All rights reserved.

Chapter 5: Arrays. Chapter 5. Arrays. Java Programming FROM THE BEGINNING. Copyright 2000 W. W. Norton & Company. All rights reserved. Chapter 5 Arrays 1 5.1 Creating and Using Arrays A collection of data items stored under a single name is known as a data structure. An object is one kind of data structure, because it can store multiple

More information

Defining Your Own Classes

Defining Your Own Classes Defining Your Own Classes In C, you are allowed to define a struct and then define variables of that struct. But Java allows you to define your own class. This means not only defining the data structure,

More information

Announcements. PS 4 is ready, due next Thursday, 9:00pm. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Announcements. PS 4 is ready, due next Thursday, 9:00pm. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am Announcements PS 4 is ready, due next Thursday, 9:00pm Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am Room TBD Scope: Lecture 1 to Lecture 9 (Chapters 1 to 6 of text) You may bring a sheet of paper (A4, both

More information

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail. OOP in Java 1 Outline 1. Getting started, primitive data types and control structures 2. Classes and objects 3. Extending classes 4. Using some standard packages 5. OOP revisited Parts 1 to 3 introduce

More information

CSEN 202: Introduction to Computer Programming Spring term Final Exam

CSEN 202: Introduction to Computer Programming Spring term Final Exam Page 0 German University in Cairo May 28, 2016 Media Engineering and Technology Prof. Dr. Slim Abdennadher Dr. Wael Aboul Saadat CSEN 202: Introduction to Computer Programming Spring term 2015-2016 Final

More information

16.216: ECE Application Programming Spring 2015 Exam 2 Solution

16.216: ECE Application Programming Spring 2015 Exam 2 Solution 16.216: ECE Application Programming Spring 2015 Exam 2 Solution 1. (20 points, 5 points per part) Multiple choice For each of the multiple choice questions below, clearly indicate your response by circling

More information

CIS 110 Fall 2016 Introduction to Computer Programming 13 Oct 2016 Midterm Exam Answer Key

CIS 110 Fall 2016 Introduction to Computer Programming 13 Oct 2016 Midterm Exam Answer Key CIS 110 Fall 2016 Midterm 1 CIS 110 Fall 2016 Introduction to Computer Programming 13 Oct 2016 Midterm Exam Answer Key 1.) The Easy One (1 point total) Check cover sheet for name, recitation #, PennKey,

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

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers; Arrays What are they? An array is a data structure that holds a number of related variables. Thus, an array has a size which is the number of variables it can store. All of these variables must be of the

More information

Lab Assignment Three

Lab Assignment Three Lab Assignment Three C212/A592 Fall Semester 2010 Due in OnCourse by Friday, September 17, 11:55pm (Dropbox will stay open until Saturday, September 18, 11:55pm) Abstract Read and solve the problems below.

More information

Lecture #6-7 Methods

Lecture #6-7 Methods Lecture #6-7 s 1. a. group of statements designed to perform a specific function b. may be reused many times i. in a particular program or ii. in multiple programs 2. Examples from the Java Library a.

More information

CSC326 Object Oriented Programming i. CSC326 Object Oriented Programming

CSC326 Object Oriented Programming i. CSC326 Object Oriented Programming i CSC326 Object Oriented Programming ii REVISION HISTORY NUMBER DATE DESCRIPTION NAME 1.0 2011-09 JZ iii Contents 1 Agenda 1 2 Classes and Objects 1 3 Classes and Functions 3 4 Classes and Methods 4 5

More information

To keep track of this new wrinkle we need some new variables at the Class level:

To keep track of this new wrinkle we need some new variables at the Class level: CS201 Arrays Part II Random Trivia Game Let s refine our trivia game, and say that we would like to randomly select four questions out of all of the questions that we loaded, ask each to the player, output

More information

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal APCS A Midterm Review You will have a copy of the one page Java Quick Reference sheet. This is the same reference that will be available to you when you take the AP Computer Science exam. 1. n bits can

More information

University of Palestine. Mid Exam Total Grade: 100

University of Palestine. Mid Exam Total Grade: 100 First Question No. of Branches (5) A) Choose the correct answer: 1. If we type: system.out.println( a ); in the main() method, what will be the result? int a=12; //in the global space... void f() { int

More information

COE 212 Engineering Programming. Welcome to the Final Exam Monday May 18, 2015

COE 212 Engineering Programming. Welcome to the Final Exam Monday May 18, 2015 1 COE 212 Engineering Programming Welcome to the Final Exam Monday May 18, 2015 Instructors: Dr. Joe Tekli Dr. George Sakr Dr. Wissam F. Fawaz Name: Student ID: Instructions: 1. This exam is Closed Book.

More information

CIS 110 Introduction to Computer Programming. 12 February 2013 Midterm. Answer Key

CIS 110 Introduction to Computer Programming. 12 February 2013 Midterm. Answer Key CIS 110 Introduction to Computer Programming 12 February 2013 Midterm Answer Key 0. (1 point) Miscellaneous (a) Write your name, recitation number, and PennKey (username) on the front of the exam. (b)

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/ SELECTING DATA STRUCTURES 2 Reading and Cleaning

More information

Handout 7. Defining Classes part 1. Instance variables and instance methods.

Handout 7. Defining Classes part 1. Instance variables and instance methods. Handout 7 CS180 Programming Fundamentals Spring 15 Page 1 of 8 Handout 7 Defining Classes part 1. Instance variables and instance methods. In Object Oriented programming, applications are comprised from

More information

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

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

More information

APCS Semester #1 Final Exam Practice Problems

APCS Semester #1 Final Exam Practice Problems Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester

More information

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof Array Lecture 12 Based on Slides of Dr. Norazah Yusof 1 Introducing Arrays Array is a data structure that represents a collection of the same types of data. In Java, array is an object that can store a

More information

5. PLEASE TAKE HOME the question bundle, but turn in 2 paper sheets: The scantron AND the paper where you wrote your programming question solution!

5. PLEASE TAKE HOME the question bundle, but turn in 2 paper sheets: The scantron AND the paper where you wrote your programming question solution! FINAL EXAM Introduction to Computer Science UA-CCI- ICSI 201--Fall13 This is a closed book and note examination, except for one 8 1/2 x 11 inch paper sheet of notes, both sides. There is no interpersonal

More information

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

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

More information

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm CIS 110 Introduction To Computer Programming February 29, 2012 Midterm Name: Recitation # (e.g. 201): Pennkey (e.g. bjbrown): My signature below certifies that I have complied with the University of Pennsylvania

More information

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial:

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial: Recursion EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion: Factorial (1) Recall the formal definition of calculating the n factorial: 1 if n = 0 n! = n (n 1) (n 2) 3 2

More information

Chapter 6 Single-Dimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Chapter 6 Single-Dimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Chapter 6 Single-Dimensional Arrays rights reserved. 1 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average. Solution AnalyzeNumbers rights

More information

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2013

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2013 CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2013 Name: This exam consists of 7 problems on the following 6 pages. You may use your single- side hand- written 8 ½ x 11 note sheet during the

More information

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency Introduction Fundamentals Declaring arrays Indexing arrays Initializing arrays Arrays and functions Multidimensional arrays Sorting and algorithm efficiency An array is a sequence of values of the same

More information

Lecture 13. Example. Encapsulation. Rational numbers: a number is rational if it can be defined as the ratio between two integers.

Lecture 13. Example. Encapsulation. Rational numbers: a number is rational if it can be defined as the ratio between two integers. Lecture 13 Example Rational numbers: a number is rational if it can be defined as the ratio between two integers Issues in object-oriented programming The class Rational completed Material from Holmes

More information

Arrays. Eng. Mohammed Abdualal

Arrays. Eng. Mohammed Abdualal Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 9 Arrays

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

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

Loops. CSE 114, Computer Science 1 Stony Brook University

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

More information

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

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

Chapter 6 Arrays. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. Chapter 6 Arrays 1 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average. 2 Solution AnalyzeNumbers Run Run with prepared input 3 Objectives

More information

Birkbeck (University of London) Software and Programming 1 In-class Test Mar Answer ALL Questions

Birkbeck (University of London) Software and Programming 1 In-class Test Mar Answer ALL Questions Birkbeck (University of London) Software and Programming 1 In-class Test 2.1 16 Mar 2017 Student Name Student Number Answer ALL Questions 1. What output is produced when the following Java program fragment

More information

Lecture 5: Methods CS2301

Lecture 5: Methods CS2301 Lecture 5: Methods NADA ALZAHRANI CS2301 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Solution public static int sum(int i1, int i2) { int

More information

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion: Principle Recursion is useful in expressing solutions to problems that can be recursively defined: Base Cases:

More information

COS 126 General Computer Science Spring Written Exam 1

COS 126 General Computer Science Spring Written Exam 1 COS 126 General Computer Science Spring 2017 Written Exam 1 This exam has 9 questions (including question 0) worth a total of 70 points. You have 50 minutes. Write all answers inside the designated spaces.

More information

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2012

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2012 CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2012 Name: This exam consists of 7 problems on the following 6 pages. You may use your single- side hand- written 8 ½ x 11 note sheet during the

More information

UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter

UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter What you will learn from Lab 7 In this laboratory, you will understand how to use typical function prototype with

More information

CS 211: Methods, Memory, Equality

CS 211: Methods, Memory, Equality CS 211: Methods, Memory, Equality Chris Kauffman Week 2-1 So far... Comments Statements/Expressions Variable Types little types, what about Big types? Assignment Basic Output (Input?) Conditionals (if-else)

More information

Array basics. How would you solve this? Arrays. What makes the problem hard? Array auto-initialization. Array declaration. Readings: 7.

Array basics. How would you solve this? Arrays. What makes the problem hard? Array auto-initialization. Array declaration. Readings: 7. How would you solve this? Array basics Readings:. Consider the following program: How many days' temperatures? Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp:

More information

Introduction to the Java Basics: Control Flow Statements

Introduction to the Java Basics: Control Flow Statements Lesson 3: Introduction to the Java Basics: Control Flow Statements Repetition Structures THEORY Variable Assignment You can only assign a value to a variable that is consistent with the variable s declared

More information

About this exam review

About this exam review Final Exam Review About this exam review I ve prepared an outline of the material covered in class May not be totally complete! Exam may ask about things that were covered in class but not in this review

More information

Tutorial 11. Exercise 1: CSC111 Computer Programming I. A. Write a code snippet to define the following arrays:

Tutorial 11. Exercise 1: CSC111 Computer Programming I. A. Write a code snippet to define the following arrays: College of Computer and Information Sciences CSC111 Computer Programming I Exercise 1: Tutorial 11 Arrays: A. Write a code snippet to define the following arrays: 1. An int array named nums of size 10.

More information

A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1

A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1 A First Look At Java Didactic Module 13 Programming Languages - EEL670 1 Outline Thinking about objects Simple expressions and statements Class definitions About references and pointers Getting started

More information

CS1150 Principles of Computer Science Arrays

CS1150 Principles of Computer Science Arrays CS1150 Principles of Computer Science Arrays Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Opening Problem Read one hundred numbers, compute their

More information

COS 126 Midterm 1 Written Exam Fall 2011

COS 126 Midterm 1 Written Exam Fall 2011 NAME: login id: Precept: COS 126 Midterm 1 Written Exam Fall 2011 This test has 8 questions, weighted as indicated. The exam is closed book, except that you are allowed to use a one page cheatsheet. No

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

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass? 1. Overriding Methods A subclass can modify behavior inherited from a parent class. A subclass can create a method with different functionality than the parent s method but with the same: Name Return type

More information

You will not be tested on JUnit or the Eclipse debugger. The exam does not cover interfaces.

You will not be tested on JUnit or the Eclipse debugger. The exam does not cover interfaces. Com S 227 Fall 2016 Topics and review problems for Exam 2 Thursday, November 10, 6:45 pm Locations, by last name: (same locations as Exam 1) A-C Curtiss 0127, first floor only D-N Hoover 2055 O-Z Troxel

More information

You must bring your ID to the exam.

You must bring your ID to the exam. Com S 227 Spring 2017 Topics and review problems for Exam 2 Monday, April 3, 6:45 pm Locations, by last name: (same locations as Exam 1) A-E Coover 2245 F-M Hoover 2055 N-S Physics 0005 T-Z Hoover 1213

More information

CS1150 Principles of Computer Science Arrays

CS1150 Principles of Computer Science Arrays CS1150 Principles of Computer Science Arrays Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Opening Problem Read one hundred numbers, compute their

More information

CISC220 Lab 2: Due Wed, Sep 26 at Midnight (110 pts)

CISC220 Lab 2: Due Wed, Sep 26 at Midnight (110 pts) CISC220 Lab 2: Due Wed, Sep 26 at Midnight (110 pts) For this lab you may work with a partner, or you may choose to work alone. If you choose to work with a partner, you are still responsible for the lab

More information

Chapter 1b Classes and Objects

Chapter 1b Classes and Objects Data Structures for Java William H. Ford William R. Topp Chapter 1b Classes and Objects Bret Ford 2005, Prentice Hall Object-Oriented Programming An object is an entity with data and operations on the

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

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

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

More information

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

Array basics. Readings: 7.1

Array basics. Readings: 7.1 Array basics Readings: 7.1 1 How would you solve this? Consider the following program: How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39 Day 4's high temp:

More information

Objects and Classes. Objects and Classes

Objects and Classes. Objects and Classes Objects and Classes Wolfgang Schreiner Research Institute for Symbolic Computation (RISC) Johannes Kepler University, Linz, Austria Wolfgang.Schreiner@risc.jku.at http://www.risc.jku.at Wolfgang Schreiner

More information

1 Short Answer (7 Points Each)

1 Short Answer (7 Points Each) 1 Short Answer ( Points Each) 1. Write a linear search method for an integer array that takes in an array and target value as parameters and returns the first position of the target in the array. If the

More information

1 Short Answer (10 Points Each)

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

More information

Esc101 Mid Semester Exam - II

Esc101 Mid Semester Exam - II Esc101 Mid Semester Exam - II Time Allowed: 1 Hour Max Marks: 75 Instructions: 1. Do not turn this page until the bell rings. 2. YOU MUST WRITE YOUR NAME, ROLL NUMBER & SECTION ON EACH SHEET. 3. Please

More information

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Arrays

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Arrays WIT COMP1000 Arrays Arrays An array is a list of variables of the same type, that represents a set of related values For example, say you need to keep track of the cost of 1000 items You could declare

More information

a) Answer all questions. b) Write your answers in the space provided. c) Show all calculations where applicable.

a) Answer all questions. b) Write your answers in the space provided. c) Show all calculations where applicable. Name: Please fill in your Student Number and Name. Student Number : Student Number: University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ 2008 January Exam Question Max Internal

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

CS171:Introduction to Computer Science II

CS171:Introduction to Computer Science II CS171:Introduction to Computer Science II Department of Mathematics and Computer Science Li Xiong 1/24/2012 1 Roadmap Lab session Pretest Postmortem Java Review Types, variables, assignments, expressions

More information

Problems with simple variables

Problems with simple variables Problems with simple variables Hard to give up values high number of variables. Complex to sort a high number of variables by value. Impossible to use loops. Example problem: Read one hundred numbers,

More information

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name: CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, 2017 Name: 1. (10 points) For the following, Check T if the statement is true, the F if the statement is false. (a) T F : In mathematics,

More information

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

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

More information

C++ for Java Programmers

C++ for Java Programmers Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even

More information

McGill University School of Computer Science COMP-202A Introduction to Computing 1

McGill University School of Computer Science COMP-202A Introduction to Computing 1 McGill University School of Computer Science COMP-202A Introduction to Computing 1 Midterm Exam Thursday, October 26, 2006, 18:00-20:00 (6:00 8:00 PM) Instructors: Mathieu Petitpas, Shah Asaduzzaman, Sherif

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1(c): Java Basics (II) Lecture Contents Java basics (part II) Conditions Loops Methods Conditions & Branching Conditional Statements A

More information

Object-Based Programming (Deitel chapter 8)

Object-Based Programming (Deitel chapter 8) Object-Based Programming (Deitel chapter 8) 1 Plan 2 Introduction Implementing a Time Abstract Data Type with a Class Class Scope Controlling Access to Members Referring to the Current Object s Members

More information

STRUCTURING OF PROGRAM

STRUCTURING OF PROGRAM Unit III MULTIPLE CHOICE QUESTIONS 1. Which of the following is the functionality of Data Abstraction? (a) Reduce Complexity (c) Parallelism Unit III 3.1 (b) Binds together code and data (d) None of the

More information

Lecture 14. 'for' loops and Arrays

Lecture 14. 'for' loops and Arrays Lecture 14 'for' loops and Arrays For Loops for (initiating statement; conditional statement; next statement) // usually incremental body statement(s); The for statement provides a compact way to iterate

More information

Lecture #8-10 Arrays

Lecture #8-10 Arrays Lecture #8-10 Arrays 1. Array data structure designed to store a fixed-size sequential collection of elements of the same type collection of variables of the same type 2. Array Declarations Creates a Storage

More information

Question: Total Points: Score:

Question: Total Points: Score: CS 170 Exam 2 Section 001 Fall 2014 Name (print): Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do NOT communicate with anyone other than

More information

Functions. Arash Rafiey. September 26, 2017

Functions. Arash Rafiey. September 26, 2017 September 26, 2017 are the basic building blocks of a C program. are the basic building blocks of a C program. A function can be defined as a set of instructions to perform a specific task. are the basic

More information

CS 1302 Chapter 9 (Review) Object & Classes

CS 1302 Chapter 9 (Review) Object & Classes CS 1302 Chapter 9 (Review) Object & Classes Reference Sections 9.2-9.5, 9.7-9.14 9.2 Defining Classes for Objects 1. A class is a blueprint (or template) for creating objects. A class defines the state

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

Course Outline. Introduction to java

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

More information

CS2141 Software Development using C/C++ C++ Basics

CS2141 Software Development using C/C++ C++ Basics CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short

More information

Getting started with Java

Getting started with Java Getting started with Java Magic Lines public class MagicLines { public static void main(string[] args) { } } Comments Comments are lines in your code that get ignored during execution. Good for leaving

More information