MIT 12043: Fundamentals of Programming
Lesson 02
S. Sabraz Nawaz
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
Fundamentals of Programming by SaNa@seu
Computing the Area of a Circle
This program computes the area of the circle.
Fundamentals of Programming by SaNa@seu
Trace a Program Execution allocate memory for radius public class ComputeArea {
/** Main method */ public static void main(String[] args) { double radius; double area; radius no value
// 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);
Fundamentals of Programming by SaNa@seu
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);
Fundamentals of Programming by SaNa@seu radius area memory no value no value allocate memory for area
Trace a Program Execution assign 20 to radius 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);
Fundamentals of Programming by SaNa@seu radius area
20 no value
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);
Fundamentals of Programming by SaNa@seu radius area memory
20
1256.636
compute area and assign it to variable area
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);
Fundamentals of Programming by SaNa@seu radius area memory
20
1256.636
print a message to the console
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.
Fundamentals of Programming by SaNa@seu
Variables are locations in memory where values can be stored
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
Fundamentals of Programming by SaNa@seu
At a given time one value can be stored under the variable quantity
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.
Fundamentals of Programming by SaNa@seu
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
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.
Fundamentals of Programming by SaNa@seu
Data Types
Name byte short int
Range
–27 (-128) to 27–1 (127)
–215 (-32768) to 215–1 (32767)
Storage Size
8-bit signed
16-bit signed
–231 (-2147483648) to 231–1 (2147483647) 32-bit signed long float
–263 to 263–1
(i.e., -9223372036854775808 to 9223372036854775807)
Negative range:
-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38 double Negative range:
-1.7976931348623157E+308 to
-4.9E-324
Positive range:
4.9E-324 to 1.7976931348623157E+308
Fundamentals of Programming by SaNa@seu
64-bit signed
32-bit IEEE 754
64-bit IEEE 754
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
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
} public static void main (String args[]) { int count;
String title; boolean isAsleep;
...
Variables are usually defined at the beginning. However this need not always
Fundamentals of Programming by SaNa@seu be the case.
int x, y, z;
String firstName, lastName;
Multiple variables can be defined under one type
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 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.
int x = 1;
double d = 1.4; int age=19; int age;
… age = 19;
The above statements are identical
Fundamentals of Programming by SaNa@seu
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
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
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
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
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
Fundamentals of Programming by SaNa@seu
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
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
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
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
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
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
3
4 x
5
10 ( y
5 )( a x
b
c )
9 (
4 x
9
y x
) 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
• 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
(1) inside parentheses first
3 + 4 * 4 + 5 * 7 – 1
(2) multiplication
3 + 16 + 5 * 7 – 1
(3) multiplication
3 + 16 + 35 – 1
19 + 35 – 1
(4) addition
(5) addition
54 - 1
(6) subtraction
53
Fundamentals of Programming by SaNa@seu
Operator Example Equivalent
+= i += 8 i = i + 8
-=
*=
/=
%= f -= 8.0
f = f - 8.0
i *= 8 i = i * 8 i /= 8 i %= 8 i = i / 8 i = i % 8
Fundamentals of Programming by SaNa@seu
Operator Name
++age age ++ preincrement
Description
The expression (++age) increments age by
1 and evaluates to the new value in age after the increment.
postincrement The expression (age ++) evaluates to the original value in age and increments age by 1.
--age age-predecrement The expression (--age) decrements age by
1 and evaluates to the new value in age after the decrement. postdecrement The expression (age --) evaluates to the original value in age and decrements age by 1.
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;
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.
Fundamentals of Programming by SaNa@seu
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
Fundamentals of Programming by SaNa@seu
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
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
// 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
A program when given three marks of an exam which calculates and prints the total and the average.
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.
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
Fundamentals of Programming by SaNa@seu
Write a program that converts a Fahrenheit degree to Celsius using the formula: celsius
( 5
9
)( fahrenheit
32 )
Fundamentals of Programming by SaNa@seu
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.
Fundamentals of Programming by SaNa@seu
Method int nextInt()
Returns
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
01
02
03
Fundamentals of Programming by SaNa@seu
Fundamentals of Programming by SaNa@seu
Fundamentals of Programming by SaNa@seu
Fundamentals of Programming by SaNa@seu
Solution for Restaurant Bill – Exam - Answer
Fundamentals of Programming by SaNa@seu
Solution for Restaurant Bill – Classroom Exam
Fundamentals of Programming by SaNa@seu
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
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
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
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
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
Fundamentals of Programming by SaNa@seu