COMP-202 Unit 2: Programming Basics. CONTENTS: The Java Programming Language Variables and Types Basic Input / Output Expressions Conversions

Size: px
Start display at page:

Download "COMP-202 Unit 2: Programming Basics. CONTENTS: The Java Programming Language Variables and Types Basic Input / Output Expressions Conversions"

Transcription

1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables and Types Basic Input / Output Expressions Conversions

2 Part 1: The Java Programming Language

3 The Java Programming Language Java was created by Sun Microsystems, Inc. It was introduced in 1995 and has become quite popular It is an object-oriented language It represents the program as a series of objects, each of which belongs to one of many categories called classes The Java programming language combines both compilation and interpretation 3

4 Java Translation and Execution (1) The Java compiler translates Java source code into a special representation called bytecode Java bytecode is not the machine language for any traditional CPU Another software tool, an interpreter called the Java virtual machine (JVM) translates bytecode into machine language and executes it Therefore the Java compiler is not tied to any particular machine Java bytecode will run on any CPU for which there exists a JVM Java is considered to be architecture-neutral 4

5 Java Translation and Execution (2) This is the standard approach to Java translation and execution Java source code.java Java compiler Java bytecode JVM (CPU 1) JVM (CPU 2).class CPU 1 CPU 2 5

6 Java Translation and Execution (3) Java source code Java compiler.java This approach to Java translation and execution is very uncommon, and probably unnecessary Bytecode compiler (to CPU 1) binary code (CPU 1) Java bytecode Bytecode compiler (to CPU 2) binary code (CPU 2) CPU 1 CPU 2.class 6

7 Java Program Structure (1) In the Java programming language: A program consists of one or more classes; each class is defined in a different file A class contains one or more methods A method contains program statements Statements are the actual commands you issue, the instructions that are executed when the program runs A Java program always has at least one class which contains a method called main() This is where the program starts executing 7

8 Java Program Structure (2) For now, all programs we develop will involve writing only one class, and this class will contain exactly one method: main() 8

9 Java Program Structure: Classes public class MyProgram { } class body class header: the name of the class The class header states that you are defining a new class whose name will be the name you specify. This class will consist of what you write in the class body. Important note: the name of the file which contains this class MUST be the name of the class, followed by extension.java Here: MyProgram.java 9

10 Java Classes There are three possible roles for a class in Java A class can be the starting point of a program; any class that defines a main() method has this role A class can be a collection of related methods; this is called a library A class can define a category of objects, and specify what objects that belong to this category look like and how they behave Many classes only have one of these roles, but some have two and even all three For now, all the classes we write will have only one role: they will be the starting point of a program 10

11 Java Program Structure: Methods public class MyProgram { } public static void main(string[] args) { } method body method header The method header states that you are defining a new method; this method consists of the statements in the method body. The method header also specifies the new method's name. 11

12 Java Methods A Java method is a list of statements that has been given a name The statements that the method consists of perform a task when they are executed together Writing a method means specifying a list of statements and giving a name to this list of statements Once a method is written, its name can be used as a single statement inside another method When that single statement is executed, all statements in the method are executed This is referred to as calling or invoking a method We will cover methods in detail later 12

13 Part 2: Java Basics

14 Our First Java Program (1) Here is our first Java program: public class HelloWorld { public static void main(string[] args) { System.out.println("Hello world!"); } } Some highlights: It involved writing a single class called HelloWorld This class contains a single method called main(), which is where the program starts The main() method contains a single statement, which requests that the sentence "Hello world!" (without the quotation marks) be displayed on the screen 14

15 Our First Java Program (2) By looking at the program and knowing what it does, can you deduce a way to modify it so that it does the following: Display "Programming is fun!" instead of "Hello world!"? Display two different sentences? 15

16 EchoNumber.java import java.util.scanner; /* This program asks the user to enter an integer, reads this integer from the keyboard, and displays it to the screen. */ public class EchoNumber { public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); int number; } } // Prompt the user for a number, read it, and display it. System.out.print("Enter a whole number: "); number = keyboard.nextint(); System.out.println("You entered the following number " + number); 16

17 Dissecting EchoNumber.java Although very simple, the program in EchoNumber.java illustrates a number of basic concepts of Java programming: Comments White space and formatting Identifiers Variables Data types Assignment statements Reading information from the keyboard Displaying information to the screen We will now cover each of these concepts in detail one by one 17

18 Comments (1) Comments are notes in a program They are meant for humans, and are completely ignored by the compiler You can write anything in a comment In most cases, they describe aspects of the program such as its purpose or the way it works Syntax Comments that start with // end when the current line ends; the compiler ignores everything between // and the end of the current line Comments that start with /* end with */ ; the compiler ignores everything between /* and the matching */ 18

19 Comments (2) Comment examples: // This is a one line comment. /* This is a multi-line comment. */ Even though they do not change how the program works, comments are important! They provide valuable information to humans who read the program about its purpose and the way it works, including to the one who wrote it in the first place! "You know you're brilliant, but maybe you'd like to understand what you did 2 weeks from now." - Linus Torvalds, Linux CodingStyle documentation 19

20 Formatting Rules Spaces, blank lines, and tabs are collectively called white space It is used to separate words and symbols in a program Extra white spaces are completely ignored A valid Java program can be formatted many different ways Programs should be formatted for readability by humans Use proper indentation Use space and new lines Use comments The program in EchoNumber.java is formatted very nicely 20

21 Bad Formatting (1) The following is an example of a (very) badly formatted program: import java.util.scanner; public class EchoNumberBad { public static void main(string[] args){ Scanner keyboard = new Scanner(System.in); int number; System.out.print("Enter a whole number: "); number = keyboard.nextint(); System.out.println( "You entered the following number " + number); }} 21

22 Bad Formatting (2) As long as a program is syntactically correct, the compiler will understand it, no matter how badly formatted it is However, humans who have to read your program (including TAs) may have trouble understanding it if it is badly formatted Make sure to format your programs so that they are readable by humans 22

23 Identifiers (1) Identifiers are the words a programmer uses in a program They are used to give names to things Examples of things that can be named with identifiers: Classes Methods Variables Constants An identifier can be made up of letters, digits, the underscore character (_), and the dollar sign ($) Identifiers cannot begin with a digit 23

24 Identifiers (2) Java is case sensitive, therefore Result and result are different identifiers Sometimes we choose identifiers ourselves when writing a program (such as number, keyboard, or EchoNumber) We should choose identifiers that are meaningful so that the program is more readable for humans 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; it cannot be used to give names to things like other identifiers 24

25 Identifiers (3) Examples of reserved words: class, public, static, void There are many others 25

26 Java Reserved Words Here is the complete list of Java reserved words: abstract double int super assert else interface switch boolean enum long synchronized break extends native this byte final new throw case finally package throws catch float private transient char for protected try class goto public void const if return volatile continue implements short while default import static do instanceof strictfp 26

27 Identifiers: Exercise Which of the following identifiers are invalid according to the Java rules for identifiers? Why are they invalid? myidentifier _my_other_identifier yet-another-identifier $can 2for1 twofor1 class my_class 27

28 Identifier Conventions There exist Java style conventions for identifiers Do not put characters between words The first letter of a word should be in upper-case The first letter of the first word should be in lower-case unless the identifier is for a class The first word of the identifier for a method should be a verb Identifiers should be descriptive and avoid abbreviations The compiler will not complain if you do not follow the conventions, but not following conventions considered bad practice See the General Instructions and Regulations for Assignments for further information regarding conventions for identifiers 28

29 Conventions: Exercise Which identifiers follow style conventions for Java? myidentifier _my_other_identifier totalvalue totval thesumofallthevaluesenteredbytheuser MyClass my_class getvalue GetValue 29

30 Variables (1) A variable is a placeholder for values We can store a value in a variable We can use the value stored in a variable to compute other values (which may be stored in other variables), to make decisions, to display it, or for other things Before we use the value that a variable contains, we must store a value in this variable, otherwise the compiler will report an error Each variable has a name The compiler allocates one or more consecutive memory cells The (combined) contents of these cells forms the value of the variable The compiler assigns the name chosen for the variable to these cells 30

31 Variables (2) We can then refer to the value stored in these memory cells using the variable name Much easier, more practical, and more flexible than using the addresses of the memory cells (and less error-prone) Each variable also has a type The type of a variable specifies the kind of values it can contain 31

32 Variable Declarations Before we can store a value in a variable or use the value it contains, we have to declare it A variable declaration is a statement that announces that want to create and use a new variable They can occur anywhere in a method, but they are typically at the beginning They must indicate the name and the type of the new variable Once a variable has been declared, we can store a value in it or use the value it contains If you try to store a value in a variable before it is declared, or use the value stored in a variable before the variable is declared, the compiler will generate an error 32

33 Syntax for Declaring Variables modifiers type identifier = value; Where: modifiers final,... (optional) type int, double, char (mandatory) identifier as defined previously (mandatory) = value an expression matching the type (optional) ; (mandatory) This is a partial definition 33

34 More on Variable Declarations Note that you can declare more than one variable with one variable declaration statement The variable names are separated using commas For example, the following statement declares three different variables, called var1, var2, and var3, each of type int: int var1, var2, var3; 34

35 Types A type is a category of values that a variable belongs to and determines: How to interpret the value it contains What are the possible values it can contain For example, it makes no sense to assign the name of a month as a value to a variable whose purpose is to hold the name of a day of the week In Java, all variables and all values have a type 35

36 The Purpose of Types The type of a variable provides an answer to the following question: should the value of the variable be considered as an integer, a real number, a character, or maybe even something else? For a computer, everything is stored as a series of ones and zeros We need a way to tell what the ones and zeros represent and how they should be interpreted by the program 36

37 Types in Java There are two broad kinds of types in Java: primitive types and reference types We will see reference types later in the course Primitive types represent very basic kinds of values They are defined by the Java language and directly supported by the compiler 37

38 Primitive Types There are exactly 8 primitive types in Java Four of them represent integers (positive and negative whole numbers): byte, short, int, long Two of them represent floating point numbers (positive and negative numbers with decimal parts): float, double One of them represents characters: char And one of them represents boolean values (true or false): boolean 38

39 Numeric Primitive Types The difference between the various numeric primitive types is their size, and therefore the values they can store: Type byte short int long float double Space 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Literal L 5.2f 5.2 Minimum ~ -9 X Maximum +/- 3.4 X (with 7 significant digits) ~ 9 X /- 1.7 X (with 15 significant digits) 39

40 Real vs. Floating Point A real number is number that can be given by an infinite decimal representation For example, π = However, we would need infinite memory to store a number with infinite decimal representation The solution: floating point numbers A floating point number is an approximation of a real number; it can only have a finite number of decimal places Floating point numbers need only finite space (they fit in a memory cell or a finite set of memory cells) 40

41 Characters A char variable stores a single character from the Unicode character set char gender; gender = 'M'; A character set is an ordered list of characters, and each character corresponds to a unique number The Unicode character set uses 16 bits (2 bytes) per character, allowing for unique characters It is an international character set, containing symbols and characters from many world languages Character values, also called character literals, are delimited by apostrophes: 'a' 'X' '7' '$' ',' '\n' 41

42 More on Characters The ASCII character set is older and smaller than Unicode, but is still quite popular The ASCII characters are a subset of the Unicode character set, including: upper-case letters lower-case letters punctuation digits special symbols control characters A, B, C,... a, b, c,... period (.), semicolon (;),... 0, 1, 2,... &,, \,... carriage return, line feed, tab,... 42

43 Escape Sequences (1) What if we wanted a store an apostrophe (') in a variable of type char? The following line would confuse the compiler because it would interpret the second apostrophe as the end of the char literal: char c = '''; // Error! An escape sequence is a series of characters that represents one special character An escape sequence begins with a backslash character (\), which indicates that the character(s) that follows should be treated in a special way: char c = '\''; // OK! 43

44 Escape Sequences (2) For example, assigning the char literal '\'' to the a char variable will result in the apostrophe being stored in the variable The backslash in the char literal tells the compiler that the apostrophe that follows does not mark the end of the char literal, but instead is part of the char literal 44

45 Java Escape Sequences Some escape sequences in Java: Escape sequence Meaning \b \t \n \r \" \' \\ Backspace Tab New line (line feed) Carriage return Double quotation mark (String) Single quotation mark (char) Backslash 45

46 Boolean Values An expression that evaluates either to true or to false Named after George Boole, the inventor of Boolean algebra Similar concept in natural (human) languages: "the traffic light is red" This expression is either true or false 46

47 Boolean Type You can declare variables which are of type boolean A boolean variable represents a true or false condition A boolean can also be used to represent any two states, such as a light bulb being on or off The literals true and false are the only valid values for a boolean type While not technically reserved words, you cannot use them for any other purpose than as a literal boolean value Example: boolean done = false; // Some code here done = true; 47

48 The Assignment Statement (1) To store a value in a variable, we use the assignment statement The assignment operator in Java is the = sign The syntax for the assignment statement is the following: variable = expression; The expression on the right of the = sign is evaluated An expression can consist of a single value, a single variable, or a more complex combination involving many operators and operands The result of evaluating the expression is stored in the variable on the left of the = sign; the previous value stored in that variable (if any) is overwritten The values stored in the variables on the right side of the assignment statement do not change (except when special operators are used) 48

49 The Assignment Statement (2) The left-hand side of the = MUST be a SINGLE variable; it CANNOT be an expression with multiple operators and operands The = operator does NOT define an equation 49

50 Reading from the Keyboard (1) To read values from the keyboard, we use Scanner First, we must declare a variable of type Scanner, and initialize it Scanner variable = new Scanner(System.in); variable can be replaced by any identifier; keyboard is a good choice, but there is nothing special about it Everything else, however, must be exactly as above This only needs to be done once in your program, but it needs to be done before you attempt to read any values To read a value of type int from the keyboard, we use the following expression: variable.nextint() 50

51 Reading from the Keyboard (2) variable must be replaced by the identifier you used when you declared the Scanner variable Thus, if you called your Scanner variable foo, you must write foo.nextint() if you want to read an int value from the keyboard The expression variable.nextint() (where variable is a variable of type Scanner) can be used as the right side of an assignment statement: int input; input = keyboard.nextint(); The right side of the assignment statement is evaluated; this results in a value of type int being read from the keyboard 51

52 Reading from the Keyboard (3) The value read from the keyboard is then stored in the variable on the left side of the assignment statement, overwriting any previous values stored in that variable To read a value of type double instead of type int, simply replace nextint() by nextdouble() 52

53 Displaying to the Monitor You can use one of two built-in commands to display something to the monitor: System.out.println(stuffToDisplay); Displays stufftodisplay followed by a line break System.out.print(stuffToDisplay); Only stufftodisplay is displayed 53

54 More on print() / println() println() and print() each take one input (also called parameter or argument) a character string: println("hello world!"); the value of a variable: println(output); the combination of both: println("the sum is " + output); a combination can have more than two parts: println("the sum is " + sum + " and the " + " difference is " + difference); 54

55 Examples of Displaying Text System.out.println("Hello world!"); The character string Hello world! is displayed int value = 5; System.out.println(value); The value 5 is displayed double price = 44.99; System.out.println("This book costs " + price + " dollars"); The character string This book costs dollars is displayed 55

56 Countdown.java public class Countdown { public static void main(string[] args) { System.out.print("Three... "); System.out.print("Two... "); System.out.print("One... "); System.out.print("Zero... "); } } System.out.println("Liftoff!"); System.out.println("Houston, we have a problem!"); What does this display? 56

57 Countdown Result The following is displayed when the Countdown program is executed Three... Two... One... Zero... Liftoff! Houston, we have a problem! _ Cursor ends up here 57

58 Aside: Calling Methods (1) When you read a value from the keyboard, what you are really doing is calling a method The method is called nextint() or nextdouble(), depending on what you are reading The method is invoked on an object which belongs to class Scanner The name of this object is the name you gave to your Scanner variable Likewise, when you display something to the monitor, you are also calling a method The method is called println() or print() The method is invoked on an object which belongs to class PrintStream 58

59 Aside: Calling Methods (2) The name of this object is System.out We will revisit this aspect of reading and displaying when we cover classes and objects 59

60 Reading and Displaying: Exercise Write a Java program which consists of one class called ReverseDisplay. This class must define a method called main() which does the following: Displays a message asking the user to enter an integer Reads this integer from the keyboard Displays a message asking the user to enter another integer Reads this second integer from the keyboard Displays the second integer entered by the user along with a message describing the meaning of this value Displays the first integer entered by the user along with a message describing the meaning of this value 60

61 Program Template To make it easier to write programs, you can use the following template as a starting point: import java.util.scanner; public class Template { // Change "Template" to the desired name // for your class public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); // Write your program statements here } } 61

62 Part 3: Expressions

63 Arithmetic Expressions An expression is a combination of operators and operands Operators are optional but operands are mandatory An operand can be a literal value (for example, 5 or 3.14), a variable, or the value returned by a method call (like nextint()) Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition: Subtraction: Multiplication: Division: Remainder: x + y x y x * y x / y x % y Negation: -x 63

64 Division With Integers If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) The remainder operator (%) returns the remainder after dividing the second operand by the first Example: int numhours = 52; int fulldays = numhours / 24; // fulldays contains 2 int remaininghours = numhours % 24; // remaininghours contains 4 Division by 0 with integers Produces run-time error The program has to avoid it, or it will crash 64

65 DivisionInt.java import java.util.scanner; public class DivisionInt { public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); int numerator, denominator, quotient, remainder; } } // Read the values System.out.print("Enter the numerator: "); numerator = keyboard.nextint(); System.out.print("Enter the denominator: "); denominator = keyboard.nextint(); quotient = numerator / denominator; remainder = numerator % denominator; System.out.println("The result is: " + quotient); System.out.println("The remainder is: " + remainder); What does this display? 65

66 Operator Precedence Operators can be combined into complex expressions: result = total + count / max offset; Operators have a well-defined precedence which determines the order in which they are evaluated Multiplication (*), division (/), and remainder (%) are evaluated prior to addition (+) and subtraction (-) Arithmetic operators with the same precedence are evaluated from left to right Parentheses can always be used to force the evaluation order 66

67 Operator Precedence Examples What is the order of evaluation in the following expressions? a + b + c + d + e a / (b + c) - d % e a + b * c - d / e a / (b * (c + (d - e)))

68 Assignment Operator Precedence The assignment operator has a lower precedence than the arithmetic operators answer = sum / 4 + MAX * lowest; Then the result is stored in the variable on the left-hand side First, the expression on the right side of the = operator is evaluated 68

69 Assignment Operator Sides The left-hand and right-hand sides of an assignment statement can contain the same variable: count = count + 1; Then, the overall result is stored into count, overwriting the original value First, 1 is added to the original value of count; the result is stored in a temporary memory location The fact that the assignment operator has lower precedence than arithmetic operators allows us to do this 69

70 Arithmetic Expressions: Exercise 1 Write a Java program which consists of one class called AddTwoIntegers. This class must define a method called main() which does the following: Displays a message asking the user to enter an integer Reads an integer from the keyboard Displays a message asking the user to enter another integer Reads another integer from the keyboard Adds the two integers read from the keyboard together Displays the result with an appropriate message How would you modify this program to add two real numbers instead? 70

71 Arithmetic Expressions: Exercise 2 Write a Java program which consists of one class called TemperatureConverter. This class must define a method called main() which does the following: Displays a message asking the user to enter a temperature in Celcius degrees Converts the temperature in Celcius degrees to Fahrenheit degrees; the formula for this calculation is f = (9c / 5) + 32, where f is the temperature in Fahrenheit, and c is the temperature in Celcius Displays the equivalent temperature in Fahrenheit with an appropriate message 71

72 Increment / Decrement Operators The increment and decrement operators are arithmetic and operate on one operand This operand must be a single variable The increment operator (++) adds one to its operand The decrement operator (--) subtracts one from its operand The increment and decrement operators can be applied in prefix form (before the variable) or postfix form (after the variable) 72

73 Increment / Decrement Semantics When used alone in a statement, the prefix and postfix forms are basically equivalent That is, when used alone in a statement, ++count; is equivalent to count++; which is equivalent to count = count + 1; However, they are not equivalent when they are used in expressions! Using these operators in expressions requires you to really know what you are doing 73

74 Increment / Decrement Advice Using increment and decrement operators is fine if this operator is the only operation in a statement i++; // OK ++j; // OK too Do not use increment and decrement operators in more complex statements total = count count; // Avoid! index = ++i * --j / k++; // Avoid too! 74

75 Assignment Operators (1) Often we perform an operation using a variable, then store the result back into that variable Java provides additional assignment operators to simplify that process They combine the assignment operator with an arithmetic operator Example 1: The statement total += 5; is equivalent to total = total + 5; Example 2: The statement result *= count1 + count2; is equivalent to result = result * (count1 + count2); 75

76 Assignment Operators (2) In general, assignment operators have the form variable op= expression; which is equivalent to variable = variable op (expression); The entire expression on the right side of the assignment operator is evaluated It can be a complex expression involving many levels of parentheses Then, the result of evaluating that expression is used on the right hand side of the operator in the assignment operator The left operand is the variable on the left of the assignment operator The final result is stored back in the variable on the left-hand side of the assignment operator 76

77 Assignment Operators (3) There are many assignment operators, including the following: Operator Example Equivalent to += x += y; x = x + y; -= *= /= %= x -= y; x *= y; x /= y; x %= y; x = x - y; x = x * y; x = x / y; x = x % y; 77

78 Boolean Expressions Instead of evaluating to a numeric value, boolean expressions evaluate to either true or false mynumber > 0 // can be either true or false You can assign the result of a boolean expression to a variable of type boolean: boolean positive; positive = (mynumber > 0); Boolean expressions are often used to control the flow of execution of a program We will see control flow in detail later in the course; we will cover boolean expressions in more detail then 78

79 Constants (1) A constant is an identifier that is similar to a variable except that it holds one value for its entire existence In Java, we use the final modifier to declare a constant final double PI = 3.14; The compiler will issue an error if you try to assign a value to a constant more than once in the program final double PI = 3.14; // Some more statements... PI = 2.718; // Error: cannot assign a value to a // final variable more than once 79

80 Constants (2) Java style conventions for constants: identifiers for constants should contain only upper-case letters, and each word in the identifier should be separated by an underscore (_) 80

81 Advantages of Constants Constants give names to otherwise unclear literal values The meaning of 0.05 may not be clear to the person reading your code, but the meaning of GST or TAX is Constants facilitate changes to the code More precision required? Change PI from 3.14 to in only one place No need to search the whole program for occurrences of the value Constants prevent inadvertent errors The programmer cannot type the wrong value by mistake If you type Pi instead of PI, the compiler will report an error; if you type 31.4 instead of 3.14, the compiler will not report an error but your calculations will probably be all wrong 81

82 Constants: Exercise Write a Java program which consists of one class called Circle. This class should define a method called main() which does the following: Displays a message asking the user to enter the radius of a circle, and reads the value of the radius from the keyboard Computes the circumference of the circle; the formula for this calculation is c = 2πr, where r is the radius of the circle and c is its circumference Computes the area of the circle; the formula for this calculation is a = πr 2, where r is the radius of the circle and a is its area Displays both values with an appropriate message You must declare π as a constant called PI, with 4 digits after the decimal, and use this constant in your calculations 82

83 Part 4: String Basics

84 The String Type (1) As we saw earlier, a variable of type char can only store a single character value char c1 = 'a'; char c2 = '%'; What could we do if we wanted to store an ordered sequence of characters, like: a word? a complete sentence, including spaces and punctuation? One possible answer: use a variable of type String 84

85 The String Type (2) The String type is a reference type, not a primitive type However, because Strings are so common, the Java programming language allows us to use the String type almost in the same way we use primitive types The differences will be explained in detail when we cover reference types 85

86 String Variables and Values Variables of type String are declared just like variables of other types But remember that Java is case-sensitive For example, if you wanted to declare a variable of type String called message, you could do it like this String message; Actual String values, often called String literals, are delimited by double quotation marks (") This is unlike char values, which are delimited by apostrophes In Java, every (legal) character sequence delimited by double quotation marks is a String literal Examples of String literals: "Hello", "world", "See ya!" 86

87 String Assignment The assignment operator works almost the same way with Strings as it does with primitive types The syntax is the same The semantics are mostly the same; the differences will be explained in detail when we cover reference types String message; message = "Hello world!"; // Variable message now contains the // String value "Hello world!" System.out.println(message); // Displays "Hello world!" 87

88 String Concatenation String concatenation occurs when a String is added to the end of another String, thus forming a new String The concatenation of "a" and "b" is "ab"; likewise, the concatenation of "ab" and "cd" is "abcd" In Java, the String concatenation operator is the + operator "hello " + "world" results in a new String This new String will be "hello world" The + operator is the only arithmetic operator which can be used with Strings 88

89 Reading and Displaying Strings We can read Strings from the keyboard just like we read int or double values Simply replace nextint() or nextdouble() by nextline() The variable on the left side of the assignment statement must be of type String nextline() reads an entire line of text We can also display Strings to the screen just like we display anything else: by using System.out.print() or System.out.println() 89

90 Facts.java public class Facts { public static void main(string[] args) { String firstname = "Cuthbert"; String lastname = "Calculus"; String fullname; } } fullname = firstname + " " + lastname; System.out.println("His name is: " + fullname); What is the output? 90

91 String Caveats (1) One must be able to distinguish String literals from String variables String variables are regular identifiers String literals are always surrounded by double quotation marks Therefore, assuming that variables text and message of type String, and that the value of variable message is the String "Hello!" The line text = "message"; assigns the String value "message" to String variable text 91

92 String Caveats (2) Thus, if the line System.out.println(text); is executed next, the following will be displayed to the screen: message On the other hand, the line text = message; assigns the String value stored in String variable message (that is, the String "Hello!") to String variable text Thus, if the line System.out.println(text); is executed next, the following will be displayed to the screen: Hello! 92

93 String Caveats (3) A String literal cannot be broken across two lines of source code by inserting an end-of-line sequence in it If you really need to split a String literal across two lines in your program, break the original literal into two smaller String literals and combine them with the concatenation operator The following code fragment causes an error: "This is a very long literal that spans two lines" // Incorrect! However, the following code fragment is legal: "These are two shorter literals " + "that are on separate lines" // OK 93

94 String Escape Sequences (1) What if we wanted to include a double quotation mark in a String literal? The following line would confuse the compiler because it would interpret the second double quotation mark as the end of the String literal: System.out.println("I said "Hello" to you."); If we want to include a double quotation mark in a String literal, the double quotation mark has to be escaped by putting a backslash (\) in front of it System.out.println("I said \"Hello\" to " + "you."); 94

95 String Escape Sequences (2) In general, escape characters work the same with Strings as they do with chars However: Double quotation marks MUST be escaped in String literals, but not in char literals Apostrophes MUST be escaped in char literals, but not in String literals Escaping a double quotation mark in a char literal or an apostrophe in a String literal has no effect 95

96 Poem.java public class Poem { public static void main(string[] args) { System.out.println("Roses are red,"); System.out.println("\t Violets are blue"); System.out.println("\t This poem " + "sucks\n\t I wish it were a haiku"); } } What does this display? 96

97 Haiku.java public class Haiku { public static void main(string[] args) { System.out.print("\t Windows Vista crashed."); System.out.print("\n\t I am the Blue Screen " + "of Death.\n"); System.out.println("\t No one hears your screams."); } } What does this display? 97

98 Strings: Exercise Write a Java program which consists of one class called Greeting. This class should define a method called main() which does the following: Displays a message asking the user to enter his/her first name, and reads the first name from the keyboard Displays a message asking the user to enter his/her last name, and reads the last name from the keyboard Displays a greeting to the user in the following format: the String "Hello, ", followed by the user's first name, followed by a single space, followed by the user's last name, followed by an exclamation mark (!) 98

99 Part 5: Data Conversion

100 Data Conversion Sometimes it is convenient to convert data from one type to another For example, we may want to treat an integer as a floating point value during a computation Conversions must be handled carefully to avoid losing information There are two types of conversions: Widening conversions Narrowing conversions But first, a word on precision 100

101 Precision The precision of a type is the range of all possible values you can express with a variable of that type Variables of type int have higher precision than variables of type short; you can express more values with a variable of type int than with a variable of type short Variables of type double have higher precision that variables of type int; again, you can express more values with a variable of type double than with a variable of type int There is a correlation between the number of bytes used to store a value of a given type, and the precision of that type byte uses only 8 bits and has the lowest precision; double uses 64 bits and has the highest precision 101

102 Conversion Types Widening conversions occur when a value whose type has lower precision is converted to a type that has higher precision (such as a short to an int or an int to a double) They are usually safe, as there is usually no information lost Narrowing conversions occur when a value whose type has higher precision is converted to a type that has lower precision (such as an int to a short or double to int) Information can be lost when conversions of this type occur 102

103 Assignment Conversion (1) In Java, data conversions can occur in three ways: Assignment conversion Arithmetic promotion Casting Assignment conversion occurs when a value of one type is assigned to a variable of another type Only widening conversions can occur via assignment (such as assigning a value of type int to a variable of type double) If we attempt a narrowing conversion via assignment (such as assigning a value of type double to a variable of type int), the compiler will issue an error 103

104 Assignment Conversion (2) Assignment conversions occur automatically For example, if we attempt to assign the value of an expression of type int to a variable of type double, the value of the expression will be automatically converted to have type double The second assignment statement below is perfectly legal: int i = 7; double d = 3 + i; The expression on the right-hand side has type int, which has lower precision than type double, the type of the variable on the left-hand side The value of 3 + i gets converted to have type double and gets assigned to d; note that the type of i does not change 104

105 Assignment Conversion (3) The assignment second assignment statement below is illegal: double d = 7.0; int i = d; The expression on the right-hand side has type double, which has higher precision than type int, the type of the variable on the left-hand side The compiler will therefore report an error 105

106 Arithmetic Promotion Arithmetic promotion happens automatically when operators in expressions convert their operands double kmperlitre; int km = 1000; float litres = 85.0f; kmperlitre = km / litres; (2) Division (1) Arithmetic promotion to float (3) Assignment conversion to double (4) Assign result to kmperlitre 106

107 Casting (1) Casting (also called typecasting) is the most powerful, general, and dangerous, technique for conversion It trusts that you know what you are doing Both widening and narrowing conversions can be accomplished by explicitly casting a value It is the only way to perform a narrowing conversion To cast, the type you want to convert a value to is put in parentheses in front of the value being converted. The general syntax is thus: (desiredtype) expression 107

108 Casting (2) The cast does not change the type of the value in a variable for the rest of the program, only for the operation in which the value is cast When casting from floating point to integer, the fractional part of the floating point is discarded double money = 25.80; int dollars; dollars = (int)money; // dollars contains the value 25 // money still contains the value

109 Casting (3) Casting has higher precedence than the arithmetic operators double a; int b, c, d; a = 3.5; b = 3; c = (int)a * b; d = (int)(a * b); Only the value of a is cast; the value of b is not cast Thus, c now contains the value 9 The product of a and b is cast Thus, d now contains the value

110 Conversion Traps (1) Consider the following variable declarations: int total = 10; int count = 4; double result; What will the value of result be after the following statement is executed? result = total / count; The value of result is now 2.0 (?!?) The two operands of the division operator have type int; thus, integer division is performed, truncating the fractional part The result of total / count is therefore 2 and has type int 110

111 Conversion Traps (2) It's only when the quotient is assigned to result that it is converted to type double via assignment conversion Casting one of the integer operands to double (or float) will result in floating point division being performed instead result = (float)total / count; The value of result is now 2.5 First, total is cast to type float Arithmetic promotion occurs to promote count to have type float; floating point division is performed and the result of the division therefore has type float The quotient is converted to type double before being assigned to result 111

112 Conversion Examples Code Fragment double x = 5.9; int y = (int) x; int a = 5; float b = 7.3f; double c = 10.03; c = b + a; int a = 2, b = 5; double c = 22; c = a / b; Result y contains value 5 c contains value 12.3 c contains value

113 Type Conversions and Strings For the most part, primitive types and Strings do not mix Assignment conversion between Strings and primitive types is forbidden If you try to assign a value whose type is a primitive type to a String variable, the compiler will report an error If you try to assign a String to a variable whose type is a primitive type, the compiler will also report an error Casting a String to a primitive type and casting a value whose type is a primitive type to a String are both forbidden The compiler will report an error in those cases as well 113

114 Mixed-Type Concatenation (1) On the other hand, we can convert a value whose type is a primitive type to a String by using something similar to arithmetic promotion Remember: the plus operator (+) is used for both arithmetic addition and for string concatenation The function that the + operator performs depends on the type of the values on which it operates Strings are considered to have higher precision than numeric types If both operands are of type String, or if one is of type String and the other is numeric, the + operator performs string concatenation (after "promoting" the numeric operand, if any, to type String by generating its textual representation) 114

115 Mixed-Type Concatenation (2) If both operands are numeric, it adds them The + operator is evaluated left to right, regardless of whether it performs addition or string concatenation However, parentheses can always be used to force the operation order This suggests a useful trick to convert a value whose type is a primitive type to a String: concatenate the empty String "" with the value int i = 42; String s = "" + i; // s contains the String "42" 115

116 Addition.java public class Addition { public static void main(string[] args) { int x = 5; int y = 2; int sum = 0; String message = "The sum is "; } } sum = x + y; message = message + sum; System.out.println(message); What is the output? 116

117 Trick Question (1) What will be the output of the following code fragment? System.out.println("The sum of 5 and 3 is " ); The answer is: The sum of 5 and 3 is 53 (?!?) Explanation: The + operator is evaluated from left to right Thus, it is first applied to "The sum of 5 and 3 is " and the int literal 5 to form the String "The sum of 5 and 3 is 5" Then, we apply the + operator to the result from the previous concatenation operation and the int literal 3 to get "The sum of 5 and 3 is 53" 117

118 Trick Question (2) What will be the output of the following code fragment? System.out.println( " is the sum of " + "5 and 3"); The answer is: 8 is the sum of 5 and 3 (?!?) Explanation: Again, the + operator is evaluated from left to right Thus, it is first applied to the int literals 5 and 3; both of these have numeric type, so addition is performed and the sum is 8 Then, the + operator is applied to the result of the addition and the String literal " is the sum of "; the sum is converted from int to String and concatenated with the String literal 118

119 Trick Question (3) Finally, the String literal "5 and 3" is concatenated to the String "8 is the sum of " to form the String "8 is the sum of 5 and 3" Lesson: When in doubt, use parentheses 119

120 Part 6: Problem Solving

121 Problem Solving The purpose of writing a program is to solve a problem (or rather, have the computer solve a problem for us) The general steps in problem solving are: Understand the problem Dissect the problem into manageable pieces Design a solution for each of the pieces Consider alternatives to the solutions and refine them Implement the solutions Test the solutions and fix any problems that exist Combine the solutions for each of the piece to obtain the solution to the original problem 121

122 Part 7: Exercises

123 Exercises (1) 1. Write a program which consists of a single class called BMICalculator. This class must define a method called main() which does the following: Asks the user to enter his/her weight (in kilograms) and his/her height (in meters) Calculates the user's Body Mass Index (BMI); a person's BMI can be computed by dividing his /her weight in kilograms by the square of his / her height in meters. Displays the user's BMI it to the screen 123

124 Exercises (2) 2. Write a program which consists of a single class called EnergyCalculator. This class defines a method called main() which does the following: Asks the user to enter a quantity of water (in kilograms), an initial temperature (in Celcius degrees), and a final temperature (also in Celcius degrees) Calculates how much energy (in joules) is needed to raise that quantity of water from the initial temperature to the final temperature; the formula for this calculation is q = 4184 m (f i), where q is the energy, m is the quantity of water, f is the final temperature, and i is the initial temperature. You may assume that there are no state transitions (from ice to water or water to steam, for example) in the temperature interval Displays the required energy quantity to the screen 124

125 Exercises (3) 3. Write a program which consists of a single class called GoalieStatsCalculator. This class defines a method called main() which does the following: Asks the user to enter the number of minutes an ice hockey goalie has played, the number of goals he / she allowed, and the total number of shots he / she faced Calculates the goalie's goals against average (GAA) and save percentage; the GAA is the number of goals allowed per 60 minutes of play, while the save percentage is the number of saves (the total number of shots minus the number of goals allowed) divided by the number of shots faced Displays the goalie's GAA and save percentage to the screen 125

COMP 202 Java in one week

COMP 202 Java in one week CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language

More information

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2 CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,

More information

COMP 202 Java in one week

COMP 202 Java in one week 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

More information

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on: Data and Expressions Data and Expressions Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration And Use Of Variables Expressions

More information

COMP 202. Java in one week

COMP 202. Java in one week COMP 202 CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator Java in one week The Java Programming Language A programming language

More information

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are

More information

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Introduce the Java programming

More information

A variable is a name for a location in memory A variable must be declared

A variable is a name for a location in memory A variable must be declared Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;

More information

Chapter. Let's explore some other fundamental programming concepts

Chapter. Let's explore some other fundamental programming concepts Data and Expressions 2 Chapter 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design 2007 Pearson Addison-Wesley. All rights reserved Data and Expressions Let's explore some

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Chapter 2: Data and Expressions

Chapter 2: Data and Expressions Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University April 21, 2015 Chapter 2: Data and Expressions CS 121 1 / 53 Chapter 2 Part 1: Data Types

More information

Chapter 2: Data and Expressions

Chapter 2: Data and Expressions Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University January 15, 2015 Chapter 2: Data and Expressions CS 121 1 / 1 Chapter 2 Part 1: Data

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods COMP-202 Unit 2: Java Basics CONTENTS: Using Expressions and Variables Types Strings Methods Assignment 1 Assignment 1 posted on WebCt and course website. It is due May 18th st at 23:30 Worth 6% Part programming,

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

For the course, we will be using JCreator as the IDE (Integrated Development Environment).

For the course, we will be using JCreator as the IDE (Integrated Development Environment). For the course, we will be using JCreator as the IDE (Integrated Development Environment). We strongly advise that you install these to your own computers. If you do not have your own computer, the computer

More information

ECE 122 Engineering Problem Solving with Java

ECE 122 Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction Outline Problem: How do I input data and use it in complicated expressions Creating complicated expressions

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

Chapter 2. Elementary Programming

Chapter 2. Elementary Programming Chapter 2 Elementary Programming 1 Objectives To write Java programs to perform simple calculations To obtain input from the console using the Scanner class To use identifiers to name variables, constants,

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Chapter 2: Data and Expressions

Chapter 2: Data and Expressions Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University August 21, 2017 Chapter 2: Data and Expressions CS 121 1 / 51 Chapter 1 Terminology Review

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

CMPT 125: Lecture 3 Data and Expressions

CMPT 125: Lecture 3 Data and Expressions CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,

More information

Elementary Programming

Elementary Programming Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Learn ingredients of elementary programming: data types [numbers, characters, strings] literal

More information

2 rd class Department of Programming. OOP with Java Programming

2 rd class Department of Programming. OOP with Java Programming 1. Structured Programming and Object-Oriented Programming During the 1970s and into the 80s, the primary software engineering methodology was structured programming. The structured programming approach

More information

2: Basics of Java Programming

2: Basics of Java Programming 2: Basics of Java Programming CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

More information

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java Introduction Objectives An overview of object-oriented concepts. Programming and programming languages An introduction to Java 1-2 Problem Solving The purpose of writing a program is to solve a problem

More information

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2 Java Foundations Introduction to Program Design and Data Structures 4th Edition Lewis TEST BANK Full download at : https://testbankreal.com/download/java-foundations-introduction-toprogram-design-and-data-structures-4th-edition-lewis-test-bank/

More information

Computer Science is...

Computer Science is... Computer Science is... Bioinformatics Computer scientists develop algorithms and statistical techniques to interpret huge amounts of biological data. Example: mapping the human genome. Right: 3D model

More information

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time Tester vs. Controller Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG For effective illustrations, code examples will mostly be written in the form of a tester

More information

Basics of Java Programming

Basics of Java Programming Basics of Java Programming Lecture 2 COP 3252 Summer 2017 May 16, 2017 Components of a Java Program statements - A statement is some action or sequence of actions, given as a command in code. A statement

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process Entry Point of Execution: the main Method Elementary Programming EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG For now, all your programming exercises will

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

3. Java - Language Constructs I

3. Java - Language Constructs I Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks

More information

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Overview of Source Code Components Comments Library declaration Classes Functions Variables Comments Can

More information

COMP-202 Unit 5: Basics of Using Objects

COMP-202 Unit 5: Basics of Using Objects COMP-202 Unit 5: Basics of Using Objects CONTENTS: Concepts: Classes, Objects, and Methods Creating and Using Objects Introduction to Basic Java Classes (String, Random, Scanner, Math...) Introduction

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings COMP-202 Unit 2: Java Basics CONTENTS: Using Expressions and Variables Types Strings Assignment 1 Assignment 1 posted on WebCt. It will be due January 21 st at 13:00 Worth 4% Last Class Input and Output

More information

Data Conversion & Scanner Class

Data Conversion & Scanner Class Data Conversion & Scanner Class Quick review of last lecture August 29, 2007 ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor: Alexander Stoytchev Numeric Primitive Data Storing

More information

Chapter 2 Elementary Programming

Chapter 2 Elementary Programming Chapter 2 Elementary Programming Part I 1 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical

More information

Chapter. Focus of the Course. Object-Oriented Software Development. program design, implementation, and testing

Chapter. Focus of the Course. Object-Oriented Software Development. program design, implementation, and testing Introduction 1 Chapter 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design 2007 Pearson Addison-Wesley. All rights reserved Focus of the Course Object-Oriented Software Development

More information

Basic Computation. Chapter 2

Basic Computation. Chapter 2 Basic Computation Chapter 2 Outline Variables and Expressions The Class String Keyboard and Screen I/O Documentation and Style Variables Variables store data such as numbers and letters. Think of them

More information

Programming Lecture 3

Programming Lecture 3 Programming Lecture 3 Expressions (Chapter 3) Primitive types Aside: Context Free Grammars Constants, variables Identifiers Variable declarations Arithmetic expressions Operator precedence Assignment statements

More information

Chapter 2 ELEMENTARY PROGRAMMING

Chapter 2 ELEMENTARY PROGRAMMING Chapter 2 ELEMENTARY PROGRAMMING Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk ١ Objectives To write Java programs to perform simple

More information

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Built in Libraries and objects CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Objects and Built in Libraries 1 Classes and Objects An object is an

More information

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015 Announcements Midterm Exams on 4 th of June (12:35 14:35) Room allocation will be announced soon

More information

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

More information

Section 2: Introduction to Java. Historical note

Section 2: Introduction to Java. Historical note The only way to learn a new programming language is by writing programs in it. - B. Kernighan & D. Ritchie Section 2: Introduction to Java Objectives: Data Types Characters and Strings Operators and Precedence

More information

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

More information

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #2

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic BIT 3383 Java Programming Sem 1 Session 2011/12 Chapter 2 JAVA basic Objective: After this lesson, you should be able to: declare, initialize and use variables according to Java programming language guidelines

More information

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value Lecture Notes 1. Comments a. /* */ b. // 2. Program Structures a. public class ComputeArea { public static void main(string[ ] args) { // input radius // compute area algorithm // output area Actions to

More information

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language Chapter 1 Getting Started Introduction To Java Most people are familiar with Java as a language for Internet applications We will study Java as a general purpose programming language The syntax of expressions

More information

CEN 414 Java Programming

CEN 414 Java Programming CEN 414 Java Programming Instructor: H. Esin ÜNAL SPRING 2017 Slides are modified from original slides of Y. Daniel Liang WEEK 2 ELEMENTARY PROGRAMMING 2 Computing the Area of a Circle public class ComputeArea

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

Primitive Data Types: Intro

Primitive Data Types: Intro Primitive Data Types: Intro Primitive data types represent single values and are built into a language Java primitive numeric data types: 1. Integral types (a) byte (b) int (c) short (d) long 2. Real types

More information

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Lesson 02 Data Types and Statements MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Topics Covered Statements Variables Constants Data Types

More information

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Introduction to Java Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) Introduce Java, a general-purpose programming language,

More information

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 2 : C# Language Basics Lecture Contents 2 The C# language First program Variables and constants Input/output Expressions and casting

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables COMP-202 Unit 2: Java Basics CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables Assignment 1 Assignment 1 posted on WebCt and course website.

More information

2 nd Week Lecture Notes

2 nd Week Lecture Notes 2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous

More information

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1 Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1 Topics 1. Expressions 2. Operator precedence 3. Shorthand operators 4. Data/Type Conversion 1/15/19 CSE 1321 MODULE 2 2 Expressions

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lesson 02 Variables and Operators Agenda Variables Types Naming Assignment Data Types Type casting Operators

More information

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics WIT COMP1000 Java Basics Java Origins Java was developed by James Gosling at Sun Microsystems in the early 1990s It was derived largely from the C++ programming language with several enhancements Java

More information

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 Announcements Slides will be posted before the class. There might be few

More information

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. Today! Build HelloWorld yourself in BlueJ and Eclipse. Look at all the Java keywords. Primitive Types. HelloWorld in BlueJ 1. Find BlueJ in the start menu, but start the Select VM program instead (you

More information

More Programming Constructs -- Introduction

More Programming Constructs -- Introduction More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and

More information

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Lesson 02 Data Types and Statements MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Topics Covered Statements Variables Data Types Arithmetic

More information

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes Entry Point of Execution: the main Method Elementary Programming EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG For now, all your programming exercises will be defined within the

More information

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence Data and Variables Data Types Expressions Operators Precedence String Concatenation Variables Declaration Assignment Shorthand operators Review class All code in a java file is written in a class public

More information

Basic Computation. Chapter 2

Basic Computation. Chapter 2 Walter Savitch Frank M. Carrano Basic Computation Chapter 2 Outline Variables and Expressions The Class String Keyboard and Screen I/O Documentation and Style Variables Variables store data such as numbers

More information

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003 Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 Java Programs A Java program contains at least one class definition. public class Hello { public static void

More information

A Java program contains at least one class definition.

A Java program contains at least one class definition. Java Programs Identifiers Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 A Java program contains at least one class definition. public class Hello { public

More information

B.V. Patel Institute of BMC & IT, UTU 2014

B.V. Patel Institute of BMC & IT, UTU 2014 BCA 3 rd Semester 030010301 - Java Programming Unit-1(Java Platform and Programming Elements) Q-1 Answer the following question in short. [1 Mark each] 1. Who is known as creator of JAVA? 2. Why do we

More information

First Java Program - Output to the Screen

First Java Program - Output to the Screen First Java Program - Output to the Screen These notes are written assuming that the reader has never programmed in Java, but has programmed in another language in the past. In any language, one of the

More information

Lecture 3: Variables and assignment

Lecture 3: Variables and assignment Lecture 3: Variables and assignment CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

More information

What did we talk about last time? Examples switch statements

What did we talk about last time? Examples switch statements Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation

More information

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp DM550 / DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ OBJECT-ORIENTED PROGRAMMING IN JAVA 2 Programming

More information

Introduction to Java Applications; Input/Output and Operators

Introduction to Java Applications; Input/Output and Operators www.thestudycampus.com Introduction to Java Applications; Input/Output and Operators 2.1 Introduction 2.2 Your First Program in Java: Printing a Line of Text 2.3 Modifying Your First Java Program 2.4 Displaying

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos. Lecture 2: Variables and Operators AITI Nigeria Summer 2012 University of Lagos. Agenda Variables Types Naming Assignment Data Types Type casting Operators Declaring Variables in Java type name; Variables

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables COMP-202 Unit 2: Java Basics CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables Part 1: Printing to the Screen Recall: HelloWorld public class

More information

Introduction to C# Applications

Introduction to C# Applications 1 2 3 Introduction to C# Applications OBJECTIVES To write simple C# applications To write statements that input and output data to the screen. To declare and use data of various types. To write decision-making

More information

JAVA Ch. 4. Variables and Constants Lawrenceville Press

JAVA Ch. 4. Variables and Constants Lawrenceville Press JAVA Ch. 4 Variables and Constants Slide 1 Slide 2 Warm up/introduction int A = 13; int B = 23; int C; C = A+B; System.out.print( The answer is +C); Slide 3 Declaring and using variables Slide 4 Declaring

More information

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

More information

AP Computer Science A

AP Computer Science A AP Computer Science A 1st Quarter Notes Table of Contents - section links Click on the date or topic below to jump to that section Date : 9/8/2017 Aim : Java Basics Objects and Classes Data types: Primitive

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

Introduction to Java Applications

Introduction to Java Applications 2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

More information

Chapter 2: Programming Concepts

Chapter 2: Programming Concepts Chapter 2: Programming Concepts Objectives Students should Know the steps required to create programs using a programming language and related terminology. Be familiar with the basic structure of a Java

More information

An overview of Java, Data types and variables

An overview of Java, Data types and variables An overview of Java, Data types and variables Lecture 2 from (UNIT IV) Prepared by Mrs. K.M. Sanghavi 1 2 Hello World // HelloWorld.java: Hello World program import java.lang.*; class HelloWorld { public

More information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

Declaration and Memory

Declaration and Memory Declaration and Memory With the declaration int width; the compiler will set aside a 4-byte (32-bit) block of memory (see right) The compiler has a symbol table, which will have an entry such as Identifier

More information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

CS102: Variables and Expressions

CS102: Variables and Expressions CS102: Variables and Expressions The topic of variables is one of the most important in C or any other high-level programming language. We will start with a simple example: int x; printf("the value of

More information

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B Java for Python Programmers Comparison of Python and Java Constructs Reading: L&C, App B 1 General Formatting Shebang #!/usr/bin/env python Comments # comments for human readers - not code statement #

More information