1 / 61

Lecture 2 - Outline

Lecture 2 - Outline. Character Strings Variables Primitive Data Types Constants Assignments and Expressions Data Conversion The String Class Interactive Programs. Java Program Structure. // Hello World Application. public class HelloWorld. { }.

symona
Download Presentation

Lecture 2 - Outline

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

E N D

Presentation Transcript


  1. Lecture 2 - Outline Character Strings Variables Primitive Data Types Constants Assignments and Expressions Data Conversion The String Class Interactive Programs

  2. Java Program Structure // Hello World Application public class HelloWorld { } // Java application to display the message // Hello World on the screen public static void main (String[] args) { } System.out.println("Hello World!");

  3. Character Strings • A string literal is a sequence of zero or more characters enclosed by double quotes. • Examples: "Hello World!" "This is a string literal." "123 Main Street" "X" • The empty string ("") is the string with no characters • String literals cannot extend over more than one line. System.out.println( "Hello World!“); The Java compiler will report a syntax error

  4. information provided to the method (argument/parameter) object method name Interactive Program - Output • To display information on the console, Java uses methods of the object System.out • The System.out object represents the monitor screen to which we can send output. • The method println display a string to the screen, then move to the next line System.out.println ("Go Dawgs!!!.");

  5. The print Method • The print method is similar to the println method, • But, it does not skip to the next line after displaying the string. It leaves the cursor where ever the last letter was printed Example: System.out.print("Merry Christmas"); System.out.println("and Happy New Year."); Merry Christmas and Happy New Year.

  6. Note: • If you want to leave a space between the words “Christmas ” and “and” you must add it either after Christmas or before and. System.out.print (“Merry Christmas ”); System.out.print (“and happy new year”);

  7. Exercise: • What is the output of the following statements? System.out.print (“I am”); System.out.print(“a student”); System.out.println (“ of:”); System.out.println (“Java”); I ama student of: Java

  8. String Concatenation • The string concatenation operator (+) is used to append one string to the end of another • System.out.println ("cats " + "and dogs“); • You can also be used to append a number to a string. System.out.println("UGA Sugar Bowl Champions "+ 2009); • The + operator is the concatenation operator when one of the operands is a string.

  9. Special Characters: • How can we display the following output ? Error. Why ? System.out.println (“He said “time is a great teacher”); He Said “Time is a great teacher”

  10. Escape Sequence \b \t \n \r \" \' \\ Meaning backspace tab newline carriage return double quote single quote backslash Escape Sequences • Special characters are represented in a string using a escape sequence. • An escape sequence is a series of characters that represents a special character • An escape sequence begins with a backslash character (\).

  11. System.out.println(“He said: \“ Time is a great teacher \“ “); System.out.println(“Harry Potter\nis very-very \n\nfamous “); He Said “Time is a great teacher” Harry Potter is very-very Famous

  12. Outline Character Strings Variables,Primitive Data Types and Constants Assignments and Expressions Data Conversion The String Class Interactive Programs

  13. variable name data type total x y z Variables • A variable is a name for a location of memory that stores a value • The value of the variable may change during the execution of the program • A variable must be declared by specifying the variable's name and the type of data that it will hold • By convention, variables names starts with a lowercase letter int total; int x, y, z;

  14. 0 sum 32 base 149 max Variables • After declaring a variable inside a method (main method in our case) you can use it anywhere inside the body of that method. int total ; total = 50; // java is case sensitive. //therefore Total = 50; is a syntax error • A variable can be given an initial value in the declaration int sum = 0; int base = 32, max = 149;

  15. Primitive Data • There are eight primitive data types in Java • Integer data types: • byte, short, int, long • Floating point numbers data types : • float, double • Characters: • char • Boolean: • boolean

  16. Type byte short int long float double Type byte short int long float double Storage 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Storage 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Min Value -128 -32,768 -2,147,483,648 < -9 x 1018 +/- 3.4 x 1038 7 significant digits +/- 1.7 x 10308 15 significant digits Min Value -128 -32,768 -2,147,483,648 < -9 x 1018 +/- 3.4 x 1038 7 significant digits +/- 1.7 x 10308 15 significant digits Max Value 127 32,767 2,147,483,647 > 9 x 1018 Max Value 127 32,767 2,147,483,647 > 9 x 1018 Numeric Primitive Data • The difference between the various numeric primitive types is their size, and therefore the range of values they can hold:

  17. Primitive Data - Characters • Achar variable stores a single character • Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n' • Example declarations: char topGrade = 'A'; char terminator = ';', separator = ' '; • A character variable holds only one character.

  18. Primitive Data - Character Sets • A character set is an ordered list of characters, with each character corresponding to a unique number or code • Java uses the Unicode character set • It is an international character set, containing symbols and characters from many world languages • Uses sixteen bits per character, allowing for 65,536 unique characters • A char variable in Java can store any character from the Unicode character set.

  19. uppercase letters lowercase letters punctuation digits special symbols control characters A, B, C, … a, b, c, … period, semi-colon, … 0, 1, 2, … &, |, \, … carriage return, tab, ... Primitive Data - Characters • The ASCII character set is older and smaller than Unicode, but is still quite popular • The ASCII character set is a subset of the Unicode character set, including:

  20. Primitive Data • There are eight primitive data types in Java • Integer data types: • byte, short, int, long • Floating point numbers data types : • float (7 significant digits), • double (8 significant digits) • Characters: • char • Boolean: • boolean

  21. Boolean • A boolean variable can also be used to represent any two states, such as a light bulb being on or off • When doing this, try to use a name that makes the interpretation of the variable obvious • Helpful: boolean lightOn • Unhelpful: boolean light

  22. Constants • A constant is an identifier for a memory location holding a value that can not be changed during its entire existence • The value is constant, not variable Note: The compiler will issue an error if you try to change the value of a constant • In Java, constants are called final variables and declared as final int MONTHS_A_YEAR = 12; finalint DAYS_A_WEEK = 7; finaldouble TAX_SALE = 0.06;

  23. Constants Constants are useful for three important reasons • Improve readability by giving meaning to otherwise unclear literal values • For example, MONTHS_A_YEAR have more meaning than the literal 12. • Facilitate program maintenance • If a constant is used in multiple places, its value need only be updated in one place. • finaldouble TAX_SALE = 0.06; • Establish that it value cannot not change, avoiding inadvertent errors by other programmers

  24. Outline Character Strings Variables,Primitive Data Types and Constants Assignments and Expressions Data Conversion The String Class Interactive Programs

  25. 1 total 55 total Assignment • An assignment statement changes the value of a variable • An assignment statement has the form variable=expression; Example: int total=1; total = 55;

  26. Binary Unary Expressions • An expression is a combination of one or more operators and operands • Arithmetic expressions compute numeric values by combining numeric operands via arithmetic operators: Addition + Subtraction - Multiplication * Division / Remainder % Increment ++ Decrement -- 5 + 3*2 = 11 (5+3) *2 = 16

  27. Division and Remainder • If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 14 / 3equals 4 8 / 12equals 0 • The modulus operator (%) returns the remainder after dividing the second operand into the first 14 % 3equals 2 8 % 12equals 8

  28. Operator Precedence • Operators have a well-defined precedence which determines the order in which they are evaluated • Multiplication,division, and remainder are evaluated prior to addition,subtraction, and string concatenation • Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order

  29. Order of Operations • Parenthesis • Multiplication (*), Division (/) and Remainder ( %) • Addition (+), subtraction (-) and String concatenation • Assignment Statement (=)

  30. 500 promotion Assignment Example: int salary = 1000; 1000 1500 salary int promotion = 500; salary = salary + promotion; 2-30

  31. Operator Precedence • To make your code more readable, you should avoid statements like the one below result = total + count / max - offset; • Instead, write the following result = total + (count / max) - offset; • The value of the expression has not changed, but it is now unambiguous

  32. Operator Precedence • What is the order of evaluation in the following expressions? a + b + c + d + e a + b * c - d / e 1 2 3 4 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1

  33. P= P= Expressions • Write the following mathematical expression in java: p = ( n*(n-1)*(n-2)+ 2) / (3*(n-3));

  34. Assignment Revisited • In an assignment statement First the expression on the right hand side of the = operator is evaluated answer = sum / 4 + MAX * lowest; 1 3 2 Then the result is stored in the variable on the left hand side

  35. Assignment Revisited • The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count count = count + 1; Then the result is stored back into count (overwriting the original value)

  36. Increment and Decrement ++ Increase the value of a variable by one. -- Decrease the value of a variable by one. • Postfix- Increment: x++ ; // increases x by 1 after the expression is evaluated • Postfix- decrement : x-- ; // decreases x by 1 after the expression is evaluated • Prefix- Increment: ++x ; // increases x by 1 before the expression is evaluated • Prefix- decrement: --x ; // decreases x by 1 before the expression is evaluated

  37. Postfix and Prefix operators Prefix - operators: will increase/decrease the variable and then evaluate the expression. Post-operators: will evaluate the expression and then increase/decrease the variable

  38. Increment and Decrement Post Fix increment: int count = 3; int total = count++; So the value of total is 3 and the value of count is 4 after this operation Pre Fix Increment: int count = 3; int total = ++count; So the value of total is 4 and the value of count is 4 after this operation

  39. Order of Operations: • Parenthesis • Prefix Operators ( ++ var, -- var) • Multiplication (*), Division (/) and Remainder ( %) • Addition (+), subtraction (-) and String concatenation • Assignment Statement (=) • Postfix operators (var++, var--)

  40. Assignment Operators • Often we perform an operation on a variable, and then store the result back into that variable • Java provides assignment operators to simplify that process <variable > ?= <expression> Where ? Is a binary operator ( + , - , *, %, …) • For example, the statement num += 3; is equivalent to num = num + 3;

  41. Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y Assignment Operators • There are many assignment operators in Java, including the following:

  42. Examples: x = 5; x = 6-4*3; x += 5; // same as x = x+5; x -= 5; // same as x = x-5; x /= 5; // same as x = x/5; x += 5+3*2 ; // same as x = x + (5+3*2); x -= 5-3 ; // same as x = x – (5-3);

  43. Outline Character Strings Variables,Primitive Data Types and Constants Assignments and Expressions Data Conversion The String Class Interactive Programs

  44. Data Conversion • Sometimes it is convenient to convert data from one type to another during a computation • For example, • in a particular situation we want to treat an integer as a floating point value. • Data Conversion do not change the type of a variable or the value that's stored in it • they only convert a value as part of a computation

  45. Data Conversion • Conversions must be handled carefully to avoid losing information • Widening conversionsare safest because they tend to go from a small data type to a larger one (such as a short to an int) • Narrowing conversionscan lose information because they tend to go from a large data type to a smaller one (such as an int to a short) • In Java, data conversions can occur in three ways: • assignment conversion • promotion • casting

  46. Data Conversion • In Java, data conversions can occur in three ways: • Promotion (arithmetic conversion) • assignment conversion • casting

  47. Promotion • Promotion happens automatically when an operator in an expression converts its operands to the largest data type of its operands. • But will always be at least an int. int num=0; int a=5; long b = 1000; float c = 1.89; double d = 2.009928;

  48. Assignment Conversion • Assignment conversion occurs when a value of one type is assigned to a variable of another • If money is a float variable and dollars is an int variable, the following assignment converts the value in dollars to a float money = dollars; • Only widening conversions can happen via assignment • Note that the value or type of dollars did not change

  49. Casting • Casting is the most powerful, and dangerous, technique for conversion • Both widening and narrowing conversions can be accomplished by explicitly casting a value • To cast, the type is put in parentheses in front of the value being converted • For example, if total and count are integers, but we want a floating point result when dividing them, we can cast total: result = (float) total / count;

  50. Outline Character Strings Variables,Primitive Data Types and Constants Assignments and Expressions Data Conversion The String Class Interactive Programs 2-50

More Related