Download presentation
Presentation is loading. Please wait.
Published byPeregrine Harvey Modified over 9 years ago
1
Data Types and Statements MIT 12043: Fundamentals of Programming Lesson 02 S. Sabraz Nawaz Fundamentals of Programming by SaNa@seu
2
Tracing a program Statements Variables Constants Data Types Arithmetic Calculations Pre and Post increment operators Taking Input from User Topics Covered Fundamentals of Programming by SaNa@seu
3
Introducing Programming with an Example Computing the Area of a Circle This program computes the area of the circle. Fundamentals of Programming by SaNa@seu
4
Trace a Program Execution 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); } no value radius allocate memory for radius Fundamentals of Programming by SaNa@seu
5
Trace a Program Execution 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); } no value radius memory no value area allocate memory for area Fundamentals of Programming by SaNa@seu
6
Trace a Program Execution 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); } 20 radius no value area assign 20 to radius Fundamentals of Programming by SaNa@seu
7
Trace a Program Execution 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); } 20 radius memory 1256.636 area compute area and assign it to variable area Fundamentals of Programming by SaNa@seu
8
Trace a Program Execution 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); } 20 radius memory 1256.636 area print a message to the console Fundamentals of Programming by SaNa@seu
9
A Statement is the simplest task you can accomplish in Java. Statements int othrs=5; System.out.println("netsalary= "+netsal); You need to put a semi colon ; at the end of a statement. You need to put a semi colon ; at the end of a statement. Fundamentals of Programming by SaNa@seu
10
Variables are locations in memory where values can be stored Variables Fundamentals of Programming by SaNa@seu
11
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 Variable Name Fundamentals of Programming by SaNa@seu
12
At a given time one value can be stored under the variable Value of a Variable quantity Fundamentals of Programming by SaNa@seu
13
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. Variable Type Fundamentals of Programming by SaNa@seu
14
Variable Type… Fundamentals of Programming by SaNa@seu
15
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 Java Data Types Fundamentals of Programming by SaNa@seu
16
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. Primitive Data Types Fundamentals of Programming by SaNa@seu
17
Data Types Fundamentals of Programming by SaNa@seu
18
Declaring Variables 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; Fundamentals of Programming by SaNa@seu
19
Assignment Statements x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a; Fundamentals of Programming by SaNa@seu
20
Declaring Variables public static void main (String args[]) { int count; String title; boolean isAsleep;... } Variables are usually defined at the beginning. However this need not always be the case. 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 Multiple variables can be defined under one type Fundamentals of Programming by SaNa@seu
22
Once declared the variable need to be initialized Initialization – Specify the value we want to store in the variable Declaring Variables int myAge; 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. You can also initialize variables as the declaration is done. Fundamentals of Programming by SaNa@seu
23
Declaring and Initializing in One Step int x = 1; double d = 1.4; int age=19; The above statements are identical int age; … age = 19; Fundamentals of Programming by SaNa@seu
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 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. 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. It’s best if you can give suitable (short but meaningful) variable names. Fundamentals of Programming by SaNa@seu
27
Constants A named constant is an identifier that represents a permanent value final datatype CONSTANTNAME = VALUE; final double PI = 3.14159; final int SIZE = 3; Fundamentals of Programming by SaNa@seu
28
Numeric Operators Fundamentals of Programming by SaNa@seu
29
Integer Division +, -, *, /, 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) Fundamentals of Programming by SaNa@seu
30
Remainder Operator 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. Fundamentals of Programming by SaNa@seu
31
Number Literals A number literal is 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; Fundamentals of Programming by SaNa@seu
32
Integer Literals 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 -2 31 (-2147483648) to 2 31 –1 (2147483647). To denote an integer literal of the long type, append it with the letter L or l. L is preferred. Fundamentals of Programming by SaNa@seu
33
Floating-Point Literals 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. Fundamentals of Programming by SaNa@seu
34
Scientific Notation 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. Fundamentals of Programming by SaNa@seu
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 OperatorExampleEquivalent +=i += 8i = i + 8 -=f -= 8.0f = f - 8.0 *=i *= 8i = i * 8 /=i /= 8i = i / 8 %=i %= 8i = i % 8 Fundamentals of Programming by SaNa@seu
38
Increment and Decrement Operators OperatorNameDescription ++agepreincrementThe expression (++age) increments age by 1 and evaluates to the new value in age after the increment. age ++postincrementThe expression (age ++) evaluates to the original value in age and increments age by 1. --age predecrementThe expression (--age) decrements age by 1 and evaluates to the new value in age after the 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 Consider the following statements: byte i = 100; long k = i * 3 + 4; double d = i * 3.1 + k / 2; Fundamentals of Programming by SaNa@seu
40
Conversion Rules 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. Fundamentals of Programming by SaNa@seu
41
Type Casting 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) Fundamentals of Programming by SaNa@seu
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 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 System class. 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. Fundamentals of Programming by SaNa@seu
44
String Concatenation // 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 Fundamentals of Programming by SaNa@seu
45
A program when given three marks of an exam which calculates and prints the total and the average. Exercises 1 Fundamentals of Programming by SaNa@seu
46
A Program when given the Currency Rate of a US Dollar. Calculates and prints the a Sri Lankan Ruppee amount into US Dollars. Exercises 2 Fundamentals of Programming by SaNa@seu
47
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 Exercises 3 Fundamentals of Programming by SaNa@seu
48
Exercises 4 Write a program that converts a Fahrenheit degree to Celsius using the formula: Fundamentals of Programming by SaNa@seu
49
Taking User Inputs Fundamentals of Programming by SaNa@seu
50
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. Using Scanner Class Fundamentals of Programming by SaNa@seu
51
Using Scanner Class MethodReturns int nextInt() Returns the next token as an int. long nextLong() Returns the next token as a long. float nextFloat() Returns the next token as a float. double nextDouble() Returns the next token as a double. String next() Finds and returns the next complete token from this scanner and returns it as a string; a token is usually ended by whitespace such as a blank or line break. String nextLine() Returns the rest of the current line, excluding any line separator at the end. Fundamentals of Programming by SaNa@seu
52
Using Scanner Class Fundamentals of Programming by SaNa@seu 01 02 03
53
Using Scanner Class… Fundamentals of Programming by SaNa@seu
54
Using Scanner Class… Fundamentals of Programming by SaNa@seu
55
Using Scanner Class… Fundamentals of Programming by SaNa@seu
56
Solution for Restaurant Bill – Exam - Answer Fundamentals of Programming by SaNa@seu
57
Solution for Restaurant Bill – Classroom Exam Fundamentals of Programming by SaNa@seu
58
Exercise 01 Write and run a Java program that prompts the user for his or her last name and first name separately and then prints a greeting like this: Enter your name: SaNa Enter your first name: Sams Hello, SaNa Sams Fundamentals of Programming by SaNa@seu
59
Exercise 02 Write and run a Java program that inputs an integer that represents a temperature on the Fahrenheit scale and then computes and prints its equivalent Celsius value. Use the conversion formula C=5(F-32)/9 Fundamentals of Programming by SaNa@seu
60
Exercise 03 Write and run a Java program that inputs an integer that represents a temperature on the Celsius scale and then computes and prints its equivalent Fahrenheit value. Use the conversion formula F= 1.8C + 32 Fundamentals of Programming by SaNa@seu
61
Exercise 04 A university pays its Academic Staff Academic Allowance 39% of Basic Salary, Research Allowance 25% of Basic Salary, and Cost of Living Allowance 5,850/=. And deducts UPF 8% of the Basic Salary. Write a Java program to input the Basic Salary. Calculate the above and display them all with Net Salary Fundamentals of Programming by SaNa@seu
62
Assignment 1.What is meant by Casting in Java? Explain with suitable examples 2.What is Constant? Explain with suitable examples Submit on or before 10 th January 2014 Fundamentals of Programming by SaNa@seu
63
End of Lecture Fundamentals of Programming by SaNa@seu
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.