690 likes | 853 Views
Chapter 2 Primitve Data Types, Input, Output, and Assignment. Go. Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java Program Sect 3 - Three Types of Java Programs Sect 4 - Data Types and Basic Input and Output Sect 5 - Calling Methods
E N D
Chapter 2Primitve Data Types, Input, Output, and Assignment Go Sect 1 - Steps for Creating and Running a Java Program Sect 2 - Framework of a Simple Java Program Sect 3 - Three Types of Java Programs Sect 4 - Data Types and Basic Input and Output Sect 5 - Calling Methods Sect 6 - Syntax and Compile-Time Errors Sect 7 - Graphics and GUI Programs Go Go Go Go Go Go
Section 1The Steps for Creating & Running a Java Program A program is a sequence of instructions that perform a task. 2
Fastest Growing Programming Language Here are some reasons that Java is the fastest growing programming language: • It is a modern object-oriented language. • It is secure. Viruses can’t be spread with Java programs. • It is robust. This means that Java programs can respond efficiently to a variety of situations while a program is running if the correct precautions are taken when writing the code. • It supports threads. This means two or more parts (threads) of a Java program can be running at the same time. • It supports the development of programs that do not overwrite memory. In other words, if one program takes up a portion of RAM memory while it is running and a second program is started. The second program cannot be loaded into the memory taken up by the first program if there is not enough RAM memory. 3
Steps for Creating & Running a Program Write the source code in a .java file Compile the source code into byte code creating a .class file JVM interprets the byte code into machine language 1s and 0s and the computer then executes the instructions 4
Source Code is Written in a .java File Step1. When a programmer writes Java code, it is stored in a source code file that has a .java extension like RobotMan.java. The source code file is what the programmer compiles and runs to see the output of a program. We will write our Java progams in the IDE software called Eclipse. IDE stands for Integrated Development Environment.An IDE lets you write, compile, and execute programs. Source code can be typed in any simple text editor, but we will use Eclipse, which is both a text editor and a compiler. Eclipse is a nice Java editor and compiler because it will point out syntax errors when java code is typed incorrectly. A program will not run until all syntax errors are removed. 5
Source Code is Compiled to Byte Code Step 2. An IDE (Integrated Development Environment) like Eclipse, has a built in compiler that translates the Java source code into Java byte code. When source code is compiled into byte code, the byte code is stored in a file that has the same name as the source code file but with a .class extension. It is not a text file and you cannot open it! For example, the source code file RobotMan.java will be compiled into a byte code file named RobotMan.class. The file is created during the compiling process, however, Eclipse sometimes translates .java files into .class files behind the scenes before you ever compile them. You can see these files in your package folders if you open your workspace folder on your hard drive. 6
Byte Code is Interpreted to Machine Code Step 3. The JVM (Java Virtual Machine) must interpret the byte code into machine language. Interpret basically means to translate. The JVM is software that acts like hardware. That is why it is called a virtual machine. Java bytecodes are translated on the fly to 1s and 0s instead of being stored in an executable file, which some languages do. The main advantage of an interpreter is that it will run on any computer and there are JVMs for Apple and Windows machines. This makes the code portable from one platform to another. Interpreting can be slow, but software improvements are always being made to speed up this process. Every kind of computer, whether it is an Apple, Windows, or Unix machine, has an operating system that contains a JVM software component. The JVM was automatically installed when your computer’s system software was installed and updates to the JVM may be contained in any system software updates you install now or in the future. 7
What are Applets? Applets are small Java programs that are embedded in web pages. When you load a web page that has a game in it, the game is an applet. More specifically, the applet is usually a jar file that contains the byte code for all the .java files that are needed for the game. A jar file is like a zip file, where a number of files are compressed into one file. An HTML web page can contain a special kind of tag called an Applet tag. That tag tells the web page that the byte code is stored in a jar file with a specific name. The browser software, like FireFox, Chrome, Camino, or Safari will then use its built-in JVM interpreter to translate the byte code into machine language 1s and 0s. 8
Just-in-Time Compilation by the JVM Some JVMs support just-in-time compilation (JIT).JITs will translate byte code instructions the first time they are encountered into machine language code and that code is saved so that the next time that code is encountered it can be executed without being re-interpreted. This can speed up the interpreting of the byte code of a program so it will run faster. 9
Machine Language Code is Executed Step 4. Finally, the machine language code (patterns of 1s and 0s), those instructions that the computer understands at the lowest level, are executed. This allows the program to appear in its runnable form, either in a console window, an applet window, or a GUI (Graphical User Interface) window. Again the overall process is …. 10
Section 2Framework of a Simple Java Program • package declaration • import statements • class declaration line • main method 11
Framework of a Simple Java Program The Framework (in order) of a simple console or standalone program: • package declaration for the file listed first (where it is stored) • followed by import statements (if any) • class declaration line • main method package ch03; import java.util.Scanner; publicclass DistanceCalculator { // opening curly brace for the DistanceCalculator class publicstaticvoid main(String args[ ]) { // opening curly brace for main method // code for program goes inside these curly braces } // ending curly brace for main method } // ending curly brace for the DistanceCalculator class All Java console and JFrame (standalone) programs have this framework. The framework for applets is different and you will become familiar with it later. Sample Skeleton Program Note: curly braces always appear in pairs. 12
Classes in Java A Java program can use more than one class file (a .java file). In fact, it may be made up of many .java files. And most of the time, every .java source code file in a Java program contains only one class. However, it is possible to have more than one class in a .java file, but this is usually done in more advanced programming projects where the code is more complicated and there is a reason for doing it. So assume that every .java file contains only one class, but a java program can use one or more .java files. A class is a module of code that can stand alone by itself and if made “public” other files can “see it” and “access parts of it”. Eclipse is a nice IDE for organizing Java files so that classes are accessible to each other if they are in the same package folder or if an appropriate import statement is used to direct Eclipse to where a package is located. Eclipse manages this behind the scenes automatically and lets you know if something is “unorganized”, so you can fix it. 13
Declaring Classes in a File A class is declared with a line like: public class RobotMan and has a set of curly braces that go with it { and }. In Java, a class like RobotMan must be stored in a file named RobotMan.java. If they don’t match, then Eclipse or any other IDE will flag it with an error and it must be corrected before the file is used in a program. Eclipse has short cuts to renaming the file (compilation unit) or the class if necessary. You’ll learn about that soon. Simple Java programs can be designed so that they contain just one class. We will now look at some examples. 14
Three Types of Java Programs There are basically three types of Java programs that a programmer can make: • A console text output program. • A standalone graphics or GUI program that can be displayed in a standard window frame. • An applet graphics or GUI program that is embedded in a web page. 16
Console Text Output Programs When there is only one file in a Java Program, we sometimes refer to that file as a “Driver file”, because it is the file that makes the program run. If a program has more than one file, then one of the files is a driver file. The driver file’s job is always to initiate the program to begin the compiling and running process. Some Java programs, like RobotMan, are displayed only in a console window, because they show only text output. You will learn how to do more than draw things with text characters in a console window. Some programs may make mathematical calculations and display them. 17
Graphics & GUI Programs Besides console text programs, you can have applet or standalone programs that contain graphics or GUI components: • GUI components are elements in a program like text fields, buttons, labels, text areas, or menus. • Graphics are lines, and curves, and pretty much anything that can be drawn. So you can have: • A web applet program with GUI components. • A web applet program with graphics. • A standalone program with GUI components. • A standalone program with graphics. • A web applet or standalone program that has both GUI components and graphics. 18
Applet GUI Output Programs Because Java programs run inside a Virtual Machine, it is possible to limit their capabilities. What this means is that some other programmer can’t inject a virus into the code you have written for an applet program.Therefore, everybody doesn’t have to worry about a Java applet infecting their computers with a virus that will erase files on their hard drive or steal sensitive information. Java appletsaresmall Java programs downloaded from web pages thatrun in a Web browser.A JVM is incorporated into every browser, so the applet can be interpreted, executed and displayed inside the browser.Any game you have played online is more than likely a Java applet. Both applet and standalone programs can have GUI components. 19 A GUI program with fields, buttons, labels, and a text area.
Applet or Standalone Graphics Output Programs Graphics program can contain lines, arcs, ovals, rounded-rectangles, etc. and they can be animated. GUI or graphics programs pretty much look the same whether they are in an applet or standalone program. 20
Section 4Data Types and the Basicsof Input and Output In this section, you will learn some very important information about: print and println Statements Variables Simple data types The assignment operator = How to declare and construct a Scanner object so you can read input from the keyboard The new operator 21
Java Is Hot Source Code package ch01; publicclass JavaIsHot { publicstaticvoid main(String args[ ]) { System.out.println( " d "); System.out.println( " o l "); System.out.println( " l r "); System.out.println( " l o "); System.out.println( " e w "); System.out.println( " H "); System.out.println( " xxxxxxxxxxxxxxxxx "); System.out.println( " x x x "); System.out.println( " x Java x x "); System.out.println( " x xxxx "); System.out.println( " x is Hot! x "); System.out.println( " x x "); System.out.println( " xxxxxxxxxxxxxx "); } // end of main method } // end of JavaIsHot class System.out.println statements are used to print text to the console output window. 22
print and println Statements Output to a console text window in Java is accomplished through the use of print and println (pronounced print-line) statements. print and println are two operations (or as we say in Java) … methods that can be called. These operations output text information to the console window in Eclipse. We call methods when we want to accomplish some operation or task. 23
print and println Statements Here are lines of code that call the two methodsprintandprintln: • System.out.print(“Hello World”); • System.out.println(“Hello World”); Think of methods as operations, but we always refer to them as methods in Java. Some other languages refer to them as functions or procedures. When we say we are “calling a method”, what we mean is that we are executing an operation! 24
print and println Statements You may be wondering what the difference between the two methods print and println are. print will display everything on one line but not start a new line for anything else that will be printed by the next print or println statement.println will display everything on one line and then start a new line of output for the output of any other print or println statement. Here is an example: System.out.print(“Hello World! ”); System.out.print(“How are you doing? ”); System.out.print(“I am doing fine.”); (Note the extra spaces at the end of the first two print statements or the sentences would jam up together in output) The output in the console window is all on one line: Hello World! How are you doing? I am doing fine. 25
print and println Statements Again … print will display everything on one line but not start a new line of output.println will display everything on one line and then start a new line of output. Consider these three lines of code: System.out. print(“Hello World! ”); System.out. println(“How are you doing?”); System.out. println(“I am doing fine.”); The output is on two lines in the console window: Hello World! How are you doing? I am doing fine. 26
print Statements and Syntax Errors So when we use the line of code: System.out.print(“Hello World”); We are calling the printmethod. Printing to a console window requires that we place System.out. prior to the word print. Please notice the periods “.” (method selector operators) that separate the words System, out, and print. Also, notice that the first S of System is capitalized (upper case). The reason is System is the name of a class. Also, notice that after the word print there are parentheses that include in double quotes the information that we want to display to the screen and the entire line of code ends in a semicolon. All of this is required and must be typed correctly or you will get a syntax error. Programs with syntax errors won’t run! 27
Semicolons End Most Java Statements • A Semicolon (;) marks the end of most Java statements.A statement is a “sentence” in a program. Examples: • System.out.println(“Hello World!”); • num1 = reader.nextInt(); • sum = num1 + num2; Some Java lines do not end in a semicolon. You will learn which ones don’t as you are introduced to other coding structures. 28
Using Variables to Store Values A variablenames a memory address (location) in RAM memory where a value can be stored. The variable is considered to be a nickname for the memory address. The memory address of a variable may be some unusual combination of 1s or 0s or a hexadecimal number, so its great that we can decide on the name of variables. We do this when we declare them. We can think of a variable as a small box that holds a value. X Y name an int variable a double variable a string variable 29
Simple Java Data Types In Java, we have different kinds of data types. Here you will learn three of them. We can store each of the three types of data values in different kinds of variables. We can have … • int variables that can holdintegers (type int) • double variables that can hold real numbers or what we refer to also as floating-point numbers (type double) • String variables that refer to an object that can hold a string of characters, in other words, a bunch of characters that make up a word (type String) The data types int and doubleare simple numeric data types and we store those kind of values in simple variables that are not considered object variables. However, Strings are objects and a String value must be stored in an object variable. Let’s look at how we do that with the assignment operator. 30
The Assignment Operator The assignment operator is the = character and you can initialize variables to literal numeric or string values in one line of code. So to store a value in a variable, we use the assignment operator. Here is how to declare the different kinds of variables and store values in them or as we like to say initialize them: int x = 129; // x is the int variable and 129 is being stored. double y = 3.14159; // y is the double variable and π is stored. String name = “Java”; In the last line of code, name is the String variable and the word “Java” is being stored. Notice the double quotes around Java since we are storing a literal String value Don’t place double quotes when you store numbers. 31
Visualizing Simple and Object Variables simple variables object variables object variables, like String or Scanner variables, can send messages to objects, but simple variables can’t. 32
Numeric Variables A numericvariablenames a memory address (location) in RAM memory where a number can be stored. It is considered to be a nickname for the memory address. Numeric variables are of type int or double. When we use the line of code: double celsius; then enough RAM memory is allocated so that a floating-point value can be stored in celsius. Java does this automatically for you! A double variable gets twice as much memory as an int variable. Thus, the data type was named double. 33
Important Facts About Variables Important points to remember about variables: • A variable’s value may change during a program,but its name remains constant. • A variable’s type defines what kind of values can be stored in RAM.The type of the variable cannot be changed while a program is running. Remember when we say type we are referring to int, double, boolean, String, or other data types. 34
Java’s Mathematical Operators Java basically has 5 mathematical operators. Addition is represented by the + sign. Subtraction is represented by the - sign. Multiplication is represented by the * sign. Division is represented by the / sign. Mod is represented by the % sign. Mod gives the remainder of int division. (You’ll be amazed at how much you will use mod) In the Convert.java program, the line of code: celsius = ( fahrenheit - 32.0 ) * 5.0 / 9.0; uses three of the above mathematical operators. You’ll see the code for the program in a few of slides. 35
We also use the assignment operator when creating objects (constructing objects) so an object variable can refer to them. If we want to receive input from the keyboard during a program,then we need to construct a Scanner object first. This allows the user to enter numbers or string values into a program. To do this we need to import Java’s Scanner class with the line: import java.util.Scanner;// goes above the class declaration line Next, inside the main method, we need to construct the Scanner object with the line: Scanner reader = newScanner(System.in); We need to use System.in as the parameter because this indicates the keyboard, which is the default input device for Java. Note: Scanner is a class so the S is capitalized. Declaring and Using Scanner Objects 36
General Form for Constructing Objects • In programming, the process of constructing an object is calledinstantiation. • In general, constructing or instantiating and object takes the general form: <Name of Class> <variable> = new<Name of Class> (<parameters>); You can see that the line of code below follows this form: Scannerreader = newScanner (System.in); You can think of reader as something that is “scanning the keyboard waiting for input”. 37
In the line of code : Scanner reader = newScanner(System.in); the name of the class Scanner is used twice. The first part of the line: Scanner reader declares reader to be an object variable of type Scanner. We need to do this or reader can’t refer to the Scanner object we construct. The second part of the line: new Scanner(System.in); constructs the Scanner object and “attaches it” to the keyboard. The word newis the new operator that we use to construct things. The assignment operator makes reader refer to the Scanner object. Constructing a Scanner Object with new 38
More About Reading Input from the Keyboard Note: the print statements “prompt” the user to enter data, otherwise he or she wouldn’t know the computer is waiting for input! Assume the following lines of code appear in the main method of a program. Scannerreader = newScanner (System.in); System.out.print(“Enter your name and press return: ”); String name = reader.nextLine(); System.out.print(“Enter your age and press return: ”); int age = reader.nextInt(); System.out.print(“Enter your gpa and press return: ”); double gpa = reader.nextDouble(); Notice when we prompt the user, we use a print statement NOT a println statement. We can receive different kinds of input using reader. We use the object variable readerto “call the method nextLine()to receive a String value from the keyboard. We use reader to “call the methodnextInt() to receive an integer and we use reader to “call the methodnextDouble() to receive a floating-point value from the keyboard. 39
Echoing the Input from the Keyboard We can now “echo the input” (print the information back to the screen that was entered) by using some println statements. In each line, we will print a literal string(something in double quotes) and the value contained in a variable. We use a plus sign to concatenatethe literal string value and the value stored in the variable together to make a larger string that is then printed. System.out.println(“Your name is: ” + name); System.out.println(“Your age is: ” + age); System.out.println(“Your gpa is: ” + gpa); Notice that there are no double quotes around the variables name, age, and gpa. 40
Algorithm for Converting Temperatures If we wanted to write the code for a program that would convert Fahrenheit temperatures to Celsius, it would be good to stop and develop an algorithm. An algorithm is a step by step procedure for solving a problem. This helps our code to be more efficient and we save a lot of time, because we consider all that needs to be done … NOT just the mathematical formula needed to convert the temperature. Any suggestions? 41
Algorithm for Converting Temperatures Consider this algorithm: • Prompt the user to enter a Fahrenheit temperature. • Read the value from the keyboard and store it in a variable. • Use the value stored in the variable in an assignment statement that applies the correct mathematical formula in code form. • Store the value calculated in a second variable. • Output the converted value to the screen. 42
package ch02; • import java.util.Scanner; • publicclass Convert • { • publicstaticvoid main(String args[]) • { • Scanner reader = new Scanner(System.in); • double fahrenheit; • double celsius; • // prompt the user to enter a value from the keyboard when the program runs. • System.out.print("Enter degrees Fahrenheit and press return: "); • // read the value from the keybaord and store it in the variable fahrenheit. • fahrenheit = reader.nextDouble(); • // calculate the equivalent celsius value and store it in the variable celsius • celsius = (fahrenheit - 32.0) * 5.0 / 9.0; • // print out the following string of characters to the terminal window. • System.out.print("The equivalent in Celsius is "); • // print out the value stored in the variable celsius to the terminal window. • System.out.println(celsius); • } • } • Note the key Scanner lines identified by the red arrows. The Convert.java Program 43
More about Import Statements In the Convert.java code you saw that the first line after the package declaration was an import statement: import java.util.Scanner; This tells the compiler where to find a class that will be used during the program. The class may be either in a Java library file or another file you have in a folder. The import statement contains the path name of where to find the class. The import statement tells us that the Scanner class is found in a sub-package folder named util that is in the java package folder. Now you know enough that you can finish the second half of the Convert.java program! 44
Section 5Calling Methods In this section, you will learn some very important information about: • Method Calls and Parameters • Concatenation • Readability of Code 45
Method Calls with Parameters Consider the following line of code: System.out.println(“Hello World!”); • System is a class and outis an object of that class that knows how to display or print characters in a console or terminal window. • printlnis the name of the method (operation) being executed. (Another way to say it is we are “sending the message println to the object represented by System.out”.) • The item inside the parentheses “Hello World”is the parameter of what needs to be printed. Here the parameter is a string (string of characters) that make up the words “Hello World”. Notice they appear in quotation marks. This tells Java to print to the screen the literal string value “Hello World”. The parameter could be a variable that contains a value instead of a literal string value in double quotes. 46
General Rule of Method Calls The general form for calling methods is: <name of object> . <name of method>(<parameters>) A message may require zero, one, or multiple parameters. Here are some examples: • To print a blank line, we can use System.out.println(); without any parameters in the ( ). • To print “Hello World”, we need only one parameter the literal string value “Hello World” in the parenthesis … System.out.println(“Hello World!”); • To print “Hello World. Java Rules”, we still need only one parameter but the parameter may be the concatenation of two literal string values as in … System.out.println(“Hello World!” + “Java Rules!”);Notice thatwe concatenate two literal strings together using a + symbol. • To call a method named calculateArea with two parameters length and width, we use the code ... calculateArea(length, width); Notice the two parameters are separated by a comma. 47
The Method Selector is the Period The Method selector operatoris the period . and is always placed between the object’s name and the method’s name. It is also placed between the name of a class and the name of an object when needed as in System.out. Scanner reader = new Scanner(System.in); System.out.println(“Enter an integer: ”); int num1 = reader.nextInt(); System.out.println(“Enter an integer: ”); int num2 = reader.nextInt(); System.out.println(“Enter a floating-point number: ”); double num3 = reader.nextDouble(); Above, reader has been declared to be a Scanner class variable that represents a new Scanner object. That Scanner object can read data from the input of the keyboard. Reader can call either of the methods nextInt() or nextDouble() to read integers or floating-point numbers from the keyboard. The variable reader is also referred to specifically as an object variable. 48
Declaring int and double Variables TIME OUT!!! What are we doing with the lines? int num1 = reader.nextInt(); double num3 = reader.nextDouble(); In the first line, we declare a variable named num1, but we have to tell what type of data we intend for it to hold. Since we want it to hold an integer (whole number), we use Java’s int data type. The type of data must be listed before the name of the variable! The assignment operator = means we want to store something in num1. What we want to store is what is on the right side of the = sign. It could be an arithmetic expression or a reader line. When a program runs and it encounters a line like reader.nextInt(), the program will pause and wait for something to be entered from the keyboard. Once the user enters an integer and presses return, then the number is read by reader’s nextInt() method, and then the value is stored in num1. With the second line of code, we declare a variable num3 that can hold a floating-point number (one that contains a decimal point like 4.237). The method nextDouble() is used to read the value from the keyboard and store it in the double (floating-point) variable num3. 49
Concatenating Output Items Consider this segment of code: System.out.println(“Enter an integer: ”); int num1 = reader.nextInt(); // a whole number is stored in num1 System.out.println(“Enter an integer: ”); int num2 = reader.nextInt(); // a whole number is stored in num2 int sum = num1 + num2; // a whole number is stored in sum System.out.println(“The sum of ” + num1 + “ and ” + num2 + “ is ” + sum); In the last output line, we concatenate 6 things together to be written to output. Three of the items are literal strings and three are variables of type int that hold integers. Notice there are NO double quotes around the variables. You never place double quotes around any variable … only literal string values. Also, notice the blank spaces at the beginning and end of some literal string values. This keeps the numbers from being jammed up against the words. 50