Explain the relationship between a class and an object. Which is general and which is specific?



Similar documents
CS 111 Classes I 1. Software Organization View to this point:

Introduction to Java

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

CS506 Web Design and Development Solved Online Quiz No. 01

Creating a Simple, Multithreaded Chat System with Java

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CS 121 Intro to Programming:Java - Lecture 11 Announcements

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Chapter 2: Elements of Java

Using Files as Input/Output in Java 5.0 Applications

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Chapter 2 Introduction to Java programming

Reading Input From A File

Sample CSE8A midterm Multiple Choice (circle one)

Java Interview Questions and Answers

Lecture 5: Java Fundamentals III

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

AP Computer Science Java Subset

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Programming Languages CIS 443

Part I. Multiple Choice Questions (2 points each):

Pemrograman Dasar. Basic Elements Of Java

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Variables, Constants, and Data Types

Introduction to Java. CS 3: Computer Programming in Java

Lesson: All About Sockets

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

J a v a Quiz (Unit 3, Test 0 Practice)

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Crash Course in Java

C Compiler Targeting the Java Virtual Machine

AP Computer Science File Input with Scanner

Java Programming Fundamentals

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

public static void main(string[] args) { System.out.println("hello, world"); } }

Computing Concepts with Java Essentials

Division of Informatics, University of Edinburgh

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Compiler Construction

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

13 File Output and Input

Object-Oriented Programming in Java

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

Java Application Developer Certificate Program Competencies

Fundamentals of Java Programming

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

No no-argument constructor. No default constructor found

WRITING DATA TO A BINARY FILE

Compiler Construction

Debugging Java Applications

CS 106 Introduction to Computer Science I

Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach ) The JdbcTemplate. Class...

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

CS170 Lab 11 Abstract Data Types & Objects

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Basic Programming and PC Skills: Basic Programming and PC Skills:

Chapter 5. Recursion. Data Structures and Algorithms in Java

Programming Project 1: Lexical Analyzer (Scanner)

Building a Multi-Threaded Web Server

Instrumentation Software Profiling

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Chapter 6: Programming Languages

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Moving from CS 61A Scheme to CS 61B Java

Week 1: Review of Java Programming Basics

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Java CPD (I) Frans Coenen Department of Computer Science

D06 PROGRAMMING with JAVA

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

INFORMATION BROCHURE Certificate Course in Web Design Using PHP/MySQL

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

(Eng. Hayam Reda Seireg) Sheet Java

Internet and Intranet Protocols and Applications

Performance Improvement In Java Application

Exception Handling In Web Development DevelopIntelligence LLC

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

D06 PROGRAMMING with JAVA

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Building Java Programs

Continuous Integration Part 2

Chapter 7D The Java Virtual Machine

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

Event-Driven Programming

C++ INTERVIEW QUESTIONS

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Java Basics: Data Types, Variables, and Loops

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

Introduction to Programming

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Quick Introduction to Java

Transcription:

A.1.1 What is the Java Virtual Machine? Is it hardware or software? How does its role differ from that of the Java compiler? The Java Virtual Machine (JVM) is software that simulates the execution of a hypothetical computer. The JVM s role differs from that of the Java Compiler in that the compiler is the device that translates the Java Source Code to the Java Byte Code, whereas the JVM actually takes the Java Byte Code and executes and interprets the commands and carries them out. Some versions of the JVM translate the Java Byte Code into native machine code at run-time. This is known as just in time compilation. The hot spot JVM that is included in the Java Development Kit from Sun observes the execution of the byte code as it is interpreted, and performs just in time compilation on code that it observes is repeatedly executed. A.1.3 Explain the relationship between a class and an object. Which is general and which is specific? A class is a named description for a group of entities that have the same characteristics. The class has properties and methods that can be performed on it. The object is a specific defined instance of a class. The class is more general; the object is more specific. A.2.1 For the following assignment statement, assume that x, y are type double and m, n are type int. List the order in which the operations would be performed. Include any widening and narrowing conversions that would occur. m = (int) (x * y + m / n / y * (m + x)); A.2.3 1. x is multiplied by y 2. m is divided by n 3. the result of step 2 (m/n) is widened to double 4. the result of step 4 is divided by y 5. m is widened to double and x is added 6. the result of step 5 is multiplied by the result of step 5 7. the result of step 6 is added to the result of step 1 8. the result of step 7 is narrowed to int (fraction part dropped) and stored into m What is the difference between a reference variable and a primitive-type variable? When a primitive data type is declared as a variable, the memory cell allocated for the variable is the actual data. When the variable is a reference variable to an object, the memory allocated for the variable is actually the address of the object referenced.

A.3.1 What is the purpose of the break statement in the preceding switch statement? List the statements that would execute when operator is ' ' with the break statements in place and if they were removed. The break statement causes execution to leave the scope of the switch statement (closing }). If the break statements were removed and the operator was ' ' then the following statements would be executed: result = x y; subtractop++; result = x * y; multiplyop++; result = x / y; divideop++; A.4.1 Identify the escape sequences in the following string. Show how this line would be displayed. Which of the escape sequences could be replaced by the second character of the pair without changing the effect? System.out.println( "Jane\'s motto is \n\"semper fi\"\n, according to Jim"); The escape sequences are: \' representing ' \n representing a new-line \" representing " The string is displayed as follows: Jane's motto is "simper fi" according to Jim The \' could be replaced by ' without changing the result. A.5.1 Evaluate each of these expressions. "happy".equals("happy") "happy".compareto("happy") "happy".equalsignorecase("happy") "happy".equals("happy".charat(0) + "Happy".substring(1)) "happy" == "happy".charat(0) + "Happy".substring(1) "happy".equals("happy") "happy".compareto("happy") +1 "happy".equalsignorecase("happy") false true

"happy".equals("happy".charat(0) + "Happy".substring(1)) "happy" == "happy".charat(0) + "Happy".substring(1) true false A.5.3 Rewrite the following statements using StringBuilder objects: String myname = "Elliot Koffman"; String mynamefirstlast = myname; myname = myname.substring(7) + ", " + myname.substring(0, 6); The first two statements do not use a StringBuilder. The last statement can be rewritten using a StringBuilder as follows: StringBuilder temp = myname.substring(7); temp.append(", "); temp.append(myname.substring(0, 6); myname = temp.tostring(); A.5.5 Revise Exercise 4 to insert a newline character between the words in result. StringBuilder result = new StringBuilder(); String sentence = "Let's all learn how to program in Java"; String[] tokens = sentence.split(\\s+); for (String token : tokens) { result.append(token); result.append('\n'); } A.6.1 Do you think objects of a wrapper type are immutable or not? Explain your answer. The objects of the wrapper types are immutable because there are no methods defined that will change their value. A.7.1 Explain why methods have public visibility but data fields have private visibility. Methods implement the operations on the data type represented by the class and data fields represent the attributes or state of the object. Only the operations (methods) should be able to change the values of the attributes. Therefore, the data fields are declared private, and the methods are declared public. In this way users of the class can access the methods but cannot directly access the data fields. A.7.3 Trace the execution of the following statements. Person p1 = new Person("Adam", "Jones", "wxyz", 0); p1.setbirthyear(1990);

Person p2 = new Person("abcd"); p2.setgivenname("eve"); p2.setfamilyname(p1.getfamilyname()); p2.setbirthyear(p1.getbirthyear() + 10); if (p1.equals(p2)) System.out.println(p1 + "\nis same person as\n\n" + p2); else System.out.println(p1 + "\nis not the same person as\n\n" + p2); Person p1 = new Person("Adam", "Jones", "wxyz", 0); Creates a Person object with the givenname Adam, the familyname Jones, an ID of wxyz and a birthyear of 0 and assigns a reference to it to the variable p1. p1.setbirthyear(1990); The birthyear of p1 (Adam Jones) is set to 1990 Person p2 = new Person("abcd"); Creates a Person object with all data fields set to null or 0 except for ID, which is set to abcd, is created and assigns a reference to it to the variable p2. p2.setgivenname("eve"); The givenname of the Person object referenced by p2 is set to "Eve" p2.setfamilyname(p1.getfamilyname()); The familyname of the Person object referenced by p2 is set to "Jones" p2.setbirthyear(p1.getbirthyear() + 10); The birthyear of the Person object referenced by p2 is set to "2000" if (p1.equals(p2)) else System.out.println(p1 + "\nis same person as\n\n" + p2); System.out.println(p1 + "\nis not the same person as\n\n" + p2); Output is Given name: Adam Family name: Jones ID number: wxyz Year of birth: 1990 is not the same person as Given name: Eve Family name: Jones ID number: abcd

Year of birth: 2000 A.8.1 Show the output that would be displayed by method main following Listing A.3. Given name: Elliot Family name: K ID number: 123 Year of birth: 1942 Given name: Paul Family name: W ID number: 234 Year of birth: 1945 A.8.3 What is the output of the following sample code fragment? int[] x; int[] y; int[] z; x = new int[20]; x[10] = 0; y = x; x[10] = 5; System.out.println(x[10] + ", " + y[10]); x[10] = 15; z = new int[x.length]; System.arraycopy(x, 0, z, 0, 20); x[10] = 25; System.out.println(x[10] + ", " + y[10]+ ", " + z[10]); 5 + 5 25 + 25 + 15 A.8.5 Assume there is no initializer list for the Pascal triangle and you are trying to build up its rows. If row i has been defined, write statements to create row i + 1. pascal[i + 1] = new int[i + 2]; pascal[i + 1][0] = 1; pascal[i + 1][i + 1] = 1; for (int j = 1; j < i + 1; j++) pascal[i+1][j] = pascal[i][j-1] + pascal[i][j]; A.9.1

Show the statements that would be required, using Swing, to read and store the data for a Person object prior to calling the constructor with four parameters. String givenname = JOptionPane.showInputDialog("Enter given name"); String familyname = JOptionPane.showInputDialog("Enter family name"); String id = JOptionPane.showInputDialog("Enter id"); String birthyear = JOptionPane.showInputDialog("Enter birth year"); Person p = new Person(givenName, familyname, id, Integer.parseInt(birtyYear)); A.10.1 Show the statements that would be required, using the console for input, to read and store the data for a Person object prior to calling the constructor with four parameters. Scanner scan = new Scanner(System.in); System.out.println("Enter given name"); String givenname = scan.next(); System.out.println("Enter family name"); String familyname = scan.next(); System.out.println("Enter id"); String id = scan.next(); System.out.println("Enter birth year"); String birthyear = scan.next(); Person p = new Person(givenName, familyname, id, Integer.parseInt(birtyYear)); A.10.3 What would happen if the output file name matched the name of a file already saved on disk? What could happen if the user forgets to close an output file? If an output file name matches the name of a file already saved on a disk then the old file is deleted and the data written replaces it. If the user forgets to close an output file, some or all of the data may not be written to the destination. A.11.1 Assume that method main calls method first at line 10 of class MyApp, method first calls method second at line 10 of class Others, and method second calls method parseint at line 20 of class Other. These calls result in a NumberFormatException at line 430 of class Integer. Show the stack trace. Exception in thread "main" java.lang.numberformatexception at java.lang.integer.parseint(integer.java 430) at Other.second(Other.java:20) at Others.first(Others.java:10) at MyApp.main(MyApp.java:10)

A.12.1 Explain the difference between the throws clause and the throw statement. The throws clause states that a method may throw the specified checked exceptions. The throw statement is how an exception is thrown. A.12.3 When would it be better to throw an exception rather than catch it in a method? If the method has the ability (available information) to handle an exception, then it should catch it and perform the appropriate handling. If the method cannot handle an exception completely, then after catching it, it should throw it or a related exception. In this case, when throwing the exception it should include the original exception as a parameter to the newly thrown exception's constructor. A.12.5 For the following situations, indicate whether it would be better to catch an exception, declare an exception, or throw an exception in the lower-level method. Explain your answer and show the code required for the lower-level method to do it. a. A lower-level method contains a call to method readline; the higher-level method that calls it contains a catch clause for class IOException. b. A method contains a call to method readline to enter a value that is passed as an argument to a lower-level method. The lower-level method s argument must be a positive number. c. A lower-level method contains a call to method readline, but the higher-level method that calls it does not have a catch clause for class IOException. d. A lower-level method reads a data string and converts it to type int. The higher-level method contains a catch clause for class NumberFormatException. e. A lower-level method detects an unrecoverable error that is an unchecked exception. a. The lower-level method should declare IOException. The caller is expecting it. b. This method should contain a catch clause within a loop for NumberFormatException to ensure that the input value is a valid number. It should also catch IOException. The catch clause should print a message and call System.exit since this is not generally a recoverable error. c. It should catch IOException. The catch clause should print a message and call System.exit since this is not generally a recoverable error. d. No special code is required for NumberFormatException, but It should catch IOException. The catch clause should print a message and call System.exit since this is not generally a recoverable error.

e. A lower-level method detects an unrecoverable error that is an unchecked exception. e. No special code is required.