Java Program Analysis Projects in Osaka University Aspect-Based Slicing System ADAS and Ran
- 格式:pdf
- 大小:64.10 KB
- 文档页数:2
第Ⅰ部分:实验指导实验1:Java开发环境J2SE一、实验目的(1)学习从网络上下载并安装J2SE开发工具。
(2)学习编写简单的Java Application程序.(3)了解Java源代码、字节码文件,掌握Java程序的编辑、编译和运行过程。
二、实验任务从网络上下载或从CD-ROM直接安装J2SE开发工具,编写简单的Java Application程序,编译并运行这个程序。
三、实验内容1.安装J2SE开发工具Sun公司为所有的java程序员提供了一套免费的java开发和运行环境,取名为Java 2 SDK,可以从上进行下载。
安装的时候可以选择安装到任意的硬盘驱动器上,例如安装到C:\j2sdk1.4.1_03目录下。
教师通过大屏幕演示J2SE的安装过程,以及在Windows98/2000/2003下环境变量的设置方法。
2.安装J2SE源代码编辑工具Edit Plus教师通过大屏幕演示Edit Plus的安装过程,以及在Windows98/2000/2003操作系统环境下编辑Java 原程序的常用命令的用法。
3.编写并编译、运行一个Java Application程序。
创建一个名为HelloWorldApp的java Application程序,在屏幕上简单的显示一句话"老师,你好!"。
public class HelloWorldApp{public static void main(String[] args){System.out.println("老师,你好!");}}4.编译并运行下面的Java Application程序,写出运行结果。
1:public class MyClass {2:private int day;3:private int month;4:private int year;5:public MyClass() {6:day = 1;7:month = 1;8:year = 1900;9:}10:public MyClass(int d,int m,int y) {11:day = d;12:month = m;13:year = y;14:}15:public void display(){16:System.out.println(day + "-" + month + "-" + year);17:}18:public static void main(String args[ ]) {19:MyClass m1 = new MyClass();20:MyClass m2 = new MyClass(25,12,2001);21:m1.display();22:m2.display();23:}24:}运行结果:1-1-190025-12-2001实验2:Java基本数据类型一、实验目的(1)掌握javadoc文档化工具的使用方法。
解决Jenkins集成SonarQube遇到的报错问题Jenkins集成Sonar过程中遇到的报错1、jenkins中⽆法添加sonarqube的token凭证因为添加的凭证类型错误,所以⽆法添加token,类型应该选择“Secret text”,⽽不是“username with password”。
2、启动sonarqube报错#完整报错:ERROR: [1] bootstrap checks failed. You must address the points described in the following [1] lines before starting Elasticsearch.bootstrap check failure [1] of [1]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]ERROR: Elasticsearch did not exit normally - check the logs at /opt/sonarqube/logs/sonarqube.log原因:由于 SonarQube 使⽤嵌⼊式 Elasticsearch,请确保您的 Docker 主机配置符合Elasticsearch ⽣产模式要求和⽂件描述符配置。
解决:在 Linux 上,您可以通过在主机上以 root ⾝份运⾏以下命令来设置当前会话的推荐值:(调整系统参数) sysctl -w vm.max_map_count=262144 sysctl -w fs.file-max=65536 ulimit -n 65536 ulimit -u 40963、es程序在sonarqube⽬录下找不到java(或者没有定义java环境变量)#完整报错:2021.07.12 05:59:54 INFO app[][o.s.a.ProcessLauncherImpl] Launch process[[key='es', ipcIndex=1, logFilenamePrefix=es]] from [/opt/sonarqube/elasticsearch]: /opt/sonarqube/elasticsearch/bin/elasticsearchcould not find java in ES_JAVA_HOME at /opt/java/openjdk/bin/java2021.07.12 05:59:54 WARN app[][o.s.a.p.AbstractManagedProcess] Process exited with exit value [es]: 12021.07.12 05:59:54 INFO app[][o.s.a.SchedulerImpl] Waiting for Elasticsearch to be up and running原因:因为⽤的是sonarqube:9.0.0-community最新版,可能是sonar版本问题(没弄明⽩)解决:换个低版本就不会有这个问题了,⽐如sonarqube:8.9.1-conmunity版本4、sonarqube⾼版本不⽀持mysql数据库#完整报错:Exception in thread "main" org.sonar.process.MessageException: Unsupported JDBC driver provider: mysql原因:sonarqube7.9以上已不再⽀持mysql数据库解决:换成postgresql、oracle、sqlserver数据库5、jenkins项⽬中配置sonarqube Scanner 报错#完整报错:ERROR: Tasks support was removed in SonarQube 7.6.ERROR:ERROR: Re-run SonarScanner using the -X switch to enable full debug logging.WARN: Unable to locate 'report-task.txt' in the workspace. Did the SonarScanner succeed?ERROR: SonarQube scanner exited with non-zero code: 2解决:删除Execute SonarQube Scanner中Task to run这⼀栏,什么东西都不要填#完整报错org.sonar.java.AnalysisException: Your project contains .java files, please provide compiled classes with sonar.java.binaries property,or exclude them from the analysis with sonar.exclusions property.原因:sonarqube的sonar-java插件从4.1.2开始,强制要求sonar.java.binaries参数解决:在Analysis properties配置中添加 ”sonar.java.binaries“ 参数到此这篇关于Jenkins集成SonarQube遇到的报错的⽂章就介绍到这了,更多相关Jenkins集成SonarQube报错内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。
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.。
Eclipse导⼊⼯程提⽰“Noprojectsarefoundtoimport”如果发现导⼊⼯程的时候,出现"No projects are found to import" 的提⽰,⾸先查看项⽬⽬录中是否有隐藏⽂件.project,还有⽬录结构也还要有⼀个隐藏⽂件.classpath, 如果没有的解决办法。
⽅法1:最直接的操作,可以把其它项⽬的.project, .classpath⽂件拷贝过来,修改相应的地⽅则可。
1).project⽂件只需要修改<name>AboxTVExchange</name>这个项⽬名称则可2) .classpath⽂件通常不⽤改,内容如下:<?xml version="1.0" encoding="UTF-8"?><classpath><classpathentry kind="src" path="src"/><classpathentry kind="src" path="gen"/><classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/><classpathentry kind="output" path="bin"/></classpath>kind= "... "是指这个⽬录在project中的类型。
kind= "src "为源⽂件⽬录,这个⽬录下的⽂件会被编译器编译. kind= "output "是java⽂件编译输出⽬录,src⽬录下的⽂件会编译到这个⽬录下。
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.。
1. The name of a Java source file (d)(d) must be the same as the class it defines, respecting case2. Which method must exist in every Java application? (a)(a) main1. Given the following code, how many tokens will be output? (b)StringTokenizer st = new StringTokenizer("this is a test");while (st.hasMoreTokens()) {stdOut.println(st.nextToken() );}(b) 42. Classes from which of the following packages are implicitly imported into every Java program? 答案:(d)(d) ng3. What is the name of the wrapper class for the type int? (d)(d) Integer4. Classes from which of the following packages are implicitly imported into every Java program?(c)(c) ng5. The term wrapper classes refers to (a)(a) a collection of Java classes that "wrap" Java primitive types6. What will be output caused by the execution of the following Java program segment? (c) String name = "Elvis";System.out.print(name + "was here");(c) Elviswas here1. What will be output when the following Java program segment is executed? (c)int x = 5;int y = 2;System.out.println(x + y);(c) 72. A difference between the methods print and println of the class java.io.PrintWriter is that (a)(a) println appends a new line to the end of its output, but print does not3. Consider the following Java program segment. (c)int x = 5;int y = 2;System.out.println(x + "1" + y);Which of the following statements is true about the program segment?(c) The output caused by the code will be 512.1. All Java exception classes are derived from the class (a)(a) ng.Throwable2. In Java, exceptions that are not handled are passed up the (b)(b) call stack3. What is the right way to handle abnormalities in input on Java? (d)(d) By handling these problems by providing exception handlers4. 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)(a) x has a legal definition, but y has an illegal definition.1. 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? (d)They define a standard interface definition language that must be used for all Java classes.They provide recommendations intended to make source code easier to read and understand. They describe one mechanism for network communication between Java and C++ programs. (d) II onlyFeedback: See section 1.1.6, subsection "CodeConvTOC" and section 1.1, subsection "Why Have Code Conventions," in the course notes.2. According to the Java code conventions, files that contain Java source code have the suffix _____, and compiled bytecode files have the suffix _____. (d)(d) .java, .classFeedback: See section 1.1.6, subsection "CodeConvTOC" and section 2.1, subsection "File Suffixes," in the course notes.3. According to the document entitled Code Conventions for the Java Programming Language, file suffixes used by Java software include which of the following? (b).obj.class.h(b) II only1. Which of the following patterns of characters opens a Javadoc comment block? (b)(b) /**1. After a typical debugger encounters a breakpoint, the programmer using the debugger may perform which of the following actions? (a)Examine the values of variables in the halted programExecute the current lineResume execution of the halted program(a) I, II, and III2. In a typical source-code debugger, a programmer can set a _____ to cause a program to stop executing at a particular line of code. (c)(c) breakpoint3. A stack trace is (b)(b) a sequence of method calls4. 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) (b)(b) debugger1.According to Javadoc convention, the first sentence of each Javadoc comment should be (c) (c) a summary sentence of the declared entryFeedback: See /j2se/javadoc/writingdoccomments/index.html#format for more information.1. In a UML class diagram's representation of a class, the top, middle, and lower rectangular compartments respectively describe the _____ of the class. (c)(c) name, attributes, and methods2. UML class diagrams can describe which of the following? (b)The internal structure of classesRelationships between classes(b) I and II1. Consider the following UML class diagram.According to the diagram, instances of the class named _____ have references to instances of the class named _____. (a)(a) A, B2. Consider the following UML class diagram.According to the diagram, which of the following statements is true? (a)(a) ClassA is composed of one instance of ClassB and one or more instances of ClassC.3. A binary association is said to exist between two classes when (a)(a) an object of one class requires an object of the other class4. The multiplicity of an association between two classes indicates the number of (a)(a) instances of one class that can be associated with an instance of the other class5. Which of the following is true about association and aggregation in UML class diagrams? (c)(c) Aggregation is a special form of association.1. A collection typically models a _____ relationship. (b)(b) one-to-many2. Consider the following UML class diagram. (c)The diagram describes a(c) self-containing class3. Consider the class described by the following diagram:If the class represents an employee and the boss attribute refers to the employee's boss, which of the following statements is (are) true? (c)Many employees can have the same boss.One employee can have many bosses.(c) I only4. Consider the following UML class diagram.Which of the following is (are) true about the system described by the diagram? (d)An instance of Picture can contain a collection of instances of the class Shape.An instance of Shape can contain a collection of instances of the class Picture.(d) I only5. If a class has an association with itself, then the class contains (b)(b) an attribute that references an object of the same class1. An object model describes which of the following? (c)Attributes of classesMethods of classesRelationships between classes(c) I, II, and III2. In an object model, the data that an object is responsible for maintaining are represented by (b)(b) attributes1. A relationship that exists between two specific instances of an object is known as a(n) (b)(b) linkFeedback: See Chapter 5, page 114, in the course textbook.2. The static model of a software system typically includes which of the following? (b) Attributes of classesActions that occur between classesStructural relationships between classes(b) I and III onlyFeedback: See Chapter 10, page 213, in the course textbook.3. Consider the following UML class diagram.According to the diagram, which of the following statements is (are) true? (c)ClassB is a specialization of ClassA.ClassA is a generalization of ClassC.ClassC is involved in a self-containment loop.(c) I, II, and III4. When using noun-phrase analysis to model a software system, which of the following should typically be eliminated from the list of potential classes? (a)References to the software system itselfNouns that imply roles between objectsSynonyms to other nouns in the list(a) I, II, and IIIFeedback: See Chapter 10, page 216-219, in the course textbook.1. The term class variable is a synonym for (c)(c) a static data field1. Which is the Java keyword used to denote a class method? (c)(c) static2. Which of the following statements about class variables in Java is not true? (c)(c) All objects have their own copy of the class variable defined in the instantiated class.3. Which of the following categorizations can be applied to both the data fields and the methods ina Java class? (a)(a) static and non-static1. What is used to indicate that a method does not return a value? (c)(c) the keyword voidFeedback: See chapter 4 of the text.2. The return type for a method that returns nothing to its caller is (c)(c) voidFeedback: See chapter 4 of the text.3. If a class contains a constructor, that constructor will be invoked (c)(c) each time an object of that class is instantiatedFeedback: See chapter 4 of the text.4. If the method int sum(int a, int b) is defined in a Java class C, which of the following methods cannot coexist as a different method in class C? (b)(b) int sum(int x, int y)Feedback: See chapter 5 of the text.5. From within a child class, its parent class is referred to via the keyword (d)(d) superFeedback: See chapter 5 of the text.6. When a subclass defines an instance method with the same return type and signature as a method in its parent, the parent's method is said to be (a)(a) overriddenFeedback: See chapter 5 of the text.7. Consider the following Java class definitions.public class Object1 {protected String d(){return "Hi";}}public class Object2 extends Object1 {protected String d(){return super.d();}}Which of the following statements is (are) true regarding the definitions? (d)Class Object2 inherits from class Object1.Class Object2 overrides method d.Method d returns equivalent results when executed from either class.(d) I, II, and IIIFeedback: See chapters 5 and 13 of the text.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)(a) The line of text "non-default"Feedback: See chapter 13 of the text.9. Which of the following statements about constructors in Java is true? (b)(b) A class can define more than one constructor.Feedback: See chapter 13 of the text.10. Which is a Java access modifier used to designate that a particular data field will not be inherited by a subclass? (c)(c) privateFeedback: See chapter 13 of the text.1. Consider the following Java program segment.int[] arr;arr = new int[3];arr[2]=19;arr[1]=17;arr[0]=15;Which of the following Java statements is syntactically correct and semantically identical to the program segment? (b)(b) int[] arr= {15, 17, 19};2. Consider the Java program below.public class Arr{public static void main(String[] args) {int[] a = {1, 2, 3};System.out.println(a[1]);System.out.println(a[3]);}}Which of the following is true about the result of executing the program? (c)(c) The number 2 is printed and a run-time exception terminates execution.3. If the length of a particular array is the value of LIMIT, what is the index of the last item in that array? (d)(d) LIMIT - 14. Legal Java statements to initialize an array reference include which of the following? (b)int[] aobj = {0, 1, 2};int[4] aobj = {0, 1, 2};int[] aobj = new int[3];(b) I and III only5. A Java array that contains n components will be indexed from _____ through _____. (b)(b) 0, n-16. Consider the following Java program segment.String[] str = {"Three","Two","One"};for (int i = 0; i < str.length; ++i) {System.out.println(str[i]+"/");}What will be output upon execution of the program segment? (d)(d) Three/Two/One/7. Regarding the following declaration, what is the index of the element containing 45? (d)int[] numbers = {-1, 45, 6, 132};(d) 11. Consider the following method call, where c is an instance of the class java.util.ArrayList.c.size();This method call returns the number of (c)(c) elements in the ArrayList represented by c2. An object that contains methods that traverse a collection linearly from start to finish is known as a(n) (a)(a) iterator3. Which of the following statements is not true of the class java.util.ArrayList? (b)(b) Once an object is inserted into an instance of ArrayList, it can never be removed.4. In which of the following ways can items be added to a collection implemented by java.util.ArrayList? (b)Items can be inserted at the beginning of the collection.Items can be inserted between two existing items in the collection.Items can be appended to the end of the collection.(b) I, II, and III5. Which of the following methods is (are) provided by java.util.Iterator? (d)next, which causes an iterator to return the next item in its iterationremove, which can remove an item from a collection associated with an iterator(d) I and II6. The class java.util.ArrayList implements a collection that (c)(c) can grow to accommodate new items1. Which of the following statements is (are) true about any abstract method in Java? (b)It contains no definition.It cannot be declared public.(b) I only2. Which of the following statements is (are) true in Java? (b)Classes that contain abstract methods must be declared abstract.Classes that contain protected methods must be declared abstract.(b) I only3. The subclass of an abstract class must (c)(c) be abstract or implement all of the parent's abstract methods1. Which of the following statements about Java classes is (are) accurate? (c)A class may have only one parent.Two or more classes may share a parent.(c) I and II2. Consider the following Java program fragment.public void drive(Vehicle v) {...}...drive(obj);The method call drive(obj) is valid if obj is which of the following? (a)A descendent of class VehicleAn ancestor of class VehicleAn object of class Vehicle(a) I and III only1. Which of the following statements is (are) true about interfaces in Java? (d)Interfaces can extend other interfaces.Interfaces can contain data fields.(d) I and II2. Which of the following statements is (are) true in Java? (d)An abstract class may contain data fields.Interfaces may contain data fields.(d) I and II3. Which of the following statements is (are) true about inheritance in Java? (c)A class can extend more than one abstract class.A class can implement more than one interface.(c) II only4. Which of the following statements is (are) true about all data fields in an interface in Java? (c) They are implicitly public.They are implicitly final.They are implicitly static.(c) I, II, and III5. Which is the Java keyword that denotes the use of an interface? (d)(d) implements6. Which of the following statements is (are) true in Java? (b)All of the methods in an abstract class must be abstract.All of the methods in an interface must be abstract.(b) II only7. In Java, all methods in an interface must be _____ and _____. (b)(b) public, abstract8. Data fields in an interface implicitly have _____ access in Java. (a)(a) public1. A design pattern is typically used to (c)(c) describe a practical solution to a common design problem1. Consider the following definition of a Java class.public class C {private static C instance = null;private C() {}public static C getInstance() {if (instance == null) {instance = new C();}return C;}}This class is an example of the design pattern (d)(d) Singleton2. The constructor of a class that adheres to the Singleton design pattern must have _____ visibility. (a)(a) private1. In which of the following design patterns is a family of algorithms encapsulated into individual but interchangeable classes? (a)(a) Strategy2. The Strategy design pattern is likely to be useful when implementing which of the following?(a) An application that offers several alternate sorting algorithmsA simple class to store the address of an organization of which only one instance can be instantiated(a) I only1. Consider the following Java program segment. (a)PrintWriter fileOut = new PrintWriter(new FileWriter("output.txt"));If the file output.txt already exists, which of the following events will occur when the program segment is executed?(a) The existing contents of output.txt will be erased.2. If a file opened for reading does not exist, which of the following events will occur in Java? (a)(a) A FileNotFoundException will be raised.1. (1)The model part of the Model-View-Controller (MVC) paradigm embodies the (a)(a) abstract domain knowledge of an application(2)The view part of the Model-View-Controller (MVC) paradigm is the (b)(b) way in which the abstract domain knowledge of an application is presented to the userFeedback: See Chapter 16, page 474, in the course textbook.2. Which of the following is true regarding the controller part in the Model-View-Controller (MVC) paradigm? (a)(a) The controller is the automatic mechanism by which the user interface is displayed and by which events are communicated between the model and the view.Feedback: See Chapter 16, page 475, in the course textbook.3. In Java, the default layout manager for a JPanel component is (c)(c) FlowLayoutFeedback: See Chapter 16, page 494, in the course textbook.4. What is the number of regions into which the BorderLayout in Java subdivides a container? (a)(a) 5Feedback: See Chapter 16, page 494, in the course textbook.5. Which of the following is (are) true regarding event handling in Java? (a)When a GUI component is created, the component automatically has the ability to generate events during user interaction.Each Listener object must be registered with the specific component object or objects for which the Listener object is to respond.(a) I and IIFeedback: See Chapter 16, page 523, in the course textbook.6. Which of the following is a Java event that is generated when a JButton component is pressed? 答案:(b)(b) ActionEventFeedback: See Chapter 16, page 525, in the course textbook.7. The ListSelectionEvent class and ListSelectionListener interface are available in the _____ package of Java. (b)(b) javax.swing.eventFeedback: See Chapter 16, page 525, in the course textbook.8. Which of the following is a Java event that is generated when the close button on a JFrame component is pressed? (b)(b) WindowEventFeedback: See Chapter 16, page 534, in the course textbook.9. In Java, what is the signature of the method in the WindowListener interface where code is to be added to end a program when the close button is pressed? (d)(d) void windowClosing (WindowEvent we)Feedback: See Chapter 16, page 537, in the course textbook.10. What is the signature of the method specified in the Java ListSelectionListener interface? (b)(b) void valueChanged (ListSelectionEvent lse)Feedback: See Chapter 16, page 540, in the course textbook.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);正确答案: C. 3The name of a Java source file正确答案: A. must be the same as the class it defines, respecting caseWhich 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.正确答案: B. 1 and 3 onlyConsider 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.What is the right way to handle abnormalities in input on Java?正确答案: C. By handling these problems by providing exception handlersThe term wrapper classes refers to正确答案: A. a collection of Java classes that "wrap" Java primitive typesFrom within a child class, its parent class is referred to via the keyword正确答案: C. superWhat is used to indicate that a method does not return a value?正确答案: B. the keyword voidWhich of the following statements about constructors in Java is true?正确答案: D. A class can define more than one constructor.When a subclass defines an instance method with the same return type and signature as a method in its parent, the parent's method is said to be正确答案: A. overriddenIf a class contains a constructor, that constructor will be invoked正确答案: B. each time an object of that class is instantiatedWhich is a Java access modifier used to designate that a particular data field will not be inherited by a subclass?正确答案: C. privateConsider the following Java class definitions.public class Object1 {protected String d(){return "Hi";}}public class Object2 extends Object1{protected String d(){return super.d();}}Which of the following statements is (are) true regarding the definitions?Class Object2 inherits from class Object1.Class Object2 overrides method d.Method d returns equivalent results when executed from either class.正确答案: C. I, II, and IIIWhen a subclass defines an instance method with the same return type and signature as a method in its parent, the parent's method is said to be正确答案: A. overriddenIf the method int sum(int a, int b) is defined in a Java class C, which of the following methods cannot coexist as a different method in class C?正确答案: C. int sum(int x, int y)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?正确答案: C. The line of text "non-default"Consider the Java program below.public class Arr{public static void main(String[] args){int[] a = {1, 2, 3};System.out.println(a[1]);System.out.println(a[3]);}}Which of the following is true about the result of executing the program?正确答案: C. The number 2 is printed and a run-time exception terminates execution.Which of the following methods is (are) provided by java.util.Iterator?next, which causes an iterator to return the next item in its iterationremove, which can remove an item from a collection associated with an iterator正确答案: C. I and IIWhich of the following statements is not true of the class java.util.ArrayList?正确答案:C. Once an object is inserted into an instance of ArrayList, it can never be removed.Regarding the following declaration, what is the index of the element containing 45?int[] numbers = {-1, 45, 6, 132};正确答案: D. 1String[] str = {"Three","Two","One"};for (int i = 0; i < str.length; ++i){ System.out.println(str[i]+"/"); }What will be output upon execution of the program segment?正确答案: C. Three/Two/One/Consider the following method call, where c is an instance of the class java.util.ArrayList.c.size();This method call returns the number of正确答案: C. elements in the ArrayList represented by cConsider the following Java program segment.int[] arr; arr = new int[3]; arr[2]=19; arr[1]=17; arr[0]=15;Which of the following Java statements is syntactically correct and semantically identical to the program segment?正确答案: D. int[] arr= {15, 17, 19};If the length of a particular array is the value of LIMIT, what is the index of the last item in that array?正确答案: A. LIMIT - 1The class java.util.ArrayList implements a collection that正确答案: D. can grow to accommodate new itemsAn object that contains methods that traverse a collection linearly from start to finish is known as a(n)正确答案: C. iteratorUML class diagrams can describe which of the following?1、The internal structure of classes2、Relationships between classes错误!未找到引用源。
java面试题英文Java Interview QuestionsIntroduction:In recent years, Java has become one of the most popular programming languages worldwide. Its versatility and wide range of applications have made it a sought-after skill in the IT industry. As a result, job interviews often include a section dedicated to Java. In this article, we will explore some commonly asked Java interview questions and provide detailed explanations and solutions. Whether you are a seasoned developer or preparing for your first Java interview, this article will help you enhance your knowledge and boost your confidence.1. What is Java?Java is a high-level, object-oriented programming language developed by Sun Microsystems. It was designed to be platform-independent, which means Java programs can run on any operating system that has a Java Virtual Machine (JVM). Java consists of a compiler, runtime environment, and a vast library, making it a powerful tool for building a wide range of applications.2. Explain the difference between JDK, JRE, and JVM.JDK (Java Development Kit) is a software package that includes the necessary tools for developing, compiling, and running Java applications. It consists of the Java compiler, debugger, and other development tools.JRE (Java Runtime Environment) is a software package that contains the necessary components to run Java applications. It includes the JVM and a set of libraries required to execute Java programs.JVM (Java Virtual Machine) is a virtual machine that provides an execution environment for Java programs. It interprets the Java bytecode and translates it into machine code that can be executed by the underlying operating system.3. What is the difference between a class and an object?In object-oriented programming, a class is a blueprint or template for creating objects. It defines the properties and behaviors that an object will possess. An object, on the other hand, is an instance of a class. It represents a specific entity or concept and can interact with other objects.4. What are the features of Java?Java is known for its robustness, portability, and security. Some key features of Java include:- Object-oriented: Java follows the object-oriented programming paradigm, allowing developers to build modular and reusable code.- Platform-independent: Java programs can run on any platform that has a JVM, including Windows, Mac, and Linux.- Memory management: Java has automatic memory management through garbage collection, which helps in deallocating memory occupied by unused objects.- Exception handling: Java provides built-in mechanisms for handling exceptions, ensuring the smooth execution of programs.- Multi-threading: Java supports concurrent programming through multi-threading, allowing programs to perform multiple tasks simultaneously.5. Explain the concept of inheritance in Java.Inheritance is a fundamental concept in object-oriented programming, where a class inherits properties and behaviors from another class, known as the superclass or base class. The class that inherits these properties is called the subclass or derived class. In Java, inheritance allows code reuse, promotes modularity, and enables hierarchical classification of objects.There are several types of inheritance in Java, including single inheritance (where a class inherits from only one superclass) and multiple inheritance (where a class inherits from multiple superclasses using interfaces).6. What is the difference between method overloading and method overriding?Method overloading refers to the ability to have multiple methods with the same name but different parameters within a class. The methods can have different return types or different numbers and types of arguments. The compiler determines which method to call based on the arguments provided during the method call.Method overriding, on the other hand, occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The signature of the overridden method (name, return type, and parameters)must match exactly with that of the superclass. The overridden method in the subclass is called instead of the superclass's method when invoked.Conclusion:In this article, we have explored some common Java interview questions and provided detailed explanations and solutions. Understanding these concepts will not only help you ace your Java interview but also enhance your overall programming skills. Remember to practice coding and explore real-world scenarios to strengthen your understanding of Java. Good luck with your Java interviews!。
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。
Java学习笔记之IntelliJIDEA报错
0x00 概述
本⽂主要讲解IntelliJ IDEA的如下两个报错
1. 报错Error:Cannot determine path to ‘tools.jar‘ library for 17 (C:\Program Files\Java\jd
2. Cannot determine path to 'tools.jar' library 与 Error:java: ⽆效的源发⾏版
0x01 Error:Cannot determine path to ‘tools.jar‘ library for 17 (C:\Program Files\Java\jd Java版本过⾼,IntelliJ版本过低,⽆法识别⾼版本Java导致。
在下图的 Project Structure 中可以清晰的看到,笔者的 IntelliJ IDEA 2020.1(Ultimate Edition) 最⾼⽀持解析 JDK 14,因此对 Java 17 ⽆能为⼒。
如果遇到这个问题,建议按照IntelliJ 2020.1的要求安装Java14,确保Java可以被正确识别;
或者升级IntelliJ到最新版本,注意新版的IntelliJ和Java版本的匹配。
0x02 Cannot determine path to 'tools.jar' library 与 Error:java: ⽆效的源发⾏版
⾸先,在Projec Structure选择JDK8
然后在Project Lanuage Level选择对应的8:
运⾏成功。
java 在类中获取项目路径的方法Java 在类中获取项目路径的方法正文:Java是一种流行的编程语言,用于编写各种应用程序和系统。
其中,获取项目路径是一种常见的操作,可以帮助开发人员确定应用程序或系统在本地或远程环境中的位置。
本文将介绍如何在Java类中获取项目路径的方法。
方法一:使用Java IO库Java IO库提供了许多用于获取项目路径的方法。
其中,最常用的方法是使用File类或Path类。
使用File类获取项目路径。
File类是Java IO库中用于文件操作的类。
通过调用File类的getLocationName()方法,可以获取文件的路径名。
然后,可以使用Path对象的fromFile()方法将该路径名转换为Path对象,以便将其用于其他操作。
下面是一个简单的示例代码,演示如何使用File类和Path类获取项目路径: ```javaimport java.io.File;import java.io.Path;public class Main {public static void main(String[] args) {File file = new File("C:/Users/user/MyApplication.app");String path = file.getLocationName();System.out.println("项目路径为:" + path);}```此示例中,我们使用File类获取了一个名为"MyApplication.app"的应用程序文件,并将其存储在C:/Users/user/MyApplication目录中。
然后,我们使用Path对象的fromFile()方法将该文件路径名转换为Path对象,以便将其用于其他操作。
方法二:使用Java内置类Java内置类提供了另一种获取项目路径的方法,即使用System.out.println()方法。
Java Program Analysis Projects in Osaka University:Aspect-Based Slicing System ADAS and Ranked-Component Search System SPARS-JReishi Yokomori†,Takashi Ishio†,Tetsuo Yamamoto††,Makoto Matsushita†,Shinji Kusumoto†and Katsuro Inoue††Graduate School of Information Science and Technology,Osaka University1-3Machikaneyama,Toyonaka,Osaka560-8531,Japan††Japan Science and Technology Corporation,4-1-8,Honmachi,Kawaguchi,Saitama332-8531,Japan{yokomori,t-isio,t-yamamt,matusita,kusumoto,inoue}@ist.osaka-u.ac.jpAbstractIn our research demonstration,we show two develop-ment support systems for Java programs.One is an Aspect-oriented Dynamic Analysis and Slice calculation system named ADAS,and another is a Software Product archiving, Analyzing,and Retrieving System for Java named SPARS-J.1.IntroductionIn our research demonstration,we will show two types of development support systems for Java programs.The one is a slicing system for Java programs named ADAS(Aspect-oriented Dynamic Analysis and Slice calculation system), and another is a retrieval system for Java components named SPARS-J(Software Product archiving,Analyzing, and Retrieving System for Java).ADAS supports debug-ging tasks for Java programs based on program slicing tech-nique,and SPARS-J provides a retrieval result with the eval-uation value based on actual use relations among compo-nents.2Aspect-oriented Dynamic Analysis and Slice Calculation System:ADASADAS is a tool,which aids debugging tasks based on program slicing technique.Program slicing has been proposed to localize faults ef-ficiently in the program[7].By definition,slicing is a tech-nique which extracts all statements that possibly affect some set of variables in the program.The set of all extracted state-ments is called a slice.We have been extended the program slicing to DC slic-ing,using dynamic data dependence information to calcu-late accurate slices with lightweight costs[6].In process of DC slice calculation,it is an important is-sue how to analyze dynamic data dependence.In the past research,such function have not been encapsulated in a sin-gle module.Actually,the function was implemented as a pre-processor which inserts analysis operations in the tar-get program code,or as a customized Java Virtual Machine (JVM).But these approaches are hard to implement and to maintain.We have applied Aspect-Oriented Programming (AOP)to collect dynamic information.Since collection of dynamic information affects over all target program,this functionality becomes a typical crosscutting concern,which is modularized as an aspect in AOP[4].ADAS is a DC slicing tool for Java.This system con-sists of three subsystems,the Dynamic Information Ana-lyzer subsystem,the PDG(Program Dependence Graph) Constructor subsystem and the Slice Calculation subsys-tem.The Dynamic Information Analyzer subsystem is imple-mented as an aspect.A programmer debugging a Java pro-gram adds this aspect to the target program and compiles all sources using AspectJ[1].When the programmer exe-cutes the target program with a test case input,the added aspect collects runtime information,such asfield data de-pendence,method polymorphism resolution and exception handling,and outputs the result to afile.AOP approach is independent of JVM features,and we prefer this approach for usability and adaptability.Since the module of the dy-namic analysis is written as an aspect,a programmer can easily extend the analysis aspect using inheritance mecha-nism of AspectJ and add the analysis aspect to thefile list to be compiled.Recent IDEs,support to manage configuration of thefiles.The PDG Constructor subsystem reads information from thefile and analyze Java sourcefiles to construct a PDG, a directed graph whose nodes represent statements in the source program,and whose edges denote dependence re-lations(data dependence or control dependence)between statements[5].The Slice Calculation subsystem provides a graphical user interface.A source code viewer shows source code and slice criterions contained in thefile.When a program-mer selects a slice criterion,the system calculates the slice and indicates it in the viewer.3.SPARS-J:Software Product Archiving,An-alyzing,and Retrieving System for JavaSPARS-J is a retrieval system for Java components.It would be easily imagined that similar programs have been developed independently in different locations of the world or in different times in the history,without sharing knowl-edge of other programs.It is considered that a well-organized collection of programs or program components will improve productivity of the development and quality of the developed software products.SPARS-J might be considered as a Google-like[2]sys-tem for software engineers.In this system,various Java source programs are collected,and they are stored in a com-ponent archive.Those components are ranked by the eval-uation values(called Component Ranks[3]),which are de-termined by their use relations.A component searcher who wants to know about a definition or a usage of a component will give queries by keywords to SPARS-J.These queries are analyzed and the matched results are listed by the Com-ponent Ranks.By the Component Ranks,we consider that components with high reusability can be found effectively.SPARS-J consists of two subsystems,Constructing Databases subsystem and Searching Components subsys-tem.In Constructing Databases subsystem,a database for component search is built from Java source codefiles.Col-lected various Java source programs are analyzed syntac-tically and stored in the archive with information,such as all the appearance words,use class names and the metrics in each component.The appearance words are indexed to make a reverse dictionary for retrieval.The use class names are analyzed to determine use-relations between compo-nents.The metrics are used for measurement of a similarity between components.In software development process,we can imagine that a component may be reused with minor changes,by not simple copying.In order to calculate these components as one group,this subsystem measures similar-ity between components.As an example of a metric value, we use LOC,cyclomatic complexity,and so on.Similar components are packed into one group,and use relations associated to those components are also merged.All com-ponents(groups)are ranked by the evaluation values called Component Ranks,which are determined by their use rela-tions,and the Component Rank of each component is also stored in the archive.On the other hand,Searching Components subsystem provides a retrieval function for user.Basically,this sub-system performs component retrieval from all the appearing words including comments in source codefiles.However, a user can request to perform an advanced search according to the purpose of the user.For example,this subsystem can remove the components with which keywords appear only in its comment from a result,or extract the only components with which keywords appears in the definition of a class or a method,or extract only the use example.A query specified by a user is analyzed and decomposed into a set of keywords.For each keyword,this subsystem checks the component with which the keyword appears by referring to reverse dictionary.A result is ordered by the Component Ranks,the user receives the result through the browser with the information of each components and a part of its code.Furthermore,the user may click the results to get detailed information on the search components,or may add keywords to perform further retrieval.In this way,the user can effectivelyfind a component that is used most fre-quently and has high reusability.References[1]AspectJ Team,“The AspectJ Programming Guide”,/doc/dist/progguide/[2]google,/[3]K.Inoue et al.:“Component Rank:Relative Signif-icance Rank for Software Component Search”,to be appeared in Proceedings of ICSE2003,Portland,Ore-gon,2003.[4]G.Kiczales et al.:“Aspect Oriented Programming”,Proceedings of ECOOP,vol.1241of LNCS,pp.220-242(1997).[5]K.J.Ottenstein and L.M.Ottenstein:“The programdependence graph in a software development environ-ment”,Proceedings of SESPSDE,pp.177–184,Pitts-burgh,Pennsylvania,April(1984).[6]T.Takada et al.:“Dependence-Cache Slicing:A Pro-gram Slicing Method Using Lightweight Dynamic In-formation”,Proceedings of IWPC2002,pp.169-177, Paris,France,June(2002).[7]M.Weiser:“Program slicing”,IEEE Transactions onSoftware Engineering,SE-10(4):352-357(1984).。