Presentation is loading. Please wait.

Presentation is loading. Please wait.

OBJECT ORIENTED PROGRAMMING I LECTURE 3 GEORGE KOUTSOGIANNAKIS

Similar presentations


Presentation on theme: "OBJECT ORIENTED PROGRAMMING I LECTURE 3 GEORGE KOUTSOGIANNAKIS"— Presentation transcript:

1 OBJECT ORIENTED PROGRAMMING I LECTURE 3 GEORGE KOUTSOGIANNAKIS
CS 201 OBJECT ORIENTED PROGRAMMING I LECTURE 3 GEORGE KOUTSOGIANNAKIS Copyright: FALL 2016 Illinois Institute of Technology- George Koutsogiannakis

2 Topics Data Types. Variables. Constants. Type casting of Data Types.
Expressions. Arithmetic Operators. Precedence of Operators.

3 Keywords When we write a program in Java we use certain words to indicate what the program should do. The words that define the command are proprietary to the programming language we use (Java in our case). That means that they are part of the vocabulary of the programming language (i.e. Java). Java Keywords can’t be used for anything else in the program (for instance to identify data). Edit Plus helps you recognize keywords by using font colors like red and blue. Thus if you are typing a keyword and it does not printed on the Edit Plus text editor in color, it is a clue to you that you are misspelling it. Example of keywords: public class

4 Data Types A Programming Language uses data types to manipulate data
Data is categorized according to the way the computer stores the data. By data type we mean a particular category of data. Each data type requires a specific amount of computer memory for storage. As an example : Storing the number 5 versus storing the number 5.34. 5 is of one type (because it is a whole number)and it may take 4 bytes of memory. Whole numbers are called integers in programming languages. The data type in java is abbreviated with the keyword int 5.34 is of a different type and it may take 8 bytes of memory. Notice that 5.34 is a decimal number. Decimal numbers are represented with either double (it takes 8 bytes of memory to store it) or float (it takes 4 bytes of memory to store it).

5 Data Types Data types can be primitive:
Java has eight primitive data types byte, short, int, long, float, double, char, boolean All of the above names for the data types are keywords in the language. Remember that keywords are words reserved for the language and as a result they can not be used by the programmer to name other attribute sof the program (i.e. the program itself). OR Data types can also be user defined (in other words the programmer decides ) as we will learn later on.

6 Primitive Data Types Primitive data types:
int : used to represent whole numbers. It takes 4 bytes of memory to store a number of type int. The range of numbers that can be represented by int is: -2,147,483,648 to 2,147,483,647 long: some integers (whole numbers) can be very large and as a result require more memory. This data type reserves 8 bytes in memory and the range of numbers that can be represented by a long data type is: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

7 Primitive Data Types short: Some whole numbers (integers) can be small enough so that we can save memory by storing them in less memory space. Short take s2 bytes of memory. The range is: -32,768 to 32,768 byte: We can save additional space in memory sometimes by representing a number in a binary format. It take sonly 1 byte of memory. float: Used to represent decimal numbers (called floating point numbers). It takes 4 bytes of memory. Not used for decimal numbers where high precision is required (in other words the number of decimal points is limited). double: Used to represent decimal numbers (called floating point numbers). It takes 8 bytes of memory. Used for decimal numbers where high precision is required (in other words the number of decimal points is large).

8 Primitive Data Types char: It takes 2 bytes of memory to store it. It represents the binary coded value of a character or symbol from the keyboard or other symbols that you don’t see keys on the keyboard (i.e alphabet of other languages). The binary coded value is based on Unicode. boolean: Sometimes we only care to evaluate a condition and see if the outcome is true or false. Java has a dedicated a data type where its value can be one of the two: true or false. It represents one bit of information ( a binary 1 or binary 0).

9 Data Types- Usage of Identifiers
In order for computers to store the data we need to identify a variable that represents the particular data type. For example in algebra we can use letters to represent numbers i.e. (x+y-z)*s The variable that we use can be a name or a letter (some kind of a symbol in other words) etc. The symbol that will represent the data type is called the identifier.

10 Data Types- Usage of Identifiers
A variable then is some identifier that identifies a specific data type. The variable can acquire different values. What’s is the meaning of the identifier as far as the computer is concern? The computer stores data in memory. Memory locations for the data are addressed by hex numbers. A human (the programmer) can’t remember all the addresses that the computer uses but he/she can remember names. Therefore an identifier is converted by the computer into a memory addresses where that particular data is stored. Both are satisfied now. The computer can use its hex system of addresses and the human can use a name (the identifier for that data) to refer to the memory location of a particular data.

11 Data Types- Usage of Identifiers
In programming languages we use the term declaration to indicate that in our program: We have chosen a particular data type and That the particular data type will be represented by some identifier ( a name or a single letter for example). We could also add an initial value to the data type during declaration i.e Notice that the identifier name that we use to identify the name can not be a keyword of the language (identifiers are not keywords). There are, however, rules for using identifier names:

12 Usage of Identifiers (rules for choosing identifier names)
Some of the rules are: Can’t start with number, it can start with any letter of the alphabet, it can even start with underscore or dollar sign, but that’s only for the first character, after that, it’s all good, you can use numbers, underscore, dollar sign and of course, letter of the alphabet. Can’t be the same as Java special words (Java keywords); there’s about 52 of them. Like all things in Java, identifiers are case sensitive  The Java language spec says that a Java identifier is unlimited in terms of length (in terms of characters).

13 Data Types int num = 3; Where int is the particular data type name that the programming language uses num is the identifier for the data type and 3 is the present value that the identifier holds. We call it the initial value. In other words assume that the box represents 4 bytes of memory: num num is the address that points to the memory location for our number 3. Keep in mind that the value 3 can change as the execution of the program progresses and that the identifier num can point to a different value later on (in the same memory location). 3

14 Data Types The computer will assign a memory space to hold the data type. In our previous example: The computer will reserve 4 bytes of memory for the identifier num because it is of int type. The computer always refers to that memory space under the name num. Thus if later on during the execution of the program num = 5 The computer goes to the memory location identified under the name num and instead of the previous value 3 it stores there the value 5 now. That memory location in ,our example, that we called num will always represent an int data type during the execution of our program. We can Not try to force a decimal number of type double in it!

15 PRIMITIVE Data Types Integer data types are denoted with int and represent whole numbers as we discussed in previous lecture. int takes up 4 bytes in memory (32 bits). Depending on how big the number is we could choose variations of int represented by byte, long, short. We use int when a number is a whole number (integer) i.e. the nymber 6 or the number 123.

16 Identifiers Programming Rule: i.e. The declaration below is not valid
Every data that we need in our program has to be declared of a particular data type. For every data beside steh data type, w ehave to use a name for that data. The generic word for the names used is : identifier. The identifier name chosen can not be a Java langage keyword and some other restrictions apply (see text for more details). The process of choosing a data type and its identifier for a specific data is called: Declaration. i.e The declaration below is not valid int class. Class is a keyword and can not be used as an identifier.

17 Example program Let us write a Java program that adds two int data types. public class Addition { public static void main(String[] args) int a=3; int another=4; int c=0; c=a+another; System.out.println(“The result is”+c); }

18 Example Program The computer will store the values of the variables: a, another, c in memory. Initially: a c another 4 bytes of memory reserved to store the number 3 4 bytes of memory reserved to store the number 4 4 bytes of memory reserved to store the number 0 Each variable has been assigned 4 bytes of memory because they have been Declared as int data type. After the calculation is performed the memory locations a and another retained the values 3 and 4 but the memory location c has the value 7 in it now.

19 PRIMITIVE Data Types Floating-Point Data Types Example declarations:
Numbers with fractional parts: Type Size Minimum Positive Maximum Value in Bytes Nonzero Value float E E38 double E E308 Example declarations: float salesTax; double interestRate; double paycheck, sumSalaries;

20 PRIMITIVE Data Types Example declarations:
char Data Type One Unicode character (16 bits - 2 bytes) Type Size Minimum Value Maximum Value in Bytes char character character encoded as encoded as FFFF (Notice that 4 hex numbers require 16 bits) Example declarations: char finalGrade; char newline, tab, doubleQuotes;

21 Special Characters Empty Character:
symbol shown as ‘ ’ Unicode encoding is decimal 32 or 0x20. Digits 0-9 have a unicode encoding also 0 (zero)is encoded: 48 or 0x30 : 57 or 0x39

22 Escape Sequences Strings are composed of characters (but Strings are not primitive data types) i.e. the String “George” is composed of characters: ‘ G’ ‘e’ ‘o’ ‘r’ ‘g’ ‘e’ (notice that characters are enclosed with single quotation marks- Strings are enclosed with double quotation marks). To include a special character in a String, use an escape sequence

23 Escape Sequences Character Escape Sequence Newline \n Tab \t
Double quotes \" Single quote \' Backslash \\ Backspace \b Carriage return \r Form feed \f

24 Escape Sequence Example:
System.out.println(“My name is Peter\n”+ “Your name is Anna”); The output will be: My name is Peter Your name is Anna

25 Assignment Operator The equal sign symbol (= ) is called the assignment operator. Assignment operator = Value on the right of the operator is assigned to the variable on the left Value on the right can be a literal (text representing a specific value), another variable, or an expression (a valid combination of variables, operators, and constants -- explained in detail later) Examples: x = 20; y = x;

26 Assignment Operator Do not confuse assignment operator with the arithmetic concept of equal. Arithmetic equal requires to equal signs i.e. x == y means x is equal to y

27 ANOTHER PRIMITIVE Data Type
boolean Data Type Two values only: true false Used for decision making or as "flag" variables Example declarations: boolean isEmpty; boolean passed, failed;

28 Assigning Values to Variables
Syntax for assigning initial values to variables: dataType variableName = initialValue; or dataType variable1 = initialValue1, variable2 = initialValue2, …; Examples: int age = 19; double taxRate = .20, salesTax = .06;

29 Literals Literals are the specific values of data types.
int, short, byte data type Literals Optional initial sign (+ or -) followed by digits 0 9 in any combination i.e int x= -8; , short y=10; byte z=2; Long data type Literals Optional initial sign (+ or -) followed by digits 0–9 in any combination, terminated with an L or l i.e. long myinteger=3504L Integer literals that begin with 0 are considered to be octal values; Integer literals that begin with 0x are considered to be hexadecimal values. i.e int x=0x23; means that x has been assigned the value of the hex number 23.

30 Floating-Point Literals
Optional initial sign (+ or -) followed by a floating-point number in fixed or scientific format, terminated by an F or f. i.e. float x=0.3; or float x=0.3F double Optional initial sign (+ or -) followed by a floating-point number in fixed or scientific format. i.e double x=0.3;

31 char and boolean Literals
Any printable character enclosed in single quotes i.e. char mychar=‘e’ ; means that the identifier mychar is of char data type and that it has been assigned the character value of e A decimal value from 0 – 65535 i.e char mychar=32; is the same as char mychar=‘ ‘ ; (empty character). Why? '\m' , where \m is an escape sequence. '\n' represents a newline, and '\t' represents a tab character. i.e char mychar=‘\n’; boolean true or false i.e boolean b=true;

32 Assigning the Values of Other Variables
Syntax: dataType variable2 = variable1; Rules: 1. variable1 needs to be defined before this statement appears in the source code 2. variable1 and variable2 need to be compatible data types; in other words, the precision of variable1 must be lower than or equal to that of variable2 i.e int x; int y; x=y;

33 Compatible Data Types A variable of any type in right column can be assigned to a variable of any type in left column: Data Type Compatible Data Types byte byte short byte, short int byte, short, int, char long byte, short, int, long, char float float, byte, short, int, long, char double float, double, byte, short, int, long, char boolean boolean char char

34 Sample Assignments This is a valid assignment: float salesTax = .05f;
double taxRate = salesTax; This is invalid because the float data type is lower in precision than the double data type: double taxRate = .05; float salesTax = taxRate;

35 String Literals String is a class, not a basic data type; String variables are objects String literal: text contained within double quotes Examples of String literals: String mystring=“hello" ; String str="Hello world“; String s="The value of x is “;

36 Common Error Trap generates these compiler errors:
String literals must start and end on the same line. This statement: System.out.println( "Never pass a water fountain without taking a drink" ); generates these compiler errors: unclosed string literal ')' expected Break long Strings into shorter Strings and use the concatenation operator: System.out.println( "Never pass a water" + "fountain without taking a drink" );

37 Constants The value of a constant cannot change during program execution Syntax: final dataType constantIdentifier = assignedValue; Note: assigning a value when the constant is declared is optional. However, a value must be assigned before the constant is used. i.e. final int x=10; means that x will always have the value 10 and can not be assigned another value.

38 Typecasting Typecasting means converting one data type to another.
A higher precision data type can be converted to a lower precision i.e. Suppose we have to divide 8.2/3.4 . The result is a decimal number of course. A program will give us a result of as an example (see next slide) But suppose we wanted the result to be a whole number instead: The following operation will convert the result to a whole number: (int) ( 8.2/3.4 ) The fact that we included (int) in front of the fraction, forces the result to be a whole number. The result in this case will be given as 2 The next slide shows the program that can test the above.

39 Typecasting public class WithoutTypecasting {
public static void main(String[] args) double a = 8.2/3.4; System.out.println(a); } The output of this program is:

40 Typecasting public class TestTypecasting {
public static void main(String[] args) int a= (int) (8.2/3.4); System.out.println(a); } The output of this program is 2 (we lost the precision of the decimals).

41 Typecasting Another example: double x=3.45; double y=1.654;
int z=(int)(x/y) ; The above type casting forces the result which normally will be a double, to be converted (type casted) to a int data type (whole number). The result will be 2 (without typecasting the result is: ) Notice that in doing so we loose precision!

42 Typecasting How about the following typecasting: double x=3.45;
double y=1.654; double z= (int) x/y What is the difference now? Write a short program to test it. Try to explain the difference in the result. Note that the result now is:

43 Typecasting Suppose that we want to convert an int to a char we can do that by using type casting: int x; (char)x; The code above will try to identify the char equivalent of the int data type value from the Unicode charts (provided x has a valid Unicode number value).

44 Typecasting The inverse can also take place where we want to convert a Unicode character to its equivalent integer value: char mychar; (int) mychar; The code above will convert the char data type represented by the identifier mychar to its equivelant Unicode number. We will discuss type casting rules again further later on in the course.

45 Expressions and Arithmetic Operators
The Assignment Operator and Expressions Arithmetic Operators Operator Precedence Integer Division and Modulus Division by Zero Mixed-Type Arithmetic and Type Casting Shortcut Operators

46 Expressions –Operators/ Operands
expression: operators and operands that evaluate to a single value -- value is then assigned to target -- target must be a variable (or constant) -- value must be compatible with target's data type i.e. 3+x; is an expression 3 and x are the operands and + is the operator. int x=5; int y=0; y=3+x; means that the expression is first evaluated to 3+5=8 and then the value of 8 is assigned to the variable y (now y holds the value of 8 instead of 0)

47 Arithmetic Operators The following operators are used with the symbols: Operator Operation + addition - subtraction * multiplication / division % modulus (remainder after division)

48 Operator Precedence Precedence refers to the order at which operators operate on operands. If more than one operator is used in an expression the order of evaluation is determined using operator precedence. Expressions in parentheses are evaluated first Multiplication, division, and modulus are performed before addition and subtraction When multiple arithmetic operators of the same precedence occur in one expression, they are evaluated left to right. Assignment is performed last, and is performed right to left.

49 Operator Precedence Operator Order of evaluation Operation ( )
left to right parentheses for explicit grouping * / % multiplication, division, modulus + - addition, subtraction = right to left assignment

50 Example You have 2 quarters, 3 dimes, and 2 nickels.
How many pennies are these coins worth? int pennies = 2 * * * 5; = = 90 // * has higher precedence than +, so the multiplications are executed first, then the additions, left to right.

51 Another Example Translate x into Java: double result = x / 2 * y;
// The following is incorrect! double result = x / 2 * y; it means divide x by 2 first and then multiply the result by y // This is correct double result = x / ( 2 * y ); The parenthesis makes the difference in determining the precedence.

52 Another Example Evaluate the expression: 2*3/2+(16-5*4/2)%3
First what is inside the parenthesis is evaluated: * and / have the same precedence which is higher than + . Therefore we perform the multiplication first then the division an d then the addition: 5*4=20 , /2=10, = 6 Now the expression looks like: 2*3/2+6%3 Next we evaluate left to right by using the operators with equal precedence (*, /, %) 2*3=6 , 6/2=3 6%3=0 Now the expression looks like: 3+0 Next we evaluate using the last operator in precedence which is the + 3+0=3


Download ppt "OBJECT ORIENTED PROGRAMMING I LECTURE 3 GEORGE KOUTSOGIANNAKIS"

Similar presentations


Ads by Google