Previous Exam 1.0. Question 1 - a Is the following statement true or false? Briefly explain your answer. A && B is the same as B && A for any Boolean.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Java Language Quick-Reference Guide B. Oracle10g: Java Programming B - 2 Console Output Java applications and applets can output simple messages to the.
Written by: Dr. JJ Shepherd
IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Kernighan/Ritchie: Kelley/Pohl:
Chapter 10 Introduction to Arrays
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Final Review.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
For use of IST410 Students only Arrays-1 Arrays. For use of IST410 Students only Arrays-2 Objectives l Declaring arrays l Instantiating arrays l Using.
Chapter 7 – Arrays.
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
J.43 ARRAYS  A Java array is an Object that holds an ordered collection of elements.  Components of an array can be primitive types or may reference.
Arrays CS Feb Announcements Exam 1 Grades on Blackboard Project 2 scores: end of Class Project 4, due date:20 th Feb –Snakes & Ladders Game.
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
Java Unit 9: Arrays Declaring and Processing Arrays.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.
Object Oriented Programming: Java Edition By: Samuel Robinson.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Quiz 1 What is this? (explain the use of the reserved word “this” in a class method). Answer each question briefly. – What is a Constructor? –Under what.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Chap. 1 Classes, Types, and Objects. How Classes Are Declared [ ] class [extends ] [implements,, … ] { // class methods and instance variable definitions.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Topic 4 Inheritance.
Review TEST 2 Chapters 4,5,7. QUESTION For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?
Object Oriented Programming Java 1 Some Notes on Cloning, Packages and Visibility Notes from Bruce Eckel’s “Thinking in Java” and “Just Java” by.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Array Declarations Arrays contain a fixed number of variables of identical type Array declaration and allocation are separate operations Declaration examples:
CS 180 Recitation 7 Arrays. Used to store similar values or objects. An array is an indexed collection of data values of the same type. Arrays are the.
BIT115: Introduction to Programming
Two Dimensional Arrays Found in chapter 8, Section 8.9.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Arrays and Array Lists CS 21a. Problem 1: Reversing Input Problem: Read in three numbers and then print out the numbers in reverse order Straightforward.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
Chapter 3 Implementing Classes
Chapter 9 Introduction to Arrays Fundamentals of Java.
Last Revision. Question1 Novice Java programmers often write code similar to, class C { public int x;... }... C[] a = new C[10]; for(int i = 0; i < a.length;
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Lecture 3 John Woodward.
Data Structures and Algorithms revision
Intro To Classes Review
CS 302 Week 11 Jim Williams, PhD.
Chapter Three - Implementing Classes
Building Java Programs Chapter 7
The Building Blocks Classes: Java class library, over 1,800 classes:
Arrays and Array Lists CS 21a.
JAVA CLASSES.
Review for Midterm 3.
Presentation transcript:

Previous Exam 1.0

Question 1 - a Is the following statement true or false? Briefly explain your answer. A && B is the same as B && A for any Boolean expressions A and B. False. If either expression has a side effect, you cannot swap them.

Question 1 - b Write a program that reads in a series of floating-point numbers and prints out the minimum, maximum and average values. Assume use of the ConsoleReader class.

Question 1 – b public class MinMaxAve { public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); double low = 0; double high = 0; double sum = 0; int count = 0; boolean done = false;

Question 1 – b String input = console.readLine(); if (input == null) done = true; else { low = Double.parseDouble(input); high = low; sum = sum + low; count++; }

Question 1 - b while (!done) { input = console.readLine(); if (input == null) done = true; else { double next = Double.parseDouble(input); sum = sum + next; count++; if (next > high) high = next; else if(next < low) low = next; }

Question 1 - b System.out.println("The maximum value is: " + high); System.out.println("The minimum value is: " + low); if (count > 0) System.out.println("The average value is: " + sum / count); }

Question 1 - c Write a method that computes the alternating sum of all elements in an integer array. For example, if the method is invoked with the array containing : then it returns – – – – 3 = 7.

Question 1 - c public int altSum(int[] a) { int r = 0; for (int i = 0; i < a.length ; i++ ) { if (i % 2 == 0) r = r + a[i]; else r = r - a[i]; } return r; }

Question 2 - a Write a simple Bank Account class that rejects negative amounts in the deposit and withdraw methods and rejects withdrawals that would result in an overdraft.

Question 2 - a public class BankAccount { private double balance; public BankAccount() { balance = 0; } public BankAccount(double initialBalance) { if (initialBalance >= 0) balance = initialBalance; }

Question 2 - a public void deposit(double amount) { if (amount >= 0) balance = balance + amount; } public void withdraw(double amount) { if (amount <= balance) balance = balance - amount; } public double getBalance() { return balance; }

Question 2 - b What is wrong with the following loop? Explain 2 ways of fixing the error. int[] v = new int [10]; for (int i = 1; i <= 10; i++) v[i] = i*i;

Question 2 - b There is a bounds error. The index of the for loop begins at 1 (thereby skipping the first element of the array) and ends with 10 (which is one past the end of the array and a fatal error). One remedy is to adjust the bounds for i: for (int i = 0; i < 10; i++) v[i] = (i + 1) * (i + 1); Another remedy is to adjust the array index: for (int i = 1; i <= 10; i++) v[i - 1] = i * i;

Question 2 - c For each of the following, say if it is true or false. –Array subscripts must be integers –Arrays cannot contain Strings as elements –Arrays cannot use Strings as subscripts –Parallel arrays must have equal length –Two-dimensional arrays always have the same number of rows and columns –Two parallel arrays can be replaced by one two- dimensional array –Elements of different columns in a two-dimensional array can have different types

Question 2 - c true (or an expression which evaluates to an integer) false, for example main(String[] args) true true (in order to be parallel) false false (the array elements might be of different types) false

Question 3 - a Explain the difference between class and instance methods/members. How can this be expressed in your code?

Question 3 - a instance method need object reference –reference.method(parameters) class methods belong to class, no need for object – ClassName.method(parameters) class methods via static

Question 3 - b Can class methods/members be used in instance methods? Explain why (not). Yes, since each object has access to the class from which it is instantiated.

Question 3 - c Can class instance methods/members be used in class methods? Explain why (not). No, a class does not have access to any of its objects.

Question 3 - d In software engineering, solutions to common design problems are often called design patterns. One of them is called Singleton and it describes how one can make sure that a certain class can have only one instance during a program's life-cycle. How would you implement such a Singleton class in Java?

Question 3 - d public class Singleton { private static Singleton instance; protected Singleton() { … } public static Singleton giveInstance() { if(instance == null) instance = new Singleton(); return instance; }

Question 3 - e How would you check that you can indeed have only one instance? reference1 == reference2)

Question 4 - a public static final double PI = 3.14; accessible from everywhere belonging to class level constant type double

Question 4 - a protected final void printString(char a) accessible from subclasses method cannot be overridden no return value takes char as an argument

Question 4 - a private BankAccount() constructor for BackAccount class default constructor only to be used inside this class

Question 4 - b Describe the mechanism of error/exception handling in java. exceptions – errors try – catch – finally throw

Question 4 - c Why would one use error handling in a constructor? What will happen with the (partial) object? to state that something went wrong during object creation object will be garbage collected

Question 4 - d Explain the differences between call-by- reference and call-by-value parameter passing? call-by-reference: pointer to memory is passed call-by-value: actual contents of memory is given - value

Question 4 - d Which systems are used in Java? objects by reference primitive types by value

Question 5 1. import java.util.*; public class Run 4. { Vector elements; public Run(int in) 9. { 10. int t = a; 11. elements = new Vector(); 12. for(int t = 0; t <in; t++) 13. { 14. if(t%2==0) 15. elements.addElement(new ElementA("a")); 16. else 17. elements.addElement(new ElementB(t)); } 20. }

public String toString() 23. { 24.String res = "; 25.int s = elements.size(); 26.for(int i=0; i<s; i++) 27. { 28.res += elements.elementAt(i); 29.res += "\n"; 30. } 31.return res; 32. } public Vector giveElements() 35. { 36.return elements; 37. } 38.

39. public static void main(String[] argv) 40. { 41.Element a = new Element(); 42.Run r = new Run(4); 43.System.out.println(r); 44.ElementA b = new Element(5); 45.Vector el = r.giveElements(); 46.System.out.println((ElementA) el.elementAt(1)); } }

1.// abstract class Element 2. 3.public abstract class Element 4.{ public Element() 8. { 9. System.out.println("Element created"); 10. } protected abstract String printContents(); protected String printType() 16. { 17. return "Element " 18. } public String toString() 21. { 22. printType(); 23. } }

1.// public class ElementA 2. 3.public class ElementA extend Element 4.{ 5. String el; public ElementA() 8. { 9. System.out.println("ElementA created"); 10.el = "nothing"; 11. } public ElementA(String input) 14. { 15.System.out.println("ElementA created with input"); 16.el = input; 17. } 18.

19. /* protected constructor */ 20. protected ElementA(a) 21. { 22.System.out.println("ElementA created with int"); 23.el = Integer.toString(a); 24. } protected String printContents() 27. { 28.return el; 29. } protected String printType() 32. { 33.return "ElementA inherits from " super.printType(); 34. } public String toString() 37. { 38.return printType() "and contains " + printContents(); }

1./ public class ElementB public class ElementB extends ElementA 6.{ Vector in; public ElementB() 11. { 12.System.out.println("ElementB created"); 13.in = new Vector(); 14. } public ElementB(String el) 18. { 19 System.out.println("ElementB created with input"); 20. super(el); }

public ElementB(int a) 25. { 26.super(a); 27.System.out.print("ElementB created with int"); 28.in = new Vector(); 29.final int el = 2; 30.System.out.println("and el equals to " + this.el); 31.el++; 32.for(int i=0;i<a; i++) 33. { 34.in.addElement(new Integer(i + el)); 35. } 36. } 37.

38. protected String printContents() 39. { 40.return el + " " + in.toString(); 41. } protected String printType() 44. { 45.return "ElementB inherits from " + super.printType(); 46. } public String toString() 49. { 50.return printType() "and contains " + printContents(); 52. } 53.

Question 5 - b Predict the output of this program. Element created ElementA created with input Element created ElementA created with int ElementB created with intand el equals to 1 Element created ElementA created with input Element created ElementA created with int ElementB created with intand el equals to 3 ElementA inherits from Element and contains a ElementB inherits from ElementA inherits from Element and contains 1 [2] ElementA inherits from Element and contains a ElementB inherits from ElementA inherits from Element and contains 3 [2, 3, 4]