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 Arithmetic Calculations Pre and Post increment operators Taking Input from User
Statements A Statement is the simplest task you can accomplish in Java. int othrs=5; System.out.println("netsalary= "+netsal); You need to put a semi colon ; at the end of a statement.
Variables Variables are locations in memory where values can be stored
Variable Name Variable is a location in memory Each location in memory has a memory address, which is a number o 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 o e.g. age, quantity The compiler and the interpreter maps this name to the memory address number
Value of a Variable At a given time one value can be stored under the variable quantity
Variable Type 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
Java Data Types Java supports eight primitive data types. o Eg: int, char In Java we write classes and class can be a data type o Eg: If you write a class called Student you can use it as the Student data type
Primitive Data Types 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 o String is a class in Java, thus it is handled as a data type derived from a class.
Data Types Name Range Storage Size byte 2 7 (-128) to 2 7 1 (127) 8-bit signed short 2 15 (-32768) to 2 15 1 (32767) 16-bit signed int 2 31 (-2147483648) to 2 31 1 (2147483647) 32-bit signed long 2 63 to 2 63 1 64-bit signed (i.e., -9223372036854775808 to 9223372036854775807) float Negative range: 32-bit IEEE 754-3.4028235E+38 to -1.4E-45 Positive range: 1.4E-45 to 3.4028235E+38 double Negative range: 64-bit IEEE 754-1.7976931348623157E+308 to -4.9E-324 Positive range: 4.9E-324 to 1.7976931348623157E+308
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;
Assignment Statements x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a;
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.
Declaring Variables int x, y, z; String firstname, lastname; Multiple variables can be defined under one type
Declaring Variables Once declared the variable need to be initialized o Initialization Specify the value we want to store in the variable 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.
Declaring and Initializing in One Step int x = 1; double d = 1.4; int age=19; int age; age = 19; The above statements are identical
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
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.
Variable Names int qty; String firstname; float basicsal, netsal; It s best if you can give suitable (short but meaningful) variable names.
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;
Numeric Operators Name Meaning Example Result + Addition 34 + 1 35 - Subtraction 34.0 0.1 33.9 * Multiplication 300 * 30 9000 / Division 1.0 / 2.0 0.5 % Remainder 20 % 3 2
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)
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.
Arithmetic Expressions 3 4x 5 10( y 5)( a x b c) 4 9( x 9 y x ) is translated to (3+4*x)/5 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)
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. 3 + 4 * 4 + 5 * (4 + 3) - 1 3 + 4 * 4 + 5 * 7 1 3 + 16 + 5 * 7 1 3 + 16 + 35 1 19 + 35 1 54-1 53 (1) inside parentheses first (2) multiplication (3) multiplication (4) addition (5) addition (6) subtraction
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
Numeric Type Conversion Consider the following statements: byte i = 100; long k = i * 3 + 4; double d = i * 3.1 + k / 2;
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.
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) range increases byte, short, int, long, float, double
Escape Sequences for Special Characters Description Escape Sequence Tab \t Linefeed \n Backslash \\ Single Quote \' Double Quote \"
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.
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
Exercises 1. A program when given three marks of an exam which calculates and prints the total and the average. 2. A Program when given the Currency Rate of a US Dollar. Calculates and prints the a Sri Lankan Rupee amount into US Dollars. 3. 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 4. Write a program that converts a Fahrenheit degree to Celsius using the formula: celsius 5 ( 9 )( fahrenheit 32)
Taking User Inputs
Using Scanner Class 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 Method int nextint() long nextlong() float nextfloat() double nextdouble() Returns Returns the next token as an int. Returns the next token as a long. Returns the next token as a float. 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.
Using Scanner Class 01 02 03
Using Scanner Class
Using Scanner Class
Using Scanner Class
Solution for Restaurant Bill Exam - Answer
Solution for Restaurant Bill Classroom Exam
Exercise 05 A university pays its Academic Staff o o Academic Allowance 39% of Basic Salary Research Allowance 45% of Basic Salary o Cost of Living Allowance 7,550/=. 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
End of Lecture