Slicing of Java Programs using the Soot Framework

合集下载

Programming with Java

Programming with Java

Programming with JavaJava is a highly versatile and popular programming language that is used in a wide variety of applications. It is known for its flexibility, reliability, and ease of use. In this article, we will explore the basics of programming with Java and how you can get started with this powerful language.One of the key advantages of Java is its platform independence, meaning that Java programs can run on any computer or device that has a Java Virtual Machine (JVM) installed. This makes Java a great choice for developing cross-platform applications that can be used on different operating systems.To start programming with Java, you will first need to download and install the Java Development Kit (JDK) on your computer. The JDK includes all the tools and libraries necessary for developing Java applications. Once you have installed the JDK, you can use a text editor or an Integrated Development Environment (IDE) such as Eclipse or IntelliJ IDEA to write and run your Java code.Java is an object-oriented programming language, which means that it is based on the concept of objects and classes. Objects are instances of classes, which define the data and behavior of the object. In Java, classes are used to encapsulate data and methods, making it easier to organize and manage your code.Here is a simple example of a Java program that prints "Hello, World!" to the console:```javapublic class HelloWorld {public static void main(String[] args) {System.out.println("Hello, World!");}}```In this program, we have defined a class called HelloWorld with a main method that prints the message "Hello, World!" to the console. The `System.out.println()` method is used to print text to the console.Java also supports features such as inheritance, polymorphism, and encapsulation, which allow you to build complex and modular applications. Inheritance allows one class to inherit properties and methods from another class, while polymorphism enables objects to be treated as instances of their parent class. Encapsulation, on the other hand, refers to the practice of hiding the internal implementation details of a class from the outside world.In addition to object-oriented programming, Java also supports functional programming paradigms with features such as lambda expressions and streams. Lambda expressions allow you to write concise and reusable code by defining anonymous functions, while streams enable you to manipulate collections of data in a functional style.When writing Java code, it is important to follow best practices and conventions to ensure that your code is clear, readable, and maintainable. This includes using meaningful variable names, commenting your code, and following coding standards such as the Java Code Conventions.Overall, programming with Java offers a powerful and flexible platform for developing a wide range of applications, from simple console programs to complex enterprise systems. Whether you are a beginner or an experienced developer, Java provides a robust and reliable environment for building software that scales and performs well on any platform. By mastering the fundamentals of Java programming, you can unlock endless possibilities and create innovative solutions to solve real-world problems.。

CREO二次开发工具汇总

CREO二次开发工具汇总

CREO 二次开发语言归纳1.Protk Pro/E 二次开发工具包1.1.Protoolkit C语言开发工具包Creo Parametric TOOLKIT is the C-language customization toolkit for PTC Creo Parametric. It provides customers and third-parties the ability to expand PTC Creo Parametric capabilities by writing C-language code and seamlessly integrating the resulting application into PTC Creo Parametric. It provides a large library of C functions that enables the external application to access the PTC Creo Parametric database and user interface in a controlled and safe manner.PTC Creo Parametric TOOLKIT is aimed at software engineers with experience in C programming. They should also be trained in the basic use of PTC Creo Parametric.1.2.Weblink JavaScript开发工具包Web开发工具包This manual describes how to use Web.Link, a tool that links the World Wide Web (WWW, or Web) to PTC Creo Parametric, enabling you to use the Web as a tool to automate and streamline parts of your engineer ingprocess.This manual assumes you have the following knowledge:• PTC Creo Parametric• HTML• JavaScript1.3.Jlink Java语言开发工具包This manual describes how to use J-Link, a Java language toolkit for PTC Creo Parametric. J-Link makes possible the development of Java programs that access the internal components of a PTC Creo Parametric session, to customize PTC Creo Parametric models.This manual assumes you have the following knowledge:• PTC Creo Parametric• The syntax and language structure of Java.2.Otk 面向对象开发工具包2.1.object_toolkit_java_user Java 面向对象开发工具包This manual describes how to use PTC Creo Object TOOLKIT Java, an object based Java toolkit API for PTC Creo Parametric and PTC Creo Direct. PTC Creo Object TOOLKIT Java makes possible the development of Java programs that access the internal components of a PTC Creo session, to customize PTC Creo models.This manual assumes you have the following knowledge:• PTC Creo Parametric• PTC Creo Direct• The syntax and language structure of Java.In future, the methods of PTC Creo Object TOOLKIT Java will be enhanced to extend support to all PTC Creo applications.2.2.object_toolkit_user C++ 面向对象开发工具包This manual describes how to use PTC Creo Object TOOLKIT C++, an object based C++toolkit API for PTC Creo Parametric and PTC Creo Direct. PTC Creo Object TOOLKIT C++ makes possible the development of C++ programs that access the internal components of a PTC Creo session, to customize PTC Creo models.This manual assumes you have the following knowledge:• PTC Creo Parametric• PTC Creo Direct• The syntax and language structure of C++.3.Domains of PTC Creo Object TOOLKIT JavaPTC Creo Object TOOLKIT Java consists of the following domains:•pfc—This domain provides classes that support basic functionality.•wfc—This domain provides classes that support advanced functionality.•uifc—This domain provides classes that allow you to create user interface components. Refer to the PTC Creo UI Editor User’s Guide, for more information on how to create and customize the user interface components.4.PTC Creo Object TOOLKIT Java Compatibility with J-LinkThe pfc domain has the same structure and functional coverage as J-Link. Applications based on J-Link can be run as PTC Creo Object TOOLKIT Java, after you make the following changes:。

JAVA数据结构习题及解答(英)

JAVA数据结构习题及解答(英)

QuestionsThese questions are intended as a self-test for readers.Answers to the questions may be found in Appendix C.1.In many data structures you can________a single record,_________it,and_______it.2.Rearranging the contents of a data structure into a certain order is called_________.30CHAPTER1Overview3.In a database,a field isa.a specific data item.b.a specific object.c.part of a record.d.part of an algorithm.4.The field used when searching for a particular record is the______________.5.In object-oriented programming,an objecta.is a class.b.may contain data and methods.c.is a program.d.may contain classes.6.A classa.is a blueprint for many objects.b.represents a specific real-world object.c.will hold specific values in its fields.d.specifies the type of a method.7.In Java,a class specificationa.creates objects.b.requires the keyword new.c.creates references.d.none of the above.8.When an object wants to do something,it uses a________.9.In Java,accessing an object’s methods requires the_____operator.10.In Java,boolean and byte are_____________.(There are no experiments or programming projects for Chapter1.)Questions31Chapter1,OverviewAnswers to Questions1.insert,search for,delete2.sorting3.c4.search key5.b6.a7.d8.method9.dot10.data typesQuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.1.Inserting an item into an unordered arraya.takes time proportional to the size of the array.b.requires multiple comparisons.c.requires shifting other items to make room.d.takes the same time no matter how many items there are.2.True or False:When you delete an item from an unordered array,in most cases you shift other items to fill in the gap.3.In an unordered array,allowing duplicatesa.increases times for all operations.b.increases search times in some situations.c.always increases insertion times.d.sometimes decreases insertion times.4.True or False:In an unordered array,it’s generally faster to find out an item is not in the array than to find out it is.5.Creating an array in Java requires using the keyword________.6.If class A is going to use class B for something,thena.class A’s methods should be easy to understand.b.it’s preferable if class B communicates with the program’s user.c.the more complex operations should be placed in class A.d.the more work that class B can do,the better.7.When class A is using class B for something,the methods and fields class A can access in class B are called class B’s__________.74CHAPTER2Arrays8.Ordered arrays,compared with unordered arrays,area.much quicker at deletion.b.quicker at insertion.c.quicker to create.d.quicker at searching.9.A logarithm is the inverse of_____________.10.The base10logarithm of1,000is_____.11.The maximum number of elements that must be examined to complete a binary search in an array of200elements isa.200.b.8.c.1.d.13.12.The base2logarithm of64is______.13.True or False:The base2logarithm of100is2.14.Big O notation tellsa.how the speed of an algorithm relates to the number of items.b.the running time of an algorithm for a given size data structure.c.the running time of an algorithm for a given number of items.d.how the size of a data structure relates to the number of items.15.O(1)means a process operates in_________time.16.Either variables of primitive types or_________can be placed in an array. Chapter2,ArraysAnswers to Questions1.d2.True3.b4.False5.new6.d740APPENDIX C Answers to Questions7.interface8.d9.raising to a power10.311.812.613.False14.a15.constant16.objectsuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.puter sorting algorithms are more limited than humans in thata.humans are better at inventing new algorithms.puters can handle only a fixed amount of data.c.humans know what to sort,whereas computers need to be told.puters can compare only two things at a time.2.The two basic operations in simple sorting are_________items and_________ them(or sometimes_________them).3.True or False:The bubble sort always ends up comparing every item with every other item.4.The bubble sort algorithm alternates betweenparing and swapping.b.moving and copying.c.moving and comparing.d.copying and comparing.5.True or False:If there are N items,the bubble sort makes exactly N*N comparisons.Questions1096.In the selection sort,a.the largest keys accumulate on the left(low indices).b.a minimum key is repeatedly discovered.c.a number of items must be shifted to insert each item in its correctlysorted position.d.the sorted items accumulate on the right.7.True or False:If,in a particular sorting situation,swaps take much longer than comparisons,the selection sort is about twice as fast as the bubble sort.8.A copy is________times as fast as a swap.9.What is the invariant in the selection sort?10.In the insertion sort,the“marked player”described in the text corresponds to which variable in the insertSort.java program?a.inb.outc.tempd.a[out]11.In the insertion sort,“partially sorted”means thata.some items are already sorted,but they may need to be moved.b.most items are in their final sorted positions,but a few still need to be sorted.c.only some of the items are sorted.d.group items are sorted among themselves,but items outside the groupmay need to be inserted in it.12.Shifting a group of items left or right requires repeated__________.13.In the insertion sort,after an item is inserted in the partially sorted group,it willa.never be moved again.b.never be shifted to the left.c.often be moved out of this group.d.find that its group is steadily shrinking.110CHAPTER3Simple Sorting14.The invariant in the insertion sort is that________.15.Stability might refer toa.items with secondary keys being excluded from a sort.b.keeping cities sorted by increasing population within each state,in a sortby state.c.keeping the same first names matched with the same last names.d.items keeping the same order of primary keys without regard to secondary keys.Chapter3,Simple SortingAnswers to Questions1.dparing and swapping(or copying)3.False4.a5.False6.b7.False8.three9.Items with indices less than or equal to outer are sorted.10.c11.d12.copies13.b14.Items with indices less than outer are partially sorted.15.buestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.1.Suppose you push10,20,30,and40onto the stack.Then you pop three items. Which one is left on the stack?2.Which of the following is true?a.The pop operation on a stack is considerably simpler than the remove operation on a queue.b.The contents of a queue can wrap around,while those of a stack cannot.c.The top of a stack corresponds to the front of a queue.d.In both the stack and the queue,items removed in sequence are takenfrom increasingly high index cells in the array.3.What do LIFO and FIFO mean?4.True or False:A stack or a queue often serves as the underlying mechanism on which an ADT array is based.5.Assume an array is numbered with index0on the left.A queue representing a line of movie-goers,with the first to arrive numbered1,has the ticket window on the right.Thena.there is no numerical correspondence between the index numbers andthe movie-goer numbers.b.the array index numbers and the movie-goer numbers increase inopposite left-right directions.c.the array index numbers correspond numerically to the locations in theline of movie-goers.d.the movie-goers and the items in the array move in the same direction.6.As other items are inserted and removed,does a particular item in a queue move along the array from lower to higher indices,or higher to lower?7.Suppose you insert15,25,35,and45into a queue.Then you remove three items.Which one is left?8.True or False:Pushing and popping items on a stack and inserting and removing items in a queue all take O(N)time.174CHAPTER4Stacks and Queues9.A queue might be used to holda.the items to be sorted in an insertion sort.b.reports of a variety of imminent attacks on the star ship Enterprise.c.keystrokes made by a computer user writing a letter.d.symbols in an algebraic expression being evaluated.10.Inserting an item into a typical priority queue takes what big O time?11.The term priority in a priority queue means thata.the highest priority items are inserted first.b.the programmer must prioritize access to the underlying array.c.the underlying array is sorted by the priority of the items.d.the lowest priority items are deleted first.12.True or False:At least one of the methods in the priorityQ.java program (Listing4.6)uses a linear search.13.One difference between a priority queue and an ordered array is thata.the lowest-priority item cannot be extracted easily from the array as it can from the priority queue.b.the array must be ordered while the priority queue need not be.c.the highest priority item can be extracted easily from the priority queue but not from the array.d.All of the above.14.Suppose you based a priority queue class on the OrdArray class in the orderedArray.java program(Listing2.4)in Chapter2,“Arrays.”This will buy you binary search capability.If you wanted the best performance for your priority queue,would you need to modify the OrdArray class?15.A priority queue might be used to holda.passengers to be picked up by a taxi from different parts of the city.b.keystrokes made at a computer keyboard.c.squares on a chessboard in a game program.d.planets in a solar system simulation.Chapter4,Stacks and QueuesAnswers to Questions1.102.bst-In-First-Out;and First-In-First-Out4.False.It’s the other way around.5.b6.It doesn’t move at all.7.458.False.They take O(1)time.9.c10.O(N)11.c12.True13.b14.Yes,you would need a method to find the minimum value.15.aQuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.Questions2451.Which of the following is not true?A reference to a class objecta.can be used to access public methods in the object.b.has a size dependant on its class.c.has the data type of the class.d.does not hold the object itself.2.Access to the links in a linked list is usually through the_________link.3.When you create a reference to a link in a linked list,ita.must refer to the first link.b.must refer to the link pointed to by current.c.must refer to the link pointed to by next.d.can refer to any link you want.4.How many references must you change to insert a link in the middle of a singly linked list?5.How many references must you change to insert a link at the end of a singly linked list?6.In the insertFirst()method in the linkList.java program(Listing5.1),the statement newLink.next=first;means thata.the next new link to be inserted will refer to first.b.first will refer to the new link.c.the next field of the new link will refer to the old first link.d.newLink.next will refer to the new first link in the list.7.Assuming current points to the next-to-last link in a singly linked list,what statement will delete the last link from the list?8.When all references to a link are changed to refer to something else,what happens to the link?9.A double-ended lista.can be accessed from either end.b.is a different name for a doubly linked list.c.has pointers running both forward and backward between links.d.has its first link connected to its last link.246CHAPTER5Linked Lists10.A special case often occurs for insertion and deletion routines when a list is ________.11.Assuming a copy takes longer than a comparison,is it faster to delete an item with a certain key from a linked list or from an unsorted array?12.How many times would you need to traverse a singly linked list to delete the item with the largest key?13.Of the lists discussed in this chapter,which one would be best for implementing a queue?14.Which of the following is not true?Iterators would be useful if you wanted toa.do an insertion sort on a linked list.b.insert a new link at the beginning of a list.c.swap two links at arbitrary locations.d.delete all links with a certain key value.15.Which do you think would be a better choice to implement a stack:a singly linked list or an array?Chapter5,Linked ListsAnswers to Questions1.b2.first3.d4.25.16.c7.current.next=null;8.Java’s garbage collection process destroys it.Chapter5,Linked Lists7419.a10.empty11.a linked list12.once,if the links include a previous reference13.a double-ended list14.bually,the list.They both do push()and pop()in O(1)time,but the list uses memory more efficiently.QuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.1.If the user enters10in the triangle.java program(Listing6.1),what is the maximum number of“copies”of the triangle()method(actually just copies of its argument)that exist at any one time?2.Where are the copies of the argument,mentioned in question1,stored?a.in a variable in the triangle()methodb.in a field of the TriangleApp classc.in a variable of the getString()methodd.on a stack3.Assume the user enters10as in question1.What is the value of n when the triangle()method first returns a value other than1?4.Assume the same situation as in question1.What is the value of n when the triangle()method is about to return to main()?5.True or false:In the triangle()method,the return values are stored on thestack.6.In the anagram.java program(Listing6.2),at a certain depth of recursion,a version of the doAnagram()method is working with the string“led”.When this method calls a new version of itself,what letters will the new version be working with?7.We’ve seen that recursion can take the place of a loop,as in the loop-oriented orderedArray.java program(Listing2.4)and the recursive binarySearch.java program(Listing6.3).Which of the following is not true?a.Both programs divide the range repeatedly in half.b.If the key is not found,the loop version returns because the rangebounds cross,but the recursive version occurs because it reaches thebottom recursion level.c.If the key is found,the loop version returns from the entire method, whereas the recursive version returns from only one level of recursion.d.In the recursive version the range to be searched must be specified in the arguments,while in the loop version it need not be.310CHAPTER6Recursion8.In the recFind()method in the binarySearch.java program(Listing6.3),what takes the place of the loop in the non-recursive version?a.the recFind()methodb.arguments to recFind()c.recursive calls to recFind()d.the call from main()to recFind()9.The binarySearch.java program is an example of the_________approach to solving a problem.10.What gets smaller as you make repeated recursive calls in the redFind() method?11.What becomes smaller with repeated recursive calls in the towers.java program (Listing6.4)?12.The algorithm in the towers.java program involvesa.“trees”that are data storage devices.b.secretly putting small disks under large disks.c.changing which columns are the source and destination.d.moving one small disk and then a stack of larger disks.13.Which is not true about the merge()method in the merge.java program(Listing6.5)?a.Its algorithm can handle arrays of different sizes.b.It must search the target array to find where to put the next item.c.It is not recursive.d.It continuously takes the smallest item irrespective of what array it’s in.14.The disadvantage of mergesort is thata.it is not recursive.b.it uses more memory.c.although faster than the insertion sort,it is much slower than quicksort.d.it is complicated to implement.15.Besides a loop,a___________can often be used instead of recursion. Chapter6,RecursionAnswers to Questions1.102.d3.24.105.false6.“ed”7.b8.c9.divide-and-conquer10.the range of cells to search11.the number of disks to transfer12.c13.b14.b15.stackQuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.1.The Shellsort works bya.partitioning the array.b.swapping adjacent elements.c.dealing with widely separated elements.d.starting with the normal insertion sort.2.If an array has100elements,then Knuth’s algorithm would start with an interval of________.Questions3613.To transform the insertion sort into the Shellsort,which of the following do you not do?a.Substitute h for1.b.Insert an algorithm for creating gaps of decreasing width.c.Enclose the normal insertion sort in a loop.d.Change the direction of the indices in the inner loop.4.True or false:A good interval sequence for the Shellsort is created by repeatedly dividing the array size in half.5.Fill in the big O values:The speed of the Shellsort is more than_______but less than________.6.Partitioning isa.putting all elements larger than a certain value on one end of the array.b.dividing an array in half.c.partially sorting parts of an array.d.sorting each half of an array separately.7.When partitioning,each array element is compared to the_______.8.In partitioning,if an array element is equal to the answer to question7,a.it is passed over.b.it is passed over or not,depending on the other array element.c.it is placed in the pivot position.d.it is swapped.9.True or false:In quicksort,the pivot can be an arbitrary element of the array.10.Assuming larger keys on the right,the partition isa.the element between the left and right subarrays.b.the key value of the element between the left and right subarrays.c.the left element in the right subarray.d.the key value of the left element in the right subarray.11.Quicksort involves partitioning the original array and then_________.362CHAPTER7Advanced Sorting12.After a partition in a simple version of quicksort,the pivot may beed to find the median of the array.b.exchanged with an element of the right subarray.ed as the starting point of the next partition.d.discarded.13.Median-of-three partitioning is a way of choosing the_______.14.In quicksort,for an array of N elements,the partitionIt()method will examine each element approximately______times.15.True or false:You can speed up quicksort if you stop partitioning when the partition size is5and finish by using a different sort.Chapter7,Advanced SortingAnswers to Questions1.c2.403.d4.false5.O(N*logN),O(N2)6.a7.pivot8.d9.true10.c11.partitioning the resulting subarrays12.b13.pivot14.log2N15.trueQuestionsThese questions are intended as a self-test for readers.Answers may be found inAppendix C.1.Insertion and deletion in a tree require what big O time?2.A binary tree is a search tree ifa.every non-leaf node has children whose key values are less than(or equalto)the parent.b.every left child has a key less than the parent and every right child has akey greater than(or equal to)the parent.c.in the path from the root to every leaf node,the key of each node isgreater than(or equal to)the key of its parent.d.a node can have a maximum of two children.3.True or False:Not all trees are binary trees.4.In a complete binary tree with20nodes,and the root considered to be at level 0,how many nodes are there at level4?5.A subtree of a binary tree always hasa.a root that is a child of the main tree’s root.b.a root unconnected to the main tree’s root.c.fewer nodes than the main tree.d.a sibling with the same number of nodes.6.In the Java code for a tree,the______and the_______are generally separate classes.Questions4237.Finding a node in a binary search tree involves going from node to node, askinga.how big the node’s key is in relation to the search key.b.how big the node’s key is compared to its right or left children.c.what leaf node we want to reach.d.what level we are on.8.An unbalanced tree is onea.in which most of the keys have values greater than the average.b.whose behavior is unpredictable.c.in which the root or some other node has many more left children thanright children,or vice versa.d.that is shaped like an umbrella.9.Inserting a node starts with the same steps as_______a node.10.Suppose a node A has a successor node S.Then S must have a key that is larger than_____but smaller than or equal to_______.11.In a binary tree used to represent a mathematical expression,which of the following is not true?a.Both children of an operator node must be operands.b.Following a postorder traversal,no parentheses need to be added.c.Following an inorder traversal,parentheses must be added.d.In pre-order traversal a node is visited before either of its children.12.If a tree is represented by an array,the right child of a node at index n has an index of_______.13.True or False:Deleting a node with one child from a binary search tree involves finding that node’s successor.14.A Huffman tree is typically used to_______text.15.Which of the following is not true about a Huffman tree?a.The most frequently used characters always appear near the top of the tree.b.Normally,decoding a message involves repeatedly following a path fromthe root to a leaf.424CHAPTER8Binary Treesc.In coding a character you typically start at a leaf and work upward.d.The tree can be generated by removal and insertion operations on apriority queue.Chapter8,Binary TreesAnswers to Questions1.O(logN)2.b3.True4.55.c6.node,tree7.a8.cChapter8,Binary Trees7439.finding10.A,A’s left-child descendents11.d12.2*n+113.Falsepress15.cQuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.1.A2-3-4tree is so named because a node can havea.three children and four data items.b.two,three,or four children.c.two parents,three children,and four items.d.two parents,three items,and four children.2.A2-3-4tree is superior to a binary search tree in that it is________.3.Imagine a parent node with data items25,50,and75.If one of its child nodes had items with values60and70,it would be the child numbered__________.4.True or False:Data items are located exclusively in leaf nodes.514CHAPTER102-3-4Trees and External Storage5.Which of the following is not true each time a node is split?a.Exactly one new node is created.b.Exactly one new data item is added to the tree.c.One data item moves from the split node to its parent.d.One data item moves from the split node to its new sibling.6.A2-3-4tree increases its number of levels when________.7.Searching a2-3-4tree does not involvea.splitting nodes on the way down if necessary.b.picking the appropriate child to go to,based on data items in a node.c.ending up at a leaf node if the search key is not found.d.examining at least one data item in any node visited.8.After a non-root node of a2-3-4tree is split,does its new right child contain the item previously numbered0,1,or2?9.A4-node split in a2-3-4tree is equivalent to a_______in a red-black tree.10.Which of the following statements about a node-splitting operation in a2-3 tree(not a2-3-4tree)is not true?a.The parent of a split node must also be split if it is full.b.The smallest item in the node being split always stays in that node.c.When the parent is split,child2must always be disconnected from itsold parent and connected to the new parent.d.The splitting process starts at a leaf and works upward.11.What is the big O efficiency of a2-3tree?12.In accessing data on a disk drive,a.inserting data is slow but finding the place to write data is fast.b.moving data to make room for more data is fast because so many items can be accessed at once.c.deleting data is unusually fast.d.finding the place to write data is comparatively slow but a lot of data can be written quickly.13.In a B-tree each node contains_______data items.Questions51514.True or False:Node splits in a B-tree have similarities to node splits in a2-3 tree.15.In external storage,indexing means keeping a file ofa.keys and their corresponding blocks.b.records and their corresponding blocks.c.keys and their corresponding records.st names and their corresponding keys.Chapter9,Red-Black TreesAnswers to Questions1.in order(or inverse order)2.b3.False4.d5.b6.rotations,changing the colors of nodes7.red8.a9.left child,right child10.d11.a node,its two children12.b13.True14.a15.TrueQuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.574CHAPTER11Hash Tablesing big O notation,say how long it takes(ideally)to find an item in a hash table.2.A__________transforms a range of key values into a range of index values.3.Open addressing refers toa.keeping many of the cells in the array unoccupied.b.keeping an open mind about which address to use.c.probing at cell x+1,x+2,and so on until an empty cell is found.d.looking for another location in the array when the one you want is occupied.ing the next available position after an unsuccessful probe is called_____________.5.What are the first five step sizes in quadratic probing?6.Secondary clustering occurs becausea.many keys hash to the same location.b.the sequence of step lengths is always the same.c.too many items with the same key are inserted.d.the hash function is not perfect.7.Separate chaining involves the use of a_____________at each location.8.A reasonable load factor in separate chaining is________.9.True or False:A possible hash function for strings involves multiplying each character by an ever-increasing power.10.The best technique when the amount of data is not well known isa.linear probing.b.quadratic probing.c.double hashing.d.separate chaining.11.If digit folding is used in a hash function,the number of digits in each group should reflect_____________.12.True or False:In linear probing an unsuccessful search takes longer than a successful search.Questions57513.In separate chaining the time to insert a new itema.increases linearly with the load factor.b.is proportional to the number of items in the table.c.is proportional to the number of lists.d.is proportional to the percentage of full cells in the array.14.True or False:In external hashing,it’s important that the records don’t become full.15.In external hashing,all records with keys that hash to the same value are located in___________.Chapter11,Hash TablesAnswers to Questions1.O(1)2.hash function3.d4.linear probing5.1,4,9,16,256.b7.linked listChapter11,Hash Tables7458.1.09.True10.d11.the array size12.False13.a14.False15.the same blockQuestionsThese questions are intended as a self-test for readers.Answers may be found in Appendix C.1.What does the term complete mean when applied to binary trees?a.All the necessary data has been inserted.b.All the rows are filled with nodes,except possibly the bottom one.c.All existing nodes contain data.d.The node arrangement satisfies the heap condition.2.What does the term weakly ordered mean when applied to heaps?3.A node is always removed from the__________.4.To“trickle up”a node in a descending heap meansa.to repeatedly exchange it with its parent until it’s larger than its parent.b.to repeatedly exchange it with its child until it’s larger than its child.c.to repeatedly exchange it with its child until it’s smaller than its child.d.to repeatedly exchange it with its parent until it’s smaller than its parent.5.A heap can be represented by an array because a heap。

Java语言程序设计第九版第八章答案

Java语言程序设计第九版第八章答案

Chapter 8 Objects and Classes1.See the section "Defining Classes for Objects."2.The syntax to define a classis public class ClassName {}3.The syntax to declare a reference variable foran object isClassName v;4.The syntax to create an object isnew ClassName();5.Constructors are special kinds of methods that arecalled when creating an object using the new operator.Constructors do not have a return type—not even void.6. A class has a default constructor only if theclass does not define any constructor.7.The member access operator is used to access adata field or invoke a method from an object.8.An anonymous object is the one that does not havea reference variable referencing it.9. A NullPointerException occurs when a null referencevariable is used to access the members of an object.10.An array is an object. The default value for theelements of an array is 0 for numeric, false for boolean,‘ u0000’ for char, null for object element type.11.(a) There is such constructor ShowErrors(int) in theShowErrors class.The ShowErrors class in the book has a defaultconstructor. It is actually same aspublic class ShowErrors {public static void main(String[] args) {ShowErrors t = new ShowErrors(5);}public ShowErrors () {}}On Line 3, new ShowErrors(5) attempts to create aninstance using a constructor ShowErrors(int), but theShowErrors class does not have such a constructor.That is an error.(b) x() is not a method in the ShowErrors class.The ShowErrors class in the book has a defaultconstructor. It is actually same aspublic class ShowErrors {public static void main(String[] args) {ShowErrors t = new ShowErrors();t.x();}public ShowErrors () {}}On Line 4, t.x() is invoked, but the ShowErrors classdoes not have the method named x(). That is an error.(c)The program compiles fine, but it has aruntime error because variable c is null when theprintln statement is executed.(d)new C(5.0) does not match any constructors in classC. The program has a compilation error because classC does not have a constructor with a double argument.12.The program does not compile because new A() is used inclass Test, but class A does not have a defaultconstructor. See the second NOTE in the Section,“Constructors.”13.falsee the Date’s no -arg constructor to create a Date forthe current time. Use the Date’s toString() method to display a string representation for the Date.15. Use the JFrame ’s no -arg constructor to create JFrame. Use thesetTitle(String) method a set a title and use the setVisible(true)method to display the frame.16.Date is in java.util. JFrame and JOptionPane are injavax.swing. System and Math are in ng.17.System.out.println(f.i);Answer: CorrectSystem.out.println(f.s);Answer: Correctf.imethod();Answer: Correctf.smethod();Answer: CorrectSystem.out.println(F.i);Answer: IncorrectSystem.out.println(F.s);Answer: CorrectF.imethod();Answer: IncorrectF.smethod();Answer: Correct18.Add static in the main method and in the factorialmethod because these two methods don ’t need referenceany instance objects or invoke any instance methods in theTest class.19. You cannot invoke an instance method or reference aninstance variable from a static method. You can invoke astatic method or reference a static variable from aninstance method? c is an instance variable, which cannot beaccessed from the static context in method2.20.Accessor method is for retrieving private data value andmutator method is for changing private data value. The namingconvention for accessor method is getDataFieldName() for non-boolean values and isDataFieldName() for boolean values. Thenaming convention for mutator method is setDataFieldName(value).21.Two benefits: (1) for protecting data and (2) for easyto maintain the class.22.Not a problem. Though radius is private,myCircle.radius is used inside the Circle class. Thus, itis fine.23.Java uses “pass by value ” to pass parameters to amethod. When passing a variable of a primitive type to amethod, the variable remains unchanged after themethod finishes. However, when passing a variable of areference type to a method, any changes to the objectreferenced by the variable inside the method arepermanent changes to the object referenced by thevariable outside of the method. Both the actualparameter and the formal parameter variables referenceto the same object.The output of the program is as follows:count 101times 024.Remark: The reference value of circle1 is passed to xand the reference value of circle2 is passed to y. The contents ofthe objects are not swapped in the swap1 method. circle1 andcircle2 are not swapped. To actually swap the contents of these objects, replace the following three linesCircle temp = x;x=y;y=temp;bydouble temp = x.radius;x.radius = y.radius;y.radius = temp;as in swap2.25. a. a[0] = 1 a[1] = 2 b.a[0] = 2 a[1] = 1c. e1 = 2 e2 = 1d. t1 ’s i = 2 t1t2 ’s i = 2 t2’s j = 1’s j = 126.(a) null(b)1234567(c)7654321(d)123456727.(Line 4 prints null since dates[0] is null. Line 5 causes a NullPointerException since it invokes toString() method from the null reference.)。

JAVA练习题含答案-answertopratice3

JAVA练习题含答案-answertopratice3

JAVA练习题含答案-answertopratice3Chapter 3Flow of ControlMultiple Choice1)An if selection statement executes if and only if:(a)the Boolean condition evaluates to false.(b)the Boolean condition evaluates to true.(c)the Boolean condition is short-circuited.(d)none of the above.Answer:B (see page 97)2) A compound statement is enclosed between:(a)[ ](b){ }(c)( )(d)< >Answer:B (see page 98)3) A multi-way if-else statement(a)allows you to choose one course of action.(b)always executes the else statement.(c)allows you to choose among alternative courses of action.(d)executes all Boolean conditions that evaluate to true.Answer:C (see page 100)4)The controlling expression for a switch statement includes all of the following types except:(a)char(b)int(c)byte(d)doubleAnswer:D (see page 104)Copyright ? 2006 Pearson Education Addison-Wesley. All rights reserved. 125)To compare two strings lexicographically the String method ____________ should be used.(a)equals(b)equalsIgnoreCase(c)compareTo(d)==Answer:C (see page 112)6)When using a compound Boolean expression joined by an && (AND) in an if statement:(a)Both expressions must evaluate to true for the statement to execute.(b)The first expression must evaluate to true and the second expression must evaluate to false forthe statement to execute.(c)The first expression must evaluate to false and the second expression must evaluate to true forthe statement to execute.(d)Both expressions must evaluate to false for the statement to execute.Answer:A (see page 116)7)The OR operator in Java is represented by:(a)!(b)&&(c)| |(d)None of the aboveAnswer:C (see page 116)8)The negation operator in Java is represented by:(a)!(b)&&(c)| |(d)None of the aboveAnswer:A (see page 116)9)The ____________ operator has the highest precedence.(a)*(b)dot(c)+=(d)decrementAnswer:B (see page 123)10)The looping mechanism that always executes at least once is the _____________ statement.(a)if…else(b)do…while(c)while(d)forAnswer:B (see page 132).Chapter 3 Flow of Control 311) A mixture of programming language and human language is known as:(a)Algorithms(b)Recipes(c)Directions(d)PseudocodeAnswer:D (see page 134)12)When the number of repetitions are known in advance, you should use a ___________ statement.(a)while(b)do…while(c)for(d)None of the aboveAnswer:C (see page 141)13)To terminate a program, use the Java statement:(a)System.quit(0);(b)System.end(0);(c)System.abort(0);(d)System.exit(0);Answer:D (see page 148)True/False1)An if-else statement chooses between two alternative statements based on the value of a Booleanexpression.Answer:True (see page 96)2)You may omit the else part of an if-else statement if no alternative action is required.Answer:True (see page 97)3)In a switch statement, the choice of which branch to execute is determined by an expression given inparentheses after the keyword switch.Answer:True (see page 104)4)In a switch statement, the default case is always executed.Answer:False (see page 104)5)Not including the break statements within a switch statement results in a syntax error.Answer:False (see page 104)6)The equality operator (==) may be used to test if two string objects contain the same value.Answer:False (see page 111)47)Boolean expressions are used to control branch and loop statements.Answer:True (see page 116)8)The for statement, do…while statement and while statement are examples of branching mechanisms.Answer:False (see page 130)9)An algorithm is a step-by-step method of solution.Answer:True (see page 134)10)The three expressions at the start of a for statement are separated by two commas.Answer:False (see page 137)Short Answer/Essay1)What output will be produced by the following code?public class SelectionStatements{public static void main(String[] args){int number = 24;if(number % 2 == 0)System.out.print("The condition evaluated to true!");elseSystem.out.print("The condition evaluated to false!");}}Answer:The condition evaluated to true!.Chapter 3 Flow of Control 52)What would be the output of the code in #1 if number was originally initialized to 25?Answer:The condition evaluated to false!3)Write a multi-way if-else statement that evaluates a persons weight on the following criteria: Aweight less than 115 pounds, output: Eat 5 banana splits! A weight between 116 pounds and 130 pounds, output: Eat a banana split! A weight between 131 pounds and 200 pounds, output: Perfect!A weight greater than 200 pounds, output: Plenty of banana splits have been consumed!Answer:if(weight <= 115)System.out.println("Eat 5 banana splits!");else if(weight <= 130)System.out.println("Eat a banana split!");else if(weight <=200)System.out.println("Perfect!");elseSystem.out.println("Plenty of banana splits have been consumed!");4)Write an if-else statement to compute the amount of shipping due on an online sale. If the cost ofthe purchase is less than $20, the shipping cost is $5.99. If the cost of the purchase over $20 and at most $65, the shipping cost is $10.99. If the cost of the purchase is over $65, the shipping cost is $15.99.Answer:if(costOfPurchase < 20)shippingCost = 5.99;else if((costOfPurchase > 20)&&(costOfPurchase <= 65))shippingCost = 10.99;elseshippingCost = 15.99;5)Evaluate the Boolean equation: !( ( 6 < 5) && (4 < 3))Answer:True66)Write Java code that uses a do…while loop that prints even numbers from 2 through 10.Answer:int evenNumber = 2;do{System.out.println(evenNumber);evenNumber += 2;}while(evenNumber <= 10);7)Write Java code that uses a while loop to print even numbers from 2 through 10.Answer:int evenNumber = 2;while(evenNumber <= 10){System.out.println(evenNumber);evenNumber += 2;}Answer:8)Write Java code that uses a for statement to sum the numbers from 1 through 50. Display the totalsum to the console.Answer:.Chapter 3 Flow of Control 7 int sum = 0;for(int i=1; i <= 50; i++){sum += i;}System.out.println("The total is: " + sum);9)What is the output of the following code segment?public static void main(String[] args){int x = 5;System.out.println("The value of x is:" + x);while(x > 0){x++;}System.out.println("The value of x is:" + x);}Answer:.10)Discuss the differences between the break and the continue statements when used in loopingmechanisms.Answer:When the break statement is encountered within a looping mechanism, the loopimmediately terminates. When the continue statement is encountered within a looping mechanism, the current iteration is terminated, and execution continues with the next iteration of the loop.8Programming projects:1. Write a complete Java program that prompts the user fora series of numbers to determine the smallestvalue entered. Before the program terminates, display the smallest value.Answer:import java.util.Scanner;public class FindMin{public static void main(String[] args){Scanner keyboard = new Scanner(System.in);int smallest = 9999999;String userInput;boolean quit = false;System.out.println("This program finds the smallest number"+ " in a series of numbers");System.out.println("When you want to exit, type Q");.Chapter 3 Flow of Control 9 while(quit != true){System.out.print("Enter a number: ");userInput = keyboard.next();if(userInput.equals("Q") || userInput.equals("q")){quit = true;}else{int userNumber = Integer.parseInt(userInput);if(userNumber < smallest)smallest = userNumber;}}System.out.println("The smallest number is " + smallest);System.exit(0);}10}2. Write a complete Java program that uses a for loop to compute the sum of the even numbers and thesum of the odd numbers between 1 and 25.public class sumEvenOdd{public static void main(String[] args){int evenSum = 0;int oddSum = 0;//loop through the numbersfor(int i=1; i <= 25; i++){if(i % 2 == 0){//even numberevenSum += i;}else{oddSum += i;.Chapter 3 Flow of Control 11 }}//Output the resultsSystem.out.println("Even sum = " + evenSum);System.out.println("Odd sum = " + oddSum);}}/*** Question2.java** This program simulates 10,000 games of craps.* It counts the number of wins and losses and outputs the probability* of winning.** Created: Sat Mar 05, 2005** @author Kenrick Mock* @version 1*/public class Question2{private static final int NUM_GAMES = 10000;/*** This is the main method. It loops 10,000 times, each simulate* a game of craps. Math.random() is used to get a random number,* and we simulate rolling two dice (Math.random() * 6 + 1 simulates* a single die).*/public static void main(String[] args){// Variable declarationsint numWins = 0;12int numLosses = 0;int i;int roll;int point;// Play 10,000 gamesfor (i=0; i<="" p="">{// Simulate rolling the two dice, with values from 1-6roll = (int) (Math.random() * 6) + (int) (Math.random() * 6) + 2;// Check for initial win or lossif ((roll == 7) || (roll == 11)){numWins++;}else if ((roll==2) || (roll==3) || (roll==12)){numLosses++;}else{// Continue rolling until we get the point or 7point = roll;do{roll = (int) (Math.random() * 6) + (int) (Math.random() * 6) +2;if (roll==7){numLosses++;}else if (roll==point){numWins++;}} while ((point != roll) && (roll != 7));}}// Output probability of winningSystem.out.println("In the simulation, we won " + numWins +" times and lost " + numLosses + " times, " +" for a probability of " +(double) (numWins) / (numWins+numLosses));}} // Question2.Chapter 3 Flow of Control 13 /*** Question6.java** Created: Sun Nov 09 16:14:44 2003* Modified: Sat Mar 05 2005, Kenrick Mock** @author Adrienne Decker* @version 2*/import java.util.Scanner;public class Question6{public static void main(String[] args){Scanner keyboard = new Scanner(System.in);while ( true ){System.out.println("Enter the initial size of the green crud" + " in pounds.\nIf you don't want to " +"calculate any more enter -1.");int initialSize = keyboard.nextInt();if ( initialSize == -1){break;} // end of if ()System.out.println("Enter the number of days: ");int numDays = keyboard.nextInt();int numOfRepCycles = numDays / 5;int prevPrevGen = 0;int prevGen = initialSize;int finalAnswer = initialSize;for ( int i = 0; i < numOfRepCycles; i++ ){finalAnswer = prevPrevGen + prevGen;14prevPrevGen = prevGen;prevGen = finalAnswer;} // end of for ()System.out.println("The final amount of green crud will be: "+ finalAnswer + " pounds.\n");} // end of while ()}} // Question6/*** Question7.java** Created: Sun Nov 09 16:14:44 2003* Modified: Sat Mar 05 2005, Kenrick Mock** @author Adrienne Decker* @version 2*/import java.util.Scanner;public class Question7{public static void main(String[] args){Scanner keyboard = new Scanner(System.in);String line;do{System.out.println("Enter the value of X for this calculation."); double x = keyboard.nextDouble();double sum = 1.0;double temp = 1.0;for ( int n = 1; n <= 10; n++){System.out.print("For n equal to: " + n.Chapter 3 Flow of Control 15+ ", the result of calculating e^x is: ");for ( int inner = 1; inner <= n; inner++){temp = 1.0;for ( double z = inner; z > 0; z--){temp = temp * (x/z);} // end of for ()sum += temp;} // end of for ()System.out.println(sum);sum = 1.0;} // end of for ()System.out.print("For n equal to 50, the result of " + "calculating e^x is: ");for ( int n = 1; n <= 50; n++){temp = 1.0;for ( double z = n; z > 0; z--){temp = temp * (x/z);} // end of for ()sum += temp;} // end of for ()System.out.println(sum);sum = 1;System.out.print("For n equal to 100, the result of " + "calculating e^x is: ");for ( int n = 1; n <= 100; n++){temp = 1.0;for ( double z = n; z > 0; z--){temp = temp * (x/z);} // end of for ()sum += temp;} // end of for ()System.out.println(sum);System.out.println("\nEnter Q to quit or Y to go again.");16keyboard.nextLine(); // Clear bufferline = keyboard.nextLine();} while (line.charAt(0)!='q' && line.charAt(0)!='Q'); // end of while () }} // Question7.。

Java_Programming_Final_Exam_Question_08W_PaperA

Java_Programming_Final_Exam_Question_08W_PaperA

Java_Programming_Final_Exam_Question_08W_PaperA 《J a v a程序设计》期末试题试卷(A)(考试形式:闭卷考试时间: 1.5⼩时)Total 8 pages《中⼭⼤学授予学⼠学位⼯作细则》第六条考试作弊不授予学⼠学位班级:___________ 姓名: ______学号:__________注意:答案⼀定要写在答卷中,写在本试题卷中不给分。

本试卷要和答卷⼀起交回。

Section 1. Choose the best answer 20 x 1 (mark each) = 20 marks1.In Java, arguments are always passed by ________.A. nameB. valueC. pointerD. array2.In Java, we can define multiple methods with the same name. This is called _____.A. method overridingB. This is not allowedC. method overloadingD. method hiding3.Which type of objects are immutable?B.StringBufferStringA.C. char [] stringD.int [] s14. A thread’s entry point is its method.run.B.A.start.E. distroy5.Given any URL object urlobj, which method can be used to retrieve its constitute parts? urlobj.getHost()B.A.urlobj.Method.urlobj.openStream()D.C.urlobj.start()6.The best way to peform custom painting is to override ____?A.repaint()B.paintComponent()C.update()D.paint()E.other method7.Which one can be used for an event source to register a listener?A. actionPerformed.B. addActionListener()C. ActionListenerD. MouseAdapter8.Which is not a benefit of encapsulation?A.Clarity of code.B.Code efficiency.C.The ability of add functionality later onD.Modifications require fewer coding changes9.OutputStreamWriter is a subclass of _ ?A.ReaderB.OutptuStreamC.PrintWriterD.BufferedWriterE.Writer10.Which one cannot help achieve plug compatibility in Java program?A.Synchronized Method.C.Access only uniform public interfaceD.Run-time method overriding11.A compile error occurs ifA.A static method in a subclass has the same signature with a static method in superclass.B. A subclass static method has the same signature as asuperclass instance method.C. A subclass field has the same name as a field used in a superclassD.Appendant member calls a method in superclassE. A superclass has a protected member12.Which of the following is a component of an event handling model?A. object registryB. proxyC. event listenerD. web client13.The GUI program execution envitonment does not suppliesA. event monitoringB. input focusingC. window renderingD. creating a POST query14.Which statement is true about wrapper or String classes?A.if x and y refer to instances of different wrapper classes, then the fragment x.equals(y) will cause a compiler failure.B.If x and y refer to instances of different wrapper classes, then x == y can sometimes be true.C.If x and y are String references and if x.equals(y) is true, then x == y is true.D.If x, y and z refer to instances of wrapper classes and x.equals(y) is true and y.equals(z) is true, then z.equals(x) will be always true.E.If x and y are String references and x == y is true, but y.equals(x) will not be true.15.Which of the following does not concern with a method signature?A.Method name.B.The number of its formal parameters.C.The order of its formal parametersD.The types of its formal parametersE.The return type16.Which statement is true?garbage collector.B.Objects with at least one reference will never be garbage collected.C.Objects from a class with the finalize() method overridden will never be garbage collected.D.Objects instantiated within anonymous inner classes are placed in the garbage collectible heap.E.Once an overridden finalize() method is invoked, there is no way to make that object ineligible for garbage collection.17.A reference variable can ?A.Hold the constant value 546B.Can be a primitive typeC.Be an array variableD.Be converted to a primitive typeE.Hold a reference to an object18.Which one of the layout can be used to arrange the components in specified rows and columns?A.FlowLayoutB.GridLayoutC.BorderLayoutD.CardLayout19.In a Java interfaceA.members can be public or privateB.All members are abstractC.Fields can be final or instanceD.Methods must be implemented20.Which method is not supplied by a URL objectA.Methods to parse the URLB.paint()C.Methods to open network connectionD.Method to retrieve information1. A dead thread can be restarted.2. Java objects are always created with new operation.3. In Java, a class can extend at most one superclass and can implemen at mostone interface.5. A thread is in the ready state after it has been created and started6. The main() method takes an argument of the String[ ].7. A double value can be cast to a byte.8. Window, Frame, Dialog, FileDialog, Panel, Applet are not container classes –False9. In Java, a class is implicitly of any superinterfave type.10. The Java overriding mechanism ensures that the calls on methods in superclass and subclass invoke the appropriate overriding methods.Section 3. Answer the Following Questions 5 x 4 (mark each) = 20 marks1. What operations will be performed when a thread calls a synchronized instance method?2. How is the method call resolution performed by Java compiler when a call is made to an overloaded method in class extension?3. What is plug-compatible object? What is polymorphism?4. In the event-handling model, what is an event source? An event listener? An event client? An event object?5. To program an Internet client using stream socket to access TCP-based server, what things you should do in your program?1. In GUI program, if you want to have a JPanel custom painting, you usually override method ____2. To add a byte buffer to a FileInputStream stream, you use _______________3. In Java, every object and class can potentially function as a ___________ anda monitor.4. In Java, the event-handling model describes how to represent, how to report, and how to ___________the events.5. A constructor can also call another constructor in its own class to help perform initializations. This can be done by calling __________6. The same identifier can be used in ________name spaces without conflict.7. It is a compile-time error if a subclass instance method has the same signature as___________________.8. In Java, a class with no declared superclass implicitly extends ____________.9. Run-time overriding is one of the conditions to help the polymorphic transfer in achieving ______________.10. The main advantage of an interface over an abstract class is thatSection 5. Write the output for the following programs 5 x 2 (mark each) = 10 marks 1. Given the following, public class runtimexceptiondemo {public static void throwit() {“);System.out.print(“throwitthrowRuntimeException();new}public static void main(String args[ ]) {try {System.out.print(“hello“);throwit();e){}catch(Exception“);System.out.print(“caughtfinally {}“);System.out.print(“finally}“);System.out.print(“after}}2. Given the following,public class switchdemo {final static short x = 2;public static int y = 0;for(int z = 0; z < 3; z++) {switch(z) {“);System.out.print(“0x:case“);System.out.print(“1x-1:case“);System.out.print(“2casex-2:}}}}class MyThread extends Thread { {MyThread() MyThread”);System.out.print(“}{run()publicvoidbar”);System.out.print(“}public void run(String s) { baz”);System.out.println(“public class TestThreads {public static void main(String [ ] args) { Thread t = new MyThread() {{publicrun()voidfoo”); System.out.print(“}};t.start();}}4. Given the following,public class commandargs {public static void main(String args[ ]) { args[1];=s1Stringargs[2];=s2Stringargs[3];=s3Stringargs[4];=s4StringSystem.out.print(“ args[2] = “ + s2);And the command line invocation, as java commandargs 1 2 3 4class test {ints;staticpublic static void main(String args[]) { new=test();testpp.start();System.out.println(s);}{voidstart()7;=xInttwice(x);“);“+System.out.print(x}void twice(int x) {x*2;x=s = x;Section 6. Programming 3 x10 (mark each) = 30 marks1.Write an applet that displays “over” when the mouse is over its display area and displays“leave” when the mouse leaves the area.2.Write a class for a mutual exclusion object in which the reading and the writing of aninternal integer X are synchronized.3.Define a base class for just displaying an integer in the screen. Then extend this baseclass to obtain a class for displaying a float number in the screen. Write a polymorphic program to demonstrate the interchangable objects of these two classes.。

高二英语编程入门单选题50题

高二英语编程入门单选题50题1.In programming, a variable is used to store _____.A.dataB.codeC.functionD.error答案:A。

选项A“data”意为“数据”,变量在编程中是用来存储数据的。

选项B“code”是“代码”,变量不是用来存储代码的。

选项C“function”是“函数”,变量不存储函数。

选项D“error”是“错误”,变量也不存储错误。

本题考查编程基础词汇“variable”的含义。

2.When you write a program, you need to use a(n) _____ to tell the computer what to do.mandmentC.libraryD.error message答案:A。

选项A“command”意为“命令”,写程序时需要用命令告诉计算机做什么。

选项B“comment”是“注释”,不是用来告诉计算机做什么的。

选项C“library”是“库”,也不是用来直接告诉计算机做什么的。

选项D“error message”是“错误信息”,不是用来指示计算机行动的。

本题考查编程相关词汇的理解。

3.In programming, an algorithm is a set of _____ to solve a problem.A.dataB.stepsC.errorsnguages答案:B。

选项A“data”是“数据”,算法不是一组数据。

选项B“steps”是“步骤”,算法是解决问题的一组步骤。

选项C“errors”是“错误”,算法不是错误的集合。

选项D“languages”是“语言”,算法不是语言的集合。

本题考查编程基础词汇“algorithm”的含义。

4.A function in programming is like a(n) _____ that performs a specific task.A.toolB.errorC.datanguage答案:A。

Java外文翻译(programming-language)

Java (programming language)From Wikipedia,the free encyclopediaJava is a programming language originally developed by James Gosling at Sun Microsystems (which has since merged into Oracle Corporation)and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low—level facilities. Java applications are typically compiled to bytecode (class file) that can run on any Java Virtual Machine (JVM)regardless of computer architecture. Java is a general-purpose,concurrent,class-based,object-oriented language that is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere," meaning that code that runs on one platform does not need to be edited to run on another. Java is currently one of the most popular programming languages in use, particularly for client—server web applications,with a reported 10 million users.[10][11] The original and reference implementation Java compilers,virtual machines, and class libraries were developed by Sun from 1995。

SSD3 选择题题库完整

SSD3 选择题题库1.Which method must exist in every Java application?(a) begin(b) paint(c) init(d) mainCorrect answer is (d)2 .Which of the following is a valid character literal in Java?(a) ';'(b) '<='(c) "'"(d) "a"Correct answer :A2.A Java identifier may begin with all but which of the following?(a) $(b) if(c) _ (the underscore)(d) 0Correct answer is (d)3.In the context of Java programming, garbage collection refers to(a) automatic balancing of parenthesis performed by some editors(b) removal of Java programs that could cause damage to a system(c) conversion of comments into Javadoc comments(d) automatic return of memory to the heap for objects no longer required by the programCorrect answer is (d)4.What will be output when the following Java program segment is executed?int x = 5;int y = 2;System.out.println(x+y);(a) 5+2(b) 5 2(c) 7(d) 52Correct answer is (c)5. Which of the following parts of an if-else-statement is optional?(a) the if part(b) the else part(c) the parenthesis around the condition(d) the conditionCorrect answer is (b)6.Which of the following is the Java loop construct typically used when the range is clear?(a) while-loop(b) for-loop(c) switch-loop(d) do-while-loopCorrect answer is (b)8.Consider the following Java program segment.import java.io.*;public class Test {public Test( ) {System.out.println("default");}public Test( int i ) {System.out.println("non-default");}public static void main(String[] args) {Test t = new Test(2);}}Which of the following will be output during execution of the program segment?(a) The line of text "non-default" followed by the line of text "default"(b) The line of text "default" followed by the line of text "non-default"(c) The line of text "default"(d) The line of text "non-default"Correct answer is (d)9.What is the name of the JDK program that processes Javadoc comments?(a) java(b) javac(c) javacom(d) javadocCorrect answer is (d)10.According to the Java code conventions, files longer than _____ lines should be _____.(a) 100, encouraged(b) 100, avoided(c) 2000, avoided(d) 2000, encouragedCorrect answer is (c)2.The primitive floating-point types available in Java are _____ and _____.(a) real, double(b) float , double(c) real , float(d) single , realCorrect answer is (b)3.How many bytes are required to represent a Unicode character?(a) Four(b) One(c) Three(d) TwoCorrect answer is (d)5.How many lines of output will be produced by the following code fragment?for (int i = 0; i < 4; ++i) {for (int j = 1; j < 3 ; ++j) {stdOut.println(i + j);(a) 12(b) 6(c) 10(d) 8Correct answer is (d)6.How many lines of output will be produced by the following code fragment?for (int i = 0; i < 3; ++i) {for (int j = 0; j < i; ++j) {stdOut.println(i + j);} }(a) 6(b) 4(c) 3(d) 5Correct answer is (c)7.Which of the following statements about class variables in Java is not true?(a) Class variables require the modifier static in the declarations.(b) All objects have their own copy of the class variable defined in the instantiated class.(c) Non-static methods in a class can access the class variable defined in the same class.(d) Class variables do not need the reference to the object of the instantiated class to access them.Correct answer is (b)8.The term class variable is a synonym for(a) an instance variable(b) a read-only variable(c) a private data field(d) a static data fieldCorrect answer is (d)9.Which of the following patterns of characters opens a Javadoc comment block?(a) /**(b) //(c) /*(d) **/Correct answer is (a)2.The term wrapper classes refers to(a) the Java classes that contain at least two data fields(b) the Java classes that contain themselves(c) a collection of Java classes that "wrap" Java primitive types(d) a collection of Java classes that contain other Java classesCorrect answer is (c)3.Given the following code, what value will be output by the last statement? StringTokenizer st = new StringTokenizer("this is,a,test of tokens", ","); String s;int count = 0;while (st.hasMoreTokens()) {s = st.nextToken();++count;}stdOut.println(count);(a) 3(b) 1(c) 6(d) 4Correct answer is (a)5.Consider the following Java program segment.int x = 5;int y = 2;System.out.println(x + "1" + y);Which of the following statements is true about the program segment?(a) The output caused by the code will be 512.(b) The output caused by the code will be 8.(c) The code will cause a compilation error.(d) The output caused by the code will be 5 1 2.Correct answer is (a)6.Consider the following Java program segment.import java.io.*;public class SomeClass{public void x() {throw new RuntimeException("Exception from x");}public void y(){throw new IOException("Exception from y");}}Which of the following is true concerning the definitions for the methods x and y?(a) Neither x nor y has a legal definition.(b) Both x and y have legal definitions.(c) x has a legal definition, but y has an illegal definition.(d) x has an illegal definition, but y has a legal definition.Correct answer is (c)7.In Java, exceptions that are not handled are passed up the(a) exception ladder(b) call stack(c) catch blocks(d) block hierarchyCorrect answer is (b)10.After a typical debugger encounters a breakpoint, the programmer using the debugger may perform which of the following actions?1. Examine the values of variables in the halted program2. Execute the current line3. Resume execution of the halted program(a) III only(b) I, II, and III(c) I only(d) I and II onlyCorrect answer is (b)1.The name of a Java source file(a) must use the extension .class(b) must be the same as the class it defines, respecting case(c) must be the same as the class it defines, ignoring case(d) has no restrictionsCorrect answer is (b)5.A difference between the methods print and println of the class java.io.PrintWriter is that(a) println appends a new line to the end of its output, but print does not(b) print appends a new line to the end of its output, but println does not(c) println inserts a new line at the beginning of its output, but print does not(d) print inserts a new line at the beginning of its output, but println does not Correct answer is (a)6.What is the right way to handle abnormalities in input on Java?(a) By handling these problems by providing exception handlers(b) By always specifying the throws clause in every method header where file I/O is performed(c) By using the class FileFilter which gracefully filters out bad input data(d) By writing while loops to guard against bad inputCorrect answer is (a)7.All Java exception classes are derived from the class(a) ng.RuntimeException(b) ng.Throwable(c) ng.Error(d) java.io.IOExceptionCorrect answer is (b)9.Which of the following statements is true of the conventions outlined by Sun Microsystems in the document entitled Code Conventions for the Java Programming Language?1. They define a standard interface definition language that must be used for all Java classes.2. They provide recommendations intended to make source code easier to read and understand.3. They describe one mechanism for network communication between Java and C++ programs.(a) III only(b) I, II, and III(c) II only(d) I and III onlyCorrect answer is (c)10.A tool that allows programmers to execute lines of a program one line at a time in order to help locate the source of a program's errors is known as a(n)(a) debugger(b) stack trace(c) exception handler(d) scopeCorrect answer is (a)2.Which of the following is not true concerning objects and their representation?(a) objects are represented by their addresses(b) objects are represented by value(c) objects are represented by reference(d) objects are represented indirectlyCorrect answer is (b)5.In programming, a loop is generally used to achieve(a) branching(b) succession(c) repetition(d) selectionCorrect answer is (c)7.If a class contains a constructor, that constructor will be invoked(a) each time an object of that class goes out of scope(b) once at the beginning of any program that uses that class(c) once the first time an object of that class is instantiated(d) each time an object of that class is instantiatedCorrect answer is (d)8.Which of the following categorizations can be applied to both the data fields and the methods in a Java class?(a) native and non-native(b) static and non-static(c) default and non-default(d) abstract and non-abstractCorrect answer is (b)10. According to the Java code conventions, files that contain Java source code have the suffix _____, and compiled bytecode files have the suffix _____.(a) .javac, .class(b) .java, .class(c) .class, .javac(d) .class, .javaCorrect answer is (b)2.Variables of primitive types are also referred to as(a) references(b) classes(c) objects(d) scalarsCorrect answer is (d)3.Based on the following declaration, what does b1 represent just after the declaration is executed?Button b1;(a) a "default" Button object(b) a Button object with no label(c) a blank Button object(d) nothingCorrect answer is (d)8. The return type for a method that returns nothing to its caller is(a) not specified in the method definition(b) false(c) null(d) voidCorrect answer is (d)2.What is the name of the wrapper class for the type int?(a) Integer(b) INT(c) integer(d) IntCorrect answer is (a)3. Which of the following statements is (are) true about the use of an asterisk (*) in a Java import statement?It does not incur run-time overhead.It can be used to import multiple packages with a single statement.It can be used to import multiple classes with a single statement.(a) III only(b) I and III only(c) I only(d) I, II, and IIICorrect answer is (b)4. What will be output caused by the execution of the following Java program segment? String name = "Elvis";System.out.print(name + "was here");(a) Elviswas here(b) name was here(c) Elvis was here(d) name + was hereCorrect answer is (a)10. As an aid in debugging a program in Java, print statements may be used to display which of the following types of information?The names of methods being calledThe values of the parameters of a methodThe values of the instance variables of a class(a) I and II only(b) I, II, and III(c) II and III only(d) I and III onlyCorrect answer is (b)2. Which package does not need to be explicitly imported into a Java program?(a) java.applet(b) java.awt(c) java.io(d) ngCorrect answer is (d)1.UML class diagrams can describe which of the following?The internal structure of classesRelationships between classes(a) None(b) II only(c) I and II(d) I onlyCorrect answer is (c)2.In a UML class diagram's representation of a class, the top, middle, and lower. .rectangular compartments respectively describe the _____ of the class.(a) name, methods, and constants(b) name, attributes, and methods(c) attributes, methods, and name(d) attributes, methods, and constantsCorrect answer is (b). . .。

java 课后答案01review

Chapter 1 Introduction to Computers, Programs, and Java1. A computer is an electronic device that stores and processes data. A computerincludes both hardware and software. In general, hardware is the physical aspect ofthe computer that can be seen, and software is the invisible instructions that controlthe hardware and make it work.2. The hardware of a computer consists of a CPU, cache, memory, hard disk, floppy disk,monitor, printer, and communication devices.3.The machine language is a set of primitive instructions built into every computer.Assembly language is a low-level programming language in which a mnemonic isused to represent each of the machine language instructions. The high-level languagesare English-like and easy to learn and program.4.Source program means the original program written in a high-level language. Acompiler is a program that translates source program into executable code.5.Java source programs are compiled into bytecode. The JVM is the interpreter thatinterprets Java bytecode.6.The operating system(OS) is a program that manages and controls a computer’sactivities. The examples of OS are Windows 98, NT, 2000, XP, or ME. Windows.Application programs such as an Internet browser and a word processor run on top ofan operating system.7.Developed by a team led by James Gosling at Sun Microsystems in 1991. Originallycalled Oak, it became Java in 1995 when it was redesigned for developing Internetapplications.Java can run on any platform with a Java Virtual Machine. The minimum requirementis the Java Runtime Environment, free from the .8. The input is the Java source code and the output is the Java bytecode (if compiledsuccessfully).9. JBuilder by Borland, Sun ONE Studio by Sun, Café by WebGain, Visual Age for Javaby IBM are the tools for developing Java programs, not dialects of Java. These toolsmake developing Java programs easier and more productive.10. HTML is a markup language for displaying static Web pages. Java is a full-fledgedprogramming language that can be used to develop dynamic Web pages. The Javaprograms that run from a Web browser are called applets. Java applets must beembedded in HTML files using the <applet> tag.11. Keywords have specific meaning to the compiler and cannot be used for otherpurposes in the program such as variables or method names. Examples of keywordsare class, static, and void.12. Java source code is case sensitive. Java keywords are always in lowercase.13. The source file extension is .java and the bytecode file extension is .class.14. Comments are used to document what a program is for and how a program isconstructed. Comments help the programmers or users to communicate andunderstand the program. Comments are not programming statements and are ignoredby the compiler. In Java, comments are preceded by two forward slashes (//) in a lineor enclosed between /* and */ in multiple lines. When the compiler sees //, it ignoresall text after // in the same line. When it sees /*, it scans for the next */ and ignoresany text between /* and */.15. System.out.println(...);JOptionPane.showMessageDialog(null, “Hello world”);16.public class Welcome {public static void main(String[] args) {System.out.println("morning");System.out.println("afternoon");}}17. Line 2. Main should be main.Line 2. static is missing.Line 3: Welcome to Java! should be enclosed inside double quotation marks.Line 5: The last ) should be }.18. javac is the JDK command to compile a program. java is the JDK command to run aprogram.19. Java interpreter cannot find the .class file. Make sure you placed the .class in the rightplace, and invoked java command with appropriate package name.20. The class does not have a main method, or the signature of the main method isincorrect.21.The System class is in the ng package. This package is implicitly imported. So,there is no need to explicitly import it.22.No performance difference.23. Output is3.5 * 4 / 2 – 2.5 is4.5。

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

Slicing of Java Programs using the Soot FrameworkD.ArvindPriti Shankararvind@csa.iisc.ernet.in,priti@csa.iisc.ernet.inDepartment of Computer Science and AutomationIndian Institute of ScienceSeptember6,2006AbstractSlicing is a technique used to identify the program subset that could affect a particular statement of interest called the slicing criterion.Slicing has applications in program understanding,testing,model checkingand functionality extraction.For computing a slice,we need to compute dependence information amongstatements.In object oriented languages,finding dependence information becomes non-trivial because oflanguage features like inheritance,objects,polymorphism,dynamic binding and so forth.We develop amethod for computing slices in object oriented programs for application in regression testing.In particularwe propose a new method for intraprocedural alias analysis for Java and implement an interprocedural slicingtechnique using the system dependence graph of Horwitz et al.1IntroductionProgram slicing is a technique that has many applications,for example regression testing,program understanding etc.A program slice is an executable subset of program statements that might affect the value of a variable v at program point p.The pair(p,v)is called the slicing criterion.For interprocedural slices Horwitz et al.defined the System Dependence Graph and a two phase reachability algorithm that ensured that only valid execution paths through procedure calls and returns are tracked by the analysis.Special properties of object oriented languages like classes,objects,inheritance polymorphism and dynamic binding present challenges that are not taken care of by slicing techniques for imperative languages.The Class Dependence Graph was defined by Larsen and Harrold [10].This can represent a class hierarchy,polymorphism and so forth.Having constructed such a graph the technique of Horwitz et al.can be used for slicing.Their technique however cannot distinguish different data members instantiated from the same class leading to imprecise slices.Tonella et al.[33]propose an extension of the linear time points to analysis of Steensgard[32]to handle object oriented constructs,but is bothflow and context insensitive.Liang and Harrold[9]propose a technique to augment the analysis of Larsen and Harrold [10]to more fully represent features of object-oriented programs.This technique is able to distinguish between data members for different objects,and address polymorphism.Regression testing is a major component in the maintenance phase where a software system may be corrected, adapted to new environment,or enhanced to improve its performance.When a program is modified,it is necessary to validate modified parts of the program as well as to ensure that other parts of the program affected by changes work correctly.The challenge is in identifying the parts of the program affected by the changes in an efficientmanner.Although the exact identification of the components affected by the changes is in general undecidable, one can design techniques that provide safe approximations.There are two important problems in data-flow regression testing:1.Identifying those existing tests that must be rerun since they may exhibit different behavior in the changedprogram,and2.Identifying those def-use associations in the program that must be re-tested to satisfy some coverage criteria.We focus on the second problem and implement a slicing based technique which identifies the subset of a program affected by a change.Incremental regression testing attempts to exploit this information in two ways First if a new component is tested by an existing test case then the costly construction of a new test case can be avoided. Second if it may be asserted that for a subset of tests,the modified program will produce the same output as the original program then the potentially costly execution of the modified program on this subset can be avoided. This occurs for example if no changed program components are executed by a test.Incremental regression testing has the following steps.1.Identify a set of affected program components of the modified program.2.Identify a subset of T the original test set that tests the affected components3.Identify untested components of the modified program that must be covered by new tests.4.Create new tests for the uncovered components5.Run the modified program on the union of the tests produced in Steps(2)and(4)We concentrate on thefirst problem in this work.2Background on Slicing2.1Intra-procedural slicing using the Program Dependence GraphThe concept of slicing was introduced by Weiser[5]who described it in terms of dataflow equations.Ottenstein [6]introduced the Program Dependence Graph and slicing was redefined as a graph reachability problem over the PDG.In a PDG,each node represents a statement or predicate expression.Edges represents data or control dependencies.A node is said to be control dependent on a predicate if the execution of the node is dependent on the value of the predicate.Control dependencies between statements can be computed using the dominance frontier information[17]Node y is said to be data dependent on node x,if x defines a variable and y uses that variable.Data dependencies(in absence of aliasing)can be calculated using standard reaching definition analysis[1].Aliasing is discussed in a separate section.2.2Handling Arbitrary controlflowIn presence of unstructured controlflow statements like goto,return,break,continue the conventional slicing algorithms produce incorrect results.Modification to the slicing algorithm to handle these statements correctly is discussed in[11],[13]and[14]2.3Interprocedural slicing using System Dependence graphHorwitz[7]extended the PDG to the interprocedural case terming the graph a System Dependence Draph.Slicing can be no longer be defined as simple graph reachability problem because procedure calls and returns should be matched.To overcome this problem,they introduced the concept of summary edges.Summary edges describe the cummulative effect of the entire procedure.This approach is a variation of the functional approach given by Sharir and Pnueli[16].An efficient method to compute the summary edges is given in[15]A system-dependence graph(SDG)is a collection of program-dependence graphs(PDG)one for each procedure. Figure1shows an example SDG.Figure1:An Example of a system Dependence GraphEach PDG contains an entry node that represents entry to the procedure.To model procedure calls parameter passing,an SDG introduces additional nodes and edges.Accesses to global variables are modeled via additional parameters of the procedure.They assume parameters are passed by value-result.They introduce additional nodes in the interprocedural case.1.Call-site nodes represent the call sites.2.Actual-in and actual-out nodes represent the input and output parameters at the call sites.They are controldependent on the call-site node.3.Formal-in and formal-out nodes represent the input and output parameters at the called procedure.Theyare control dependent on the procedure’s entry node.They also introduce additional edges to link the program dependence graphs together:1.Call edges link the call-site nodes with the procedure entry nodes.2.Parameter-in edges link the actual-in nodes with the formal-in nodes.3.Parameter-out edges link the formal-out nodes with the actual-out nodesTo create these additional nodes and edges,we need information about the variables that are accessed or modified by a function.We use GMOD and GREF information to compute this information[20].The interprocedural backward slicing algorithm consists of two phases.Thefirst phase traverses back-wards from the node in the SDG that represents the slicing criterion along all edges except parameter-out edges,and marks those nodes that are reached.The second phase traverses backwards from all nodes marked during the first phase along all edges except call and parameter-in edges,and marks reached nodes.The slice is the union of the marked nodes.We implemented a variation of the two phase slicing algorithm and summary computation algorithm as discussed in[3]2.4Call Graph ConstructionThis subsection describes call graph construction for Java programs.The call graph construction algorithm proceeds as follows.Start with initial set(S)of reachable methods.Trace through these methods and look for call statements.If a static call statement is found,then there is only one target we add that to set S.If a virtual call statement is found,then we need to estimate the possible types of the receiver(using an algorithm like Class Hierarchy Analysis(CHA)or Rapid Type analysis(RTA))and add each potential target method to the set S.An call edge exists from the current call statement to eachpotential target method.2.5Class Hierarchy AnalysisClass Hierarchy Analysis is a method to conservatively estimate the types of receiver.Given a receiver o of a declared type d,hierarchy-types(o,d)for Java is defined as follows:1.If d is a class type C,hierarchy-types(o,d)includes C plus all subclasses of C.2.If d is a interface type I,hierarchy-types(o,d)includes:1)the set of all classes that implement I or implementa sub-interface of I,which we call implements(I),plus2)all subclasses of implements(I).2.6Rapid Type AnalysisThe basic idea in rapid type analysis is that some classes are never instantiated in reachable methods,and we can prune away some call edges that are computed using class hierarchy analysis3Alias Analysis3.1Problem in presence of aliasingComputation of data dependence is complicated by the presence of aliasing.The problem is illustrated by an example.In the example(Table1),the object O1could be accessed both by reference variables x and y.x.a and y.a refer to the same object.The fact that there is a dependency between line4and line5could not be inferred from the def boxes and use boxes calculated by the framework Soot[28].Table1:Def Use computation with aliasingLine Def1y2x3y4x.a5yEdges in OFG represent constraints.Denote the set of objects pointed by x as O x and the set of objects pointed by y as O y.Each statement induces some set constraints.An assignment statement such as x=y says that the sets of objects pointed by x is a superset of the set of objects pointed by y.i.e O x⊇O y.Anderson’s algorithm [18]is one method to solve a set constraint problem.Aiken[19]discusses various set constraint problems and their application to program analysis.Statements that influence the points-to information of a reference variable are as follows.1.Allocation statement(x=new Object();)The heap object allocated at this statement is abstracted by the object node O i and an edge is drawn from x to O i.2.Assignment statement(x=y)An inclusion edge is drawn from x to y.3.Load statement(x=y.f)for every inclusion edge from the named”x”to some O i,we add a new inclusion edge from the named y to O i.f4.Store statement(x.f=y)for every inclusion edge from the given x to some O i we add a new inclusion edge from O i.f to the given y.Solving the constraints using Anderson’s algorithm involves computing the transitive closure of the OFG.Tran-sitive closure gives information about reachability of one node from another and thus we can ascertain which object nodes are accessible from any reference variable nodes.The analysis does not consider the order in which the statements are executed and is therefore termedflow insensitive.We now propose a technique forflow sensitive analysis which we implement in our slicing algorithm.3.5Flow Sensitive Alias Analysis using Path Expressions3.5.1Problem withflow insensitive alias analysisConsider the program in table2.If we applyflow insensitive alias analysis,then the analysis will conclude that x and y can be aliased and thus there is a dependency between line4and5.But this dependency is spurious,since that alias relation holds only after the assignment at line6.Theflow insensitive algorithm gives rise to spurious alias relations.This is because at a particular point in the program,only a subgraph of the Object Flow Graph is valid,whereas theflow-insensitive objectflow analysis assumed that the entire graph is valid at every point. Maintaining subgraphs of the OFG at every program point is expensive in space though it would give us aflow sensitive algorithm.We propose an intermediate solution here.Table2:Problem withflow insensitive alias analysis1234563.5.2Incorporating Flow SensitivityFlow sensitive analysis also has to take the program point into account.Aflow sensitive analysis must be able to answer queries like’what objects could be accessed by a particular reference variable at a particular program point’.Aflow insensitive OFG maps Reference variable→Set of objects,whereas we need the mapping (Reference variable,Program Point)→Set of objects forflow sensitive analysis.The basic idea is to associate with every program point,the set of edges of the OFG that are valid at that point.We need to construct the mapping Program point→Valid Edges which associates each program point with the set of edges that are valid at that point.We need another mapping that gives the set of objects that are accessed by a reference variable under the condition that only some of the edges are valid.(Reference Variable,Valid Edges)→Set of objects This is more precise than theflow insensitive analysis since we query only the valid subgraph at that point.3.5.3Algorithm forflow sensitive Objectflow analysisWe have seen that there are four statements that contribute to OFG(the allocation statement,assignment statement,load statement and store statement).In this section,we develop aflow sensitive alias analysis algorithm (without considering load and store statements).The next section extends them to load and store statements. Step-1:Create the Objectflow graph(OFG)Figure2:OFGEach edge has label E i that was created due to statement S i.Set GEN set of statement S i is set as E i.Figure 1shows the OFG created for the program in table-3Step-2:Associate with each point,the set of valid edges of the OFG.The valid edges form a subgraph of the OFG.We already have the GEN set computed on CFG in step1.OUT is defined as union over all predecessors.Do aflow analysis tillfixed point is reached.This associates with each program point the set of edges of the OFG (i.e the OFG subgraph)that are valid at that point.This step does the mapping Program point→Valid Edges Table-4computes this information.An example to show that advantage of aflow sensitive OFG over an insensitive one is illustrated by considering ”d.f”at line6.It is obvious from the program that d cannot access O1.This fact is captured by the OFG Subgraph (comprising of e0,e4,e5,e6).The dotted lines show the edges that are invalid at that program rmation couldflow only thro e0,e4,e5,e6.This shows that d could not access O1.Table3:GENa=new Objectif(P){b=a;c=b;d=c;}else{d=new Foo();c=a;b=c;}OUTa=new Object e0b=a;e0,e12e2d=c;e0,e1,e2,e3d=new Foo();e0,e45e5b=c;e0,e4,e5,e6}Step-3:Computing the path expressionFigure-3gives an example of associating each reference variable with a set of subgraphs.We will see how to compute this information shortly.The information1+5.6present on’b’says that O1willflow to b if either edge 1is present or edges5and6are presentThe algorithm associates with every variable a path expression.The path expression consists of a set of terms. Each term has an associated object and it consists of a set of edges.If all the edges are present,it means that the associated objectflows to the reference variable.The computation of a path expression for each variable can be considered as a dataflow problem.Initially each variable in the OFG is given empty expression.At every iteration,the path expression of a node N having predecessors P1,P2...is defined to be P1.e1+P2.e2+....where e1,e2..are edge labels present on P1→N,P2→N etc.Step-4:Finding the set of objects accessible by a reference variableTofind what objectsflow to a particular reference variable at a program point,wefirstfind the set of validFigure3:OFG(valid subgraph)Figure4:OFG(path expression)edges(step2).We substitute the set of valid edges in the path expression to compute the set of objects thatflow into the reference variable.4Work CompletedWe have implemented the data dependence subgraph without aliasing and used the control dependence graph implementation of TRDDC.Construction of the system dependence graph for interprocedural slicing has also been implemented along with summary computation.The slicing algorithm at present uses a conservative callgraph.Though rapid type analysis has been implemented as a separate module it has not yet been integrated into the slicer.We have also implemented an intraprocedural version of the new path expression based alias analyser.References[1]A.V.Aho,R.Sethi and J.D.Ullman,Compilers:Principles,Techniques and Tools,Addison Wesley,1986.[2]Frank Tip.A survey of program slicing techniques.Journal of programming languages,3(3),September1995.[3]Jens Krinke.Advanced Slicing of Sequential and Concurrent Programs Ph.D Thesis.Universitt Passau April2003[4]J.Ferrante,K.J.Ottenstein and J.D.Warren.The program dependence graph and its use in optimization,ACM TOPLAS,9(3):319-349,July1987.[5]Mark Weiser.Program slicing.IEEE Transactions on Software Engineering,10(4):352-357,July1984.[6]Karl J.Ottenstein and Linda M.Ottenstein.The program dependence graph in a software development envi-ronment.In Proceedings of the ACM SIGSOFT/SIGPLAN Software Engineering Symposium on Practical Software Development Environments,volume19(5)of ACM SIGPLAN Notices,pages177-184,1984.[7]Susan B.Horwitz,Thomas W.Reps,and David Binkley.Interprocedural slicing using dependence graphs.ACM Transactions on Programming Languages and Systems,12(1):26-60,January1990.[8]R.Gupta,M.J.Harrold and M.L.Soffa.An Approach to Regression Testing using Slicing.Proceedings ofthe Conference on Software Maintenance(CSM’92),pages299–302,November1992.[9]D.Liang and M.J.Harrold,Slicing Objects Using System Dependence Graph,in Proceedings of the Interna-tional Conference on software Maintenance,ICSM98,November1998.[10]Lors Larsen and M.J.Harrold,Slicing object Oriented Software,in Proceedings of the International Confer-ence on software Engineering,ICSE1996,1996.[11]T.Ball and S.Horwitz.Slicing programs with arbitrary controlflow.In Lecture Notes in Computer Science,volume749,New York,NY,November1993.Springer-Verlag.[12]Raja Vallee-Rai et al,Soot-A Java Optimization Framework IBM Center for Advanced Studies Confer-ence(CASCON),1999.[13]J.Choi and J.Ferrante.Static slicing in the presence of goto statements.ACM Trans.on ProgrammingLanguages and Systems,16(4):10971113,July1994.[14]Sumit Kumar and Susan Horwitz.Better slicing of programs with jumps and switches.In Proceedings ofFASE2002:Fundamental Approaches to Software Engineering,volume2306of Lecture Notes in Computer Science,pages96-112.Springer,2002.[15]Thomas Reps,Susan Horwitz,Mooly Sagiv,and Genevieve Rosay.Speeding up slicing.In Proceedings ofthe ACM SIGSOFT’94Symposium on the Foundations of Software Engineering,pages11-20,1994.[16]M.Sharir and A.Pnueli.Two approaches to interprocedural dataflow analysis.In S.S.Muchnick and N.D.Jones,editors,Program Flow Analysis:Theory and Applications,chapter7,pages189234.Prentice-Hall, Englewood Cliffs,NJ,1981.Cytron,[17]Ferrante,Rosen,Wegman,Zadeck Efficiently Computing Static Single Assignment Form and the ControlDependence Graph TOPLAS13:4,p.451,October91[18]L.O.Andersen.Program Analysis and Specialization for the C Programming Language.PhD thesis,Univer-sity of Copenhagen,DIKU,1994.[19]Alexander Aiken.Introduction to set constraint-based program analysis.Science of Computer Programming,35(23):79111,1999.[20]Banning,J.P.An efficient way tofind the side effects of procedure calls and the aliases of variables.InProceedings of the6th Annual ACM Symposium on Principles of Programming Languages,ACM,New York,29-41.(Jan.1979)[21]Cooper,K.D.,and Kennedy,K.Efficient computation offlow-insensitive interprocedural summary infor-mation.In Proceedings of the SIGPLAN84Symposium on Compiler Construction;SIGPLAN Not.19,6, 247-258.(June1984)[22]Randy Allen and Ken Kennedy Optimizing Compilers for Modern Architectures Elsevier Publications[23]Mark Harman and Sebastian Danicic Using Program Slicing to Simplify Testing Journal of Software Testing,Verification and Reliability,vol5,no.3,1995,pp.143-162.[24]D.Binkley,The application of program slicing to regression testing Information and Software Technology,vol.40,no.11/12,1998,pp.583-594.[25]R Gupta,M.J.Harrold and M.L.Soffa,An approach to regression testing using slicing In Proc.Conferenceon Software Maintenance,1992,pp.299-308.[26]B.Steensgaard,Points-to Analysis in Almost Linear Time,in Proceedings of23rd ACM SIGACT-SIGPLANInternational Conference on Principles of Programming Languages,POPL96,1996.[27]P.Tonella G.antoniol,R.Fiutem,E.Merlo,Flow Insensitive C++Pointers and Polymorphism Analysisand its Application to Slicing,in Proceedings of the International Conference on software Engineering,1997.[28]Raja Vallee-Rai et al,Soot-A Java Optimization Framework IBM Center for Advanced Studies Confer-ence(CASCON),1999.[29]Mark Harman and Sebastian Danicic Using Program Slicing to Simplify Testing Journal of Software Testing,Verification and Reliability,vol5,no.3,1995,pp.143-162.[30]D.Binkley,The application of program slicing to regression testing Information and Software Technology,vol.40,no.11/12,1998,pp.583-594.[31]R Gupta,M.J.Harrold and M.L.Soffa,An approach to regression testing using slicing In Proc.Conferenceon Software Maintenance,1992,pp.299-308.[32]B.Steensgaard,Points-to Analysis in Almost Linear Time,in Proceedings of23rd ACM SIGACT-SIGPLANInternational Conference on Principles of Programming Languages,POPL96,1996.[33]P.Tonella G.Antoniol,R.Fiutem,E.Merlo,Flow Insensitive C++Pointers and Polymorphism Analysisand its Application to Slicing,in Proceedings of the International Conference in Software Engineering1997.。

相关文档
最新文档