1 / 63

Data Types and Statements

Data Types and Statements. MIT 12043: Fundamentals of Programming Lesson 02 S. Sabraz Nawaz. Topics Covered. Tracing a program Statements Variables Constants Data Types Arithmetic Calculations Pre and Post increment operators Taking Input from User.

lam
Download Presentation

Data Types and Statements

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. Data Types and Statements MIT 12043: Fundamentals of Programming Lesson 02 S. Sabraz Nawaz Fundamentals of Programming by SaNa@seu

  2. Topics Covered Fundamentals of Programming by SaNa@seu Tracing a program Statements Variables Constants Data Types Arithmetic Calculations Pre and Post increment operators Taking Input from User

  3. Introducing Programming with an Example Fundamentals of Programming by SaNa@seu Computing the Area of a Circle This program computes the area of the circle.

  4. Trace a Program Execution allocate memory for radius radius no value Fundamentals of Programming by SaNa@seu public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } }

  5. Trace a Program Execution memory radius no value area no value allocatememoryforarea Fundamentals of Programming by SaNa@seu public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } }

  6. Trace a Program Execution assign 20 to radius radius 20 area no value Fundamentals of Programming by SaNa@seu public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } }

  7. Trace a Program Execution memory radius 20 area 1256.636 compute area and assign it to variable area Fundamentals of Programming by SaNa@seu public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } }

  8. Trace a Program Execution memory radius 20 area 1256.636 print a message to the console Fundamentals of Programming by SaNa@seu public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } }

  9. Statements intothrs=5; System.out.println("netsalary= "+netsal); You need to put a semi colon ; at the end of a statement. Fundamentals of Programming by SaNa@seu A Statement is the simplest task you can accomplish in Java.

  10. Variables 90 Fundamentals of Programming by SaNa@seu Variables are locations in memory where values can be stored

  11. Variable Name Fundamentals of Programming by SaNa@seu • Variable is a location in memory • Each location in memory has a memory address, which is a number • This long number is inconvenient to use when we want to access the memory location • We give a human understandable name to refer to this number • e.g. age, quantity • The compiler and the interpreter maps this name to the memory address number

  12. Value of a Variable quantity 90 Fundamentals of Programming by SaNa@seu At a given time one value can be stored under the variable

  13. Variable Type Fundamentals of Programming by SaNa@seu You need to specify what type of data is to be stored. e.g. int, char This is because we must instruct how much memory should be reserved by the program to store the value of a variable The amount of memory needed depends on the maximum of the value we need to store in the variable.

  14. Variable Type… Fundamentals of Programming by SaNa@seu

  15. Java Data Types Fundamentals of Programming by SaNa@seu • Java supports eight primitive data types. • Eg: int, char… • In Java we write classes and class can be a data type • Eg: If you write a class called Student you can use it as the Student data type

  16. Primitive Data Types Fundamentals of Programming by SaNa@seu • These are built into the language itself. • Consists of Numeric Types, char type and Boolean type. • Remember String is not a primitive data type in Java • String is a class in Java, thus it is handled as a data type derived from a class.

  17. Data Types Fundamentals of Programming by SaNa@seu

  18. Declaring Variables Fundamentals of Programming by SaNa@seu int x; // Declare x to be an // integer variable; double radius; // Declare radius to // be a double variable; char a; // Declare a to be a // character variable;

  19. Assignment Statements Fundamentals of Programming by SaNa@seu x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a;

  20. Declaring Variables public static void main (String args[]) { intcount; String title; boolean isAsleep; ... } Variables are usually defined at the beginning. However this need not always be the case. Fundamentals of Programming by SaNa@seu

  21. Declaring Variables int x, y, z; String firstName, lastName; Multiple variables can be defined under one type Fundamentals of Programming by SaNa@seu

  22. Declaring Variables intmyAge; myAge= 32; String myName = “SaNa"; boolean isTired = true; int a = 4, b = 5, c = 6; You can also initialize variables as the declaration is done. Fundamentals of Programming by SaNa@seu • Once declared the variable need to be initialized • Initialization – Specify the value we want to store in the variable

  23. Declaring and Initializingin One Step int age=19; int age; … age = 19; The above statements are identical Fundamentals of Programming by SaNa@seu int x = 1; double d = 1.4;

  24. Variable Names int age; float $money; char my_char; long _no; String Name7; A Variable Name should start with an Alphabetical letter or $, or _ symbol The other characters can include numbers But you cannot use symbols like @, #, etc Fundamentals of Programming by SaNa@seu

  25. Variable Names int my age; float @money; char 6my_char; long no*; The above names are incorrect. You cannot have spaces and other special symbols. Fundamentals of Programming by SaNa@seu

  26. Variable Names int qty; String firstName; float basicSal, netSal; It’s best if you can give suitable (short but meaningful) variable names. Fundamentals of Programming by SaNa@seu

  27. Constants Fundamentals of Programming by SaNa@seu A named constant is an identifier that represents a permanent value final datatype CONSTANTNAME = VALUE; final double PI = 3.14159; final int SIZE = 3;

  28. Numeric Operators Fundamentals of Programming by SaNa@seu

  29. Integer Division Fundamentals of Programming by SaNa@seu +, -, *, /, and % 5 / 2 yields an integer 2 5.0 / 2 yields a double value 2.5 5 % 2 yields 1 (the remainder of the division)

  30. Remainder Operator Fundamentals of Programming by SaNa@seu Remainder is very useful in programming. For example, an even number % 2 is always 0 and an odd number % 2 is always 1. So you can use this property to determine whether a number is even or odd.

  31. Number Literals Fundamentals of Programming by SaNa@seu A number literalis a constant value that appears directly in the program. For example, 34, 1,000,000, and 5.0 are literals in the following statements: int i = 34; long x = 1000000; double d = 5.0;

  32. Integer Literals Fundamentals of Programming by SaNa@seu An integer literal can be assigned to an integer variable as long as it can fit into the variable. A compilation error would occur if the literal were too large for the variable to hold. For example, the statement byte b = 1000 would cause a compilation error, because 1000 cannot be stored in a variable of the byte type. An integer literal is assumed to be of the int type, whose value is between -231 (-2147483648) to 231–1 (2147483647). To denote an integer literal of the long type, append it with the letter L or l. L is preferred.

  33. Floating-Point Literals Fundamentals of Programming by SaNa@seu Floating-point literals are written with a decimal point. By default, a floating-point literal is treated as a double type value. For example, 5.0 is considered a double value, not a float value. You can make a number a float by appending the letter f or F, and make a number a double by appending the letter d or D. For example, you can use 100.2f or 100.2F for a float number, and 100.2d or 100.2D for a double number.

  34. Scientific Notation Fundamentals of Programming by SaNa@seu Floating-point literals can also be specified in scientific notation, for example, 1.23456e+2, same as 1.23456e2, is equivalent to 123.456, and 1.23456e-2 is equivalent to 0.0123456. E (or e) represents an exponent and it can be either in lowercase or uppercase.

  35. Arithmetic Expressions is translated to (3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y) Fundamentals of Programming by SaNa@seu

  36. How to Evaluate an Expression • Though Java has its own way to evaluate an expression behind the scene, the result of a Java expression and its corresponding arithmetic expression are the same. Therefore, you can safely apply the arithmetic rule for evaluating a Java expression. Fundamentals of Programming by SaNa@seu

  37. Shortcut Assignment Operators Operator Example Equivalent += i += 8 i = i + 8 -= f -= 8.0 f = f - 8.0 *= i *= 8 i = i * 8 /= i /= 8 i = i / 8 %= i %= 8 i = i % 8 Fundamentals of Programming by SaNa@seu

  38. Increment and Decrement Operators Operator Name Description ++agepreincrement The expression (++age) increments age by 1 and evaluates to the new value in age afterthe increment. age ++postincrement The expression (age ++) evaluates to the original value in age and increments age by 1. --age predecrement The expression (--age) decrements age by 1 and evaluates to the new value in age afterthe decrement. age--postdecrement The expression (age --) evaluates to the original value in age and decrements age by 1. Fundamentals of Programming by SaNa@seu

  39. Numeric Type Conversion Fundamentals of Programming by SaNa@seu Consider the following statements: byte i = 100; long k = i * 3 + 4; double d = i * 3.1 + k / 2;

  40. Conversion Rules Fundamentals of Programming by SaNa@seu When performing a binary operation involving two operands of different types, Java automatically converts the operand based on the following rules: 1.    If one of the operands is double, the other is converted into double. 2.    Otherwise, if one of the operands is float, the other is converted into float. 3.    Otherwise, if one of the operands is long, the other is converted into long. 4.    Otherwise, both operands are converted into int.

  41. Type Casting Fundamentals of Programming by SaNa@seu Implicit casting double d = 3; (type widening) Explicit casting int i = (int)3.0; (type narrowing) int i = (int)3.9; (Fraction part is truncated)

  42. Escape Sequences for Special Characters Description Escape Sequence Backspace \b Tab \t Linefeed \n Carriage return \r Backslash \\ Single Quote \' Double Quote \" Fundamentals of Programming by SaNa@seu

  43. The String Type Fundamentals of Programming by SaNa@seu The char type only represents one character. To represent a string of characters, use the data type called String. For example, String message = "Welcome to Java"; String is actually a predefined class in the Java library just like the Systemclass. The String type is not a primitive type. It is known as a reference type. Any Java class can be used as a reference type for a variable.

  44. String Concatenation Fundamentals of Programming by SaNa@seu // Three strings are concatenated String message = "Welcome " + "to " + "Java"; // String Chapter is concatenated with number 2 String s = "Chapter" + 2; // s becomes Chapter2 // String Supplement is concatenated with character B String s1 = "Supplement" + 'B'; // s1 becomes SupplementB

  45. Exercises 1 Fundamentals of Programming by SaNa@seu A program when given three marks of an exam which calculates and prints the total and the average.

  46. Exercises 2 Fundamentals of Programming by SaNa@seu A Program when given the Currency Rate of a US Dollar. Calculates and prints the a Sri Lankan Ruppee amount into US Dollars.

  47. Exercises 3 Fundamentals of Programming by SaNa@seu Write a program to input how many notes, coins of denominations of 1000/=, 500/=, 200/=, 100/= 50/=,20/=,10/=,5/=, 2/= and 1/= are available. Print the total amount

  48. Exercises 4 Fundamentals of Programming by SaNa@seu Write a program that converts a Fahrenheit degree to Celsius using the formula:

  49. Taking User Inputs Fundamentals of Programming by SaNa@seu

  50. Using Scanner Class Fundamentals of Programming by SaNa@seu The Scanner class is a class in java.util, which allows the user to read values of various types. The Scanner looks for tokens in the input. A token is a series of characters that ends with what Java calls whitespace. A whitespace character can be a blank, a tab character, a carriage return, or the end of the file. 

More Related