Variance in the Java Programming Language

合集下载

JAVA程序设计实用教程 (第3版) 叶核亚 习题答案 所有答案1 12章

JAVA程序设计实用教程 (第3版)  叶核亚 习题答案  所有答案1 12章
7.什么是解释执行?Java 怎样解释执行两种应用程序? 【答】解释执行即将字节码解释成本地机器码并执行。
Java 源程序文件经编译后生成字节码文件,若是 application 应用程序,则将字节码文件 交由 Java 解释器解释执行,最后在 windows 操作系统上运行。若是 applet 应用程序,则将 字节码文件嵌入超文本文件并下载到 web 浏览器上,最后由 windows 操作系统中的 Java 虚 拟机运行。
int i=1,n=10,s=0; for(i=1,i<=n,i++);
s+=i; System.out.pointln(“Sum=1+……+”+n+”=”+s); 有错误,正确的如下
int i=1,n=10,s=0; for(i=1,i<=n,i++)
s+=i; System.out.pointln(“Sum=1+……+”+n+”=”+s);
8.作为一个软件开发人员,应该具备那些基础知识用以开发 windows 应用程序? 【答】略
第2章
1.标示符和关键字在定义和使用方面有何区别? 【答】定义方面:标示符是用户定义的、以字母开头的字母数字序列,关键字是由 Java 语 言定义的、具有特定含义的英文单词。
使用方面:标示符用于命名变量、常量、类、对象等元素,每一个关键字都有特定的含 义,不能被赋予别的含义。
11.输出以下数字的形式; (1) 0 0 0 0
011 1 012 2 012 3 〖解答〗采用二重循环的程序如下。
public class Phalanx {
public static void main(String args[]) {

java语言程序设计课后习题答案解析

java语言程序设计课后习题答案解析

习题23.使用“= =”对相同内容的字符串进行比较,看会产生什么样的结果。

答:首先创建一个字符串变量有两种方式:String str = new String("abc");String str = "abc";使用“= =”会因为创建的形式不同而产生不同的结果:String str1 = "abc";String str2 = "abc";System.out.println(str1= =str2); //trueString str1 = new String("abc"); String str2 = "abc";System.out.println(str1= =str2); //falseString str1 = new String("abc"); String str2 = new String("abc"); System.out.println(str1= =str2); //false因此自符串如果是对内容进行比较,使用equals方法比较可靠。

String str1 = "abc";String str2 = "abc";System.out.println(str1= =str2); //trueString str1 = new String("abc"); String str2 = "abc";System.out.println(str1.equals(str2)); //trueString str1 = new String("abc"); String str2 = new String("abc"); System.out.println(str1.equals(str2)); //true5.编写一个程序,把变量n的初始值设置为1678,然后利用除法运算和取余运算把变量的每位数字都提出来并打印,输出结果为:n=1678。

Java语言程序的设计第三版_习题答案

Java语言程序的设计第三版_习题答案

Java语⾔程序的设计第三版_习题答案第⼀章绪论1.简述Java技术体系的组成。

Java技术体系主要由三部分组成:Java平台标准版Java SE,Java平台企业版Java EE,以及Java 平台微缩版Java ME。

Java SE为Java桌⾯和⼯作组级应⽤的开发与运⾏提供了环境。

它的实现主要包括Java SE Development Kit(JDK)和Java SE Runtime Environment(JRE)。

Java SE提供了编写与运⾏Java Applet与Application的编译器、开发⼯具、运⾏环境与Java API。

Java EE 定义了基于组件的多层企业级应⽤的开发标准,⾯向企业级和⾼端服务器的Internet应⽤开发。

它基于Java SE,包括Enterprise JavaBeans(EJB),Java Servlets API以及Java Server Pages(JSP)等技术,并为企业级应⽤的开发提供了各种服务和⼯具。

Java ME是针对消费类电⼦设备如移动、电视置顶盒、汽车导航系统等的嵌⼊式计算的⼀组技术和规。

2.Java的特征有哪些?简述这些特征的含义。

Java语⾔的特征包括:简单(Simple)、⾯向对象(Object oriented)、分布式(Distributed)、解释型(Interpreted)、健壮(Robust)、安全(Secure)、体系结构中⽴(Architecture neutral)、可移植(Portable)、⾼性能(High performance)、多线程(Multithreaded)和动态(Dynamic)●简单性:Java语⾔语法和语义都⽐较单纯,容易学习和使⽤。

另外,去掉C++中的指针,取消多重继承和运算符重载,存管理由程序员移向Java嵌的⾃动存回收机制等●⾯向对象:作为⼀种⾯向对象的编程语⾔,Java不仅最为“纯洁”,也对⾯向对象⽅法学的⽀持也最为全⾯。

java leetcode刷题笔记

java leetcode刷题笔记

java leetcode刷题笔记Learning to solve Leetcode problems in Java can be both challenging and rewarding. The process of working through each problem requires a deep understanding of data structures, algorithms, and the Java programming language. It also requires patience and determination, as some problems can be quite complex and may require multiple iterations to solve.学习用Java解决Leetcode的问题可能既具有挑战性,也具有回报性。

解决每个问题的过程需要对数据结构、算法和Java编程语言有深入的理解。

它也需要耐心和决心,因为一些问题可能会非常复杂,可能需要多次迭代才能解决。

One of the key benefits of solving Leetcode problems in Java is the opportunity to improve your problem-solving skills. Each problem presents a unique challenge that requires you to think critically and creatively to come up with an efficient solution. This process helps to sharpen your analytical skills and expand your problem-solving toolkit, which can be valuable not only in programming but also in many other areas of life.用Java解决Leetcode问题的一个关键好处是提高你的解决问题的能力。

C++面向程序对象语言(双语)选择题+答案

C++面向程序对象语言(双语)选择题+答案

C++面向程序对象语言(双语)选择题+答案mChapter I: Principles of Object-Oriented Programming1. Which of the following languages is not a procedure-oriented programming language?a) ALGOL(算法语言)b) COBOL(面向商业通用语言)c) FORTRAN(公式翻译程序语言)d) None of the above2. Which of the following programming approach (程序设计方法)used functions as a keyconcept to perform action-oriented tasks?(指导任务??)a) Structured(结构化)programmingb) Modular (模块化)programmingc) Procedure-oriented programming(面向对象)d) Object-oriented programming3. Identify the drawback(缺点)of using procedure-oriented programming, if any:a) Data is hidden(隐藏)from external functions(外部函数)b) New functions can be added whenever necessaryc) Does not reflect real world problemsd) All of the above4. Which is not associated(联系)with Object-oriented programming?a) Data abstraction(数据提取)b) Automatic initialization(自动初始化)c) Dynamic binding(动态绑定)d) None5. The term operator overloading(操作符重载)in C++ refers to:a) Inheritance(继承)b) Message passing (信息传递)c) Polymorphism(多态性)d) None6. Which one of the following OOP concepts enables reusability (再利用)of components(成员)?a) Inheritanceb) Encapsulation(数据分装)c) Polymorphismd) All of the above7. The concept of hierarchical classification (层次分类)is related to:a) Abstractionb) Inheritancec) Function overloading(重载)d) None8. Object-based (基于对象)programming languages do not support:i. Inheritanceii. Dynamic bindingiii. Encapsulationiv. All of the abovea) Both i and iib) iii onlyc) iv onlyd) i, ii, and iii9. C++ does not supporti. Genericity(泛型C#)ii. Early bindingiii. Garbage collection(碎片收集)iv. Multiple Inheritance(多重继承)a) i onlyb) ii onlyc) iii onlyd) ii, iii and iv10. Which of the following is an Object-oriented programming language?i. Smalltalkii. Object Pascaliii. Javaiv. All of the abovea)Both ii and iiib)i onlyc) i ii onlyd) iv onlyChapter II: Beginning With C++1. Which one of the following options is true on the topic of Simula67?i. It is the first Object-oriented programming languageii. It?s a predecessor to C++iii. It was designed for doing simulationsiv. All of the abovea) Both i and iib) i onlyc) iii onlyd) iv only2. Which of the following features (特征)that distinguish (区别)object orientedprogramming from other conventional(常规的)programming?i. Structural design(结构设计)ii. Inheritanceiii. Modular programming(模)iv. bottom-upa) i onlyb) Both ii and iiic) Both ii and ivd) iv only3. Comments (解释)in C++ starts with _______ symbol.a) //b) \\c) **d) None of the above4. The insertion operator(插入操作符)is another name fora) input operatorb) output operator(输出操作符)c) extraction operatord) None of the above5. Which header file in C++ does contain function prototypes for memory(记忆)allocation(分配)?a)b)c)d)6. What is the output of the following code?int n=10;while (n<10)cout<< “Number:”<<n+1;< p="">a) 10b) 11c) No outputd) None of the above7. Which of the following statements require the header file to be included?a) a=b/c;b) cout << a;c) c=sqrt(a);(平方根)d) Both a and c8. Identify the error, if any: char str_name …a…;a) str_name is not a valid variable nameb) Variables cannot be initialized at the time of declarationc) Missing = sign between str_name and …a?d) No error9. Name the library that must be included while using cin.a)b) (输入输出流)c)d)10. A C++ program structure is based on the concept ofa) Client-server modelb) N-Tier modelc) Both a and bd) None of the aboveChapter III: Tokens, Expre ssions and Control Structure s1. return is an example of aa) Keyword(关键字)b) Functionc) Statement (声明)d) Comment2. Which of the following is not a keyword?i. forii. friendiii. virtualiv. privatea) i onlyb) Both ii and iiic) Both i and ivd) ii, iii and iv3. Identify the valid (有效地)variable(可变的)name from the following:i. charii. var_nameiii. _varnameiv. str_name2a) Both i and iiib) Both ii and ivc) ii, iii, and ivd) i only4. Which of the following is not a user-defined data type?a) arrayb) structurec) uniond) class5. Write the equivalent C++ statement for the following expression, X= b a +*c/da) X=sqrt(a+b) *(c/d);b) X=(squareroot(a+b)*c)/d;c) X=()(b a +* c)/d;d) None of the above6. The statement int main() is a ___________.a) function prototypeb) function callc) function header lined) None of the above7. The declaration of global variables (全局变量) must be madea) inside the functionb) outside the functionc) in a function header lined) None of the above8. Identify the error, if any:double avg=tot/n;a) Declaration should not contain any expressionb) Initialization cannot be done in the declaration statementc) Dynamic initialization is not possibled) No error9. Which of the following is true about scope resolution operator?a) Qualifies a namespace member to its namespaceb) Allows you to access a global variablec) Qualifies the hidden variabled) All of the above10. Which of the following is not a member-dereferencing operator?a) ::*b) ::c) *d) *11. Which of the following is true about new operator?i. While using new operator, sizeof() operator is not needed ii. It is also not necessary to use cast operatoriii. new operator can be overloadediv. All of the abovea) Both i and iib) Both i and iiic) ii onlyd) iv only12. Identify the manipulators in C++:a) Endl(输出时换行)b) setw(设置域宽)c) Both a and bd) None of the above13. a = (b = 5); The C++ statement is an example ofa) Compound (合成)assignmentb) Embedded (嵌入)assignmentc) Chained (束缚)assignmentd) Multiple (多重)assignment14. Water-fall model is associated witha) Control structuresb) Type conversionsc) Manipulatorsd) None of the above15. Selection structure is also known bya) Branching(歧义)b) straight linec) iterationd) None of the above16. Consider the following code:cout<< “Welcome”;This is an example ofa) C++ statementb) Return typec) Functiond) Both a and cChapter IV: Functions in C++1. Which of the following is true about a function call in a C++ program?a) A function must be called atleast onceb) A function cannot be called from other functionsc) A function may be called whenever it is necessaryd) Both a and c2. Function prototyping definesa) The return type of the functionb) The identifier of the functionc) The number and type of argumentsd) All of the above3. Find if the following function prototype contains any error:double area(int )a) No errorb) Variable name is not included in the argument listc) Semicolon(分号)is not foundd) None of the above4. Identify which function prototype exhibits(显示)the following: Name of the function issample_calc, which receives two values of type double and returns no value;a) sample_calc(double, double);b) void sample_calc(double, double);c) double sample_calc(void);d) void sample_calc(double, double)5. When you call a function by passing the address of a data variable, it is called ________.a) Call by referenceb) Call by valuec) Call by two directionsd) Both b and c6. Which of the following function calls is correct while providing default arguments:I. double calc(int a, float b=12.0);II. double calc(int a=3, float b=12.0, int c);III. double calc(int a=3, float b, int c=8);IV. double calc(int a, float b=12.0, int c=8);a) I onlyb) II onlyc) Both I and IVd) Both II, and III7. Which function call does invoke the following function prototype?float sub1(int a, float b);a) X=sub1(5.0,6.5);b) X=sub1(5,6.5);c) X=sub1(5,6);d) Both b and c8. Identify the variables, which are local to the following function:int calc(int p, int n){int q;q=pow(p,n);return(q);}a) p and nb) p,n, and qc) qd) Cannot be determined without the main() function9. Which of the following statements is true about the function that contains the constargument?a) The function should not modify the const argumentb) Const declaration is necessary only when the arguments are passed by referencec) Both b and cd) None of the above10. Which of the following functions in C++ replace the usage of macros in C?a) friend functionb) virtual functionc) inline functiond) All of the aboveChapter IX: Pointers, Virtual Functions and Polymorphism1. Which of the following is true about pointers?a) A pointer is a data typeb) A pointer is a keywordc) A special type of integer (整数)variabled) None of the above2. Which of the following statement(s) is true according to the following statement?p=*ptr;a) p must be a pointer variableb) The value of ptr is assigned to the variable pc) The address of the pointer ptr is assigned to the variable pd) The value of the variable that the pointer ptr is pointing to is assigned to thevariable p3. Compile time polymorphism is also known asa) early bindingb) static bindingc) static linkingd) All of the above4. C++ supports a mechanism virtual function to achievea) compile time polymorphismb) function overloadingc) run time polymorphismd) operator overloading5. Which of the following is NOT true about virtual functions?I. They cannot be static membersII. A virtual function can be a friend of another classIII. We can have virtual constructors, but we cannot have virtual destructorsIV. They are accessed by using object pointersa) II onlyb) III onlyc) Both II and IIId) I, II and IV6. Consider the following code segment:int main(){int x, *x_ptr=&xx=5;x_ptr=NULL;cout<< x << “ “ << *x_ptr;return 0;}What is the output of the above code?a) 0b) but addresses are samec) but having different addressesd) 57. Consider the following code segment:int main(){double f, *f_ptr=&ff=5.25;f_ptr=4.5;cout<< “Value of f is:” << “ “ << f;return 0;}What is the output of the above code?a) Value of f is: 5.25b) Value of f is:c) Value of f is: 4.5d) Compiler error8. How will you assign value …5? to the variable …x? inside a member function using thispointer?a) this->x=5;b) this.x=5;c) x=5;d) None of the above9. Consider a class X, which includes a virtual function called X_output. The virtual functionreceives a float value and returns nothing. Find out the function prototype for the same.a) virtual void X_output(float );b) X:: virtual void X_output(float );c) virtual X:: void X_output(float );d) virtual :: void X_output(float );10. What would be the output of the following code?#include#includeclass A{public:virtual void disp(){cout<<"This is from class A";}};class B : public A{public:void disp(){cout<<"This is from class B";}};void main(){clrscr();A *s;s = new B();s->disp();}a) This is from class Ab) This is from class Bc) This is from class A This is from class Bd) None of the above11. Which of the following is NOT true about pure virtual function?a) It is also called do-nothing functionb) It cannot declare its own objectsc) A virtual function, which is not equated to zero is called a pure virtual functiond) None of the aboveChapter V: Classe s and Objects1. The declaration of a class includesa) Declaration of data membersb) Declaration of function prototypec) Return statements of functionsd) Both a and b2. By default, the members of a class area) privateb) publicc) protectedd) static3. Which OOP feature can be enabled by using private declaration for the class members?a) Data abstractionb) Polymorphismc) Encapsulationd) Modularity4. Which of the following will assign the value to the class member variable num?void getnum(int a)a) {num=a};b) {num=a;}c) {a=num};d) {a=num;}5. Which of the following is not true about member functions?a) Can access private data variablesb) Can call another function directly without using dot ope ratorc) Both a and bd) None of the above6. Identify all the members of the following class xyz:class xyz{int x,y;public:xyz();void calc(int a, int b);void output_calc(void);};a) Data members x and yb) Data members x and y, Constructor, and member functions calc() andoutput_calc()c) Data members x and y, and member functions calc() andoutput_calc()d) Constructor and member functions calc() and output_calc()7. Which of the following is not true about static member variable?a) Only one instance of static member can be createdb) Visible only within the classc) It can be initialized whenever necessaryd) Both a and b8. What is the general format of calling a static member function using a class name?a) class-name :: function-nameb) function-name :: class-namec) class-name :: function-name;d) function-name :: class-name;9. Which of the following is true while passing objects as function arguments? It is possiblea) to pass copy of the entire object to the functionb) to pass only the address of the object to the functionc) to pass the objects to a non-member functiond) All of the above10. A friend functionI. Can be invoked similar to other functions without using objectsII. Cannot access to other member functions directlyIII. Cannot be called using the object of the class to which it has beendeclared as friendIV. Can be declared only in the public part of a classa) I, II and IIIb) I, II and IVc) I, II, III and IVd) IV onlyChapter VI: Constructors and Destructors1. Which of the following is not true about constructors and destructors?a) They must have the same name as classb) They cannot return valuesc) They cannot be called more than once in a programd) They are called automatically2. The default constructor for class A isa) A :: A()b) A :: A(int)c) A :: A(int);d) A :: A();3. Which of the following statements do correctly describe the charac teristics ofconstructors?I. They cannot be inheritedII. They cannot be virtualIII. They need not be declared in the public sectionIV. We cannot refer to their addressesa) Both I and IIb) I, II, and IVc) Both II and IIId) I, III and IV4. Which of the following is called an implicit constructor for the class xyz?a) xyz(){ }b) xyz(int){}c) xyz(){ };d) None of the above5. Consider the following code segment:class simple{int a,b;public:simple();simple(char[]);};Which of the following would assigns the string “welcome” to the second c onstructor?a) simple s(“welcome”);b) simple s(welcome);c) simple s=”welcome”;d) None of the above6. Identify if any error in the following code segment1. class example2. {3. f loat x;4. p ublic:5. void example();6. example(int, float);7. };a) Line 7 should not include the semicolonb) Line 6 is an incorrect statementc) Line 5 cannot include voidd) No error7. Which of the following statements are true about copy constructors?I. It declares and initializes an object from another objectII. It will not be useful when arguments are passed by value III. It can be used to pass arguments by referenceIV. The compiler provides its own copy constructor, if it is not defined.a) I, II, IVb) All are correctc) Both II and IIId) III only8. The following statement creates a constant object of a class simple:const simple m(a,b);Which the following is true regarding the above statement?a) The compiler generates compile-time error if you try to change the values of …a?and …b?b) Const member is a function prototypec) The compiler generates an error if m tries to invoke non-const member functionsd) All of the above9. Which of the following statements do incorrectly describe the characteristics ofdestructors?I. A destructor is a member function, which has the same name as classnameII. A destructor receives only one argumentIII. A destructor does not return any valueIV. Usage of destructors in a program clean up memory space that is not useda) Both I and IIb) All are incorrectc) Both II and IIId) I, II and IV10. Which of the following is a correct description of the destructor …sample? and incl udesoutput statements (if possible)?a) sample :: ~sample() {cout << “Welcome”; }b) sample :: ~sample() { };c) void ~sample() { }d) ~sample() { };Chapter VII: Operator Overloading and Type Conversions1. Which of the following operators cannot be overloaded?a) ?:b) ::c) .*d) All of the above2. Operator Overloading is also known by the terma) runtime polymorphismb) compile-time polymorphismc) Both a and bd) None of the above3. Operator overloading is necessary becausea) C++ attempts to make the user-defined classes act like built-in typesb) To provide new definitions for most of the C++ operatorsc) To add user-defined data type like basic data typesd) All of the above4. Which of the following is required to overload an operator in C++?a) operator functionb) built-in functionc) Both a and bd) None of the above5. Identify the correct definition of an operator function for the class sample, which overloadsa unary minus operator and returns no values.a) sample :: oper-() { };b) void sample :: operator-() { }c) void sample :: operator-() { };d) sample :: operator-() { }6. Which of the following is not true about the code segment given below?float sample :: operator +(float x) {// code }a) It receives only one float type argument explicitlyb) It returns a float type valuec) It is a member function of sampled) None of the above7. Which of the following operators cannot use friend functions for overloading?I. ==II. ( )III. [ ]IV. ->a) I onlyb) II onlyc) II, III and IVd) I, II and III8. Which of the following is not true about operator overloading?a) Only existing operators can be overloadedb) Binary arithmetic operators (+,-,*,/) (二进制算子)need not return a valuec) It is impossible to redefine an operatord) All of the above9. Which of the following code segments will convert (改变)a class object namely sample totype double?a) sample :: operator double() { }b) operator double() { }c) sample :: operator double();d) operator double();10. Which of the following statements does correctly describe the casting operator function?a) It must not specify return typeb) It must be a class memberc) It must not have any argumentsd) All of the aboveChapter VIII: Inheritance: Extending Classe s1. Which of the following OOP concepts is supported by Inheritance?a) Abstractionb) Encapsulationc) Reusability (再利用)d) None of the above2. Which of the following does a derived class inherit from a base class?(从基类继承)a) public and protected(受保护)class membersb) public and private class membersc) only public datad) Everything3. Which of the following statement(s) is true, if a derived class is publicly inherited from abase class?I. The public members of the base class become public members of thederived classII. The public members of the base class become private members of the derived classIII. The public members of the base class are inaccessible(不可达到)to the objects of the derived classIV. All of the abovea) I onlyb) Both I and IIc) Both I and IIId) IV only4. Consider the following code segment:class A{int a;public:int b;void inp();}class B : A{// members of B}Which of the following statement(s) is NOT true regarding the above code?a) The public members, namely …b? and inp() of class Abecome private members ofclass Bb) The public members, namely …b? and inp() of class A can be accessed by themember functions of class Bc) The public members, namely …b? and inp() of class A are inaccessible to theobjects of class Bd) None of the above5. According to the following code, which of the following class members does the derivedclass inherit from the base class?class base{float x;int y;public:int a;void get_a();void put_a();}class derived : public base{// members of B}a) float xb) int yc) get_a(), void put_a()d) All of the above6. Which of the following statement(s) is true about thevisibility(能见度?)of inheritedmembers?a) When a class is inherited in protected mode, the private members of the baseclass become protected members of the derived classb) When a class is inherited in private mode, only the public members of the baseclass can be inherited to the derived classc) When a class is inherited in public mode, the private members of the base classcannot be inheritedd) None of the above7. What are the visibility modifiers(修饰语)available in C++?a) publicb) privatec) protectedd) All of the above</n+1;<>。

java语言程序设计-基础篇--课件(第8章)英文

java语言程序设计-基础篇--课件(第8章)英文

Example: Defining Classes and Creating Objects
10
Objective: Demonstrate creating objects, accessing data, and using methods.
TV
TestTV Run
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
1
Chapter 8 Objects and Classes
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
Motivations
2
After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java features are not sufficient for developing graphical user interfaces and large scale software systems. Suppose you want to develop a graphical user interface as shown below. How do you program it?

Towards verification of Java programs in √ erICS

Towards verification of Java programsin√erICS⋆Andrzej Zbrzezny1,Bo˙z ena Wo´z na1,Maciej Orzechowski1and Franco Raimondi21IMCS,Jan D l ugosz University of Cz¸e stochowaAl.Armii Krajowej13/15,42-200Cz¸e stochowa,Polandemail:{m.orzechowski,b.wozna,a.zbrzezny}@ajd.czest.pl2DCS,University College LondonGower Street,London WC1E6BT,UKemail:F.Raimondi@Abstract.VerICS is a tool for the automated verification of timed au-tomata and protocols written in both the Intermediate Language andthe specification language Estelle.Recently,the tool has been extendedto work with Timed Automata with Discrete Data and with multi-agentsystems.This paper presents a prototype translation from a subset of theJava programming language to Timed Automata with Discrete Data.Inaddition,we show how to use the translator together with the verifica-tion core of VerICS to validate the well-known alternating bit protocolwritten in Java.1IntroductionGiven a description of a system S and a property(specification)P the verifica-tion problem consists in establishing whether S satisfies P.This can be achieved by using either homogeneous or heterogeneous verification methods.The former class of methods assumes that both the system and the specification are given in the same formalism,while the latter allows the system and the specification to be described in different formalisms.Model checking is a verification technique that was originally developed for temporal logics.Its main idea consists in representing afinite state system,of-ten derived from a hardware or software design,as a labelled transition system (model),representing a specification by a temporal formula,and checking auto-matically whether the formula holds in the model.For the last twenty years model checking has became a widely recognised and prominent technique in hardware[16]and protocol verification[11].Also, during the last two decades surprisingly many efficient verification tools have appeared.The most advanced and popular are SPIN[12],NuSMV[4],Uppaal [20],AVISPA[3].This paper employs Ver ICS,a new verification tool developed in the pastfive year.Ver ICS is fully automated and geared toward verification of time dependent and multi-agent systems as well as communication and security protocols.It can be downloaded from[1].The tool is designed to accept a number of input languages that either are translated into Intermediate Language(IL)[7]or di-rectly into a formalism called Timed Automata with Discrete Data(TADD)[14, 23].The core of the verification engine of the tool is mainly based on transla-tions of the model checking problem into the SAT problem[9].Further,Ver ICS uses state-of-art SAT solvers like zchaff[17]and MiniSat[8],and it is also equipped with GUI interfaces.The architecture of Ver ICS is composed of the following modules:–Language Translator:it takes a system description in Estelle[13],which is an ISO standard specification language designed for describing communica-tion protocols and distributed systems,and it translates this description into IL that allows for describing a system as a set of processes,which exchange information by message passing(via bounded or unbounded channels)or memory sharing(using global variables).–Automata Translator:it constructs timed automata(with discrete data) from an IL program.–BMC Analyser:it verifies ECTLK[15]properties over models for timed automata and TECTL[19]properties over models for TADD.–UMC Analyser:it verifies CTLK properties over models for timed au-tomata.Verifying programs written in programming languages like Java or C/C++ is different from verifying hardware or protocols;the state space is often infinite and the relationships between possible states are harder to understand because of asynchronous behaviour and complex underlying semantics of the languages. Further,the size and complexity of software force us to treat model checking rather as a debugging technique in software verification than a fully automated validation process of the software.In particular,for what concerns verification of Java programs,we see model checking as a method that can be applied to the more crucial parts of a Java software.In order to investigate the challenges that software poses for model checking, we have developed a preliminary Java to TADD translator that will become a part of the tool VerICS,which,as one can see from the architecture presented above,does not support verification of Java programs yet.Therefore,the main aim of the present paper is to describe this translator,which will allow for verification of Java programs in VerICS.To support the claim,in addition,we show how to use our translator together with the verification core of VerICS to validate the well-known alternating bit protocol written in Java.The rest of the paper is organised as follows.The next section provides a discussion on related works.In Section3we define translations of a subset of Java to TADD.Finally,we test the translation on the alternating bit protocol. 2Related WorkModel checking of Java programs has become increasingly popular during the last decade.However,to the best of our knowledge,there are only two existing modelcheckers that can verify Java programs.Thefirst tool is called JavaPathFinder [10,21,18]and the second one is called Bandera[5].Thefirst release of JavaPathFinder(JPF1)is described in[10].JPF1trans-lates Java code into Promela code,which then can be model checked by means of the SPIN model checker[12].In this realisation Java programs may contain: dynamic creation of objects with data and methods,class inheritance,threads, synchronized statements,the wait and notify methods,exceptions,thread in-terrupts and most of the standard programming languages constructs such as assignment statements,conditional statements and loops.However,the trans-lator misses some features,such as packages,overloading,method overriding, recursion,strings,floating point numbers,some thread operations like suspend and resume,and some control constructs such as the continue statement.In addition,arrays are not objects as they are in Java,but are modelled using Promela’s own arrays to obtain efficient verification.The second generation of JavaPathFinder(JPF2)is described in[21,18].This version of JPF2combines model checking techniques with techniques for dealing with large or infinite state spaces.These techniques include a static analysis for supporting partial order reductions of the set of transitions to be explored by the model checker,a predicate abstraction for abstracting the state space,and a runtime analysis such as race condition detection and lock order analysis to pinpoint potentially problematic code fragments.JPF2techniques operate on the Java bytecode.The papers[6,5]provide an overview of the Bandera tool.In particular,they describe a theory of translating Java programs into transition models,making use of a static pointer analysis to aid virtual coarsening,which reduces the size of the models.The Bandera tool is designed to be a bridge between a non-finite-state software system expressed as Java source code and tools like NuSMV and SPIN.3TranslationThis section describes a prototype translator of Java programs into Timed Au-tomata with Discrete Data(TADD).These automata are standard diagonal timed automata[22]augmented to include integer variables over which a stan-dard arithmetic and Boolean expressions can be defined.Moreover these au-tomata take as an input a set of initialised integer variables and a set of propo-sitional variables true at particular states.Since each real Java software is writ-ten as a set of communicating processes(classes),it is reasonable to translate classes of the software into a net of TADDs that run in parallel,communicate with each other via shared variables and perform transitions with shared labels synchronously;we assume here a standard definition of parallel composition[2].We start by describing our running example:the Alternating Bit Protocol (ABP),a well-known communication protocol that is often used as a test case for automated verification tools.3.1Alternating Bit ProtocolThe protocol involves three active components:a sender,a receiver and a bidi-rectional communication channel.Each message that is sent from the sender to the receiver goes through an unreliable communication channel and contains a data part together with a one-bit identifier.public cl a s s A l t B i t P r o t o c o l{public s ta ti c void main(S t r i n g[]args){LossyChannel channel=new LossyChannel();(new Thread(new Sender(channel))).s t a r t();(new Thread(new R eceiv er(channel))).s t a r t();}}Fig.1.Java source code of the main classimport jav a.u t i l.Random;public cl a s s Sender implements Runnable{private LossyChannel channel;public Sender(LossyChannel channel){this.channel=channel;}public void run(){boolean p r o t o c o l B i t=f a l s e;Random random=new Random();while(true){i f(p r o t o c o l B i t!=channel.getAckBit()){channel.put(p r o t o c o l B i t);}e l s e{p r o t o c o l B i t=!p r o t o c o l B i t;}try{Thread.s l e e p(random.n ex t I n t(1500));}catch(I n t erru p t ed Ex cep t i on e){}}}}Fig.2.Java source code of SenderThe protocol works in the following way.The sender reads a message at his input and extends it with a control bit to form a frame.Then it starts sending the frame to the receiver,which is initially silent.The sending of the frame proceeds until the sender receives an acknowledgement.After that,the senderflips the control bit and starts all over again.As soon as the receiver receives the frame with the control bit that matches its internal control bit,the message in the frame is sent to the output port,and an acknowledgement is sent to the sender. Then the receiverflips his internal control bit and waits for another frame.The communication channel transmits frames both from the sender to the receiver,and from the receiver to the sender.There are four possible situations that can occur.Frames are properly transmitted from the sender(the receiver) to the receiver(the sender),or frames are corrupted or lost during such a trans-mission.Figures1,3,2and4show a Java source code of ABP,which will then be translated into a network of TADDs.import jav a.u t i l.Random;public cl a s s R eceiv er implements Runnable{private LossyChannel channel;public R eceiv er(LossyChannel channel){this.channel=channel;}public void run(){Random random=new Random();while(true){boolean p r o t o c o l B i t=channel.get();channel.putAckBit(p r o t o c o l B i t);try{Thread.s l e e p(random.n ex t I n t(1500));}catch(I n t erru p t ed Ex cep t i on e){}}}}Fig.3.Java source code of Receiver3.2A Translation of Java programs to TADDThe subset of Java,which we use in our translator contains:definitions of inte-ger variables,standard programming language constructs like assignment state-ments,conditional statements and loops,definitions of classes,objects,methods and threads(we allow to create threads in the main class only),synchronized methods,and the methods wait(),notify(),sleep()and random().In order to translate the Java code into timed automata with discrete data, we proceed in the following way.First we partition the input Java code into several modules that contain respectively the application class,thread classes and classes that do not extend the thread classes.Then,we parse each module in accordance with the Java subset we have chosen(this is currently performed by hand),and we start a step-by-step analysis of the application class.The translation of the application class consists in:–introducing integer variables for all the variable declarations of the type int and Boolean;–introducing a set of integer variables for each Java declaration of the type className variable.These variables represent thefields of the object vari-able,also those inherited from the base classes.For example,the declara-tion LossyChannel channel introduces the following four integer variables: channel channelEmpty,channelrandom.–producing one TADD for each thread.import jav a.u t i l.Random;public cl a s s LossyChannel{private boolean p r o t o c o l B i t,channelEmpty=true,ackBit=true;private Random random;public LossyChannel(){random=new Random();}public synchronized boolean getAckBit(){n o t i f y();return ackBit;}public synchronized void putAckBit(boolean ackBit){ this.ackBit=ackBit;int i g n o r e B i t=random.n ex t I n t(5);i f(i g n o r e B i t>2){this.ackBit=!this.ackBit;}n o t i f y();}public synchronized boolean get(){while(channelEmpty){try{wait();}catch(I n t erru p t ed Ex cep t i o n e){}}channelEmpty=true;n o t i f y();return p r o t o c o l B i t;}public synchronized void put(boolean p r o t o c o l B i t){ while(!channelEmpty){try{wait();}catch(I n t erru p t ed Ex cep t i o n e){}}this.p r o t o c o l B i t=p r o t o c o l B i t;channelEmpty=f a l s e;int ign orePack et=random.n ex t I n t(5);i f(ign orePack et>2){channelEmpty=true;}n o t i f y();}}Fig.4.Java source code of the communication channelAll the variables introduced above are shared by all the resulting automata.To produce an automaton for a thread,we proceed as follows.First,for all the variables var of type int or Boolean of the considered thread class that are defined in the body of the method run(),we introduce corresponding local integer variables threadNameTr(if(B){S1}else{S2})(a)(b)Fig.5.A translation of:(a)an assignment statement;(b)a conditional statement.Tr(while(B){S1})statement S1; statement S2;(a)(b)Fig.6.A translation of:(a)a loop statement;(b)concatenation of two statements.–If there is a loop statement of the form while(condition B){statement S1;},then wefirst build an automaton for S1,written T r(S1),and next weproduce an automaton as it is shown in Figure6(a).–If there are two consecutive statements statement S1;statement S2;, then wefirst build automata for S1and S2,written T r(S1)and T r(S2).Next,we produce an automaton which is the concatenation of T r(S1)and T r(S2),that is,the new automaton has as a initial location the initial lo-cation of T r(S1)(i.e.,in1),as afinal location thefinal location of T r(S2)(i.e.,out2),and as a“contact”location a new location(out1-in2),which isa merger of thefinal location of T r(S1)(i.e.,out1)and the initial locationof T r(S2)(i.e.,in2)(see Figure6(b)).–If there is a method wait(),then the translation is as shown in Figure7(a), that is,we have an automaton of four locations with(m−1)+2tran-sitions,where m is the number of threads.Thefirst transition is labelled by action wait j which denotes the fact that a thread number j goes to a waiting state and opens the semaphore.In this state the thread is wait-ing to be notified by any other thread.Here this is represented by the actions notify(1,j),...,notify(j−1,j),notify(j+1,j),...,notify(m,j);these are synchronized actions between threads.Once that action happens,the thread gets into the ready state.A thread in this state is ready for execution,but is not being currently executed.Once a thread in the ready state gets accessto the CPU,it gets converted to the running state.This is done by invoking a synchronized action active j ,which will close thesemaphore.Tr(wait())jj(1,j ),...,notify (j −1,j ),(j +1,j ),...,notify (m,j )(a)wait()Tr(notify())none j k ∈{1,...,j −1,j +1,...m }(j,k )(b)notify()Tr(synchronized method)(c)a synchronized methodFig.7.A translation of methods wait(),notify()and a synchronized method for thread j .–If there is a method notify()that wakes up an arbitrary chosen thread from all the threads waiting on the object’s lock,then the translation is as shown in Figure 7(b).Namely,we have an automaton of two locations with two transitions labelled by notify (j,k ),for k ∈{1,...,j −1,j +1,...,m },and none j ,respectively.The synchronized action notify (j,k )represents the fact that thread number j notifies the thread number k which thereby is moved to the ready state .If there are no waiting threads,the notify()method has no effect;this is realised by the local action none j .–A translation of synchronized methods is shown in Figure 7(c).As one can see,we build an automaton that has two special locations in and out ,and two special transitions that are labelled with synchronized actions in j and out j ,respectively,where j denotes the number of a thread which has invoked the synchronized method under consideration,in denotes the entrance to the method,and out denotes the exit from the method.The synchronization process is realised by using a binary semaphore.Note that in the translation process the labels in j and out j will have re-spectively the following general form:inthreadNumber (for example in 1)and out threadNumber (for exampleout1)(see the resulting automata for the alternating bit problem).–A translation of the method sleep()consists in introducing a new clockwith the general name xthreadNametion of the form x threadNamethreadName sendernumber threadNumber:=0; and(3)a guard of the form0≤x threadNamesenderthreadNumbermethodNamemethodNamethreadNameclassNames_protocolBit = sender_protocolBit ;s_ignorePacket=sender_1_ignorePacketLEGEND: s = x1_sender_1 ; sleep_1 = sleep_1_sender_1 ;s_put=sender_1_put ;s_getackBit=sender_1_getackBitFig.9.An automaton forSenderr_protocolBit:=receiver_1_protocolBitLEGEND: r_get=receiver_1_get ;r_putackBit:=receiver_1_putackBit ;r_ignoreBit=receiver_1_ignoreBitr=x1_receiver_1 ;Fig.10.An automaton for ReceiverAMD Athlon XP1800(1544MHz),1GB main memory and the operating system Linux2.6.21.Since the BMC module is designed to look for errors,we have introduced in our Java code the following errors:in the class LossyChannel we have set the variable channelEmpty to zero(i.e.,we have put channelEmpty=0),and we have exchanged the condition of the while loop in the method get()to the following one:while(!channelEmpty){...}.These two small changes cause the protocol to stop working nearly imme-diately;indeed,none of the threads can do anything.Tofind the cause of this behaviour,we have checked this modified Java code of ABP for the existence of deadlocks.The simplest way tofind deadlocks is to verify whether the gen-erated network of TADDs admitsfinite runs only.To this end,it is enough to check whether the ECTL formula EF true is true in the model of the considered network for any possible length of a run.In our example,it is possible to verify that there is no run of length longer than24.The generated witness shows the reason for such a situation:the protocol gets into a state where both threads wait for a notification from another thread,but none of them can invoke the method notify().Table1reports this witness;experimental results are reported in Table2.locations Sender’s clock<0,0,0>,<0,0/4>,<0,0,0>,<1471,3/4>,<1,0,0>,<1471,3/4>,<1,0,0>,<2069,2/4>,<1,1,1>,<2069,2/4>,<1,1,1>,<2312,0/4>,<1,2,0>,<2312,0/4>,<1,2,0>,<2817,0/4>,<2,2,1>,<2817,0/4>,<2,2,1>,<3516,0/4>,<3,3,1>,<3516,0/4>,<3,3,1>,<0,1/4>,<4,3,1>,<0,1/4>,<4,3,1>,<514,1/4>,<5,3,0>,<514,1/4>,<5,3,0>,<2016,0/4>,<5,1,1>,<2016,0/4>,<5,1,1>,<2016,0/4>,<5,2,0>,<2016,0/4>,<5,2,0>,<2180,2/4>,<6,2,1>,<2180,2/4>,<6,2,1>,<2887,1/4>,<7,2,1>,<2887,1/4>,<7,2,1>,<3296,2/4>,<8,2,0>,<3296,2/4>,Table1:The witnessIn Table1thefirst column shows the length of the witness,the second column shows locations of Sender,Receiver and Semaphore,respectively,the third column shows values of integer variables with the meaning:z0:chan-nel protocolBit,z2:r protocolBit,z4 :r ackBit,z5:channel ignoreBit,z7:ss put,z10:sk clauses BMC MB MiniSAT MB4390.00.0YES 416756 2.2 4.412022 1.50.1YES 1249000 3.6 6.023606 3.30.7YES 2081244 5.07.935190 4.70.9YES 26105427 6.08.935.87.31and waitLength values of variables Receiver’s clock 0:<1,0,0,0,0,1,0,0,1,0,0>,<0,0/4>1:<1,0,0,0,0,1,0,0,1,0,0>,<877,1/4>2:<1,0,0,0,0,1,0,0,1,0,0>,<877,1/4>3:<1,0,0,0,0,1,0,0,1,0,0>,<2102,2/4>4:<1,0,0,0,0,1,0,0,1,0,0>,<2102,2/4>5:<1,0,0,0,0,1,0,0,1,0,0>,<3186,0/4>6:<1,0,0,0,0,1,0,0,1,0,0>,<3186,0/4>7:<1,0,0,0,0,1,0,0,1,0,0>,<273,2/4>8:<1,0,0,0,0,1,0,0,1,0,0>,<273,2/4>9:<1,0,0,0,0,1,0,0,1,0,0>,<941,3/4>10:<1,0,0,0,0,1,0,0,1,0,0>,<941,3/4>11:<1,0,0,0,0,1,0,0,1,0,0>,<2440,0/4>12:<1,0,0,0,0,1,0,0,1,0,0>,<2440,0/4>13:<1,0,0,0,0,1,0,0,1,0,0>,<3637,3/4>14:<1,0,0,0,0,1,0,0,1,0,0>,<3637,3/4>15:<1,0,0,0,0,1,0,0,1,0,0>,<40,1/4>16:<1,0,0,0,0,1,0,0,1,0,0>,<40,1/4>17:<1,0,0,0,0,1,0,0,1,0,0>,<1331,1/4>18:<0,0,0,0,0,1,0,0,1,0,0>,<1331,1/4>19:<0,0,0,0,0,1,0,0,1,0,0>,<1486,3/4>20:<0,0,0,0,0,1,0,0,1,0,1>,<1486,3/4>21:<0,0,0,0,0,1,0,0,1,0,1>,<1817,0/4>22:<0,0,0,0,0,1,0,0,1,0,1>,<1817,0/4>23:<0,0,0,0,0,1,0,0,1,0,1>,<2211,0/4>24:<0,0,0,0,0,1,0,0,1,0,1>,<2211,0/4>25:<0,0,0,0,0,1,0,0,1,0,1>,<2805,2/4>26:<0,0,0,0,0,1,0,0,1,0,1>,<2805,2/4>27:<0,0,0,0,0,1,0,0,1,0,1>,<3713,0/4>28:<0,0,0,0,0,1,0,0,1,0,1>,<3713,0/4>29:<0,0,0,0,0,1,0,0,1,0,1>,<112,2/4>30:<0,0,0,0,0,1,0,0,1,0,1>,<112,2/4>31:<0,0,0,0,0,1,0,0,1,0,1>,<281,2/4>32:<0,0,0,0,0,1,0,0,1,0,1>,<281,2/4>33:<0,0,0,0,0,1,0,0,1,0,1>,<1540,3/4>34:<0,0,0,0,0,1,0,0,1,0,1>,<1540,3/4>35:<0,0,0,0,0,1,0,0,1,0,1>,<2816,0/4>36:<0,0,0,0,0,1,0,0,1,0,1>,<2816,0/4>37:<0,0,0,0,0,1,0,0,1,0,1>,<75,2/4>38:<0,0,0,0,0,1,0,0,1,0,1>,<75,2/4>39:<0,0,0,0,0,1,0,0,1,0,1>,<1016,0/4>40:<0,0,0,0,0,1,0,0,1,0,1>,<1016,0/4>41:<0,0,0,0,0,1,0,0,1,0,1>,<1277,3/4>42:<0,0,0,0,0,1,0,0,1,0,1>,<1277,3/4>43:<0,0,0,0,0,1,0,0,1,0,1>,<2049,0/4>44:<0,0,0,0,0,1,0,0,1,0,1>,<2049,0/4>45:<0,0,0,0,0,1,0,0,1,0,1>,<3008,0/4>46:<0,0,0,0,0,1,0,0,1,0,1>,<3008,0/4>k clauses BMC MB MiniSAT MB4450.10.0NO416798 2.1 4.412044 1.40.1NO1249090 3.6 6.023644 2.60.4NO2081382 5.07.735244 4.0 1.5NO28113674 6.39.746844 5.3 1.7NO361459667.711.358444 6.4 4.1NO441782589.113.2671447.511.3YESIn total:9.413.8Table4:Property EF(wait state)5SummaryIn this paper we have proposed a preliminary Java to Timed Automata with Discrete Data translator,which is going to be a part of the tool VerICS.We have also provided preliminary experimental results.We are currently working on examples to compare the performance of our method with Bandera and JPF.Acknowledgement:The authors wish to thank an anonymous reviewer for constructive comments on this paper.References1.VerICS.http://verics.ipipan.waw.pl/verics/.2.R.Alur.Timed Automata.In Proc.of CAV’99,volume1633of LNCS,pp.8–22.Springer-Verlag,1999.3. A.Armando,D.Basin,Y.Boichut,Y.Chevalier,pagna,J.Cuellar,P.Han-kes Drielsma,P.-C.H´e am,J.Mantovani,S.Moedersheim,D.von Oheimb,M.Rusi-nowitch,J.Santiago,M.Turuani,L.Vigan`o,and L.Vigneron.The AVISPA Tool for the Automated Validation of Internet Security Protocols and Applications.In Proc.of CAV’05,volume3576of LNCS,2005.4. A.Cimatti,E.Clarke,F.Giunchiglia,and M.Roveri.NuSMV:A new symbolicmodel verifier.In Proc.of CAV’99,volume1633of LNCS,pp.495–499.Springer-Verlag,1999.5.J.Corbett,M.Dwyer,J.Hatcliff,Robby C.Pasareanu,ubach,and H.Zheng.Bandera:Extractingfinite-state models from java source code.In Proc.of ICSE ’00,pp.439–448.ACM Press,2000.6.James C.Corbett.Constructing compact models of concurrent java programs.InInternational Symposium on Software Testing and Analysis,pp.1–10,1998.7. A.Doro´s,A.Janowska,and P.Janowski.From specification languages to TimedAutomata.In Proc.of CS&P’02,volume161(1)of Informatik-Berichte,pp.117–128.Humboldt University,2002.8.N.E´e n and N.S¨o rensson.An Extensible SAT-solver.In Proc.of SAT’03,volume2919of LNCS,pp.502–518.Springer Berlin/Heidelberg,2004.9.J.Gu,P.Purdom,J.Franco,and B.Wah.Algorithms for the satisfiability(SAT)problem:a survey.In Satisfiability Problem:Theory and Applications,volume35 of DIMASC,pp.19–152.American Mathematical Society,1996.10.K.Havelund and T.Pressburger.Model checking JAVA programs using JAVAPathFinder.International Journal on Software Tools for Technology Transfer, V2(4):366–381,March2000.11.G.J.Holzmann.Design and Validation of Computer Protocols.Prentice Hall,1991.12.G.J.Holzmann.The model checker SPIN.IEEE transaction on software engi-neering,23(5):279–295,1997.13.ISO/IEC9074(E),Estelle-a formal description technique based on an extendedstate-transition model.International Standards Organization,1997.14. A.Janowska and P.Janowski.Slicing of timed automata with discrete data.Fun-damenta Informaticae,72(1-3):181–195,2006.15.M.Kacprzak,A.Lomuscio,and W.Penczek.From bounded to unbounded modelchecking for temporal epistemic logic.Fundamenta Informaticae,63(2,3):221–240, 2004.16.K.L.McMillan.Symbolic Model Checking.Kluwer Academic Publishers,1993.17.M.Moskewicz,C.Madigan,Y.Zhao,L.Zhang,and S.Malik.Chaff:Engineeringan efficient SAT solver.In Proc.of DAC’01,pp.530–535,June2001.18. C.Pasareanu and W.Visser.Verification of Java Programs Using Symbolic Exe-cution and Invariant Generation.In Proc.of SPIN’04,volume2989of LNCS,pp.164–181.Springer-Verlag,2004.19.W.Penczek,B.Wo´z na,and A.Zbrzezny.Bounded model checking for the universalfragment of CTL.Fundamenta Informaticae,51(1-2):135–156,2002.20.P.Pettersson and rsen.Uppaal2k.Bulletin of the European Associationfor Theoretical Computer Science,70:40–44,February2000.21.W.Visser,K.Havelund,G.Brat,and S.Park.Model checking programs.In Proc.of ASE’00,September2000.22. A.Zbrzezny.SAT-based reachability checking for timed automata with diagonalconstraints.Fundamenta Informaticae,67(1-3):303–322,2005.23. A.Zbrzezny and A.P´o lrola.Sat-based reachability checking for timed automatawith discrete data.Fundamenta Informaticae,79(3–4):579–593,2007.。

《Java语言程序设计:基础篇》课后复习题答案-第五章

Chapter5Methods1.At least three benefits:(1)Reuse code;(2)Reduce complexity;(3)Easy to maintain.See the Sections5.2and5.3on how to declare and invoke methods.What is thesubtle difference between“defining a method”and“declaring a variable”?A declaration usually involvesallocating memory to store a variable,but a definitiondoesn’t.2.void3.Yes.return(num1>num2)?num1:num2;4.True:a call to a method with a void return type is always a statement itself.False:a call to a value-returning method is always a component of an expression.5.A syntax error occurs if a return statement is not used to return a value in a value-returning method.You can have a return statement in a void method,whichsimply exits the method.But a return statement cannot return a value such asreturn x+y in a void method.6.See Section5.2.puting a sales commission given the sales amount and the commission ratepublic static double getCommission(double salesAmount,doublecommissionRate)Printing a calendar for a monthpublic static void printCalendar(int month,int year)Computing a square rootpublic static double sqrt(double value)Testing whether a number is even and return true if it ispublic static boolean isEven(int value)Printing a message for a specified number of timespublic static void printMessage(String message,int times)Computing the monthly payment,given the loan amount,number of years,and annual interest rate.public static double monthlyPayment(double loan,intnumberOfYears,double annualInterestRate)Finding the corresponding uppercase letter given a lowercase letter.public static char getUpperCase(char letter)8.Line2:method1is not defined correctly.It does not have a return type or void.Line2:type int should be declared for parameter m.Line7:parameter type for n should be double to match method2(3.4).Line11:if(n<0)should be removed in method,otherwise a compile error is reported.9.public class Test{public static double xMethod(double i,double j){ while(i<j){j--;}return j;}}10.You pass actual parameters by passing the right type of value in the right order.The actual parameter can have the same name as its formal parameter.11."Pass by value"is to pass a copy of the value to the method.(A)The output of the program is0,because the variable max is not changed byinvoking the method max.(B)224248248162481632248163264(C)Before the call,variable times is3n=3Welcome to Java!n=2Welcome to Java!n=1Welcome to Java!After the call,variable times is3(D)12121421i is 512.Just before max is invoked.Space required for the main methodmax: 0Just entering max.Space required for the max methodmax: 0value2: 2 value1: 1Just before max is returnedSpace required for the main methodmax: 0Space required for the max methodmax: 2value2: 2 value1: 1 Space required for the main methodmax: 0Space required for the main methodmax: 0Right after max is returned13.Two methods with the same name,defined in the same class,is called method overloading.It is fine to have same method name,but different parameter types.You cannot overload methods based on return type,or modifiers.14.Methods public static void method(int x)and public static int method(int y)have the same signature method(int).15.Line 7:int n =1is wrong since n is already declared in the method signature.16.True17.(a)34+(int)(Math.random()*(55–34))(b)(int)(Math.random()*1000)(c)5.5+(Math.random()*(55.5–5.5))(d)(char)(‘a’+(Math.random()*(‘z’–‘a’+1))18.Math.sqrt(4)= 2.0Math.sin(2*Math.PI)=0Math.cos(2*Math.PI)=1Math.pow(2,2)= 4.0Math.log(Math.E)=1Math.exp(1)= 2.718Math.max(2,Math.min(3,4))=3 Math.rint(-2.5)=-2.0Math.ceil(-2.5)=-2.0Math.floor(-2.5)=-3.0Math.round(-2.5f)=-2Math.round(-2.5)=-2Math.rint(2.5)= 2.0Math.ceil(2.5)= 3.0Math.floor(2.5)= 2.0Math.round(2.5f)=3Math.round(-2.5)=-2Math.round(Math.abs(-2.5))=3。

java程序设计教程(第六版)课后习题答案

pp2.3public class fudian {public static void main(String[] args) {float a=2.10f,b=3.70f;float Result1,Result2,Result3;Result1=a+b;Result2=a-b;Result3=a*b;System.out.println("Result1 is:"+Result1);System.out.println("Result2 is:"+Result2);System.out.println("Result3 is:"+Result3);}}2.4public class TempConverter {public static void main(String[] args) {final int BASE = 32;final double CONVERSION_FACTOR = 5.0 / 9.0;double celsiusTemp;int fahrenheitTemp = 70; // value to convertcelsiusTemp = (fahrenheitTemp - BASE)*CONVERSION_FACTOR;System.out.println ("Fahrenheit Equivalent: " + fahrenheitTemp);System.out.println ("Celsius Temperature: " + celsiusTemp);}}2.5public class yinglizhuanqianmi {public static void main(String[] args) {float Base=1.60935f;float Qianmi;float Yingli=19.85f;Qianmi=Yingli*Base;System.out.println ("Ying Li: " + Yingli);System.out.println ("Qian Mi: " +Qianmi);}}2.6public class TimeConverter1 {public static void main(String[] args) {int Hour=5,Minute=35,Second=51;int SECONDS;SECONDS=Hour*60*60+Minute*60+Second;System.out.println (+Hour+"时"+Minute+"分"+Second+"秒");System.out.println ("换算成秒: " + SECONDS);}}2.7public class TimeConverter2 {public static void main(String[] args) {int SECONDS=10853;int Hour,Minute,Second;Second=SECONDS%60;Minute=(SECONDS-Second)%60;Hour=(SECONDS-Second-Minute*60)/3600;System.out.println (SECONDS+"秒,转化为");System.out.println (Hour+"时"+Minute+"分"+Second+"秒");}}2.9import java.util.*;public class Dollarbill {public static void main(String[] args) {float Dollar1,Dollar2;int Ten,Five,One,Quarters,Dimes,Nickles,Pennies;Scanner reader=new Scanner(System.in);System.out.println("输入币值:");Dollar1=reader.nextFloat();Dollar2=Dollar1*100;Pennies= (int)Dollar2%5;Nickles=((int)Dollar2%10-Pennies)/5;Dimes=((int)Dollar2-Pennies-Nickles*5)%50/10;Quarters=(int)Dollar2%100/50;One=((int)Dollar2- Pennies-Nickles*5-Dimes*10-Quarters*50)%500/100;Five=(int)Dollar2%1000/500;Ten=(int)Dollar2/1000;System.out.println(Ten+ "ten dollar bills");System.out.println(Five+ " five dollar bills");System.out.println(One+ "one dollar bills");System.out.println(Quarters+ "quarters dollar bills");System.out.println(Dimes+ "dimes dollar bills");System.out.println(Nickles+ "nickles dollar bills");System.out.println(Pennies+ "pennies dollar bills!");}}2.11import java.util.*;public class Fenshuzhuanhuan {public static void main(String[] args) {int x,y;double Result=0;Scanner reader=new Scanner(System.in);System.out.println("输入x:");x=reader.nextInt();System.out.println("输入y:");y=reader.nextInt();Result+=x/y;System.out.println ("分数"+x+"/"+y);System.out.println ("转换成小数是: " + Result);}}2.16import javax.swing.JApplet;import java.awt.*;public class Olympiclogo extends JApplet{public void paint (Graphics page) {page.setColor(Color.blue);page.drawOval(25, 65, 40, 40);page.setColor(Color.yellow);page.drawOval (55, 65, 40, 40);page.setColor(Color.black);page.drawOval (85, 65, 40, 40);page.setColor(Color.green);page.drawOval (115, 65, 40, 40);page.setColor(Color.red);page.drawOval (145, 65, 40, 40);// circlepage.setColor(Color.cyan);page.drawString ("OL YMPIC LOGO", 40, 30);}}2.19import java.applet.*;import java.awt.*;public class Ex2_19 extends Applet{public void paint (Graphics page){page.setColor(Color.BLACK);page.setFont(new Font("楷体",Font.ITALIC+Font.BOLD,30));page.drawString ("林少锋", 40, 30);page.setColor(Color.blue);page.setFont(new Font("宋体",Font.BOLD,30));page.drawString ("林少锋", 70, 80);}}2.20import java.applet.*;import java.awt.*;public class Ex2_20 extends Applet{public void paint (Graphics page){page.drawOval(35, 35, 130, 130);page.setColor(Color.red);page.fillArc(35, 35, 130, 130,0,45);page.setColor(Color.blue);page.fillArc(35, 35, 130, 130,45,45);page.setColor(Color.yellow);page.fillArc(35, 35, 130, 130,90,45);page.setColor(Color.cyan);page.fillArc(35, 35, 130, 130,135,45);page.setColor(Color.gray);page.fillArc(35, 35, 130, 130,180,45);page.setColor(Color.green);page.fillArc(35, 35, 130, 130,225,45);page.setColor(Color.darkGray);page.fillArc(35, 35, 130, 130,270,45);page.setColor(Color.pink);page.fillArc(35, 35, 130, 130,315,45);}}PP4.1方法1import java.util.*;public class CreateSphere {/*** @param args*/public static void main(String[] args) {// TODO 自动生成方法存根System.out.println("请输入直径d:");Scanner scan=new Scanner(System.in);double d=scan.nextDouble();Sphere D=new Sphere(d);D.Square();D.Volum();System.out.println(D.toString());}}public class Sphere {final double PI=3.14;double V,S;double d;Sphere(double d){this.d=d;}public void V olum(){V=(4/3)*PI*(d/2)*(d/2)*(d/2);}public void Square(){S=4*PI*(d/2)*(d/2);}public String toString(){String s="";String result1=Double.toString(S);String result2=Double.toString(V);s=("体积为:"+result2+"面积为:"+result1);return s;}}方法2//Sphere.javapublic class Sphere{private double diameter;public Sphere(){//构造方法:无参数this.diameter = 1.0;}public Sphere(double d){ //构造方法:带一个参数this.diameter = d;}public void setDiameter(double d) {//设置直径值的方法this.diameter = d;}public double getDiameter(){//获取直径值的方法return this.diameter;}public double volume(){//计算球的体积return 4*Math.PI*Math.pow(this.diameter/2,3)/3;}public double area(){//计算球的表面积return 4*Math.PI*Math.pow(this.diameter/2,2);}public String toString(){String out = "该球体的直径为:" + this.diameter + "\n" + "该球体的表面积为:" + this.area() + "\n" +"该球体的体积为:" + this. volume();return out;}}//MultiSphere.javaimport java.util.Scanner;public class MultiSphere{public static void main(String[] args){Scanner scan = new Scanner(System.in);Sphere sphere1 = new Sphere();Sphere sphere2 = new Sphere(3.5);System.out.println("sphere1: " + sphere1 + "\n");System.out.println("sphere2: " + sphere2 + "\n");System.out.println("sphere1和sphere2分别调用无参构造方法" +"和带一个参数的构造方法进行初始化。

JAVA语言程序的设计第8版第5章完整答案programmingexercises程序练习题答案完整版

5_1public class Exercise01 {public static void main(String[] args) {final int PENTAGONAL_NUMBERS_PER_LINE = 10;final int PENTAGONAL_NUMBERS_TO_PRINT = 100;int count = 1;int n = 1;while (count <= PENTAGONAL_NUMBERS_TO_PRINT) {int pentagonalNumber = getPentagonalNumber(n);n++;if (count % PENTAGONAL_NUMBERS_PER_LINE == 0)System.out.printf("%-7d\n", pentagonalNumber);elseSystem.out.printf("%-7d", pentagonalNumber);count++;}}public static int getPentagonalNumber(int n) {return n * (3 * n - 1) / 2;}}5_2import java.util.Scanner;public class Exercise02 {public static void main(String[] args) {Scanner input = new Scanner(System.in);//Prompt the user to enter an integerSystem.out.print("Enter an interger: ");long number = input.nextLong();System.out.println("The sum of the digits in " + number + " is " + sumDigits(number));}public static int sumDigits(long n) {int sum = 0;long remainingN = n;do {long digit = remainingN % 10;remainingN = remainingN / 10;sum += digit;} while (remainingN != 0);return sum;}}第03题import java.util.Scanner;public class Exercise03 {public static void main(String[] args) {Scanner input = new Scanner(System.in);//Prompt the user to enter an integerSystem.out.print("Enter an integer: ");int number = input.nextInt();//Display resultSystem.out.println("Is " + number + " a palindrome? " + isPalindrome(number));}public static boolean isPalindrome(int number) {if (number == reverse(number))return true;elsereturn false;}public static int reverse(int number) {int reverseNumber = 0;do {int digit = number % 10;number = number / 10;reverseNumber = reverseNumber * 10 + digit;} while (number != 0);return reverseNumber;}}第04题import java.util.Scanner;public class Exercise04 {public static void main(String[] args) {Scanner input = new Scanner(System.in);//Prompt the user to enter an integerSystem.out.print("Enter an integer: ");int number = input.nextInt();//Display resultSystem.out.print("The reversal of " + number + " is ");reverse(number);}public static void reverse(int number) {int reverseNumber = 0;do {int digit = number % 10;number = number / 10;reverseNumber = reverseNumber * 10 + digit;} while (number != 0);System.out.println(reverseNumber);}}第05题import java.util.Scanner;public class Exercise05 {public static void main(String[] args) {Scanner input = new Scanner(System.in);//Prompt the user to enter three numbersSystem.out.print("Enter three numbers: ");double num1 = input.nextDouble();double num2 = input.nextDouble();double num3 = input.nextDouble();System.out.print(num1 + " " + num2 + " " + num3 + " in increasing order: ");displaySortedNumbers(num1, num2, num3);}public static void displaySortedNumbers(double num1, double num2, double num3) {double max = Math.max(Math.max(num1, num2), num3);double min = Math.min(Math.min(num1, num2), num3);double second = 0;if (num1 != max && num1 != min)second = num1;if (num2 != max && num2 != min)second = num2;if (num3 != max && num3 != min)second = num3;System.out.println(min + " " + second + " " + max);}}5.6import java.util.Scanner;public class Exercise06 {public static void main(String[] args) {Scanner input = new Scanner(System.in);//Prompt the user to enter an integerSystem.out.print("Enter an integer: ");int number = input.nextInt();displayPattern(number);}public static void displayPattern(int n) {int i;int j;for (i = 1; i <= n; i++) {for (j = 0; j < n - i; j++)System.out.print(" ");for (j = 0; j <= i - 1; j++)System.out.printf("%-5d", i - j);System.out.println();}}}5.7import java.util.Scanner;public class Exercise07 {public static void main(String[] args) {Scanner input = new Scanner(System.in);//Prompt the user to enter investment amountSystem.out.print("Enter the investment amount: ");double investmentAmount = input.nextDouble();//Prompt the user to enter interest rateSystem.out.print("Enter the annual interest rate: ");double annualInterestRate = input.nextDouble();//Prompt the user to enter yearsSystem.out.print("Enter number of years: ");int years = input.nextInt();System.out.println("\nThe amount invested: " + investmentAmount);System.out.println("Annual interest rate: " + annualInterestRate + "%");System.out.println("Years\tFuture Value");for (int i = 1; i <= years; i++) {System.out.print(i + "\t");System.out.printf("%10.2f\n",futureInvestmentValue(investmentAmount, annualInterestRate / 1200, i));}}public static double futureInvestmentValue(double investmentAmount, doublemonthInterestRate, int years) {return investmentAmount * Math.pow(1 + monthInterestRate, years * 12);}}5.8public class Exercise08 {public static void main(String[] args) {System.out.println("Celsius\tFahrenheit\tFahrenheit\tCelsius");for (double celsius = 40, fahrenheit = 120; celsius >= 31 && fahrenheit >= 30; celsius--, fahrenheit -= 10) {System.out.println(celsius + "\t" + (int)(celsiusToFahrenheit(celsius) * 100) / 100.0 + "\t\t" +fahrenheit + "\t\t" + (int)(fahrenheitToCelsius(fahrenheit) * 100) / 100.0);}}public static double celsiusToFahrenheit(double celsius) {return (9.0 / 5) * celsius + 32;}public static double fahrenheitToCelsius(double fahrenheit) {return (fahrenheit - 32) * 5.0 / 9;}}5.9public class Exercise09 {public static void main(String[] args) {System.out.println("Feet\tMeters\tMeters\tFeet");for (double feet = 1, meters = 20; feet <= 10 && meters <= 65; feet++, meters += 5) {System.out.println(feet + "\t" + (int)(footToMeter(feet) * 1000) / 1000.0 + "\t" +meters + "\t" + (int)(meterToFoot(meters) * 1000) / 1000.0);}}public static double footToMeter(double foot) {return foot * 0.305;}public static double meterToFoot(double meter) {return meter / 0.305;}}5.10public class Exercise10 {public static void main(String[] args) {int count = 0;int number = 1;for (number = 1; number < 10000; number++) {if (isPrime(number))count++;}System.out.println("The number of prime numbers less than 10000 is " + count);}public static boolean isPrime(int number) {for (int i = 2; i <= number / 2; i++) {if (number % i == 0)return false;}return true;}}5.11public class Exercise11 {public static void main(String[] args) {System.out.println("Sales Amount\tCommission");for (double salesAmount = 10000.0; salesAmount <= 100000; salesAmount += 5000) {System.out.println(salesAmount + "\t\t" + computeCommission(salesAmount));}}public static double computeCommission(double salesAmount) {if (salesAmount <= 5000)return salesAmount * 0.08;else if (salesAmount <= 10000)return 5000 * 0.08 + (salesAmount - 5000) * 0.10;elsereturn 5000 * 0.08 + (10000 - 5000) * 0.10 + (salesAmount - 10000) * 0.12;}}5.12public class Exercise12 {public static void main(String[] args) {char ch1 = '1';char ch2 = 'Z';int number = 10;printChars(ch1, ch2, number);}public static void printChars(char ch1, char ch2, int numberPerLine) { int count = 1;for (char i = ch1; i <= ch2; i++) {if (count % numberPerLine == 0)System.out.println(i);elseSystem.out.print(i + " ");count++;}}}5.13public class Exercise13 {public static void main(String[] args) {System.out.println("i\tm(i)");for (int i = 1; i <= 50; i++) {System.out.print(i + "\t");System.out.printf("%-10.4f\n", m(i));}}public static double m(int n) {double sum = 0;for (double i = n; i >= 1; i--)sum += i / (i + 1);return sum;}}5.14public class Exercise14 {public static void main(String[] args) {System.out.println("i\tm(i)");for (int i = 10; i <= 100; i += 10) {System.out.print(i + "\t");System.out.printf("%-10.5f\n", m(i));}}public static double m(int n) {double sum = 0;for (double i = n; i >= 0; i -= 2) {sum += 4 * (1 / (2 * i + 1) - 1 / (2 * (i + 1) + 1));}return sum;}}5.15public class Exercise15 {public static void main(String[] args) {System.out.println("Taxble Single Married Married Head of");System.out.println("Income Joint Separate a House");int taxableIncome;int status;for (taxableIncome = 50000; taxableIncome <= 60000; taxableIncome += 50) {System.out.printf("%-5d", taxableIncome);System.out.print(" ");for (status = 0; status <= 3; status++) {System.out.printf("%-5d", (int)computetax(status, taxableIncome));System.out.print(" ");}System.out.println();}}public static double computetax(int status, double taxableIncome) { double tax = 0;double income = taxableIncome;if (status == 0) {if (income <= 8350)tax = income * 0.10;else if (income <= 33950)tax = 8350 * 0.10 + (income - 8350) * 0.15;else if (income <= 82250)tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (income - 33950) * 0.25;else if (income <= 171550)tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (income - 82250) * 0.28;else if (income <= 372950)tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (income - 171550) * 0.33;elsetax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (372950 - 171550) * 0.33 + (income - 372950) * 0.35;}else if (status == 1) {if (income <= 16700)tax = income * 0.10;else if (income <= 67900)tax = 16700 * 0.10 + (income - 16700) * 0.15;else if (income <= 137050)tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (income - 67900) * 0.25;else if (income <= 208850)tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (income - 137050) * 0.28;else if (income <= 372950)tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (208850 - 137050) * 0.28 + (income - 208850) * 0.33;elsetax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (208850 - 137050) * 0.28 + (372950 - 208850) * 0.33 + (income - 372950) * 0.35;}else if (status == 2) {if (income <= 8350)tax = income * 0.10;else if (income <= 33950)tax = 8350 * 0.10 + (income - 8350) * 0.15;else if (income <= 68525)tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (income - 33950) * 0.25;else if (income <= 104425)tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (income - 68525) * 0.28;else if (income <= 186475)tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (104425 - 68525) * 0.28 + (income - 104425) * 0.33;elsetax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (104425 - 68525) * 0.28 + (186475 - 104425) * 0.33 + (income - 186475) * 0.35;}else if (status == 3) {if (income <= 11950)tax = income * 0.10;else if (income <= 45500)tax = 11950 * 0.10 + (income - 11950) * 0.15;else if (income <= 117450)tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (income - 45500) * 0.25;else if (income <= 190200)tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (income - 117450) * 0.28;else if (income <= 372950)tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (190200 - 117450) * 0.28 + (income - 190200) * 0.33;elsetax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (190200 - 117450) * 0.28 + (372950 - 190200) * 0.33 + (income - 372950) *0.35;}return tax;}}5.16public class Exercise16 {public static void main(String[] args) {for (int year = 2000; year <= 2010; year++) {System.out.println("Year " + year + " has " + numberOfDaysInAYear(year) + " days.");}}public static int numberOfDaysInAYear(int year) {if (isLeapYear(year))return 366;elsereturn 365;}public static boolean isLeapYear(int year) {boolean isLeapYear = false;if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)isLeapYear = true;return isLeapYear;}}5.17import java.util.Scanner;public class Exercise17 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter an integer number: ");int n = input.nextInt();printMatrix(n);}public static void printMatrix(int n) {for (int i = 1; i <= n; i++) {for (int j = 1; j <= n; j++)System.out.print((int)(Math.random() * 2) + " ");System.out.println();}}}5.18public class Exercise18 {public static void main(String[] args) {System.out.println("Number\tSquareRoot");for (int i = 0; i <= 20; i += 2) {System.out.print(i + "\t ");System.out.printf("%6.4f\n", squareRoot(i));}}public static double squareRoot(int n) {return Math.sqrt(n);}}5.19import java.util.Scanner;public class Exercise19 {/*** main method*/public static void main(String[] args) {//Create a ScannerScanner input = new Scanner(System.in);//Prompt the user to enter three sides for a triangleSystem.out.print("Enter three sides for a triangle: ");double side1 = input.nextDouble();double side2 = input.nextDouble();double side3 = input.nextDouble();if (isValid(side1, side2, side3))System.out.println("The area of the triangle is " + area(side1, side2, side3));elseSystem.out.println("The input is invalid!");}/*** Returns true if the sum of any two sides is greater than the third side */public static boolean isValid(double side1, double side2, double side3) { boolean isValid = false;if (side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1) isValid = true;return isValid;}/*** Returns the area of the triangle*/public static double area(double side1, double side2, double side3) { double s = (side1 + side2 + side3) / 2;double area = Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));return area;}}5.20public class Exercise20 {public static void main(String[] args) {System.out.println("Degree \tSin \tCos");for (int degree = 0; degree <= 360; degree = degree + 10) {System.out.print(degree + "\t ");System.out.printf("%6.4f\t ", sin(Math.toRadians(degree)));System.out.printf("%6.4f\n", cos(Math.toRadians(degree)));}}public static double sin(double radians) {return Math.sin(radians);}public static double cos(double radians) {return Math.cos(radians);}}5.21import java.util.Scanner;public class Exercise21 {public static void main(String[] args) {Scanner input = new Scanner(System.in);//Prompt the user to enter ten numbersSystem.out.print("Enter ten numbers: ");double n0 = input.nextDouble();double n1 = input.nextDouble();double n2 = input.nextDouble();double n3 = input.nextDouble();double n4 = input.nextDouble();double n5 = input.nextDouble();double n6 = input.nextDouble();double n7 = input.nextDouble();double n8 = input.nextDouble();double n9 = input.nextDouble();System.out.println("The mean is " + computeMean(n0, n1, n2, n3, n4, n5, n6, n7, n8, n9));System.out.println("The standard deviation is " + standardDeviation(n0, n1, n2, n3, n4, n5, n6, n7, n8, n9));}public static double computeMean(double n0, double n1, double n2, double n3, double n4, double n5, double n6, double n7, double n8, double n9) {return (n0 + n1 + n2 + n3 + n4 + n5 + n6 + n7 + n8 + n9) / 10;}public static double standardDeviation(double n0, double n1, double n2, double n3, double n4, double n5, double n6, double n7, double n8, double n9) { double i = n0 * n0 + n1 * n1 + n2 * n2 + n3 * n3 + n4 * n4 + n5 * n5 + n6 * n6 + n7 * n7 + n8 * n8 + n9 * n9;double j = (n0 + n1 + n2 + n3 + n4 + n5 + n6 + n7 + n8 + n9) * (n0 + n1 + n2 + n3 + n4 + n5 + n6 + n7 + n8 + n9);return Math.sqrt((i - j / 10) / (10 - 1));}}5.22import java.util.Scanner;public class Exercise22 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a number: ");double num = input.nextDouble();System.out.println("The approximate square root of " + num + " is " + approximateSquareRoot(num));}public static double approximateSquareRoot(double n) {double lastGuess = 1;double nextGuess = (lastGuess + (n / lastGuess)) / 2;while (Math.abs(nextGuess - lastGuess) > 0.0001) {lastGuess = nextGuess;nextGuess = (lastGuess + (n / lastGuess)) / 2;}return nextGuess;}}5.23public class Exercise23 {public static void main(String[] args) {final int NUMBERS_PER_LINE = 10;int count = 1;for (int i = 0; i < 100; i++) {if (count % NUMBERS_PER_LINE != 0)System.out.print(.jackfangqi.chapter05.examples.RandomCharacter.getRandomUp perCaseLetter() + " ");if (count % NUMBERS_PER_LINE == 0)System.out.println(.jackfangqi.chapter05.examples.RandomCharacter.getRandom UpperCaseLetter());count++;}count = 1;for (int i = 0; i < 100; i++) {if (count % NUMBERS_PER_LINE != 0)System.out.print(.jackfangqi.chapter05.examples.RandomCharacter.getRandomDi gitCharacter() + " ");if (count % NUMBERS_PER_LINE == 0)System.out.println(.jackfangqi.chapter05.examples.RandomCharacter.getRandom DigitCharacter());count++;}}}5.24public class Exercise24 {public static void main(String[] args) {showCurrentDate();showCurrentTime();}public static void showCurrentDate() {System.out.println("Current date is " + getMonthName() + " " + getCurrentDay() + ", " + getCurrentYear());}public static long totalNumberOfDays() {//Obtain the total milliseconds since midnight, Jan 1, 1970long totalMilliseconds = System.currentTimeMillis();long totalSeconds = totalMilliseconds / 1000;long totalMinutes = totalSeconds / 60;long totalHours = totalMinutes / 60;long totalDays = totalHours / 24;return totalDays;}public static int getCurrentYear() {long n = 0;int year = 1970;while (n <= totalNumberOfDays()) {if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))n += 366;elsen += 365;year++;}return year - 1;}public static long getRemainingDays() {long m = 0;for (int i = 1970; i < getCurrentYear(); i++) {if (i % 400 == 0 || (i % 4 == 0 && i % 100 != 0))m += 366;elsem += 365;}return totalNumberOfDays() - m;}public static int getCurrentMonth() {int j = 0;int i = 0;while (j <= getRemainingDays()) {i++;if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12)j += 31;if (i == 4 || i == 6 || i == 9 || i == 11)j += 30;if (i == 2) {if (getCurrentYear() % 400 == 0 || (getCurrentYear() % 4 == 0 && getCurrentYear() % 100 != 0))j += 29;elsej += 28;}}return i;}public static String getMonthName() {String monthName = "";switch (getCurrentMonth()) {case 1: monthName = "January";break;case 2: monthName = "February";break;case 3: monthName = "March";break;case 4: monthName = "April";break;case 5: monthName = "May";break;case 6: monthName = "June";break;case 7: monthName = "July";break;case 8: monthName = "August";break;case 9: monthName = "September";break;case 10: monthName = "October";break;case 11: monthName = "November";break;case 12: monthName = "December";}return monthName;}public static long getCurrentDay() {int j = 0;for (int i = 1; i < getCurrentMonth(); i++) {if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12)j += 31;if (i == 4 || i == 6 || i == 9 || i == 11)j += 30;if (i == 2) {if (getCurrentYear() % 400 == 0 || (getCurrentYear() % 4 == 0 && getCurrentYear() % 100 != 0))j += 29;elsej += 28;}}return getRemainingDays() - j + 1;}public static void showCurrentTime() {//Obtain the total milliseconds since midnight, Jan 1, 1970long totalMilliseconds = System.currentTimeMillis();//Obtain the total seconds since midnight, Jan 1, 1970long totalSeconds = totalMilliseconds / 1000;//Compute the current second in the minute in the hourlong currentSecond = totalSeconds % 60;//Obtain the total minuteslong totalMinutes = totalSeconds / 60;//Compute the current minute in the hourlong currentMinute = totalMinutes % 60;//Obtain the total hourlong totalHours = totalMinutes / 60;//Compute the current hourlong currentHour = totalHours % 24 + 8;System.out.println("Current time is "+currentHour+":"+currentMinute+":"+currentSecond+" (GMT+8)");}}5.25import java.util.Scanner;public class Exercise25 {public static void main(String[] args) {Scanner input = new Scanner(System.in);//Prompt the user to enter millisecondsSystem.out.print("Enter milliseconds: ");long milliseconds = input.nextLong();System.out.print(milliseconds + " is " + convertMillis(milliseconds));}public static String convertMillis(long millis) {//Obtain the total secondslong totalSeconds = millis / 1000;//Compute the remaining secondslong remainingSeconds = totalSeconds % 60;//Obtain the total minuteslong totalMinutes = totalSeconds / 60;//Compute the remaining minuteslong remainingMinutes = totalMinutes % 60;//Obtain the total hourslong totalHours = totalMinutes / 60;return totalHours + ":" + remainingMinutes + ":" + remainingSeconds;}}5.26public class Exercise26 {public static void main(String[] args) { int countOfPalindromicPrimes = 0;int count = 1;int i = 2;while (countOfPalindromicPrimes < 100) { if (isPrime(i) && isPalindrome(i)) {if (count % 10 != 0)System.out.printf("%6d ", i);elseSystem.out.printf("%6d\n", i);count++;countOfPalindromicPrimes++;}i++;}}public static boolean isPrime(int m) {boolean isPrime = true;for (int j = 2; j <= m / 2; j++) {if (m % j == 0) {isPrime = false;break;}}return isPrime;}public static boolean isPalindrome(int n) { if (n == reverse(n))return true;elsereturn false;}public static int reverse(int n) {int reverseNumber = 0;do {int digit = n % 10;n = n / 10;reverseNumber = reverseNumber * 10 + digit;} while (n != 0);return reverseNumber;}}5.27public class Exercise27 {public static void main(String[] args) {int countOfEmirps = 0;int countOfEmirpsPerLine = 1;int i = 2;while (countOfEmirps < 100) {if (isPrime(i) && isNonpalindrome(i) && isPrime(reverse(i))) { if (countOfEmirpsPerLine % 10 != 0)System.out.printf("%4d ", i);elseSystem.out.printf("%4d\n", i);countOfEmirps++;countOfEmirpsPerLine++;}i++;}}public static boolean isPrime(int n) {boolean isPrime = true;for (int i = 2; i <= n /2; i++) {if (n % i == 0) {isPrime = false;break;}}return isPrime;}public static boolean isNonpalindrome(int n) {if (n == reverse(n))return false;elsereturn true;}public static int reverse(int n) {int reversal = 0;do {int digit = n % 10;n = n / 10;reversal = reversal * 10 + digit;} while (n != 0);return reversal;}}5.28public class Exercise28 {public static void main(String[] args) {System.out.println("p\t2^p - 1");for (int p = 2; p <= 31; p++) {if (isPrime(Math.pow(2, p) - 1))System.out.println(p + "\t" + (Math.pow(2, p) - 1));}}public static boolean isPrime(double n) {boolean isPrime = true;for (int i = 2; i <= n /2; i++) {if (n % i == 0) {isPrime = false;break;}}return isPrime;}}5.29public class Exercise29 {public static void main(String[] args) {//Generate two random numbers between 1 and 6int i = (int)(Math.random() * 6 + 1);int j = (int)(Math.random() * 6 + 1);if (isCraps(i, j))System.out.println("You rolled " + i + " + " + j + " = " + sum(i, j) + "\nYou lose");if (isNatural(i, j))System.out.println("You rolled " + i + " + " + j + " = " + sum(i, j) + "\nYou win");if (isPoint(i, j))point(i, j);}public static int sum(int n, int m) {return n + m;}public static boolean isCraps(int i, int j) {boolean isCraps = false;if (sum(i, j) == 2 || sum(i, j) == 3 || sum(i, j) == 12)isCraps = true;return isCraps;}public static boolean isNatural(int i, int j) {boolean isNatural = false;if (sum(i, j) == 7 || sum(i, j) == 11)isNatural = true;return isNatural;}public static boolean isPoint(int i, int j) {boolean isPoint = false;if (!isCraps(i, j) && !isNatural(i, j))isPoint = true;return isPoint;}public static void point(int i, int j) {int point = sum(i, j);System.out.println("You rolled " + i + " + " + j + " = " + point + "\npoint is " + point);//Generate two random numbers between 1 and 6i = (int)(Math.random() * 6 + 1);j = (int)(Math.random() * 6 + 1);if (sum(i, j) == 7)System.out.println("You rolled " + i + " + " + j + " = " + sum(i, j) + "\nYou lose");if (sum(i, j) == point)System.out.println("You rolled " + i + " + " + j + " = " + sum(i, j) + "\nYou win");while (sum(i, j) != 7 && sum(i, j) != point) {i = (int)(Math.random() * 6 + 1);j = (int)(Math.random() * 6 + 1);System.out.println("You rolled " + i + " + " + j + " = " + sum(i, j));if (sum(i, j) == 7)System.out.println("You lose");if (sum(i, j) == point)System.out.println("You win");}}}5.30public class Exercise30 {public static void main(String[] args) {for (int i = 2; i < 1000; i++) {if (isPrime(i) && isPrime(i + 2))System.out.println("(" + i + ", " + (i + 2) + ")");}}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Variance in the Java Programming LanguageA WhitepaperSun Microsystems,Aarhus University and the Alexandra InstituteMay22,20031IntroductionThis paper describes a proposed extension of The Java Programming Lan-guage,adding variance annotations to generic types and array types.The reader is assumed to be familiar with the JSR-14proposal,and we refer to the language proposed therein as Generic Java.There are a number of reasons for adding variance annotations to the Java programming language:Increased abstraction:Generic classes suffer from a certain rigidity,pre-cluding code that mixes generic instances with closely related argu-ment types.Arrays circumvent this problem,but at the cost of static type safety.Variance annotations allow theflexibility of traditional arrays with the static type guarantees of generic classes.The result isa potential for increased code reuse and improved static type safety oflibraries and frameworks.Improved type inference:Polymorphic methods in Generic Java have their type arguments inferred from the call context.The presence of variant types often allow the inference mechanism to do a much better job.Language integration:To a certain degree,Generic Java alienates arrays and generic classes,because the former require runtime type checks that the latter do not support.Variance introduces a class of arrays that are fully checked at compile time,thereby allowing a smoother integration of generic classes and array types.1This white paper describes the variance mechanism from a usage per-spective,highlighting its consequences to the programmer if distributed as part of a future release of the Java platform.2Variance on generic classesIn Generic Java,as described in JSR-14,there is no type relationship be-tween e.g.Set<Integer>and Set<Number>.To declare a variable that can alternately hold instances of both,we have two options for its type:We can use Object,which is safe,but hides all their common properties.Or we can use the raw type Set,which may result in unsafe code,and still hides the element type of the sets.Variance is designed to provide better types for this kind of situation. In the above example,there might be three reasons why we wish to hold on to common properties of the two Set types:Read-only:We want to read from the Set(ing its iterator() method),knowing that what we get out are certainly instances of NumberWrite-only:We want tofill entries into the Set,knowing that it will cer-tainly hold Integer instancesOther manipulation:We do not care about the element type,but only wish to operate on the Set using element type independent operations, such as size()or clear().These three situations correspond to the three kinds of variance annotation proposed:CovarianceTo accommodate the read-only situation,we may declare and use our vari-able as follows:Set<+Number>aReadOnlySet;...aReadOnlySet=new HashSet<Integer>();Iterator<+Number>i=aReadOnlySet.iterator();double sum=.0;while(i.hasNext())sum+=i.next().doubleValue();2The type Set<+Number>is said to be covariant in Number.The covariance annotation’+’signals that the type ranges over all instances of Set<T>, where T is a specialization(e.g.a subclass)of Number.Thus it can be used e.g.for an instance of Set<Integer>,as in the example above.The downside of thisflexibility is that we cannot call methods on it,which take arguments of the element type.If we allowedaReadOnlySet.add(new Double(.75);//illegalin the situation where aReadOnlySet contains an instance of Set<Integer> we would get a type error.The term co-variance refers to the direction of specialization:Set<+B> specializes Set<+A>if B specializes A:they vary in the same direction. ContravarianceThe write-only situation is quite symmetrical to covariance,and is handled with the contravariance annotation’-’:Set<-Integer>aWriteOnlySet;...aWriteOnlySet=new HashSet<Number>();aWriteOnlySet.add(new Integer(10));Thus,Set<-Integer>ranges over all instances of Set<T>,where Integer is a specialization of T.An instance of e.g.Set<Number>may be assigned to it.On the downside,if we call methods on it which return results of the element type,we know nothing about the type of the returned element.Again,the term contra-variance refers to the direction of specialization: Set<-A>specializes Set<-B>if B specializes A:they vary in the opposite direction.BivarianceFinally,if we do not care about the element type,we may make use of the bivariance type argument’*’:Set<*>anUnkownSet;...anUnkownSet=new HashSet<Number>();if(!anUnknownSet.isEmpty())anUnknownSet.clear();The type Set<*>ranges over all instances of Set<T>for any T.It is called bi-variant because it is the combination of the two above variances: one may neither read from nor write to instances.3InvarianceIn light of the new forms of type arguments introduced above,one may referto the plain type arguments of Generic Java as in-variant:Set<A>specializesSet<B>only if A equals B.Invariant Set s of different element type do not mingle,and may therefore be both read from and written to.For clarity,the invariance may be explicitly denoted by’=’as in Set<=Integer>.A specific instance of Set must always have a particular element type.For this reason,type arguments to the classes/interfaces of new expressionsas well as extends and implements clauses must always be invariant.2.1Library classesVariance annotations are useful for loosening up the types of methods that donot both read from and write to their arguments.This is commonly the casein Java platform libraries,such as the Collection classes.As an example,take the addAll()method of the Collection interface:it only needs toread from its argument Collection,which can therefore be covariant:public interface Collection<E>{...public boolean addAll(Collection<+E>c);}As an example of a contravariant library method,consider the polymorphicfill()and copy()methods of the Collections class:public static<T>void fill(List<-T>list,T o){...}public static<T>void copy(List<-T>dest,List<+T>src){...} Variance may also be useful in constructor declarations.Consider the three nontrivial constructors of TreeSet:public class TreeSet<E>extends...{public TreeSet(Comparator<-E>c){...}public TreeSet(Collection<+E>c){...}public TreeSet(SortedSet<E>s){...}...}When taking a Comparator,the TreeSet only needs to write to it,in orderto determine the ordering of its elements.Thus,it may accept a more general Comparator than Comparator<E>.4On the other hand,when taking a Collection,the TreeSet will only read from it,adding its elements to itself.Therefore it may accept a Collection of a more special element type than Collection<E>.Finally,when taking a SortedSet,the TreeSet reuses both its elements and its Comparator.Thus it combines the needs of the two above con-structors to both read and write its elements to the element type of the SortedSet,which must therefore be exactly E.2.2Applied variance:a large exampleThe usefulness of variance is best appreciated in larger examples.In order to promote decoupling and reuse,large scale applications often employ a number of design patterns giving rise to complex structures of mutually dependent objects.Genericity is an appealing approach to increase the abstraction of such systems,but the invariant requirements of Generic Java often become to restrictive.An example is an event handling library consisting of listeners and providers.Both concepts are represented as interfaces parameterized with an Event type,on the grounds that specific EventProvider s generate spe-cific kinds of Event s just as different EventListener s may be able to handle only certain kinds of Event s:public interface Event{/**Return the original provider of the event*/EventProvider<*>source();}public interface EventProvider<E extends Event>{/**register a listener*/void addListener(<EventListener<-E>>listener);/**unregister a listener*/void removeListener(<EventListener<-E>>listener);}public interface EventListener<E extends Event>{/**handle an event*/void eventHappened(E event);}There may also be a supporting partial implementation of the EventProvider5interface:public abstract class AbstractEventProvider<E extends Event> implements EventProvider<E>{private List<EventListener<-E>>listeners=new ArrayList<EventListener<-E>>();public void addListener(EventListener<-E>listener){listeners.add(listener);}public void removeListener(EventListener<-E>listener){listeners.remove(listener);}protected void fireEvent(E event){Iterator<EventListener<-E>>i=listeners.iterator();while(i.hasNext())i.next().eventHappened(event);}}The class implements the register of EventListener s,and provides a fireEvent() method to its subclasses to handle the distribution of events.Because of variance,the listeners register may contain a variety of EventListener sat any given time,all with the common property that they accept events oftype E.In a given application there may be a hierarchy of event types:public class GUIEvent implements Event{public EventProvider<*>source(){...}public Object getComponent(){...}}public class MouseEvent extends GUIEvent{public int getX(){...}public int getY(){...}}For these,a number of providers and listeners exist,e.g.:public class Window extends AbstractEventProvider<GUIEvent>{...} public class Mouse extends AbstractEventProvider<MouseEvent>{...} public class GUILogger implements EventListener<GUIEvent>{public void eventHappened(GUIEvent event){System.out.println("GUIEvent from"+e.getComponent());6}}public class MouseLogger implements EventListener<MouseEvent>{ public void eventHappened(MouseEvent event){System.out.println("MouseEvent at"+e.getX()+","+e.getY());}}These may be combined in the following ways:Window window;Mouse mouse;GUILogger gl;MouseLogger ml;window.addListener(gl);mouse.addListener(gl);mouse.addListener(ml);But not:window.addListener(ml);//illegalbecause window.add()expects an EventListener<-GUIEvent>which can handle all GUIevent s,while a MouseLogger is an EventListener<MouseEvent>, which can only handle MouseEvent s.In real life,a GUI application like this contains many kinds of events, providers and listeners,which must be dynamically configured and recon-figured in complex structures.With standard invariant generic classes,they would all have to be declared with the same event type in order tofit to-gether.In other words all classes,however specialized,would“pose”as deal-ing with events in general,causing a widespread need for runtime castingto reestablish specific event information.Thus,the possibility of a reliable compile time check of the configuration operations is lost.With variance, components can declare their“real”event type without risk of notfitting in with the others,thereby holding on to type information that would otherwise have to be reestablished by the use of casts.2.3Improved type inferencePolymorphic methods in Generic Java can be called without explicitly giving type arguments to the method:they are inferred on the basis of the call site type information.As an example,given the declarations7<T>T choose(T t1,T t2);Set<Integer>is;List<String>sl;what is the type of choose(is,sl)?Although both arguments are Collection s, in Generic Java the inference mechanism will have to disregard this infor-mation,because the most specific type that ranges over both arguments rather disappointingly is Object.With variant types,although the element types of the two collections differ,we may still infer T to be a COllectionof something,i.e.,Collection<*>.3Variance on array typesVariance annotations may also be applied to array types,denoting varianceof their element type.The annotation is placed within the square bracketsas in:Number[+]nums=new Integer[10];//Covariant/read-onlyInteger[-]ints=new Number[20];//Contravariant/write-only String[=]strings=new String[30];//Invariant/read-writeAs with generic classes,new expressions on arrays always create invariant arrays,so when a dimension is specified,no variance annotation is needed, avoiding the potential syntactic conflict of having both within the same pair of brackets.The notation extends to multidimensional arrays,allowing expressions such as new Number[10][+],which allocates a size10array with element type Number[+].For syntactic reasons,there is no bivariance on arrays.The type Object[+] has the same property of ranging over all possible array types,and may be used instead.Contrary to generic classes,the explicit’[=]’annotation of invariance isnot optional,because traditional array types with’[]’are not invariant:by allowing assignments such asNumber[]numbers=new Integer[10];they are closer to being covariant,but unlike explicitly covariant array types they do allow write operations.These are checked at runtime with the riskof throwing an ArrayStoreException,as innumbers[0]=new Double(.0);//Runtime store check8For this reason,we refer to the“old”style of array types as dynamic arrays, whereas the new explicitly variance-annotated array types,with[=],[+]and[-],may be called statically safe arrays,because their runtime store checks do not fail.3.1Arrays of generic classesGeneric classes are implemented by means of a technique called erasure, which removes information about type arguments from the compiled versionof the code.This means that generic classes cannot be expected to behave right in runtime type checks,and hence not in the store checks of dynamic arrays.The following example illustrates the problem:Object[]objects=new Comparable<Integer>[10];//Warningobjects[0]=new Double(.0);//Runtime check succeedsThis should really fail at runtime,but the store check does not have the infor-mation at hand to distinguish Comparable<Integer>from Comparable<Double>, so the assignment is wrongfully allowed.To prevent this kind of situation,a warning is issued whenever an array of generic element type is assignedto a dynamic array type.For compatibility reasons,it is not a compile time error:combinations of old and new code should be allowed.However,if the warning is not the result of integration with old code,programmers should regard it as an error and rearrange their code to avoid it,typicallyby shifting to statically safe arrays.For similar reasons,dynamic arrays of generic classes and of type vari-ables are not allowed:class C<T>{T[]ts;//RejectedC<Object>[]cs;//Rejected}Such examples cannot occur as a result of integration with old code,as both generic classes and type variables are new features of Generic Java.Hence,the declarations cause compile time errors.3.2Library classesAll array-related methods of the standard API are updated to exclusivelyuse statically safe array types.This is to ensure that the methods apply toall array objects,including those that involve generic element types.A few examples from java.util.Arrays:9public static<T>void sort(T[=]a,Comparator<-T>c){...} public static<T>void fill(T[-]a,T val){...}The sort()method needs to both read and write the array elements,and hence invariance on its array argument,whereas the fill()method only needs to write to its array argument,and is therefore declared to be con-travariant.The changes may cause old code to emit warnings,as inNumber[]nums=new Integer[20];//dynamic arrayArrays.fill(nums,new Double(.0));//warningThis code abuses the assumption of the fill()method that input arrays will always accept thefilling object passed in,but cannot be made illegal for compatibility reasons.4Implementation of varianceVariance annotations are implemented as an extension to javac which com-piles source code into JVM byte code.The extension involves passing the new syntax,checking the augmented types and transforming the code to a version without variance.Also,method and constructor signatures in ng and java.util have been modified to include variance.The extension is closely integrated with the generic extension proposed under JSR-14,and shares most of its advantages and limitations.It remains compatible with old code,and the output bytecode runs on unmodified JVM platforms.The downside,lack of runtime type information,also remains, although statically safe array types eliminate a particular problem in Generic Java by allowing arrays of generic classes.The current experimental implementation is the result of a joint research project of Sun Microsystems,Aarhus University and the Alexandra Insti-tute.References[BOSW98]Gilad Bracha,Martin Odersky,David Stoutamire,and Philip Wadler.Making the future safe for the past:Adding generic-ity to the Java programming language.In Proc.OOPSLA’98,October1998.10[GJSB00]James Gosling,Bill Joy,Guy Steele and Gilad Bracha.The Java Language Specification,Second Edition.Java Series,SunMicrosystems,2000.ISBN0-201-31008-2.[IgVi02]Atsushi Igarashi and Mirko Viroli.On Variance-based Subtyping for Parametric Types.ECOOP2002[ThoTor99]Kresten Krab Thorup and Mads Torgersen Unifying Generic-ity:Combining the benefits of virtual types and parameterizedclasses.ECOOP199911。

相关文档
最新文档