Introduction to Java Applications Part II
In this chapter you will learn: Different data types( Primitive data types). How to declare variables? How to initialize variables? Different methods to input data. Arithmetic operators. Compound assignment. Increment and decrement. 2
Java has two sorts of data: 1. Values of primitive data type 2. Instances of classes (objects) (reference types) 1.1 Primitive data types ◦ A primitive data type is defined as a set of values together with operations that can be preformed on them. ◦ There are three categories of primitive data types: numbers, characters, Booleans. Each has it own memory size and range of values.
4
5
float ◦ Single-precision floating-point numbers ◦ Seven significant digits double Stores numbers with greater magnitude and precision than float. 6
A literal is a comprehensible textual representation of a particular value of some type. E.g. ‘X’ is a char literal, 4.23 is a double literal, “hello there” is a string literal. 17 is the literal that represents the int 17. If you want to represent the same number 17 as a long you need to use the literal 17L (L or l). The default type of a real number is double, so 17.5 is double not float and 1.9F (F or f) represents a value of type float.
8
9
Each variable should have a type which represents the type of information that will be stored in this variable. Variable declaration in Java Data_Type identifier; An identifier: is the variable name that you will use during the program, and in fact it is translated to an address of the memory location. Data type: this shows the type of data that will be stored in this variable. When a variable declared, a memory allocation is reserved for it according to its data type.
11
Variables ◦ Every variable has a name, a type, a size and a value Name corresponds to location in memory ◦ When new value is placed into a variable, it replaces (and destroys) previous value. Overwrite ◦ Reading variables from memory does not change them. 12
Given below is the code of java program that adds two numbers which are entered by the user 13
14 import declaration imports class Scanner from package java.util. Declare and initialize variable input, which is a Scanner. Declare variables number1, number2 and sum. Read an integer from the user and assign it to number1.
15 Read an integer from the user and assign it to number2. Calculate the sum of the variables number1 and number2, assign result to sum. Display the sum using formatted output. Two integers entered by the user.
16
17
18
import declarations ◦ Used by compiler to identify and locate classes used in Java programs ◦ Tells compiler to load class Scanner from java.util package Begins public class Addition ◦ Recall that file name must be Addition.java Lines 8-9: begin main 19 3 import java.util.Scanner; // program uses class Scanner 5 public class Addition 6 {
◦ Variable Declaration Statement ◦ Variables ◦ A variable is a location in the computer’s memory where value can be stored for use by a program. ◦ Declaration : Data Type Identifier int – integer numbers char – characters double – floating point numbers ◦ All variables must be declared with a name and data type before they can be used in program. int integer1; int integer2; int sum; // create Scanner to obtain input from command window 11 Scanner input = new Scanner( System.in );
Note: ◦ You can declare several variables of same type in one declaration: Comma-separated list int integer1, integer2, sum;
Input is of type Scanner Enables a program to read data for use Variable name: any valid identifier ◦ Declarations end with semicolons ; ◦ Initialize variable in its declaration Equal sign Standard input object System.in 10 // create Scanner to obtain input from command window 11 Scanner input = new Scanner( System.in );
◦ Declare variable number1, number2 and sum of type int int holds integer values (whole numbers): i.e., 0, -4, 97 Types float and double can hold decimal numbers Type char can hold a single character: i.e., x, $, \n, 7 int, float, double and char are primitive types ◦ Can add comments to describe purpose of variables ◦ Can declare multiple variables of the same type in one declaration ◦ Use comma-separated list int number1; // first number to add 14 int number2; // second number to add 15 int sum; // sum of number 1 and number 2 int number1, // first number to add number2, // second number to add sum; // sum of number1 and number2
By convention, variable-name identifiers begin with a lowercase letter, and every word in the name after the first word begins with a capital letter. For example, variable-name identifier firstNumber has a capital N in its second word, Number. 24
◦ Message called a prompt - directs user to perform an action ◦ Package java.lang ◦ Result of call to nextInt given to number1 using assignment operator = Assignment statement = binary operator - takes two operands Expression on right evaluated and assigned to variable on left Read as: number1 gets the value of input.nextInt() System.out.print( "Enter first integer: " ); // prompt 18 number1 = input.nextInt(); // read first number from user
By default, package java.lang is imported in every Java program; thus, java.lang is the only package in the Java API that does not require an import declaration. 26
◦ Similar to previous statement Prompts the user to input the second integer ◦ Similar to previous statement Assign variable number2 to second integer input ◦ Assignment statement Calculates sum of number1 and number2 (right hand side) Uses assignment operator = to assign result to variable sum Read as: sum gets the value of number1 + number2 number1 and number2 are operands System.out.print( "Enter second integer: " ); // prompt 21 number2 = input.nextInt(); // read second number from user 23 sum = number1 + number2; // add numbers
◦ Use System.out.printf to display results ◦ Format specifier %d Placeholder for an int value ◦ Calculations can also be performed inside printf ◦ Parentheses around the expression number1 + number2 are not required System.out.printf( "Sum is %d\n: ", sum ); // display sum System.out.printf( "Sum is %d\n: ", ( number1 + number2 ) );
Choosing meaningful variable names helps a program to be self-documenting (i.e., one can understand the program simply by reading it rather than by reading manuals or viewing an excessive number of comments). 29
All import declarations must appear before the first class declaration in the file. Placing an import declaration inside a class declaration’s body or after a class declaration is a syntax error. 30
Forgetting to include an import declaration for a class used in your program typically results in a compilation error containing a message such as “ cannot resolve symbol. ” When this occurs, check that you provided the proper import declarations and that the names in the import declarations are spelled correctly, including proper use of uppercase and lowercase letters. 31
Write a program to find the Perimeter and area of the square. The perimeter and area of the square are given by the following formula. Perimeter = SideLength* 4 Area = sideLength * sideLength Input square sideLength Processing Area= sideLength * sideLength Output Print Out the perimeter and area 32
Initialization means to give a variable an initial value. Variables can be initialized when declared: Int first=13, second=10; Char ch=‘ ’; Double x=12.6; All variables must be in initialized before they are used in an arithmetic operation.(very important) - But not necessary during declaration. 33
Arithmetic calculations used in most programs ◦ Usage * for multiplication / for division % for remainder +, - ◦ Integer division truncates remainder 7 / 5 evaluates to 1 ◦ Remainder operator % returns the remainder 7 % 5 evaluates to 2 34
35
36
Operator precedence ◦ Some arithmetic operators act before others (i.e., multiplication before addition) Use parenthesis when needed ◦ Example: Find the average of three variables a, b and c Do not use: a + b + c / 3 Use: ( a + b + c ) / 3 37
38
Using parentheses for complex arithmetic expressions, even when the parentheses are not necessary, can make the arithmetic expressions easier to read. 39
40
?= 1+2*(3+4) - Evaluated as 1+(2*(3+4)) and results is 15 ?= 5*2+9%4 -Evaluated as (5*2) + (9%4) and the result is 11 ?= 5* 2 % (7-4) Evaluated as (5*2) % (7-4) and the result is 1 41
42 Assignment expression abbreviations ◦ Addition assignment operator Example c = c + 3; abbreviates to c += 3; Statements of the form variable = variable operator expression ; can be rewritten as variable operator = expression ; Other assignment operators ◦ d -= 4 (d = d - 4) ◦ e *= 5 (e = e * 5) ◦ f /= 3 (f = f / 3) ◦ x %= 9 (x = x % 9)
43
44 Unary increment and decrement operators ◦ Unary increment operator ( ++ ) adds one to its operand. ◦ Unary decrement operator ( -- ) subtracts one from its operand. ◦ Prefix increment (and decrement) operator Changes the value of its operand, then uses the new value of the operand in the expression in which the operation appears ◦ Postfix increment (and decrement) operator Uses the current value of its operand in the expression in which the operation appears, then changes the value of the operand
45
46
47
48 Assuming that integer division rounds (rather than truncates) can lead to incorrect results. For example, 7 ÷ 4, which yields 1.75 in conventional arithmetic, truncates to 1 in integer arithmetic, rather than rounding to 2.
End