LAB MANUAL Course: CSC103-Programming Fundamentals Department of Computer Science Learning Procedure J (Journey inside-out the concept) Stage a1 (Apply the learned) Stage v (Verify the accuracy) Stage a2 (Assess your work) 1) Stage 2) 3) 4) COMSATS University Islamabad (CUI) undamentals CSC103-Fundamentals Fundamentals 1 Table of Contents Lab # Lab # 01 Topics Covered Lab # 04 Introduction to Flowcharting using Raptor Basic Flowcharting symbols and their use Selection and Iteration Symbols in Raptor and their usage Java Installation FirstProgram in Java if-else structure, nested if statements Lab # 05 for loop, nested for loops Lab # 02 Lab # 03 Page # Lab Sessional 1 Lab # 06 while and do-while loops Lab # 07 Methods Lab # 08 Arrays (1-D & 2-D) Passing arraysto methods Strings Lab # 09 Lab # 10 Methods Overloading Recursion Lab Sessional 2 Lab # 11 File handling I Lab # 12 File handling II Lab # 13 Test cases Lab # 14 Test cases generations Terminal Examination CSC103-Fundamentals Fundamentals undamentals 2 LAB # 01 Statement Purpose: The objective of this lab is to make student familiar with basic programming concepts using flowcharting techniques. Activity Outcomes: This lab teaches you the following topics: An introduction to Raptor Tool Basic flowchart Symbols Creating, Running and Saving flowcharts in Raptor CSC103-Fundamentals Fundamentals undamentals 3 1) StageJ(Journey) Introduction: Make yourself familiar with the Raptor Tool 1.1 Understand the symbols for Input, Process and Output 1.2 Placing symbols and saving your first flowchart 1.3 Running the flowchart and getting the output in console Making program flowcharts is a powerful technique for logic building and learning syntax free programming. Using Raptor, a GUI based drag and drop tool you can easily test your logic building skill, just drape your logic with the syntax of any programming language and claim yourself to be a programmer. CSC103-Fundamentals Fundamentals undamentals 4 2) Stage a1 (apply) Lab Activities: Activity 1: Create flowchart for “Hello World” Solution: Launch Raptor, you will see two set of windows, the main working pane and the console window. The main window is where you can drag and drop symbols and test your logic while the console window gives you output and some basic information regarding the last execution done. The start and end symbols are placed by default. CSC103-Fundamentals Fundamentals undamentals 5 Task 1.1: Hello World and it's Execution ➜ Pick the output symbol from symbols pane and drag it in between the start and end symbol, the application might ask you to save your work, give it a meaningful name like HelloWorld and it will be saved with rap extension. ➜ Single click inside the output symbol to select it. ➜ Double click inside the output symbol and you will see a popup window asking what you want to output. ➜ In the output popup window type (with double quotes) “Hello World”. ➜ You can optionally change the speed of execution using the scrolling pointer given immediately after the buttons toolbar. CSC103-Fundamentals Fundamentals undamentals 6 Activity 2: Flowchart for calculating Area of Circle Solution: The formula to calculate area of circle is Area = 3.1415 * radius * radius It's clear that the only variable in the above formula is “radius” of the circle, this means we require it as an input from user to get a meaningful answer of the expression. ➜ Select the New option from File menu ● Place the Input Symbol from the list of symbols. ● Place the Assignment Symbol just below the Input Symbol. Finally place an Output Symbol after the Assignment and just before the End Symbol. ● ➜ Double click on the input symbol and tell the Raptor the message you want to display in the Prompt section and the variable name in which you want to store the input from the user. ➜ Double click the Assignment Symbol and introduce a new variable named “area” in the Set field and the formula for expression in the “to” field. ➜ Double click the Output Symbol and tell the Raptor what you want to display as output, the literal message in double quotes concatenated with the plus symbol and the variable whose value you want to display. "The Area of Circle with Radius " + radius + " is " + area ➜ Execute the flow chart, give the required input for “radius” and verify the output. CSC103-Fundamentals Fundamentals undamentals 7 CSC103-Fundamentals Fundamentals undamentals 8 Activity 3: Update Activity 2 to calculate Perimeter of Circle (2*3.1415*radius) along with Area 3) Stage v (verify) Home Activities: 1. Create a flowchart that prompts the user to enter two points (x1, y1) and (x2, y2) and displays their distance between them. The formula for computing the distance is sqrt((x2 - x1)2 + (y2 - y1)2). Note that you can use the built-in method sqrt(x) for calculating square root of a given number. 2. Given an airplane’s acceleration a and take-off speed v, you can compute the minimum runway length needed for an airplane to take off using the following formula: length = (v * v)/(2*a) Draw a flowchart that prompts the user to enter v in meters/second and the acceleration a in meters/second squared and displays the minimum runway length. 4) Stagea2(assess) Lab Assignment and Viva voce CSC103-Fundamentals Fundamentals undamentals 9 LAB # 02 Statement Purpose: The objective of this lab is to make student understand the basic concepts of selection and looping using flowcharting technique in Raptor. Activity Outcomes: This lab teaches you the following topics: At the end of this lab student will know how to develop logic of a program Students will get clear understanding of two important Problem-Solving techniques which are: o Selection o Iteration or Looping Instructor Note: As pre-lab activity, the concepts from Chapter 3 and Chapter 5 are covered from the book (Introduction to JAVA Programming, Liang, Y.D., 10th Edition (2015), Prentice Hall). Although it’s too early to go in to the details of selection and looping in second lab but a quick overview and concept of both can be introduced so that students can practice the two important options given in the Raptor’s symbol list. CSC103-Fundamentals Fundamentals undamentals 10 1) StageJ(Journey) Introduction Selection Selection means selecting a set of statements for execution under a certain condition, the condition should a logical test involving logical and relational operators, e.g. display A/B only when B is not equal to zero, means we have to test B for the specific value of zero. Raptor uses the symbol for selection type statements . the diamond symbol represents the logical test and YES branch means execution path when condition evaluates to be true, obviously NO side branch represents execution path when the condition evaluates to be false. Iteration or Looping Iteration means repetition i.e. to repeat a set of statements a certain number of times or to repeat the statements until a specific condition is met, e.g. if the user enters a negative value for his age then ask him to enter the age repeatedly until he enters a value greater than zero. Raptor uses the symbol for looping. CSC103-Fundamentals Fundamentals undamentals 11 2) Stage a1 (apply) Lab Activities: Activity 1: Draw a flowchart that tells user whether the Integer entered is Even or Odd Number, use % symbol to test the remainder value. Solution: CSC103-Fundamentals Fundamentals undamentals 12 Activity 2: Draw a flowchart to accept two values from user and display the larger one. Solution: CSC103-Fundamentals Fundamentals undamentals 13 Activity 3: Draw a flowchart for a program that reads two numbers and displays the number series from first to last number. CSC103-Fundamentals Fundamentals undamentals 14 3) Stagev(verify) Home Activities: 1. Draw a flow chart to calculate the Sum of series from Starting to Ending Number, the increment per cycle is also entered by the user. 2. Construct flow chart to Calculate Factorial of a Number entered by the user. 4) Stagea2(assess) Lab Assignment and Viva voce CSC103-Fundamentals Fundamentals undamentals 15 LAB # 03 Statement Purpose: This lab covers the following topics: • • • • • • • Install NetBeans Getting Started with NetBeans Creating a Project Creating a Class Compiling a Class Running a Java Application Forcing a Program to Terminate This tutorial applies to NetBeans 6, 7, or a higher version. Activity Outcomes: This lab teaches you the following topics: Installing java Create first java program CSC103-Fundamentals Fundamentals undamentals 16 1) StageJ(Journey) Introduction This tutorial is for students who are currently taking a Java course using NetBeans with Introduction to Java Programming. You can use the JDK command line utility to write Java programs. The JDK command line utility consists of a set of separate programs, such as compiler and interpreter, each of which is invoked from a command line. Besides the JDK command line utility, there are more than a dozen Java development tools on the market today, including NetBeans, JBuilder, and Eclipse. These tools support an integrated development environment (IDE) for rapidly developing Java programs. Editing, compiling, building, debugging, and online help are integrated in one graphical user interface. Using these tools effectively will greatly increase your programming productivity. This brief tutorial will help you to become familiar with NetBeans. Specifically, you will learn how to create projects, create programs, compile, run, and debug programs. CSC103-Fundamentals Fundamentals undamentals 17 2) Stage a1 (apply) Lab Activities: Activity 1:Install NetBeans Download and install JDK 1.8 and NetBeans 8.0 from one bundle at http://www.oracle.com/technetwork/java/javase/downloads/jdknetbeans-jsp-142931.html CSC103-Fundamentals Fundamentals undamentals 18 Activity 2:Getting Started with NetBeans Assume that you have successfully installed NetBeans on your machine. Start NetBeans from Windows, Linux, Mac OS X, or Solaris. The NetBeans main window appears, as shown in Figure 1. Figure 1 The NetBeans main window is the command center for the IDE. The NetBeans main window contains menus, toolbars, project pane, files pane, runtime pane, navigator pane, and other panes. 1.1 The Main Menu The main menu is similar to that of other Windows applications and provides most of the commands you need to use NetBeans, including those for creating, editing, compiling, running, and debugging programs. The menu items are enabled and disabled in response to the current context. 1.2 The Toolbar The toolbar provides buttons for several frequently used commands on the menu bar. The toolbars are enabled and disabled in response to the current context. Clicking a toolbar is faster than using the menu bar. For many commands, you also can use function keys or keyboard shortcuts. For example, you can save a file in three ways: • Select File, Save from the menu bar. • Click the "save" toolbar button ( ). • Use the keyboard shortcut Ctrl+S. TIP: You can display a label known as ToolTip for a toolbar button by pointing the mouse to the button without clicking. 1.3 Workspaces CSC103-Fundamentals Fundamentals undamentals 19 A workspace is a collection of windows that are pertinent to performing certain types of operations, such as editing, execution, output, or debugging. The workspace windows can be displayed from the Window menu. CSC103-Fundamentals Fundamentals undamentals 20 Activity 3:Creating a Project A project contains information about programs and their dependent files, and it also stores and maintains the properties of the IDE. To create and run a program, you have to first create a project. Here are the steps to create a demo project: 1. Choose File, New Project to display the New Project dialog box, as shown in Figure 2. 2. Select General in the Categories section and Java Application in the Projects section and click Next to display the New Java Application dialog box, as shown in Figure 3. 3. Type demo in the Project Name field and c:\michael in Project Location field. 4. (Optional) You can create classes after a project is created. Optionally you may also create the first class when creating a new project. To do so, check the Create Main Class box and type a class name, say First, as the Main Class name. 5. Click Finish to create the project. The new project is displayed, as shown in Figure 4. Figure 2 The New Project dialog box enables you to specify a project type. Figure 3 The New Java Application prompts you to enter a project name, location, and a main class name. CSC103-Fundamentals Fundamentals undamentals 21 Figure 4 A new demo project is created. CSC103-Fundamentals Fundamentals undamentals 22 Activity 4:Creating a Class You can create any number of classes in a project. Here are the steps to create Welcome.java. 1. Right-click the top demo node in the project pane to display a context menu, as shown in Figure 5. Choose New, Java Class to display the New Java Class dialog box, as shown in Figure 6. 2. Type Welcome in the Class Name field and select the Source Packages in the Location field. Leave the Package field blank. This will create a class in the default package. (Note that it is not recommended to use the default package, but it is fine to use the default package to match the code in the book. Using default package is appropriate for new Java students. Section 10, “Using Packages,” will introduce how to create a class in a nondefault package.) 3. Click Finish to create the Welcome class, as shown in Figure 7. The source code file Welcome.java is placed under the <default package> node, because you did not specify a package name for the class in Figure 6. 4. Modify the code in the Welcome class to match Listing 1.1, as shown in Figure 8. Figure 5 You can create a new class in a project. Figure 6 CSC103-Fundamentals Fundamentals undamentals 23 The New Java Class dialog box enables you to specify a class name, location, and package name to create a new class. Figure 7 A new Java class is created in the project. Figure 8 The source code for Welcome.java is entered. TIP You can show line numbers in the Source Editor by choosing View, Show Line Numbers from the main menu. NOTE The source file Welcome.java is stored in c:\michael\demo\src. CSC103-Fundamentals Fundamentals undamentals 24 Activity 5:Compiling a Class To compile Welcome.java, right-click Welcome.java to display a context menu and choose Compile File, or simply press F9, as shown in Figure 9. The compilation status is displayed in the Output pane, as shown in Figure 10. If there are no syntax errors, the compiler generates a file named Welcome.class, which is stored in c:\michael\demo\build\classes. Figure 9 The Compile File command in the context menu compiles a source file. CSC103-Fundamentals Fundamentals undamentals 25 Output pane Figure 10 The compilation status is shown in the output pane. NOTE: When you compile the file, it will be automatically saved. CSC103-Fundamentals Fundamentals undamentals 26 Activity 6:Running a Java Application To run Welcome.java, right-click Welcome.java to display a context menu and choose Run File, or simply press Shift + F6, as shown in Figure 12. The output is displayed in the Output pane, as shown in Figure 13. Figure 12 The Run File command in the context menu runs a Java program. Output Figure 13 The execution result is shown in the Output pane. CSC103-Fundamentals Fundamentals undamentals 27 NOTE: The Run File command invokes the Compile File command if the program is not compiled or was modified after the last compilation. CSC103-Fundamentals Fundamentals undamentals 28 Activity 7:Forcing a Program to Terminate If a program does not terminate due to a logic error, you can force it to terminate by clicking the Stop icon, as shown in Figure 18. Figure 18 You can force a program to terminate from the runtime pane. CSC103-Fundamentals Fundamentals undamentals 29 3) Stagev(verify) Home Activities: 1. Every student is required to make installation on his / her personal computer before next lab. 4) Stagea2(assess) Lab Assignment and Viva voce CSC103-Fundamentals Fundamentals undamentals 30 CSC103-Fundamentals Fundamentals undamentals 31 LAB # 04 Statement Purpose: This lab will give you practical implementation of different types of Conditional Statements (ifelse and switch). Activity Outcomes: This lab teaches you the following topics: Use of indentation Use of simple if statement Use of if-else statement Use of nested-if statement Use of switch statement Instructor Note: As pre-lab activity, read Chapter 3 from the book (Introduction to Java Programming, Brief VersionPrentice Hall (2012) By Y. Daniel Liang), and also as given by your theory instructor. CSC103-Fundamentals Fundamentals undamentals 32 1) Stage J (Journey) Introduction: if statement is used to perform logical operation. In order to perform decision making, we need to check certain condition(s) before processing. Java supports if statement for doing so. There are various formats of if statement including if-else and if-ellse-if. Apart from if statement, Java also supports switch statement. switch statement is used to select one of the various options. The basic and shortest form of if statement is as below: if (condition) statement; If the condition is true in above case then the statement written after the if statement will be executed otherwise the given statement will be simple ignored. If there are more than one statements to be executed when the condition is true then we need to write those statements in a pair of curly brackets as below. if (condition) { statement1; statement2; … … } If the condition is true then the specified block of statements written within a pair of curly brackets will be executed. It is important to note that the block is specified by the use of a pair of curly brackets. We can also write the else block associated with the if statement as below. if (condition) statement1; else statement2; The else part of if statement is always optional but if is written then will be executed only if the condition written after the if statement is false. In above case if the condition is true then statement1 will be executed and statement2 will be ignored. On the other hand, if the condition written after the if statement is false then statement2 will be executed and statement1 will be ignored. We can also write more than one statements in the if block or in the else block as shown below. CSC103-Fundamentals Fundamentals undamentals 33 if (condition) { statement1; statement2; … … } else { statement3; statement4; … … } If we are required to test a number of conditions and want to execute one of the many blocks of statements, then we can use multi-way if-else statements as below. if (condition1) { statement1; statement2; … … } else if (condition2) { statement3; statement4; … … } else if (condition3) { statement5; statement6; … … } else { statement7; statement8; } In the above case only one of the written blocks will be executed depending on the condition to be true. If none of the conditions is true then the block written after the last else will be executed. If we have not written the last block then nothing will be executed if all the conditions are false. Java supports another statement as alternative of the above case, called switch statement as discussed below. CSC103-Fundamentals Fundamentals undamentals 34 switch statement The syntax of switch statement is as below. switch (variable/expression) { case value1: statement1; statement2; … … break; case value2: statement3; statement4; … … break; case value3: statement5; statement6; … … break; default: statement7; statement8; … … break; } In switch statement, only one of the case block can be executed depending on the value of the variable or expression written after the switch statement. Every case block will have a unique value and will be executed if the value hold by the switch variable (or expression) matches that case value. The break statement is important to write in each case block. It takes control out of the switch statement. If break statement is not written in any case block then the following case block will be executed until break statement is found or the last statement written in the switch statement is executed. The default block is optional and will be only executed if none of the case value is equal to the value contained of the switch variable (or expression). 2) Stage a1 (apply) Lab Activities: Activity 1: Let us take an integer from user as input and check whether the given value is even or not. Solution: CSC103-Fundamentals Fundamentals undamentals 35 A. Create a new Java file using an appropriate IDE and type the following code. B. Run the code. You will get the following output. Activity 2: Let us modify the code to take an integer from user as input and check whether the given value is even or odd. If the given value is not even then it means that it will be odd. So here we need to use if-else statement an demonstrated below. Solution: A. Create a new Java file using an appropriate IDE and type the following code. B. Run the code by pressing F5. You will get the following output. CSC103-Fundamentals Fundamentals undamentals 36 Activity 3: Let us modify the above code in order to apply nested if structure. Sometimes we need to use an if statement within the block of another if to find the solution of the problem. The following code example illustrates that how nested if can be used in Java. Solution: A. Create a new Java file and type the following code. B. Run the code by pressing F5. You will get the following output. Activity 4: The code written in activity 3 can also be written as multi-way if-else statement and is in fact a preferred way of writing multiple if-else statements in order to make the code more readable. Solution: A. Create a new Java file and type the following code. B. Run the code by pressing F5. CSC103-Fundamentals Fundamentals undamentals 37 You will get the following output. Activity 5: In this activity, you will be using multi-level if-else statement. You are required to accept two integer values from user and calculate their addition, subtraction, multiplication and division depending on the given choice. Solution: A. Create a new Java file and type the following code. B. Run the code by pressing F5. CSC103-Fundamentals Fundamentals undamentals 38 You will get the following output. Activity 6: In this activity, you will rewrite the above code by using switch statement instead of using multi-level if-else statement. You are required to accept two integer values from user and calculate their addition, subtraction, multiplication and division depending on the given choice. Solution: A. Create a new Java file and type the following code. B. Run the code by pressing F5. CSC103-Fundamentals Fundamentals undamentals 39 You will get the following output. CSC103-Fundamentals Fundamentals undamentals 40 3) Stage v (verify) Home Activities: Activity 1: Write a Java code to accept marks of a student from 1-100 and display the grade according to the following formula. Grade F if marks are less than 50 Grade E if marks are between 50 to 60 Grade D if marks are between 61 to 70 Grade C if marks are between 71 to 80 Grade B if marks are between 81 to 90 Grade A if marks are between 91 to 100 Activity 2: Write a Java code to accept temperature value from user (in centigrade) and display an appropriate message as below. FREEZING if temperature in less than 0 COLD if temperature is between 0 to 15 WARM if temperature is between 16 to 30 HOT if temperature is between 31 to 40 VERY HOT if temperature is greater than 40 4) Stage a2 (assess) Assignment: For this student will submit Lab Assignment before the deadline. CSC103-Fundamentals Fundamentals undamentals 41 LAB # 05 Statement Purpose: This lab will give you practical implementation of different types of for loops including nested for loops. Activity Outcomes: This lab teaches you the following topics: for loop nested for loop Use of break statement in for loop Instructor Note: As pre-lab activity, read Chapter 4 from the book (Introduction to Java Programming, Brief VersionPrentice Hall (2012) By Y. Daniel Liang), and also as given by your theory instructor. CSC103-Fundamentals Fundamentals undamentals 42 1) Stage J (Journey) Introduction: Loops are one of the basic structures of a programming language. Loops are performed to repeat a step or steps for a certain number of times. Java offers a number of loop statements. One of them is for loop. This lab session covers the for loop. for loop for loop is probably the most commonly used loop in Java. It is preferred to use in situations when the number of iterations are known in advance, i.e. we already know that how many times the loop will be repeated. The syntax of for loop is as below. for(exp1;exp2;exp3) statement; or for(exp1;exp2;exp3) { statement1; statement2; statement3; … … } Where, exp1 is called initialization. Here we initialize the variable to be used to control the loop iterations. exp2 is a condition. Loop will continue to iterate as long as this condition is true. exp3 is an increment or decrement statement. It will increment or decrement the loop variable initialized in exp1. CSC103-Fundamentals Fundamentals undamentals 43 2) Stage a1 (apply) Lab Activities: Activity 1: Calculate the sum of all the values between 0-10 using for loop. Solution: C. Create a new Java and type the following code. D. Run the code by pressing F5. You will get the following output. Activity 2: Accept an integer values from user and display its numeric table. Solution: C. Create a new Java file and type the following code. D. Run the code by pressing F5. CSC103-Fundamentals Fundamentals undamentals 44 You will get the following output. Activity 3: Accept an integer values from user and display its factorial. Solution: C. Create a new Java file type the following code. D. Run the code by pressing F5. CSC103-Fundamentals Fundamentals undamentals 45 You will get the following output. Activity 4: Write a Java code to accept an integer value from user and check that whether it is prime or not. In this activity, you will also learn the use of break statement in for loop. break statement is used in for loop to terminate the for loop immediately and the next iterations will not be performed as they may not be required further. Solution: C. Create a new Java file and type the following code. D. Run the code by pressing F5. You will get the following output. CSC103-Fundamentals Fundamentals undamentals 46 Activity 5: In this activity, you will learn the use of nested for statements. If we use a for statement within the body of another for statement then it is called nested for statements. You are required to write a Java program to display all the prime numbers between 100 to 200. Solution: A. Create a new Java file and type the following code. B. Run the code by pressing F5. You will get the following output. CSC103-Fundamentals Fundamentals undamentals 47 3) Stage v (verify) Home Activities: Activity 1: Write a Java program to accept 10 integer values from user and display sum of positive values. Activity 2: Write a Java program to generate the following output. CSC103-Fundamentals Fundamentals undamentals 48 Activity 3: Write a Java program that prompts the user to enter two positive integers and find their greatest common divisor as below. Activity 4: Fibonacci series is that when you add the previous two numbers the next number is formed. You have to start from 0 and 1. E.g. 0+1=1 → 1+1=2 → 1+2=3 → 2+3=5 → 3+5=8 → 5+8=13 So the series becomes 0 1 1 2 3 5 8 13 21 34 55 …………………………………… Steps: You have to take an input number that shows how many terms to be displayed. Then use loops for displaying the Fibonacci series up to that term e.g. input no is =6 the output should be 011235 CSC103-Fundamentals Fundamentals undamentals 49 4) Stage a2 (assess) Assignment: For this student will submit Lab Assignment before the deadline. CSC103-Fundamentals Fundamentals undamentals 50 LAB # 06 Statement Purpose: This lab will give you practical implementation of while and do-while loops. Activity Outcomes: This lab teaches you the following topics: while loop do-while loop Instructor Note: As pre-lab activity, read Chapter 4 from the book (Introduction to Java Programming, Brief VersionPrentice Hall (2012) By Y. Daniel Liang), and also as given by your theory instructor. CSC103-Fundamentals Fundamentals undamentals 51 1) Stage J (Journey) Introduction: Java provides different types of loop statements including while and do-while statements. Although these loop statements can be used as alternatives of for loop but are preferred to be used when the number of iterations are not known in advance. while loop This is also called as pre-test loop where a condition is tested first before the body of the loop is executed. The body of the loop is executed as long as the condition followed by the while statement remains true. The syntax of while loop is as below. while (condition) { statement1; statement2; ... ... } As you can see in the above syntax, a condition is followed by the while statement. This condition must remain true for the execution of the loop. As long as the condition will remain true, the loop will be iterated and will stop when the condition becomes false. do-while loop This is also called post-test loop where the condition is tested once the body of the loop is executed. If the condition is true then the body of the loop is executed again and this process continues until the condition becomes false. It means that the body of the loop will be executed at least once whether the condition is true or false as the body is executed first and then the condition is checked. The syntax of do-while loop is as below. do { statement1; statement2; ... ... }while (condition); CSC103-Fundamentals Fundamentals undamentals 52 2) Stage a1 (apply) Lab Activities: Activity 1: Calculate the sum of all the values between 0-10 using while loop, Solution: A. Create a new Java file and type the following code. B. Run the code by pressing F5. You will get the following output. Activity 2: Repeat the above code by accepting 5 integer values from user and display the sum of given values. Solution: A. Create a new Java file and type the following code. B. Run the code by pressing F5. CSC103-Fundamentals Fundamentals undamentals 53 You will get the following output. Activity 3: Rewrite the above code to keep accepting integer values from user until 0 is entered. Display sum of the given values. Solution: A. Create a new Java file and type the following code. B. Run the code by pressing F5. CSC103-Fundamentals Fundamentals undamentals 54 You will get the following output. Activity 4: Rewrite the above code using do-while loop. Solution: A. Create a new Java file and type the following code. B. Run the code by pressing F5. You will get the following output. CSC103-Fundamentals Fundamentals undamentals 55 Activity 5: Write a Java program to accept two integer values from user and calculate their addition, subtraction, multiplication and division depending on the given choice. Keep accepting the values until a choice related to quit the process is selected. Solution: A. Create a new Java file and type the following code. B. Run the code by pressing F5. You will get the following output. CSC103-Fundamentals Fundamentals undamentals 56 3) Stage v (verify) Home Activities: Activity 1: Write a Java program that prompts the user to enter an answer for a question on addition of two single digits and let the user repeatedly enter a new answer until it is correct as below. Activity 2: Guessing Numbers---The problem is to guess what number a computer has in mind. You will write a program thatrandomly generates an integer between 0 and 100, inclusive. The program prompts the user to enter a number continuously until the number matches the randomly generated number. For each user input, the program tells the user whether the input is too low or too high, so the user can make the next guess intelligently. Here is a sample run: CSC103-Fundamentals Fundamentals undamentals 57 Activity 3: Write a Java program to keep accepting integer values from user until a prime number is entered. Activity 4: Write a Java program to keep accepting marks and names of students until a negative number is entered against marks. Display name of the student having maximum marks. 4) Stage a2 (assess) Assignment: For this student will submit Lab Assignment before the deadline. CSC103-Fundamentals Fundamentals undamentals 58 LAB # 07 Statement Purpose: This lab will give you practical implementation of different types of user-defined methods. Activity Outcomes: This lab teaches you the following topics: How to define own methods How to use user-defined methods Passing different types of arguments Instructor Note: As pre-lab activity, read Chapter 5 from the book (Introduction to Java Programming, Brief VersionPrentice Hall (2012) By Y. Daniel Liang), and also as given by your theory instructor. CSC103-Fundamentals Fundamentals undamentals 59 1) Stage J (Journey) Introduction: It is usually a better approach to divide a large code in small methods. A method is a small piece of code used to perform a specific purpose. Methods are defined first then called whenever needed. A program may have as many methods as required. Similarly a method may be called as many times as required. How to Define Methods Functions are defined as below. returnType methodName(dataType par1, dataType par2, ...) { statement1; statement2; ... return value; } A method may or may not return a value. If a method does not return a value then the return type must be void otherwise you need to return the data type of the value to be returned. A method must have an appropriate name and a pair of parenthesis. In parenthesis, you need to mention that whether a method will accept or not any parameters. If a method is not accepting any parameter then the parenthesis must be left blank otherwise you need to mention the name and type of parameters to be accepted. A method must return a value if the return type is not void. How to Call A Function Once a method is defined then it can be called by using its name and providing values to the parameters. The following activities demonstrate that how methods are defined and called in Java. CSC103-Fundamentals Fundamentals undamentals 60 2) Stage a1 (apply) Lab Activities: Activity 1: Define a method to accept an integer value and return its factorial. Solution: A. Create a new Java file and type the following code. B. Run the code by pressing F5. You will get the following output. Activity 2: Write a function to accept 2 integer values from user and return their sum. Solution: A. Create a new Java file and type the following code. B. Run the code by pressing F5. CSC103-Fundamentals Fundamentals undamentals 61 You will get the following output. Activity 3: Define a function to accept an integer value from user and check that whether the given value is prime number or not. If the given value is a prime number then it will return true otherwise false. Solution: A. Create a new Java file and type the following code. B. Run the code by pressing F5. CSC103-Fundamentals Fundamentals undamentals 62 You will get the following output. Activity 4: Define a function to accept an integer value and display its numeric table. Solution: A. Create a new Java file and type the following code. B. Run the code by pressing F5. CSC103-Fundamentals Fundamentals undamentals 63 You will get the following output. Activity 5: Write a Java program to find the sum of integers from 1 to 10, from 11 to 20, and from 21 to 30, respectively. Solution: A. Create a new Java file and type the following code. B. Run the code by pressing F5. CSC103-Fundamentals Fundamentals undamentals 64 You will get the following output. 3) Stage v (verify) Home Activities: Activity 1: Write a method to accept an integer ‘n’ and display ‘n’ elements of Fibonacci series. Activity 2: Write a method to accept three integer values and return the largest value. CSC103-Fundamentals Fundamentals undamentals 65 Activity 3: Write a method to accept marks of a student (between 0-100) and return the grade according to the following criteria. 0 - 49 50 – 60 61 – 70 71 – 80 81 – 90 91 – 100 F E D C B A 4) Stage a2 (assess) Assignment: For this student will submit Lab Assignment before the deadline. CSC103-Fundamentals Fundamentals undamentals 66 CSC103-Fundamentals Fundamentals undamentals 67 LAB # 08 Statement Purpose: In this lab, students will know about the basic concepts of Array data structure, storing different types of data in arrays, creating arrays of integers, double, Strings and passing arrays to the methods. Activity Outcomes: This lab teaches you the following topics: Create Arrays Accessing indexes/location of variables in arrays Accessing maximum, minimum numbers in arrays Different array’s operation Passing arrays to methods Instructor Note: As pre-lab activity, read Chapter 7 and 8 from the book (Introduction to JAVA Programming, Liang, Y.D., 10th Edition (2015), Prentice Hall), and also as given by your theory instructor. CSC103-Fundamentals Fundamentals undamentals 68 1) StageJ(Journey) Introduction Often you will have to store a large number of values during the execution of a program. Suppose, for instance, that you need to read 100 numbers, compute their average, and findout how many numbers are above the average. Your program first reads the numbers andcomputes their average, then compares each number with the average to determine whetherit is above the average. In order to accomplish this task, the numbers must all be stored invariables. You have to declare 100 variables and repeatedly write almost identical code100 times. Writing a program this way would be impractical. So, how do you solve thisproblem? An efficient, organized approach is needed. Java and most other high-level languages providea data structure, the array, which stores a fixed-size sequential collection of elements ofthe same type. In the present case, you can store all 100 numbers into an array and access themthrough a single array variable. Array is a data structure that represents a collection of the same types of data. The array elements are accessed through the index. The array indices are 0-based, i.e., it starts from 0 to arrayRefVar.length-1. • Declaring arrays: elementType[] arrayRefVar; The elementType can be any data type, and all elements in the array will have the same data type. For example, the following code declares a variable myList that references an array of double elements. double[] myList; • Creating arrays: arrayRefVar = new elementType[arraySize]; CSC103-Fundamentals Fundamentals undamentals 69 2) Stage a1 (apply) Lab Activities: Activity 1: Create a menu driven program, with the following functionalities: (Note: all of the functionalities should be created in a single program with following menu options) 1. Input elements in array. (details of this functionality is given in Step a) 2. Search element and its location. (details of this functionality is given in Step b) 3. Find largest and smallest value in the array. (details of this functionality is given in Step c) 4. Copy data. (details of this functionality is given in Step d) a) Input 10 elements in the array and display the array. (Note: this should call two methods Input(int Array[ ] ) and display(int A[ ]) ) b) Search element is in the array then print “Element found” along with its location. (Note: this should call two methods Input(int Array[ ]) and search(intsearchkey, int Array[ ]). You should call the same Input() method that is called in step a ) c) Find the largest and the smallest element in array. Then place largest element on 0th index and smallest element on the last index 9th. (Note: this should call three methods previously used Input(int Array[]) , Largest(int Array[]) and Smallest (int Array[]) d) Copy the contents of one array into another.(Note: this should call two methods Input(int Array[]) and copydata(int Array[], intcopiedArray[]). Solution: CSC103-Fundamentals Fundamentals undamentals 70 CSC103-Fundamentals Fundamentals undamentals 71 You will get the following output. CSC103-Fundamentals Fundamentals undamentals 72 Activity 2: Write a program which takes 50 characters as input in array and counts the occurrences of each character. E.g. A occurs 2 times Y occurs 1 time E occurs 1 time O occurs 2 times K occurs 1 time @ occurs 1 time ……. So on… Solution: CSC103-Fundamentals Fundamentals undamentals 73 You will get the following output. Activity 3: Write a program to insert elements in 2D array. Then print the array in matrix form. CSC103-Fundamentals Fundamentals undamentals 74 You will get the following output. Activity 4: Write a program that reads two 2-D arrays of 3X3 each and Swap their values and then print both matrices. CSC103-Fundamentals Fundamentals undamentals 75 CSC103-Fundamentals Fundamentals undamentals 76 You will get the following output. Activity 5: Program below will show the difference between passing a primitive datatype value and an array reference variable to a method.The program contains two methods for swapping elements in an array. The first method,named swap, fails to swap two int arguments. The second method, named swapFirst-TwoInArray, successfully swaps the first two elements in the array argument. CSC103-Fundamentals Fundamentals undamentals 77 You will get the following output. CSC103-Fundamentals Fundamentals undamentals 78 3) Stagev(verify) Home Activities: 1. Forty students were asked to rate the quality of food in the student cafeteria, on a scale of 1 to 10 (1 means awful and 10 means excellent). Place the forty responses in an integer array and summarize the results of the poll. 2. Write a program which performs the following tasks: • initialize an integer array of 10 elements in main( ) • Pass the entire array to a function modify( ) • In modify( ) multiply each element of array by 3 • return the control to main( ) and print the new array elements in main( ) 3. Write a program to copy the contents of one array into another in the reverse order. 4) Stagea2(assess) Lab Assignment and Viva voce LAB # 09 Statement Purpose: This lab will teach you about strings in Java. How strings are defined and used Java? Activity Outcomes: This lab teaches you the following topics: How to define strings How to use strings in problem solving Using predefined string methods CSC103-Fundamentals Fundamentals undamentals 79 Passing strings to methods Instructor Note: As pre-lab activity, read Chapter 9 from the book (Introduction to Java Programming, Brief VersionPrentice Hall (2012) By Y. Daniel Liang), and also as given by your theory instructor. CSC103-Fundamentals Fundamentals undamentals 80 1) Stage J (Journey) Introduction: Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and manipulate strings [Oracle]. String literals are collection of characters enclosed in double quotation marks. In many programming assignments, you will be required to accept or process alphabetic or alphanumeric data. For this purpose you may use strings to get the required results. The String Class Java provides a built-in String class which provides a number of useful methods which may be used to process strings. Constructing a String Strings can be constructed in a number of ways as below. String s=new String(“COMSATS”); Or String s=”COMSATS” We may also take strings as input from user at runtime. For this purpose we may use next() or nextLine() methods of Scanner class as discussed in the later activities of this lab session. Concatenating Strings Anything added with a string is called string concatenation. For example if we add “abc” with “xyz”, then the result will be “abcxyz”. Similarly if we add “street” with a mu,eric integer 1 then the result will be “street1” as below. “street”+1 will result “street1”. Strings can also be concatenated by using built-in concat() method as below. “string1”.concat(“string2”) CSC103-Fundamentals Fundamentals undamentals 81 String Built-in Methods Strings class has a number of useful methods. Some of them are as below. “string1”.equals(“string2”) returns true if “string1” and “string2” have same value otherwise false “string1”.equalsIgnoreCase(“string2”) returns true if “string1” and “string2” have same value otherwise false ignoring the case “string1”.compareTo(“string2”) Returns o, positive or negative integer value depending on that whether string1 is equal to, greater than or less than string2. “string1”.compareToIgnaoreCase(“string2”) Returns 0, positive or negative integer value depending on that whether string1 is equal to, greater than or less than string2 ignoring case. “string”.length() Returns length of the string. “string”.charAt(index) Returns the character at specified index. “string”.concat(“string2”) Concatenates the two strings. “Pakistan”.substring(0,3) Returns a 3-charcter long substring starting at index 0. “Pakistan”.indexOf(“k”) Returns index of “k” in “Pakistan”, i.e. 2. If the string to find is not present in the string then returns a negative integer. “Pakistan”.lastIndexOf(“a”) Returns last index of “a” in “Pakistan”, i.e. 6 in this example. CSC103-Fundamentals Fundamentals undamentals 82 2) Stage a1 (apply) Lab Activities: Activity 1: Write a Java program to accept two strings from user and check that whether they are same or not. Solution: C. Create a new Java file and type the following code. D. Run the code by pressing F5. You will get the following output. Here is another output if the strings are different. If strings are same but one is given in lowercase and the other in uppercase, then the output will be as below. CSC103-Fundamentals Fundamentals undamentals 83 Activity 2: Rewrite the last code to accept two strings from user and compare with each other ignoring case. Solution: C. Create a new Java file and type the following code. D. Run the code by pressing F5. You will get the following output. Activity 3: Write a java program to accept two strings from user and display the smaller string. Kindly note that smaller does not mean here that it will have less number of characters in it but you need to compare the strings on the basis of ASCII character. For example, “ahsan” is less than “zia” as ASCII code of “a” is less than that of “z”. Solution: C. Create a new Java file and type the following code. D. Run the code by pressing F5. CSC103-Fundamentals Fundamentals undamentals 84 You will get the following output. Activity 4: Write a Java program to accept names of 5 students and sort in ascending order. Solution: C. Create a new Java file and type the following code. D. Run the code by pressing F5. CSC103-Fundamentals Fundamentals undamentals 85 You will get the following output. Activity 5: Write Java program to accept names of 5 students from user in an array. Pass this array to a method. The method will sort the names in descending order. Solution: C. Create a new Java file and type the following code. D. Run the code by pressing F5. You will get the following output. CSC103-Fundamentals Fundamentals undamentals 86 3) Stage v (verify) Home Activities: Activity 1: Write a Java program to accept names and marks of 10 students. Display names of student having maximum marks. Activity 2: Write a Java program to accept names and marks of 10 students. Sort this data according to names in ascending order. Activity 3: Write a Java method to accept marks of a student between 0-100 and return the grade according to the following criteria. 0 - 49 50 – 60 61 – 70 71 – 80 81 – 90 91 – 100 F E D C B A 4) Stage a2 (assess) Assignment: For this student will submit Lab Assignment before the deadline. CSC103-Fundamentals Fundamentals undamentals 87 LAB # 10 Statement Purpose: This lab will give you practical implementation of method overloading and recursion. Activity Outcomes: This lab teaches you the following topics: Methods overloading Recursion Instructor Note: As pre-lab activity, read Chapters 5 and 20 from the book (Introduction to Java Programming, Brief Version-Prentice Hall (2012) By Y. Daniel Liang), and also as given by your theory instructor. CSC103-Fundamentals Fundamentals undamentals 88 1) Stage J (Journey) Introduction: Methods overloading means to define more than one methods having same name but different signatures in the same class. It enables us to use the same method’s name multiple time in the same class. The functionality of each method may be different. It is important to note that the return type of the method has nothing to do with overloading. The return type may be kept same or different but the number or type of parameters must be different to implement methods overloading. Sometimes it may be required that a method should call itself to solve a particular problem. If this happens then this is called recursion. Methods Overloading The important points in methods overloading are as below. 1. 2. 3. 4. All the methods involved in overloading must be defined in the same class. Names of all the methods must be same. Number of parameters should be different. If number of parameters are same then data type of at least on of them should be different from other methods. 5. Names of parameters do no matter in methods overloading 6. Return type of methods may be same or different as return type is also not considered in methods overloading Recursion In recursion, a method calls itself. If a method starts calling itself then a kind of loop starts to happen. You must write some statements to break this loop so recursion stops. 2) Stage a1 (apply) Lab Activities: Activity 1: Write a Java program to have two methods of same name called sum. One of them should accept two integer values and return their sum. The other sum method should accept three integer values and return their sum. CSC103-Fundamentals Fundamentals undamentals 89 Solution: E. Create a new Java file and type the following code. F. Run the code by pressing F5. You will get the following output. Here is the modified to code call the method having three parameters. CSC103-Fundamentals Fundamentals undamentals 90 The output will be as below. Activity 2: Write two methods having name sum. One of them will add two integer values and the other will add two double values. Solution: E. Create a new Java file and type the following code. F. Run the code by pressing F5. CSC103-Fundamentals Fundamentals undamentals 91 You will get the following output. Activity 3: Write two methods having name max. One of them will accept an array of integers and return maximum value. The other will accept an array of strings and return thr string having maximum number of characters in it. Solution: E. Create a new Java file and type the following code. F. Run the code by pressing F5. CSC103-Fundamentals Fundamentals undamentals 92 You will get the following output. Activity 4: Write a method to find factorial of an integer using recursion. Solution: E. Create a new Java file and type the following code. F. Run the code by pressing F5. CSC103-Fundamentals Fundamentals undamentals 93 You will get the following output. Activity 5: Write a Java program to display Fibonacci series by using a recursive method. Solution: E. Create a new Java file and type the following code. F. Run the code by pressing F5. CSC103-Fundamentals Fundamentals undamentals 94 You will get the following output. 3) Stage v (verify) Home Activities: Activity 1: Write the following overloaded methods and use them in a Java program. int multiply(int a, int b) double multiply(double x, double y) float multiply(float a, float b) CSC103-Fundamentals Fundamentals undamentals 95 Activity 2: Write two overloaded methods having name sort. One of them will accept an array of strings and sort them in descending order. The other will accept an array of integer values and will sort them in descending order. Activity 3: Write a recursive method to build tower of Hanoi. 4) Stage a2 (assess) Assignment: For this student will submit Lab Assignment before the deadline. CSC103-Fundamentals Fundamentals undamentals 96 LAB # 11 Statement Purpose: In this lab you will experiment with the Java Input/Output components by implementing two programs that read input from a file and write output to a file. The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, object, localized characters, etc. Activity Outcomes: Student will be able to: 1. 2. 3. 4. Describe the concept of an I/O stream Explain the difference between text files and binary files Save data Read data Instructor Note: Java: An Introduction to Problem Solving and Programming, Savitch, W., 6th Edition (2012), Addison-Wesley CSC103-Fundamentals Fundamentals undamentals 97 1) Stage J (Journey) Introduction The character input and output shown so far has used the pre-defined “standard” streams System.in and System.out. Obviously in many real applications it is necessary to access named files. In many programming languages there is a logical (and practical) distinction made between files that will contain text and those while will be used to hold binary information. Files processed as binary are thought of as sequences of 8- bit bytes, while ones containing text model sequences of characters. Java uses names typically based on the word Stream for binary access, and Reader and Writer for text. So when you read the documentation expect to find two broadly parallel sets of mechanisms, one for each style of access. 2) Stage a1 (apply) Lab Activities: Activity 1: creates InputStreamReader to read standard input stream until the user types a "q". Solution: import java.io.*; public class ReadConsole { public static void main(String args[]) throws IOException { InputStreamReader cin = null; try { cin = new InputStreamReader(System.in); System.out.println("Enter characters, 'q' to quit."); char c; do { c = (char) cin.read(); System.out.print(c); } while(c != 'q'); }finally { if (cin != null) { cin.close(); CSC103-Fundamentals Fundamentals undamentals 98 } } } } Activity 2: Write a java program to demonstrate InputStream and OutputStream Solution: import java.io.*; public class fileStreamTest { public static void main(String args[]) { try { byte bWrite [] = {11,21,3,40,5}; OutputStream os = new FileOutputStream("test.txt"); for(int x = 0; x < bWrite.length ; x++) { os.write( bWrite[x] ); // writes the bytes } os.close(); InputStream is = new FileInputStream("test.txt"); int size = is.available(); for(int i = 0; i < size; i++) { System.out.print((char)is.read() + " "); } is.close(); }catch(IOException e) { System.out.print("Exception"); } } } Activity 3: CSC103-Fundamentals Fundamentals undamentals 99 A java program to show that a method called to read characters, and that it returns the integer -1 at end of file. Solution: import java.io.*; public class InputOP1 { public static void main(String args[]) throws IOException { Reader r = new FileReader("filename"); int c; while ((c = r.read()) != -1) { System.out.printf("Char code %x is \"%<c\"%n", c);} r.close(); } } Activity 3: Write a java program by using list( ) method provided by File object to list down all the files and directories available in a directory. Solution: import java.io.File; public class ReadDir { public static void main(String[] args) { File file = null; String[] paths; try { // create new file object file = new File("/tmp"); // array of files and directory paths = file.list(); // for each name in the path array for(String path:paths) { // prints filename and directory name System.out.println(path); } CSC103-Fundamentals Fundamentals undamentals 100 }catch(Exception e) { // if any error occurs e.printStackTrace(); } } } Activity 4: Write a java program to compare paths of two files? Solution: import java.io.File; public class Main { public static void main(String[] args) { File file1 = new File("C:/File/demo1.txt"); File file2 = new File("C:/java/demo1.txt"); if(file1.compareTo(file2) == 0) { System.out.println("Both paths are same!"); } else { System.out.println("Paths are not same!"); } } } CSC103-Fundamentals Fundamentals undamentals 101 Activity 5: Write a java program to create a new file? Solution: import java.io.File; import java.io.IOException; public class Main { public static void main(String[] args) { try { File file = new File("C:/myfile.txt"); if(file.createNewFile())System.out.println("Success!"); else System.out.println ("Error, file already exists."); } catch(IOException ioe) { ioe.printStackTrace(); } } } Activity 6: Write a java program to create a new file (another way)? Solution: import java.io.IOException; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; CSC103-Fundamentals Fundamentals undamentals 102 import java.util.List; public class JavaApplication1 { public static void main(String[] args) throws IOException { createFileUsingFileClass(); createFileUsingFileOutputStreamClass(); createFileIn_NIO(); } private static void createFileUsingFileClass() throws IOException { File file = new File("c://testFile1.txt"); //Create the file if (file.createNewFile()) { System.out.println("File is created!"); } else { System.out.println("File already exists."); } //Write Content FileWriter writer = new FileWriter(file); writer.write("Test data"); writer.close(); } private static void createFileUsingFileOutputStreamClass() throws IOException { String data = "Test data"; FileOutputStream out = new FileOutputStream("c://testFile2.txt"); out.write(data.getBytes()); out.close(); } private static void createFileIn_NIO() throws IOException { String data = "Test data"; Files.write(Paths.get("c://testFile3.txt"), data.getBytes()); List<String> lines = Arrays.asList("1st line", "2nd line"); Files.write(Paths.get( "file6.txt"), lines, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); } } CSC103-Fundamentals Fundamentals undamentals 103 Activity 7: Write a java program to get last modification date of a file? Solution: import java.io.File; import java.util.Date; public class Main { public static void main(String[] args) { File file = new File("Main.java"); Long lastModified = file.lastModified(); Date date = new Date(lastModified); System.out.println(date); } } Stage v (verify) Home Activities: Activity 1: Write a java program to create a file in a specified directory? Activity 2: Write a java program to check a file exist or not? 3) Stage a2 (assess) Assignment: 1) Write a java program to make a file read-only? 2) Write a java program to rename a file? LAB # 12 Statement Purpose: CSC103-Fundamentals Fundamentals undamentals 104 In this lab you will experiment with the Java Input/Output components by implementing two programs that read input from a file and write output to a file. The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, object, localized characters, etc. Activity Outcomes: Student will be able to: 1) Describe the concept of an I/O stream 2) Explain the difference between text files and binary files 3) Save data 4) Read data Instructor Note: Java: An Introduction to Problem Solving and Programming, Savitch, W., 6th Edition (2012), Addison-Wesley 1) Stage J (Journey) CSC103-Fundamentals Fundamentals undamentals 105 2) Stage a1 (apply) Lab Activities: Activity 1: Write a java program to get a files size in bytes? Solution: import java.io.File; public class Main { public static long getFileSize(String filename) { File file = new File(filename); if (!file.exists() || !file.isFile()) { System.out.println("File doesn\'t exist"); return -1; } return file.length(); } public static void main(String[] args) { long size = getFileSize("c:/java.txt"); System.out.println("Filesize in bytes: " + size); } } Activity 2: Write a java program to get a files size in bytes? Solution: import java.io.File; public class Main { public static long getFileSize(String filename) { File file = new File(filename); if (!file.exists() || !file.isFile()) { System.out.println("File doesn\'t exist"); CSC103-Fundamentals Fundamentals undamentals 106 return -1; } return file.length(); } public static void main(String[] args) { long size = getFileSize("c:/java.txt"); System.out.println("Filesize in bytes: " + size); } } Activity 3: Write a java program to change the last modification time of a file? Solution: import java.io.File; import java.util.Date; public class Main { public static void main(String[] args) throws Exception { File fileToChange = new File ("C:/myjavafile.txt"); fileToChange.createNewFile(); Date filetime = new Date (fileToChange.lastModified()); System.out.println(filetime.toString()); System.out.println (fileToChange.setLastModified (System.currentTimeMillis())); filetime = new Date (fileToChange.lastModified()); System.out.println(filetime.toString()); } } Activity 4: Write a java program to create a temporary file? Solution: import java.io.*; CSC103-Fundamentals Fundamentals undamentals 107 public class Main { public static void main(String[] args) throws Exception { File temp = File.createTempFile ("pattern", ".suffix"); temp.deleteOnExit(); BufferedWriter out = new BufferedWriter (new FileWriter(temp)); out.write("aString"); System.out.println("temporary file created:"); out.close(); } } Activity 5: Write a java program to append a string in an existing file? Solution: import java.io.*; public class Main { public static void main(String[] args) throws Exception { try { BufferedWriter out = new BufferedWriter(new FileWriter("filename")); out.write("aString1\n"); out.close(); out = new BufferedWriter(new FileWriter("filename",true)); out.write("aString2"); out.close(); BufferedReader in = new BufferedReader(new FileReader("filename")); String str; while ((str = in.readLine()) != null) { System.out.println(str); } } in.close(); catch (IOException e) { System.out.println("exception occoured"+ e); CSC103-Fundamentals Fundamentals undamentals 108 } } } 3) Stage v (verify) Home Activities: Activity 1: Write a java program to copy one file into another file? Activity 2: Write a java program to delete a file? 4) Stage a2 (assess) Assignment: 1) Write a java program to read a file? 2) Write a java program to write into a file? LAB # 13 Statement Purpose: An exception is an object that signals the occurrence of an unusual event during the execution of a program. The process of creating this object that is generated an exception is called throwing an exception. CSC103-Fundamentals Fundamentals undamentals 109 Activity Outcomes: 1) Describe the notation of exception handling 2) React correctly when certain exceptions occur 3) Use Java’s exception-handling facilities effectively in classes and programs Instructor Note: Java: An Introduction to Problem Solving and Programming, Savitch, W., 6th Edition (2012), Addison-Wesley 1) Stage J (Journey) Introduction Unit testing can be done in two ways − manual testing and automated testing. CSC103-Fundamentals Fundamentals undamentals 110 Manual Testing 1. Executing a test cases manually without any tool support is known as manual testing. 2. Time-consuming and tedious − Since test cases are executed by human resources, it is very slow and tedious. 3. Huge investment in human resources − As test cases need to be executed manually, more testers are required in manual testing. 4. Less reliable − Manual testing is less reliable, as it has to account for human errors. 5. Non-programmable − No programming can be done to write sophisticated tests to fetch hidden information. Automated Testing 6. Taking tool support and executing the test cases by using an automation tool is known as automation testing. 7. Fast − Automation runs test cases significantly faster than human resources. 8. Less investment in human resources − Test cases are executed using automation tools, so less number of testers are required in automation testing. 9. More reliable − Automation tests are precise and reliable. 10. Programmable − Testers can program sophisticated tests to bring out hidden information. A Unit Test Case is a part of code, which ensures that another part of code (method) works as expected. To achieve the desired results quickly, a test framework is required. JUnit is a perfect unit test framework for Java programming language. A formal written unit test case is characterized by a known input and an expected output, which is worked out before the test is executed. The known input should test a precondition and the expected output should test a post-condition. There must be at least two unit test cases for each requirement − one positive test and one negative test. If a requirement has sub-requirements, each sub-requirement must have at least two test cases as positive and negative. 2) Stage a1 (apply) Lab Activities: Activity 1: Write a java program that catches arithmetic exception. Solution: class Example1 { public static void main(String args[]) { CSC103-Fundamentals Fundamentals undamentals 111 int num1, num2; try { // Try block to handle code that may cause exception num1 = 0; num2 = 62 / num1; System.out.println("Try block message"); } catch (ArithmeticException e) { // This block is to catch divide-by-zero error System.out.println("Error: Don't divide a number by zero"); } System.out.println("After try-catch block in Java."); } } Activity 2: A java program for an array declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception. Solution: import java.io.*; public class Example2{ public static void main(String args[]) { try { int a[] = new int[2]; System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); }} Activity 3: Java program to access the index in an array that is not present in it. Solution: public class Example3{ public static void main(String args[]) { int a[] = new int[2]; try { System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); }finally { a[0] = 6; System.out.println("First element value: " + a[0]); System.out.println("The finally statement is executed"); } } } Activity 4: CSC103-Fundamentals Fundamentals undamentals 112 Java program for multiple try catch blocks. Solution: class Example4{ public static void main(String args[]){ try{ int a[]=new int[7]; a[4]=30/0; System.out.println("First print statement in try block"); } catch(ArithmeticException e){ System.out.println("Warning: ArithmeticException"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Warning: ArrayIndexOutOfBoundsException"); } catch(Exception e){ System.out.println("Warning: Some Other exception"); } System.out.println("Out of try-catch block..."); } } Activity 5: Java program for nested try loops Solution: class Example5{ public static void main(String[] args) { try { int arr[]={5,0,1,2}; try { int x=arr[3]/arr[1]; } catch(ArithmeticException ae){ System.out.println("divide by zero"); } arr[4]=3; } catch(ArrayIndexOutOfBoundsException e) { System.out.println("array index out of bound exception"); } }} 3) Stage v (verify) Home Activities: CSC103-Fundamentals Fundamentals undamentals 113 Activity 1: Create your own exception sub class simply by extending java Exception class. You can define a constructor for your Exception sub class (not compulsory) and you can override the toString() function to display your customized message on catch. 4) Stage a2 (assess) Assignment: Write a statement that will throw an exception of type Exception if the value of the String variable named status is “bad”. The string recovered by getMessage should be “Exception thrown: Bad Status.” You need not write the try block and catch block. LAB # 14 Statement Purpose: One of the secrets of the low latency is that each implementation can generate a custom built fix engine based exactly on the schema it requires. Activity Outcomes: 1) Describe the notation of exception handling 2) React correctly when certain exceptions occur 3) Use Java’s exception-handling facilities effectively in classes and programs Instructor Note: CSC103-Fundamentals Fundamentals undamentals 114 Java: An Introduction to Problem Solving and Programming, Savitch, W., 6th Edition (2012), Addison-Wesley 1) 2) Stage J (Journey) Stage a1 (apply) Lab Activities: Activity 1: Java program that extends java Exception class. Solution: class MyException1 extends Exception1 { private int ex; CSC103-Fundamentals Fundamentals undamentals 115 MyException1(int a) { ex=a; } public String toString() { return "MyException1[" + ex +"] is less than zero"; } } class Test { static void sum(int a,int b) throws MyException1 { if(a<0) { throw new MyException1(a); } else { System.out.println(a+b); } } public static void main(String[] args) { try { sum(-10, 10); } catch(MyException1 me) { System.out.println(me); } } } Activity 2: NOTE: If Super class method throws an exception, then Subclass overriden method can throw the same exception or no exception, but must not throw parent exception of the exception thrown by Super class method. It means, if Super class method throws object of NullPointerException class, then Subclass method can either throw same exception, or can throw no exception, but it can never throw object of Exception class (parent of NullPointerException class). Subclass overridden method with exception. Solution: import java.io.*; class Super { void show() throws Exception { System.out.println("parent class"); } } public class Sub extends Super { void show() throws Exception //Correct { System.out.println("child class"); } CSC103-Fundamentals Fundamentals undamentals 116 public static void main(String[] args) { try { Super s=new Sub(); s.show(); } catch(Exception e){} } } Activity 3: Subclass overridden method with no exception. Solution: import java.io.*; class Super { void show() throws Exception { System.out.println("parent class"); } } public class Sub extends Super { void show() //Correct { System.out.println("child class"); } public static void main(String[] args) { try { Super s=new Sub(); s.show(); } catch(Exception e){} } } Activity 4: Subclass overridden method with parent Exception. Solution: import java.io.*; class Super { void show() throws ArithmeticException { System.out.println("parent class"); } public class Sub extends Super { void show() throws Exception { System.out.println("child class"); } } //Cmpile time Error public static void main(String[] args) { try { Super s=new Sub(); s.show(); } CSC103-Fundamentals Fundamentals undamentals 117 catch(Exception e){} } } Activity 5: Using ObjectInputStream to Read from a File Solution: public class BinaryInput { public static void main(String[] args) { String fileName = "numbers.dat"; try { ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(fileName)); System.out.println("Reading the nonnegative integers"); System.out.println("in the file " + fileName); int anInteger = inputStream.(readInt); while (anInteger >= 0) { System.out.ptintln(anInteger); anInteger = inputStream.readInt(); } System.out.println("End of reading from file."); inputStream.close(); } catch(FileNotFoundException e) { System.out.println("Problem opening the file " + fileName); } catch(EOFException e) { System.out.println("Problem reading the file " + fileName); System.out.println("Reached end of the file."); } catch(IOException e) { System.out.println("Problem reading the file " + fileName); } }} 3) Stage v (verify) Home Activities: Activity 1: Write java code to create an input stream of type ObjectInputStream that is named from File and is connected to a file named stuff.data. CSC103-Fundamentals Fundamentals undamentals 118 Activity 2: Write a Java program that asks the user for the name of a binary file and writes the first data item in that file to the screen. Assume that the first data item is a string that was written to the file with method WriteUTF. 4) Stage a2 (assess) Assignment: Write a complete Java program that asks the user for a file name, tests whether the file exists, and if the file does exist, ask the user whether or not it should be deleted and then does as the user requests. CSC103-Fundamentals Fundamentals undamentals 119