COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises
Please Do Ask Questions It's perfectly normal not to understand everything Most of you haven't programmed before There are no stupid questions Nobody can blame you for not having programmed before If you feel I'm going too fast, just ask questions Or just tell me I'm going too fast We have plenty of time to cover all course materials I mean you, people in the back rows COMP 202 - Java in 1 week 2
What's a Compiler? The Compiler translates Java into machine language This is done by a program called javac Eclipse uses this program to compile your code Another program called java executes compiled code Eclipse (IDE) Java code javac (Compiler) Compiled code java (VM) Eclipse hides this COMP 202 - Java in 1 week 3
The Java Programming Language Programming languages define the syntax How to structure a program What is a valid Java program Syntax is grammar (as in English) Also define precise semantics Every keyword has a precise meaning Tell the computer exactly what you want it to do COMP 202 - Java in 1 week 4
Java Program Structure In the Java programming language: Pograms are made of classes (one per file) Classes contain methods Methods contain statements Statements are commands you issue Instructions for the computer (do this first, then this) All Java program contain one main method Starting point of the execution COMP 202 - Java in 1 week 5
Java Program Structure // comments about the class public class MyProgram { { } } // comments about the method class header: The name of public static void main (String[] args) the class method body method header Comments can be added almost anywhere COMP 202 - Java in 1 week 6
Inside Method Bodies: Statements Each statement is a command i.e.: computer, add two integers! Kinds of statements we have seen Declaration statements e.g.: int val1; Assignment statement e.g.: val = value; var = val1 + val2; Control statements (if, while) Method calls e.g.: System.out.println( print this ); COMP 202 - Java in 1 week 7
Statements Contain Identifiers Identifiers are the words a programmer uses in a program. They are used to give names to things. An identifier can be made up of letters, digits, the underscore character (_), and the dollar sign Identifiers cannot begin with a digit Java is case sensitive, therefore Result and result are different identifiers COMP 202 - Java in 1 week 8
Identifiers Sometimes we choose identifiers ourselves when writing a program (such as input1, AddTwoIntegers) Sometimes we are using another programmer's code, so we use the identifiers that they chose (such as println) Often we use special identifiers called reserved words that already have a predefined meaning in the language A reserved word cannot be used in any other way Main, class, public, COMP 202 - Java in 1 week 9
Java's Reserved Words abstract continue for new switch assert default goto* package synchronized boolean do if private this break double implements protected throw byte else import public throws case enum instanceof return transient catch extends int short try char final interface static void class finally long strictfp volatile const* float native super while * = not used COMP 202 - Java in 1 week 10
Formatting rules Spaces, blank lines, and tabs are collectively called white space separates words and symbols in a program Extra white spaces are ignored by Java A valid Java program can be formatted many different ways Programs should be formatted for readability use proper indentation use space and new lines use comments COMP 202 - Java in 1 week 11
Formatting and Errors COMP 202 - Java in 1 week 12
How You Should Format Code When opening a curly brace { Indent everything inside (using spaces or tabs) Until you meet its closing brace } Use spaces, new lines to facilitate readability Don't pack all your code closely Use comments Describe/explain what you are doing For you, and for others No comments means you lose marks! COMP 202 - Java in 1 week 13
Programming Errors A program can have three types of errors Syntax errors (compile-time errors) The code you wrote is not valid Java Grammar error The program is not compiled, you can't run it Semantic/logical error The computer isn't doing what you wanted You didn't phrase it properly Execution aborts because of a problem (run-time errors) Divide by zero Wrong data type COMP 202 - Java in 1 week 14
Development Life Cycle Debugging Write code Syntax Errors Compiler 0 errors Errors may take a long time to debug! Run program Logic and run-time errors Important Note: When you compile for the first time and see the 150 errors, do not despair. Only the first 1 or 2 errors are relevant. Fix those and compile again. There should be fewer errors (like 50). Repeat until no errors. COMP 202 - Java in 1 week 15
Constants A constant is an identifier that is similar to a variable except that it holds one value for its entire existence The compiler will issue an error if you try to change a constant In Java, we use the final modifier to declare a constant final double PI = 3.14; Constants: give names to otherwise unclear literal values facilitate changes to the code More precision required: change PI only once to 3.14159 prevent inadvertent errors COMP 202 - Java in 1 week 16
Arithmetic Expressions An expression is a combination of operators and operands radius * radius * PI Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition Subtraction Multiplication Division Remainder Negative x + y x - y x * y x / y x % y - x If either or both operands to an arithmetic operator are floating point (double), the result is floating point (double) COMP 202 - Java in 1 week 17
Boolean Expression An expression that evaluates either to true or to false Named after George Boole, inventor of the Boolean Algebra (we will discuss it in more detail later) Similar concept in natural language the traffic light is red This expression is either true or false COMP 202 - Java in 1 week 18
Comparison Boolean Expressions often contain comparisons; if (denominator == 0) If the denominator is zero Note the difference of comparison == to assignment = One of the most common errors If (denominator!= 0) If the denominator is not zero if (balance > amount), if (balance < amount) If the balance is larger / smaller than the amount If (balance >= amount) If the balance is larger or equal to the amount If (balance <= amount) If the balance is smaller or equal to the amount COMP 202 - Java in 1 week 19
The simple if-then-else Statement if ( condition expression ) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, not both COMP 202 - Java in 1 week 20
The While-loop syntax while is a reserved word while ( condition expression ) { statement1; statement2; } If the condition is true, the statement is executed. Then the condition is evaluated again. The statement is executed repetitively until the condition becomes false. COMP 202 - Java in 1 week 21
Calculator VII: Adding an arbitrary amount of numbers COMP 202 - Java in 1 week 22
Classes So far, we have used some existing classes: Scanner: Allows us to read from keyboard: nextint, nextdouble, System.out Allows us to print information to the screen: println We call the operations that we can perform methods So far, we have developed a set of own classes Division, AddArbitrary, But are these conceptually classes? They are rather tasks of a class calculator! COMP 202 - Java in 1 week 23
The calculator class Provides Addition and Division Expects repetitive input from user User must indicate type of operation (addition, division, ) User must indicate input Calculator performs operation Calculator exits if user does not want to have further computation COMP 202 - Java in 1 week 24
Summary Variables, variable assignments, expressions are the fundamental building blocks Variables can have different data types So far integer and floating point We can perform basic operations on variables +, -, *, / If-then-else control when certain statements are executed While loops execute statements repetitively concept of a class bundle related functionality COMP 202 - Java in 1 week 25
Exercise #2 I want you to write a Java program which: Reads an input temperature in Celsius Asks the user whether he wants to convert it into: A temperature in Fahrenheit A temperature in Kelvin Performs the necessary conversion Prints out the result Where should you start? Write a program that just does Celsius to Fahrenheit first Look at the simpler Calculator examples Add the possibility to enter a user choice You will need an if-else statement (but no loop) Look at the Calculator example from last class COMP 202 - Java in 1 week 26
Calculator II: COMP 202 - Java in 1 week 27
Exercise #2 Try writing everything yourself Don't copy and paste, practice your syntax skills Don't look at other people's code But feel free to discuss orally Some useful notes: The temperature should be floating point Use all doubles The choice can be an int Type 1 for Celsius to Fahrenheit Type 2 for Celsius to Kelvin Feel free to come to my office hours COMP 202 - Java in 1 week 28