Tutorial 1 Topics Java Syntax o Variables o Fundamental Data Types o Arithmetic Conversions Control Structure Forte Tutorial Tutorial Problems Design Exercises Java Syntax Variables A variable is a chunk of computer memory that contains a value. The name of a variable is an identifier that refers to that variable. Java variable names: are case sensitive begin with a letter, an underscore (_) or a $ sign can contain letters, numbers and underscores Java keywords can't be used as variable names A variable's data type determines the size of the chunk of memory occupied by the variable and the way the bits in this chunk are interpreted. If the data type of a variable is an int, the variable holds a 32- bit signed integer. If the data type of a variable is a double, the variable holds a 64-bit signed floating point number. When you tell the Java compiler the type of a variable, you are said to declare the variable. Examples of variable declarations are: int counter; double myDouble; Storing a value in a variable is called variable assignment. Examples of variable assignments are: counter = 5; myDouble = 4.56; You can initialize a variable in the same statement in which the variable is declared. Example: int i = 6; char x = 'a'; Fundamental Data Types In Java, every piece of data in a program is an object except for variables of the fundamental (or primitive) data types. The primitive data types are: boolean (true or false) byte char short int long float double A note about characters in Java: Every character in Java has a corresponding integer representation. The set of characters a computer uses and the corresponding integer representations for those characters is called that computer's character set. You can indicate a character value in a program by simply enclosing that character in single quotes as with 'A'. You can determine the integer equivalent of a character by casting it to an integer, as with (int) 'A'.For example, the statement: System.out.println("The character " + 'a' + " has a value of " + ((int) 'a')); prints the char a and its integer value as follows: The character a has the value of 97 The integer 97 is the character's numerical representation in the computer. Java uses the ISO (International Standards Organization) Unicode character set in which 97 represents the lowercase letter 'a'. Many computers today use the ASCII (American Standard Code for Information Interchange) character set. The ASCII character set is a subset of the Unicode character set. ASCII characters and their integer values can be found in your book's Appendix. There is a better way to find the integer value of a character that we cover later in 1.00. Arithmetic Conversions Java converts the value of the "lower" type to that of the "higher" type, and then performs the required operation, producing a value of the "higher" type. If one of the operands is a double, Java converts the other(s) to a double Otherwise, if one of the operands is a float, it converts the other(s) to a float. Otherwise, if one of the operands is a long, it converts the other(s) to a long ... and so on. You can use casts to force the conversion of one data type to another. The use of a cast overrides the standard rules for type conversions. The cast operator does not change the value stored in the variable. Hierarchy of Data Types double float long int char short byte Data Type double float long int char short byte Allowed Promotions None double float,double long,float,double int,long,float,double int, long,float,double short,int,long,float,double Example: byte b_val; char c_val; short s_val; int i_val, x; float f_val; double d_val; long l_val; Expression c_val * i_val f_val - 7.3 d_val + c_val s_val - l_val s_val + 7 s_val - 7.0 7 + 7.0 (double)i_val/x Result Type int double double long int int double double double Applets vs. Applications There are two types of Java programs: - Applets, which are programs that can run within web browsers, - Applications, which are stand-alone Java programs. For the problem sets, you'll only be writing Java applications. As seen in class, all Java programs contain one or more class definitions, each of which may contain various method definitions. In particular, every application must contain a class definition that defines a method named main. When you start a Java program, the Java virtual machine performs the computations specified in the main method. Java Application Example: Let's write a Java application that adds three integers. Step 1: Define the class: public class Demonstrate { ........... } The public keyword indicates that this class is accessible by any other class The class keyword indicates that a class is about to be defined. This class has to be saved in a file called Demonstrate.java Step 2: Write main: public class Demonstrate { public static void main (String args[]) { // declare the variables int first = 1; int second = 2; int third = 3; // add the variables int total = first + second + third; // output the total System.out.println("The total is " + total); System.exit(0);} } The public keyword indicates that this function is accessible by any other method. The static keyword indicates that the main method is a class method, not an instance method. The void keyword indicates that this method returns no value. Step 3: Compile, debug and run Throughout this course, you will be using the Forte IDE to develop your code. Therefore, it's unlikely that you will be using the javac command. However, the javac command can still be useful in the event that you have problems with Forte: To compile, type javac Demonstrate.java To run, type java Demonstrate Basic Control Structures There are two basic control structures Conditional statements: if … else… Iteration: while loop, do … while loop, and for loop Conditional Statement The general form of an if statement is: if(expression) statement1 else statement2 next statement If the expression is true, statement1 gets executed. If it is false, statement2 gets executed. For example: if (grade >= 90) System.out.println("Yeah I got an A!"); else System.out.println("So I got a B!"); System.out.println (“Always printed”); Iteration Structure Sometimes, you need to repeat the same statements multiple times. In that case, you need to use the iteration structure. There are two kinds of iteration structure: indeterminate loops and determinate loops. In an indeterminate loop, you don’t know how many times a loop will be executed. Therefore, you need the help of a Boolean expression: while (expression) { statements; …………………. } The statements will be executed repeatedly as long as the expression is true. Here is an example: Grade = 0; while (Grade <= 90) { System.out.println("Work harder!"); Grade += 10; } System.out.println("Great job!"); Here, the message "Work harder!" is printed 10 times while your grade progresses from 0 to 90. Only then will you see the message “Great job!”. A variant of the while loop is the do-while structure. Instead of testing the expression at the beginning of the loop, a do-while structure tests the expression at the end of the loop. The general form of the do-while structure is: do statement while (expression); next statement Here is the do-while flow chart for the above example. If you want to control how many times the statements will be executed (“determinate loop”), you need to use the for loop. In a for loop, you set up a counter which is updated after every iteration. The loop will exit when the counter reaches its limit. Here is an example: for(grade = 0; grade <= 90; grade+=10) { System.out.println("Work harder!"); } System.out.println("Good job!"); Here, grade is initialized to 0. At every iteration, we add 10 points to the grade. When it reaches 90, the loop terminates and control is passed to the next statement. As you can see from the flow chart below, the for loop does the same thing as the while loop. Forte Tutorial This short exercise will guide you in details through the process of creating a very simple Java application. You will build a simple application that will print a message on your screen. Step 1. Creating a Project In the IDE, you always work in a project whether it is the default IDE project or a project that you have created. Organize your work in the IDE into projects allows you to: Compile all files in the project in one command. Designate a main project class so you can run your project without having to find the main class. Create unique configurations (such as mounted filesystems, compiler types) for each type of project. You don't have to worry about configuration options for the moment. Use the Project tab in the explorer to only work with files that have been added to the current project. The project tab is always labeled with the name of the current project. Choose Project -> Project Manager from the main Window. In the Project Manager toolbox, choose new and name your project 'HelloWorld' and click OK. The window state, project settings and the project tab in the explorer are all updated. Clicking on the 'Project HelloWorld' tab in the explorer will show you all the files that have been added to your project. For the moment, you should only see the root Project node (named 'Project HelloWorld') with no files attached to it. Step 2. Adding a new File to the Project Click the 'HelloWorld' Project tab in the explorer and right click on the root Project node. Choose Add New from the contextual menu. A template wizard should pop up. We want to create a file that will contain the main class. Go to the Classes folder in the Template Chooser dialog box. You should start a new file from scratch by choosing Empty. Click the Next button. In the Name Textbox, enter HelloWorld (without spaces). This will be the filename and the classname of the file you are creating. Leave the package as <default package>. Click Finish. The file you have created should appear in both the FileSystems and the Project tab. Step 3. Editing the 'HelloWorld' class Now that you have created a file, you need to edit it and add the code to allow the application to print on the screen a 'Hello World' message. To edit the 'HelloWorld' file, double click on it. The Source Editor will open (it may already be open). In the Source Editor, type the following code lines: public static void main(String args[]){ System.out.println("Hello World"); } public class HelloWorld{ } The application is complete. All you need to do now is build and run your project. Step 4. Building and running the Project Choose Project -> Build Project from the menu bar. All classes are compiled (You can compile only uncompiled and out-of-date classes by choosing Project -> Compile Project). You can also use Build->Build to compile the file that is selected. Note that if you have several files, the Build->Build will only compile the selected file and not all the files contained in the project. If the compilation is successful, 'Finished Project HelloWorld' should appear in the main Window. If there are errors in the compilation, the error messages are displayed in the output window. You can double-click on an error-message to jump on the line of code that generated this error. Once the build is complete, you can run the application. Run 'HelloWorld' by choosing Project ->Execute Project. Since it is the first time you are running this project, you get a dialog box that asks you to select the main class. Select 'HelloWorld' and press OK. The IDE is switched to the 'Running' Workspace. You can see the program's output in the Output Window. Step 5. Debugging and stepping through the code Using the debugger, you can locate and correct the bugs in your program. Go back to the editor workspace by clicking the Editing tab in the main window, and select the 'HelloWorld' class. Put the cursor in the Source Editor. Add the following lines of code to your main method after the System.out.println("Hello World"); statement (we have deliberately introduced an error on line 4 and 5; there is no variable called number1): int num1, num2, sum = 0; num1 = 1; num2 = 2; sum = number1 + num2; System.out.println("The sum of " +number1+ " and "+num2+" is "+ sum); Choose Project -> Build Project from the menu bar. Since we know that we have errors in our code, 'Errors compiling Project HelloWorld' should appear in the main window. The error messages are displayed in the output window in red. Click on the first error-message to jump on the line of code that generated this error (the line of code should be highlighted in green). Modify the line of code from : number1 = 1; to: num1 = 1; Click on the second error-message (not in red but will turn into red) to jump on the line of code that generated this error. Modify the line of code from: sum=number1+num2; to: sum=num1+num2; Compile the Project once again. If you have successfully removed the errors, you should get a 'Finished Project HelloWorld' message. Run 'HelloWorld' by choosing Project ->Execute Project. The output window shows you the two statements: Hello World The sum of 1 and 2 is 3 What if you wanted to go step by step into your program instead of having the program running from start to end without stopping? Or what if you wanted to monitor the values of individual variables during execution? You can do that using the Debugger. All you have to do is specify the breakpoints where your program will pause and the variables you want to watch. Try the following: Go back to the editor workspace (click the Editing tab in the main window) and put the cursor before the following line of code: sum = num1 + num2; Choose Debug->Add Breakpoint. Click Ok in the Add Breakpoint dialog box. The line is highlighted to indicate that the breakpoint was set Add a second breakpoint on the following line of code: System.out.println("The sum of " + num1 + " and " + num2 + " is "+ sum); Next choose Debug -> Start. A debugging session starts and the program runs until it reaches the breakpoint (highlighted in blue). The IDE switches to the debugging workspace which shows: The Debugger Window: This window is used to manipulate breakpoints and watch program variables and the state of threads. These are each displayed under a separate tab (in case it doesn't appear, go to View->Debugger Window). Messages from the Debugger in the output window. The Output window is split vertically, the left panel displaying the output of the debugged program and the right panel showing the messages from the debugger itself. The Source Editor: which shows you where you are Currently, under the Breakpoints tab in the Debugger Window, you will see the breakpoints we have just set, listed by source name and line number. The debugger should have executed all the statements before the first breakpoint (which is highlighted in blue). The output statement: System.out.println("Hello World"); should have already been executed and you should see in the Output Window the "Hello World" message. Under the Watches tab, you will see the sum variable you are monitoring. The value of sum is still 0 because the sum = num1 + num2; statement has not been executed yet. Choose Debug ->Continue. You should see the "The sum of 1 and 2 is 3" message printed in the output window, and that should end the debugging session. You can select the Editing tab to return to the Explorer to work on this or another program. Tutorial Problems 1. What do the following expressions evaluate to? Specify values and types of evaluation result. 3 / 2; 3 / 2.0; 3 / 2.0F; int i = 2; 3 / (float) i; 2. Write the results of the following expressions. 1 % 3; 7 % 3; 3. What are the values of i and d after the following piece of code is executed? int i =0, d; d = i++; 4. What does the following piece of code output? for (int i = 1; i < 4; i++) { for (int j = 1; j < 3; j++) { System.out.println("i = " + i + " + j = " + j + "\n" ); } } 5. Class Box is defined as follows in Box.java: public class Box { private double width; private double height; private double length; // Constructor Box(double w, double h, double l){ width = w; height = h; length = l; } double volume () { return width * height * length; } } The class TestBox is defined in TestBox.java as follows: } public class TestBox { public static void main(String args[]){ Box b1 = new Box (1, 2, 3); Box b2; b2 = new Box (2, 2, 5); System.out.println ("b1: " + b1.volume()); System.out.println ("b2: " + b2.volume()); } What is the output when you run TestBox? 6. do-while loop: Write a piece of code that uses a do - while loop to output the even integers from 2 to 100: int counter = 2; do { } while (____________________); Design Exercises Using conditional statement and iteration control structure to output all the odd integers from 1 to 101 that are not dividable by either 3 or 5. Your program should output integers such as 1, 7, 11, 13, 19...