html5
1 / 62

A Sample Program

Learn the basics of Java programming and understand concepts such as data objects, variables, and assignment statements.

bensonj
Télécharger la présentation

A Sample Program

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. A Sample Program public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); } }

  2. Program Outline <import statements> public class <ClassName> { <field declarations> public static void main(String args[]) { <code for main> } <method declarations> }

  3. Another Simple Program import java.util.Scanner; public class AddNumbers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter two numbers > "); int a = sc.nextInt(); int b = sc.nextInt(); System.out.println("Total = " + (a+b)); } }

  4. Elements of the Program import java.util.Scanner; This allows the program to use the Scanner class for easy inputting of data. Other packages may be imported as well.

  5. Elements of the Program public class HelloWorld { } All field and method declarations must be in some class. Usually, classes are stored in a file with the same name as the class with the extension .java. The public keyword indicates that any other class may reference this class.

  6. Elements of the Program public static void main(String[] args) This is the standard function heading for the main function. Every program needs a main function. This function takes an array of strings as arguments (String[] args) and does not return a value (void). It is a public method (public), so anyone can call it, and it is a method that is common to the entire class (static).

  7. Elements of the Program { } The brackets surround the actual code of the main function.

  8. Elements of the Program System.out.println("Hello, World!") This prints out the text Hello, world! in a console window and then starts a new line. System.out is the standard output, in this case, the console window on the display. println is a method for printing strings followed by a new line.

  9. Data Objects Data objects are boxes in memory that hold values. Each box can hold exactly one value. Values can be integers, floating point numbers (similar to real numbers), characters, strings, and so on. Each data object has a specific type of object it can hold. So, a data object for an integer is different than a data object for a floating point number.

  10. Identifiers and Variables To use a data object, we give it a name. Many things in a Java program have names – data objects, functions (e.g., “main”), packages (e.g., “util”). The name of a data object is called a variable.

  11. Rules for Identifiers There are rules for valid identifiers. In Java, an identifier must start with either a letter (a-z, A-Z) the underscore character (_) (usually reserved for system stuff), or the dollar sign ($) (but never use $). The rest of the character can be letters, digits, or underscore, or the dollar sign. Identifiers are case-sensitive. FOOBEAR is different from foobear and different from FooBear

  12. Examples of Identifiers • Valid Identifiers: • x • x1 • x13bc • George • abc_def • myStudent • Invalid Identifiers • 12 • hello.cpp • data-1 • change/3

  13. Identifier Conventions In addition to the rules, there are also conventions about identifiers that are commonly used: • Variables start with lower-case letters • Classes start with upper-case letters • Literals are all upper-case • If a variable is more than one word, the first word starts with a lower-case letter, other words begin with upper-case letters, e.g., myFirstVariable • Underscores are mostly in system names

  14. Keywords Certain identifiers are reserved keywords and should not be used. Examples are: final, class, public, int, char, ...

  15. Variables Variables are identifiers which are names for data objects. They are used for storing values in data objects and for accessing those values. Think of the data object as a box and the variable as the label on the box. (A box can have more than one label on it – we will get to that later.)

  16. Definitions and Declarations Before a data object can be used it must be created and given a type (what kind of thing can be stored in it). This is called a definition. Before a variable can be used it must be given a type as well. This is called a declaration. In Java, we may combine a declaration with a definition or they may occur separately.

  17. Declarations and Definitions - Exs. int a; This creates a new data object that can hold an integer, and assigns the name a to that data object. a is an integer variable (works for primitive types). char foobear; This creates a data object that can hold a character and assigns the name foobear to it. foobear is a character variable.

  18. Primitive Types The are several common types of data objects: integers (int), floating point – similar to reals (float, double), characters, (char), Boolean – true/false (boolean). There are also other primitive types, long and short.

  19. Sizes of Types

  20. Sizes of Types

  21. Assignment Statements An assignment statement is a way to change the value stored in a data object. The left-hand side of an assignment statement is the name of the data object (a variable), and the right-hand side is the value that will replace the contents of the data object. The right-hand side may be an expression whose value is put into the data object.

  22. Assignment Statement - Example The syntax for an assignment statement is Variable = Expression; For example, x = x + y; is an an assignment statement. The variable on the left-hand side indicates where to put the value. Any variables on the right-hand side are used to retrieve values stored in their data objects.

  23. Assignment Statement - Example x = x + 1; means to take the old value of the data object (box) labeled x, add 1 to that value, and store that value back in the data object labeled x.

  24. Variable Initialization Be sure to put a value into a data object before trying to use that value, i.e., all variables should be initialized before being used. Initialization can be done at the same time as declaration/definition. For example, int a = 5; creates a new int data object, labels it with the variable a, and sets its initial value to 5.

  25. Expressions Simple expressions combine operators, variables, and literals in a meaningful way. Java uses common symbols for arithmetic operators, + (plus), - (minus), * (times), / (divides), and also % for remainder. The order of evaluation is the one used in mathematics: • *, /, % (done first) • +, - (done next) Parentheses may be used to change the order.

  26. Expressions - Examples • a + b * c / 2 – 5 • (a + b) * c / (2 – 5) • frodo + samwise + gandalf + strider • 7.2 / 5.0 – 6

  27. Exercise Write a short program that calculate and prints out the area of a circle of radius 7. Create a double, called PI, to store the value of PI. Create a int, r, for the radius 7. Have an output statement to calculate and print out the area.

  28. Literals Aliteral(sometimes called a constant) is a symbol which evaluates to itself, i.e., it is what it appears to be. Examples: 5 int literal 6.3333 floating point literal 6.0 floating point literal 6E7 floating point literal 'a' character literal "Simon" String literal true boolean literal

  29. Constants It is often useful to name literals, that is, to use symbolic names rather than the literals directly. The final modifieris used to declare a data object whose value cannot be changed once it is initialized (and so it must be initialized to set the original value) final double PI = 3.1415926;

  30. String Literals String literals are sequences of characters enclosed in double quotes ("). This is different from a char literal which consists of a single character enclosed in single quotes ('). You can put a double quote inside of a string by using an escape sequence, that is, preceding the double quote by a backslash. Example: "This is a double quote \"."

  31. Assignment Compatibility A data object can only hold one type of object (int, float, double, char, string), but sometimes you can convert an object of one type to another type before storing it. For example, double a = 4; is perfectly fine. 4 is converted to a double, 4.0, before being stored in a. int b = 3.6; is not okay.

  32. Shorthand Assignment Statements In Java. you can abbreviate an assignment statement which modifies the variable on the left hand side. For example, a += 5; is shorthand for a = a + 5; Similarly, *=, -=, /= are shorthand for their respective operations

  33. Integer Division One thing to watch out for is integer division. If you divide two ints, the result is another int, not a floating point number. So, 19/4 is 4, not 4.75. If you divide two floating point numbers, the result is a floating point number: 19.0/4.0 is 4.75. If you divide an int by a floating point number, the int is converted to floating point first.

  34. Increment and Decrement Java provides shorthand operators for incrementing and decrementing values. n++; increments the value of n by 1 and the value is n before the increment ++n; increments the value of n by 1 and the value is n after the increment n-- and --n are similar, but decrement the value.

  35. String Class The String class provides literals and variables: "Hello, world!" // string literal String word = "abracadabra"; // string variable There is also an operator, +, for string concatenation: String name = "Simon"; System.out.println("Hello, " + name);

  36. Output The variable System.out represents the output stream, that is, normally the terminal. You can send strings to the output stream by using the print or println methods. If print (or println) has a non-string argument, that value is converted to a string before printing. The concatenation operation, '+' can be used to put strings together, e.g. System.out.println("The total of " + a + " and " + b + " is " + (a + b)); Note that the parenthesis around "a+b" are necessary, otherwise a and b are each converted to strings.

  37. Input The variable System.in represents standard input, that is, normally the keyboard. You can use the a Scanner object to read in and set variables easily. To create a Scanner object, you must specify where to read the input from. For example, to read in two ints from standard input: import java.util.Scanner; // inside main method: Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); will read in two ints and store them in a and b.

  38. Exercise Write a Java program that will prompt the user for a temperature (in Fahrenheit) and then convert that temperature to Celsius and print out the new temperature along with a text message. You will need: • A double variable, f, to represent the Fahrenheit temperature • A double variable, c, to represent the Celsius temperature

  39. Exercise (cont'd) • An output line to print out the prompt message • An input line to read in the Fahrenheit temperature • A line to calculate and store the Celsius temperature c = (f ­ 32) * 5/9. • A line to print out the result.

  40. Floating point numbers are printed out in some default format, which is usually not how you want them to print out. For example, if you want to print out dollars and cents: double price = 78.50; System.out.println("Price is $" + price); You might see Price is $78.5 Printing Numbers

  41. If that's not what you want, you can use the DecimalFormat class. The following commands tell the computer to use a fixed format (rather than scientific notation), to always show the decimal point, and to show two digits to the right of the decimal point: import java.text.DecimalFormat; public static void main(String args[]) { DecimalFormat myFormat = new DecimalFormat("###.##"); System.out.println(myFormat.format(price)); } Formatting Numbers

  42. Formatting Patterns

  43. Comments are human-readable lines of text which can be used to document your program. The computer ignores comments. There are two ways to indicate a comment. Two slashes ("//") indicate that everything that follows them until the end of the line is a comment. A block of text is treated as a comment if it begins with "/*" and ends with "*/". Comments

  44. /* This program was written by Don Simon on 01/15/2010 for the COSC 160 class */ import java.util.Scanner; //scanner Example Comments

  45. For this class, each program should have the following documentation: Author's name, date, name of program Short program description Description of each variable (if not obvious) Each function and method should have a short description, including the inputs and outputs Description of major sections of code Details of any tricky (non-obvious) code Documentation Standards

  46. The idea is that some one who reads the code should understand what is going on. The comments should not mimic the code, that is, restate the code in English, but should provide the gist of what each major section of code does. For example: a = a + 1; // add 1 to a. is not an appropriate comment, but /* Read in the students' test scores and find the average */ is. Documentation Standards (cont'd)

  47. The Java system is divided into a core language and a set of APIs (application programming interface). The APIs provide additional functionality. One of the commonly used APIs contains the Scanner class. Another, DecimalFormat has functions for manipulating how things are printed out. To use an API, you must have an import line near the top of your program to load the API classes: import java.util.Scanner; import java.text.DecimalFormat; Libraries

  48. As noted before, you can use arithmetic operators in expressions to manipulate numeric values: a + b * 7 – (b + 3) There is an order of precedence which determines which operators are done first: First *, /, and % are performed, and then + and -. Two arithmetic operators of the same precedence are done from left to right. Parentheses can be used to change the order. Arithmetic Expressions

  49. There are also operators which compare values and return true or false. For example “a < b” returns true if a is less than b and false otherwise. These are called relational operators: == equals != not equal to < less than > greater than <= less than or equal to >= greater than or equal to Relational Operators

  50. We can combine simple relational tests together into more complex expressions using Boolean operators. Boolean operators work on logical (or Boolean) values (true, false) and return true and false. The common operators are: && and || or ! not Example: 0 <= a && a <= 10 // a is between 0 and 10 incl. Boolean Expressions

More Related