Scarborough College University of Toronto Fall 1997 _________________________________________________________ CSC A06F: Introduction to Computer Programming Lecture notes 2: The elements of programs _ Part 1 _________________________________________________________ Reading: fflLewis and Loftus, chapters 2 and 3. Copyright cfl1997 Philip Edmonds. All rights reserved. CSC A06F LECTURE NOTES 2 2 Program structure A Java program is a set of one or more classes. A class is a set of one or more methods. A method contains statements. An example import java.io.*; // Prints a quote on the screen public class Quote - public static void main (String args[]) - System.out.println (" I have fallen off the wagon, "); System.out.println (" for I am a slave to tea."); " " CSC A06F LECTURE NOTES 2 3 The main method When you run a Java application it starts with the statements in the main method. Every application requires a main method. It must always be declared like this: public static void main (String[] args) - ... " It looks for the main method in the class that has the same name as the file that you compile and run. (E.g., in "Quote.java") CSC A06F LECTURE NOTES 2 4 Statements A programming statement is an instruction that is carried out when the program is compiled and/or executed. Three kinds: fflExecutable statement : says to do something. fflDeclaration: gives information necessary for the executable statements to work. fflComments: are for humans. They are ignored by the com- puter. There are rules , called the syntax of the language, that tell you how to build up valid statements. Always use comments. Give some insight into why you wrote the program the way you did. Don't repeat the obvious. Another programmer must be able to read and understand your pro- gram easily. CSC A06F LECTURE NOTES 2 5 Anatomy of a statement A statement is built up from reserved words, symbols, identifiers, and literals . Reserved words Reserved words are the official words defined in the language. Some indicate what kind of action to take: while if new Others indicate what kind of information is being declared: class int void final private See Figure 2.1, page 41, for a list all the reserved words. CSC A06F LECTURE NOTES 2 6 Symbols Symbols serve a purpose similar to reserved words. Some are operators (i.e., they do something to something): + - * . = Others are punctuation: , fg () ; CSC A06F LECTURE NOTES 2 7 Identifiers Identifiers are words that you make up to name the things that your program uses and manipulates. They have no predefined meaning in the language. (Except for main). The things you can identify are: fflpackages fflclasses and interfaces fflmethods fflvariables fflconstants You can use any combination of letters, digits, the underscore (_), and the dollar sign ($). But a digit cannot be first. Java is case sensitive , so Max, max, and MAX are all different iden- tifiers. CSC A06F LECTURE NOTES 2 8 Conventions for identifiers There are conventions for identifiers that Java programmers use so that it's easy to tell what kind of thing is being identified. _______________________________________________________ Class Begins with an uppercase letterQuote Method Begins with lowercase main(...) Variable Begins with lowercase max _Constant__All_uppercase________________MAX_STUDENTS___ Identifiers should be ffldescriptive (not meaningless like x or a), fflbut not overly verbose (i.e., not too long) Make their meaning obvious to anyone who is reading the program. CSC A06F LECTURE NOTES 2 9 Literals Literals are explicit data values. Integer literals: 17 -38465 Floating point literals: 3.1415927 -0.0005 59.99f Character literals: 'a' 'A' '$' '"n' String literals: "for I am a slave to tea." CSC A06F LECTURE NOTES 2 10 The Java API Other programmers have already developed a lot of Java code that you can use. It is called the Java Applications Programming Interface . An API is any collection of pre-existing software. The Java API provides many standard and fundamental services, like System.out.println, that are not predefined in the Java language. It is divided into packages that you import in order to use. E.g., import java.io.*; lets you use System.out.println Software re-use is very easy with object-oriented programming. CSC A06F LECTURE NOTES 2 11 Variables A variable is a location in memory used to store a data value. Key idea: you can change the value of a variable. Without variables, you wouldn't be able to do much in a program. You couldn't even get input from the user. To use a variable, you must first declare it: int count; int max = 0; Syntax of a variable declaration: data-type variable-name; OR data-type variable-name = initial-value; CSC A06F LECTURE NOTES 2 12 Referencing a variable To use a variable, you make a reference to it. Its current value will be used. Example: // An example of assignment to change the value of a variable public class Assign_example - public static void main (String args[]) - int count = 193; System.out.println ("There were " + count + " students enrolled."); count = 213; System.out.println ("Now there are " + count); " " The first call to the println method references the variable count. What does it output? What does the second println do? CSC A06F LECTURE NOTES 2 13 Assignment to a variable An assignment statement puts the value of an expression into a variable. variable-name = expression; The assignment operator (=) says to evaluate the expression on the right-hand side, and assign the result to the variable on the left-hand side. The old value is lost. CSC A06F LECTURE NOTES 2 14 Primitive data types A data type is defined by a set of values and the operations that you can perform on those values. Every data value has a data type. Java has eight built-in data types, which are called primitive data types. Integers Integers have no fractional part. Four types: _Type____Storage__Min_value_______________Max_value____________ byte 8 bits 128 127 short 16 bits 32 768 32 767 int 32 bits 2 147 483 648 2 147 483 647 _long____64_bits__9_223_372_036_854_775_8089_223_372_036_854_775_807 CSC A06F LECTURE NOTES 2 15 Floating point numbers Floating point numbers have a fractional part, although it can be zero. Two types: _Type______Storage_Min_value____Max_value__ float 32 bits 3:4 1038 3:4 1038 _double____64_bits_1:7__10308___1:7__10308_ A float has only 7 significant digits, e.g., can't represent 1234.5678 A double has 15 significant digits. CSC A06F LECTURE NOTES 2 16 Characters All the valid characters are kept in a ordered list called a character set . Even control characters like line-feed and tab, which don't have symbols. Java uses the Unicode character set, which is an extension of the ASCII (American Standard Code for Information Exchange) char- acter set. _Type___Storage__Values______________________ _char___16_bits__Anything_from_the_Unicode_set_ CSC A06F LECTURE NOTES 2 17 Booleans A boolean type can have one of two values: true or false (i.e., on or off, 0 or 1). _Type_______Storage_Values______ _boolean____1_bit___true_or_false_ The boolean literals: true and false. CSC A06F LECTURE NOTES 2 18 Constants A constant stores a value, but the value can never be changed. For instance: final int MAX_STUDENTS = 300; declares the constant MAX_STUDENTS to have the value 300. (It's just like a variable declaration, except that we add the word final) Use a constant instead of a variable to avoid inadvertently changing its value. Use a constant instead of a literal to make your programs more readable. CSC A06F LECTURE NOTES 2 19 Expressions An expression is any sequence of operators and data values that can be evaluated to give a new data value. Arithmetic: Operators: (), + -, * / %, + - E.g., 5 * (2 + 3) + 7 =) 27 String: Operators: + E.g., "xxx" + "yyy" =) "xxxyyy" Boolean: Operators: < <= > >=, == != E.g., (2 < 5) =) true Of course, an expression can have variable references in it, and any- thing else that gives an appropriate value (like calls to methods). CSC A06F LECTURE NOTES 2 20 Input/Output (I/O) Input and output is made through streams , which are sources or destinations for data. The Java API lets you define many kinds of stream. Two predefined output streams: System.out and System.err One predefined input stream: System.in Basic output to the screen is easy using the println and print methods of the System.out stream. CSC A06F LECTURE NOTES 2 21 Input To use the predefined input stream, you have to first convert it to a special kind of stream called a BufferedReader. BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); This creates a new stream called stdin out of System.in A BufferedReader has a method called readLine that reads a string: String firstline = stdin.readLine(); To convert a string to an integer, use the method parseInt of the Integer class. int number = Integer.parseInt (firstline); // OR, all in one line! number = Integer.parseInt (stdin.readLine); CSC A06F LECTURE NOTES 2 22 The if statement For making decisions that control the path of execution. Syntax: if (condition) statement; The condition is simply a boolean expression. If it evaluates to true, then the statement is executed. If false, then the statement is skipped. E.g., // if the number is bigger than max, // then it's the new max if (number > max) max = number;