Java and C# in depth

Similar documents
AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Introduce C# as Object Oriented programming language. Explain, tokens,

15CS45 : OBJECT ORIENTED CONCEPTS

Declarations and Access Control SCJP tips

Midterm Exam CS 251, Intermediate Programming March 6, 2015

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

MCSA Universal Windows Platform. A Success Guide to Prepare- Programming in C# edusum.com

Midterm Exam CS 251, Intermediate Programming March 12, 2014

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Introduction to Computing II (ITI 1121) Final Examination

Synchronization SPL/2010 SPL/20 1

Midterm Exam CS 251, Intermediate Programming October 8, 2014

C# Programming in the.net Framework

CSE 431S Type Checking. Washington University Spring 2013

No Aids Allowed. Do not turn this page until you have received the signal to start. Read this entire page or you ll miss the bonus question.

Course Hours

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Introduction to C# Applications

Examination Questions Midterm 1

Chapter 1 Getting Started

20 Most Important Java Programming Interview Questions. Powered by

CSE 307: Principles of Programming Languages

PESIT Bangalore South Campus

C#: framework overview and in-the-small features

Java Overview An introduction to the Java Programming Language

Course Description. Learn To: : Intro to JAVA SE7 and Programming using JAVA SE7. Course Outline ::

CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2013

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Final Exam CS 251, Intermediate Programming December 10, 2014

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

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Software Development & Education Center. Java Platform, Standard Edition 7 (JSE 7)

Core Java Contents. Duration: 25 Hours (1 Month)

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

Inheritance and Interfaces

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Last name:... First name:... Department (if not D-INFK):...

1 Shyam sir JAVA Notes

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

Object-Oriented Programming in C# (VS 2015)

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Chapter 5 Object-Oriented Programming

Class, Variable, Constructor, Object, Method Questions

CSC Java Programming, Fall Java Data Types and Control Constructs

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

Java Primer 1: Types, Classes and Operators

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

Principles of Software Construction: Objects, Design, and Concurrency. Objects (continued) toad. Spring J Aldrich and W Scherlis

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

CMSC 330: Organization of Programming Languages

Program Correctness and Efficiency. Chapter 2

Chapter 4 Defining Classes I

Java 8 Programming for OO Experienced Developers

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

Midterm Exam (REGULAR SECTION)

F I N A L E X A M I N A T I O N

Last name:... First name:... Department (if not D-INFK):...

CS159. Nathan Sprague

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

Object-Oriented Programming

Course Syllabus C # Course Title. Who should attend? Course Description

Object-Oriented Programming in C# (VS 2012)

What are the characteristics of Object Oriented programming language?

INSTRUCTIONS TO CANDIDATES

Introduction to Programming Using Java (98-388)

Thread Programming. Comp-303 : Programming Techniques Lecture 11. Alexandre Denault Computer Science McGill University Winter 2004

Programming Kotlin. Familiarize yourself with all of Kotlin s features with this in-depth guide. Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI

Pace University. Fundamental Concepts of CS121 1

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

CMSC132, Practice Questions

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

INSTRUCTIONS TO CANDIDATES

Microsoft. Microsoft Visual C# Step by Step. John Sharp

CMSC 132: Object-Oriented Programming II

Java SE 8 Programmer I and II Syballus( Paper codes : 1z0-808 & 1z0-809)

CPSC 410 Advanced Software Engineering Mid-term Examination (Term I ): Solution Instructor: Gail Murphy

Relation Overriding. Syntax and Semantics. Simple Semantic Domains. Operational Semantics

COPYRIGHTED MATERIAL. Contents. Part I: C# Fundamentals 1. Chapter 1: The.NET Framework 3. Chapter 2: Getting Started with Visual Studio

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

Final Exam CS 152, Computer Programming Fundamentals December 9, 2016

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

CS-140 Fall 2018 Test 2 Version A Nov. 12, Name:

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

CS4215 Programming Language Implementation

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Conversions and Casting

CS143 Final Spring 2016

Java: introduction to object-oriented features

A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p.

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

C++ Important Questions with Answers

Core Java SYLLABUS COVERAGE SYLLABUS IN DETAILS

Method Resolution Approaches. Dynamic Dispatch

Object typing and subtypes

Safety SPL/2010 SPL/20 1

Transcription:

Java and C# in depth ETH Zurich Date: 27 May 2013 Family name, first name:... Student number:.. I confirm with my signature, that I was able to take this exam under regular circumstances and that I have read and understood the directions below. Signature:... Directions: Exam duration: 105 minutes. All personal documents are allowed. Exchanging documents during the examination would mean failing the examination. Electronic equipment (laptops, cell phones, PDA, etc.) are not allowed. Using them would mean failing the examination. Use a pen (not a pencil)! Please write your student number onto each sheet. All solutions can be written directly onto the exam sheets. If you need more space for your solution ask the supervisors for a sheet of official paper. You are not allowed to use other paper. Only one solution can be handed in per question. Invalid solutions need to be crossed out clearly. Please write legibly! We will only correct solutions that we can read. Manage your time carefully (take into account the number of points for each question). Please immediately tell the exam supervisors if you feel disturbed during the exam. Good luck! Question Number of possible points Points 1 16 2 12 3 12 4 15 5 10 TOTAL 68 1

1 Java and C# Fundamentals (16 Points) All questions below refer to the Java language version 7 and C# language version 5.0 as taught in the course. Multiple correct answers are possible; there is at least one correct answer per question. A correctly checked or unchecked box is worth 0.5 points. An incorrectly checked or unchecked box is worth 0 points. Example. Which of the following statements are true? a. The sun is a mass of incandescent gas. 0.5 points b. 2 2 = 4 0 points c. Britney Spears is a honoured doctor of ETH. 0.5 points d. Rösti is a kind of sausage. 0 points 1. Casting and Autoboxing a. In C#, all value types (built-in or user-defined) can be boxed. b. In C#, no explicite type cast is necessary to box and unbox value types. c. In Java, all conversions between built-in primitive types are implicit. d. In Java and C#, no cast is necessary to convert an int to a float, even though you loose precision. 2. Method redefinition and dispatching. Consider the following C# classes: public class A { public virtual string m() { return "A"; public string T { get ; set ; public A() { T = m (); public class B : A { public new string m() { return "B"; public class C : A { public override string m() { return "C"; and the following corresponding declarations: A a = new A (); B b = new B (); C c = new C (); A x = new B (); A y = new C (); (a) What does the following statement print? Console. WriteLine (a.m() + b.m() + c.m() + x.m() + y.m ()); (Spaces between letters are added for readability.) a. A A C A C b. A B C A C c. A B C B C d. A B C A A 2

(b) What does the following statement print? Console. WriteLine (a.t + b.t + c.t + x.t + y.t); (Spaces between letters are added for readability.) a. A A C A C b. A B C A C c. A A C A A d. The statement does not compile 3. Genericity (in Java). Consider the following declaration of a generic class GC in Java: import java. util.*; public class GC <T extends List < Number >> { Which of the following definitions produce a compilation error (not just warning) in Java? (Remember that, in the Java typesystem, Integer is a subclass of Number, and ArrayList is a subclass of List.) a. GC ex_a = new GC(); b. GC<Number> ex_b = new GC<Number>(); c. GC<List<Number>> ex_c = new GC<List<Number>>(); d. GC<List<Number>> ex_d = new GC<>(); e. GC<List<Integer>> ex_e = new GC<List<Integer>>(); f. GC<List<Number>> ex_f = new GC<List<Integer>>(); g. GC ex_g = new GC<List<Number>>(); h. GC<List<Number>> ex_h = new GC<ArrayList<Number>>(); i. GC<ArrayList<Number>> ex_i = new GC<ArrayList<Number>>(); 4. Exception (in Java). Consider the following Java code: class Test { public static void main ( String [] args ) { try { try { throw new Exception (); catch ( RuntimeException e) { System. out. println (" Inner runtime exception "); finally { System. out. println (" Finally "); try{ ; catch( Exception e){ System. out. println (" Exception caught "); throw new RuntimeException (); catch ( RuntimeException e) { System. out. println (" Outer runtime exception "); catch ( Exception e) { System. out. println (" Outer exception "); throw new RuntimeException (); 3

Which of the following statement(s) about the program behavior is/are true? a. The program prints Inner runtime exception b. The program prints Finally c. The program prints Exception caught d. The program prints Outer runtime exception e. The program prints Outer exception f. The program terminates with an exception 5. Value and Reference types (in C#). Consider the following C# snippet: struct Sample { private int x; public int Increment () { this.x = this.x + 1; return this. x; class { Foo public readonly Sample s = new Sample (); class Program { static void Main ( string [] args ) { Foo f = new Foo (); System. Console. WriteLine (f.s. Increment ()); System. Console. WriteLine (f.s. Increment ()); System. Console. WriteLine (f.s. Increment ()); What is behaviour of this program? a. The program prints 1 2 3 b. The program prints 0 0 0 c. Some exception will be thrown d. The program prints 1 1 1 e. The program won t compile 6. Java Serialization and versioning. Consider the following two versions of the Java class Test: class Test implements Serializable { // Version 1 private int data = 5; String [] stringarray = {"a","b","c"; transient double temp = 1.1; class Test implements Serializable { // Version 2 private int data = 5; String [] stringarray = {"a","b","c"; double temp = 1.1; 4

What can you do to make sure that you can deserialize objects of version 1 from within objects of version 2? a. Doing nothing works: the default deserialization mechanism will accept objects of version 1 from within objects of version 2. b. Insert in version 1 a private static final long serialversionuid attribute and initialize it to the right value e.g. using the Eclipse IDE support. c. Insert in version 1 a private static final long serialversionuid attribute and providing a custom value, e.g. 1L. d. Insert in version 2 a private static final long serialversionuid attribute and initialize it to the right value e.g. using the Eclipse IDE support. e. Insert in version 2 a private static final long serialversionuid attribute and providing a custom value, e.g. 1L. 7. Reflection (in C#). Which of the following combinations of binding flags will work to invoke method internal void AMethod (double, int) passing default values? a. BindingFlags bf = BindingFlags.InvokeMethod BindingFlags.NonPublic; b. BindingFlags bf = BindingFlags.InvokeMethod BindingFlags.Internal; c. BindingFlags bf = BindingFlags.CreateInstance BindingFlags.NonPublic; d. BindingFlags bf = BindingFlags.CreateInstance BindingFlags.Internal e. BindingFlags bf = BindingFlags.DefaultArgs BindingFlags.NonPublic; Old questions start 8. Consider the following Java code: String a = " Good luck!"; String b = " Good "; String c = b; b += " luck!"; System. out. print (a == b); System. out. print ( ); System. out. print (b == c); System. out. print ( ); System. out. print (a. equals (b )); System. out. print ( ); System. out. print (a. equals (c )); What is printed? a. true false true false b. false true true true c. false false false false d. false false true false 9. Consider the following C# code (similar to the Java code from the previous question): string a = " Good luck!"; string b = " Good "; string c = b; b += " luck!"; Console. Write (a == b); Console. Write ( ); Console. Write (b == c); Console. Write ( ); Console. Write (a. Equals (b )); Console. Write ( ); Console. Write (a. Equals (c )); 5

What is printed? a. true false true false b. false true true true c. false false false false d. false false true false 10. You would like a method of your public C# class to be visible to other classes inside the same assembly, as well as to every subclass (including those outside the assembly). Which visibility modifier provides exactly the desired access? a. internal b. protected c. protected internal d. It is not possible to express this level of visibility in C#. e. This is not needed, because it is not allowed to add subclasses outside the assembly. 11. Consider the following C# code: 1 class Test { 2 public static int x = 3; 3 public static int y; 4 5 public int a = x; 6 public int b; 7 8 static Test () { 9 x = 5; 10 11 12 public Test () { 13 x ++; 14 15 16 static void Main () { 17 Test t1 = new Test (); 18 Test t2 = new Test (); 19 Console. Write ( Test.x); 20 Console. Write ( ); 21 Console. Write ( Test.y); 22 Console. Write ( ); 23 Console. Write (t2.a); 24 Console. Write ( ); 25 Console. Write (t2.b); 26 27 What is printed as a result of running Main? (A question mark denotes an undefined value, i.e., any integer value can be printed.) a. 6 0 5 0 b. 7 0 6 0 c. 6? 5? d. 3 0 3? e. 4 0 4 0 f. The code does not compile 6

12. Consider the following Java code: try { try { throw new RuntimeException (); catch ( RuntimeException e) { System. out. println (" Inner runtime exception "); throw e; catch ( Exception e) { System. out. println (" Inner exception "); finally { System. out. println (" Finally!"); throw new Exception (); catch ( RuntimeException e) { System. out. println (" Outer runtime exception "); catch ( Exception e) { System. out. println (" Outer exception "); Which of the following lines are printed? a. Inner runtime exception b. Inner exception c. Finally! d. Outer runtime exception e. Outer exception f. The code does not compile 13. Which of the following declarations produce a compilation error in Java? (Remember that Integer is a subclass of Number and ArrayList is a subclass of List.) a. Number[] a = new Integer[10]; b. ArrayList<int> list1 = new ArrayList<int>(10); c. List<Integer> list2 = new ArrayList<Integer>(10); d. ArrayList<Number> list3 = new ArrayList<Integer>(10); e. ArrayList<?> list4 = new ArrayList<Integer>(10); f. ArrayList<? extends Number> list5 = new ArrayList<Integer>(10); g. ArrayList list6 = new ArrayList<Integer>(10); 7

2 Java Fundamentals (12 Points) The class Address is used to store street addresses consisting of a street and postal code. The subclass ExtendedAddress has an additional field for a country code, and can be used for international addresses. Finish the implementation of these two classes, so that we can use them to index hashtables. 2.1 Class Address public class Address { // Street part of address. public final String street ; // Postal code of address. public final int postalcode ; // Initilize street to s, and postal code to p. public Address ( String s, int p) { street = s; postalcode = p; 8

2.2 Class ExtendedAddress public class ExtendedAddress extends Address { // Country code of address. public final String country ; // Initilize street to s, postal code to p, and country code to c. public ExtendedAddress ( String s, int p, String c) { super(s, p); country = c; 9

10

3 Bounded queue(12 points) Bounded queues are widely spread in the multithreading. In this question you need to implement a bounded thread-safe queue with 2 essential operations: enqueue and dequeue. Enqueue blocks the calling thread if queue stores more than K elements. Dequeue blocks the calling thread, if queue is empty. There can be many threads blocked on one operation. When a blocking condition is gone (an element is added or removed), waiting threads should be waked up. In this question we ask you to implement the singnaling constructs with Monitors & single lock object. The implementation should be thread-safe. Quick reference for Monitor s methods Monitor.Enter(object lock) Enters the critical sections, assosiated with lock. Monitor.Exit(object lock) Leaves the previously entered critical section. In C# locks are recursive (or reentrant), i.e. one thead can enter the several critical section without any problems. Monitor.Wait(object lock) suspends the executioning thread, ceases all previosly obtained locks. Maybe waked upon notification. Monitor.Pulse(object lock) and Monitor.PulseAll(object lock) notifies (awakens) one (all) waiting on the lock. Your tasks: Add necessary private fields to your implementation Implement constructor, which accepts a maximum queue capacity. Note, that capacity should be positive - the implementation should fail on incorrect input by throwing an appropriate exception. Implement Enqueue and Dequeue methods. Note, that there can be more than one thread enqueing and dequeing at the same time. You should use a single lock for your signaling constructs. Implement Properties Max and Count. using System ; using System. Collections. Generic ; using System. Threading ; namespace { Concurrency Listing 1: Selector class public sealed class BoundedQueue <T > { private readonly Queue <T > _queue ; // define here the neccessary fields // define here the constructor, // which accepts the maximum amount of elements. 11

// Enqueues a new item to the queue. // Blocks, if the queue already contains Max elements. public void Enqueue ( T item ) { // Dequeues the last item from the queue. // Blocks, if the queue is empty public T Dequeue () { // Gets the maximum amount of items. public int Max { 12

// Gets the current amount of items, stored in the queue public int Count { 13

4 Delegate (13 points) In C#, one way to represent a criterion regarding certain type of objects is to use delegates. For example, a delegate of type delegate bool IntCriterion(int t); can encode a criterion regarding integers, and be used to select the integers satisfying the criterion from a list. In this question you need to program a library to support composite criteria construction using existing delegates and logical connectives like negation and conjunction. The library should also facilitate the application of such composite criteria in selecting objects from enumerable containers. Note: To keep the question text short, the design of the class hierarchy is not the optimum; Using of namespaces System, System.Collections.Generic, and System.Linq are omitted from all the listings. 4.1 Composite criterion construction Listing 2 shows a use case of composite criterion construction, and Listing 3 gives the sketch of the abstractions for different criteria and their visitors. Add code to the dotted lines to complete the abstractions in a way that supports the use case. Your tasks: Provide a lambda expression at location A. The expression takes a single argument of type int and returns true if and only if the argument can be divided by 3; Provide an anonymous method at location B. The method takes a single argument of type int and returns true if and only if the argument can be divided by 4; Add code at locations C, D, E, and F so that objects of type CriterionVisitor could be used to visit Criterion objects (the Visitor Pattern). Listing 2: Use case for composite criterion construction namespace CompositeCriterion { class Program { static void Main ( string [] args ){ PrimitiveCriterion < int > p1 = new PrimitiveCriterion < int >(... A ); PrimitiveCriterion < int > p2 = new PrimitiveCriterion < int >(... B ); NegCriterion <int > n1 = new NegCriterion <int >( p2 ); // a1 is satisfied by integers that can be divided by 3 // but not by 4. AndCriterion <int > a1 = new AndCriterion <int >( p1, n1 ); namespace CompositeCriterion { Listing 3: Composite criterion classes 14

public delegate bool crifunc <T >( T t); interface Criterion <T >{... C interface CriterionVisitor <T >{... D class PrimitiveCriterion <T >: Criterion <T >{ private crifunc <T > criterionfunc ; public crifunc <T > CriterionFunc { get { return criterionfunc ; protected set { criterionfunc = value ; public PrimitiveCriterion ( crifunc <T > cf ){ CriterionFunc = cf;... E class NegCriterion <T > : Criterion <T >{ private Criterion <T > subcriterion ; public Criterion <T > SubCriterion { get { return subcriterion ; protected set { subcriterion = value ; public NegCriterion ( Criterion <T > sc ){ SubCriterion = sc; // Other details omitted class AndCriterion <T > : Criterion <T >{ private Criterion <T > leftcriterion ; private Criterion <T > rightcriterion ; public Criterion <T > LeftCriterion { get { return leftcriterion ; private set { leftcriterion = value ; 15

public Criterion <T > RightCriterion { get { return rightcriterion ; private set { rightcriterion = value ; public AndCriterion ( Criterion <T > lc, Criterion <T > rc ){ LeftCriterion = lc; RightCriterion = rc;... F 4.2 Checking fulfillment of criterion Class CriterionChecker in Listing 4 implements the visitor pattern to check if an object fulfills an criterion, and method check is the interface for the check. Please provide necessary code at locations G, H, and I to realize the intended semantics of CriterionChecker.check. Note: No need to provide the visit method for NegCriterion at location I. namespace CompositeCriterion { Listing 4: Criterion fulfillment checker class class CriterionChecker <T> : CriterionVisitor <T >{ // Declare necessary attributes here.... G // Check if subject satisfies criterion. // Return true if yes, otherwise false. public bool check ( T subject, Criterion <T > criterion ){ this. subject = subject ;... H... // Define necessary methods here. // Note: No need to provide the visit method for NegCriterion.... I 16

4.3 Using criterion objects in element selection When using Criterion objects to select elements from a container, there are different choices as for how to select and return the result selection. For example, eager selection checks all the elements from the container and stores the ones satisfying the criterion into a separate object, which is then returned to the client, while lazy selection searches for and returns the next element satisfying the criterion in the container, only when the element is accessed by the client through the return selection. Class Selector in Listing 5 intends to support both lazy and eager selection. Code in Listing 6 uses the criterion object from Listing 2 in element selection, where the two foreach loops should output the same sequence of integers. Your tasks: Please briefly compare the performance of eager selection and lazy selection (Describe at least one advantage for each.) Lazy selection:............................................................................................................................................................................................................................................. Eager selection:............................................................................................................................................................................................................................................. Please add necessary code at locations J and K, so that the return objects from both methods LazySelected and EagerSelected could be enumerated to access all the objects satisfying cri from source, in the lazy and the eager way respectively. Listing 5: Selector class namespace CompositeCriterion { class Selector <T >{ public static CriterionChecker <T> checker = new CriterionChecker <T >(); public static IEnumerable <T > LazySelected ( IEnumerable <T > source, Criterion <T > cri ){... J 17

......... public static IEnumerable <T > EagerSelected ( IEnumerable <T > source, Criterion <T > cri ){ List <T > result = new List <T >(10);... K......... Listing 6: Use case for using criterion objects in element selection namespace CompositeCriterion { class Program { static void Main ( string [] args ){ // Continuing from Listing 2 // Generate an array of integers [1, 2, 3,..., 20] int [] values = Enumerable. Range (1, 20). ToArray (); // Should print : 3,6,9,15,18, foreach( int i in Selector <int >. LazySelected ( values, a1 )){ Console. Write (i); Console. Write (","); Console. WriteLine (); // Should print : 3,6,9,15,18, foreach( int i in Selector <int >. EagerSelected ( values, a1 )){ Console. Write (i); Console. Write (","); 18