2 data types and operators
TRANSCRIPT
-
8/12/2019 2 Data Types and Operators
1/50
Data types andOperators by Komal Sangtani
-
8/12/2019 2 Data Types and Operators
2/50
Topics to be covered: Primitive Datatypes, Declarations, Ranges Variable Names Conventions Numeric Literals, Character Literals String Literals
Arrays (One dimensional; two- dimensional)
Array of Object References Accessing arrays, manipulating arrays Enumerated Data Types Non-Primitive Datatypes Defining a class, variable and method in
Java Method Signature; method calls
Expressions in Java;
Introduction to variousoperators Assignment Operator Arithmetic Operators Relational Operators Logical Operators Conditional Operators Operator Precedence Implicit Type Conversions Upcasting and
downcasting Strict typing Type conversion
-
8/12/2019 2 Data Types and Operators
3/50
Steps for writing & compiling prog.
Create source code file (call it for exampleHello.java).
To compile:
prompt >> javac MyFirstProgram.java This produces byte code file named
Hello. class To run:
prompt >> java MyFirstProgram
-
8/12/2019 2 Data Types and Operators
4/50
Writing first class
File:- Hello.java public class Hello {
public static void main(String args[]){
System.out.println (Hello World..!); }
}
-
8/12/2019 2 Data Types and Operators
5/50
How it works!
-
8/12/2019 2 Data Types and Operators
6/50
Identifiers - symbolic names Identifiers are used to name classes, variables,
and methods Identifier Rules:
Must start with a "Java letter" A - Z, a - z, _, $, and Unicode letters
Can contain essentially any number of Javaletters and digits, but no spaces
Case sensitive!! Number1 and number1 are different!
Cannot be keywords or reserved words
-
8/12/2019 2 Data Types and Operators
7/50
Program Building Blocks
The Statement Performs some action Terminates with a semicolon (;) Can span multiple lines
-
8/12/2019 2 Data Types and Operators
8/50
Building Blocks - The Block The Block
0, 1, or more statements Begins and ends with curly braces { } Can be used anywhere a statement is allowed.
-
8/12/2019 2 Data Types and Operators
9/50
Building Blocks - White Space Space, tab, newline are white space characters At least one white space character is required
between a keyword and identifier Any amount of white space characters are
permitted between identifiers, keywords,operators, and literals
To increase readability of your code, surroundoperators and operands with white space andskip lines between logical sections of program.
-
8/12/2019 2 Data Types and Operators
10/50
Building Blocks - Comments Comments explain the program to yourself and others Block comments
Can span several lines
Begin with /* End with */ Compiler ignores all text between /* and */
Line comments Start with // Compiler ignores text from // to end of line
-
8/12/2019 2 Data Types and Operators
11/50
Data Types, Variables, andConstants
Declaring Variables Primitive Data Types Initial Values and Literals String Literals and Escape Sequences Constants
-
8/12/2019 2 Data Types and Operators
12/50
Data Types For all data, assign a name (identifier) and a data
type Data type tells compiler:
How much memory to allocate Format in which to store data Types of operations you will perform on data
Compiler monitors use of data Java is a "strongly typed" language
Java "primitive data types"byte, short, int, long, float, double, char, boolean
-
8/12/2019 2 Data Types and Operators
13/50
Declaring Variables Variables hold one value at a time, but that value
can change Syntax:
dataType identifier;or
dataType identifier1,
identifier2, ; Naming convention for variable names:
first letter is lowercase embedded words begin with uppercase letter
-
8/12/2019 2 Data Types and Operators
14/50
Integer Types - Whole NumbersType Size in bytes Minimum Value Maximum Value byte 1 -128 127short 2 -32,768 32,767int 4 -2, 147, 483, 648 2, 147, 483, 647long 8 -9,223,372,036,854,775,808 9,223,372,036,854,775,807
Example declarations:int testGrade;
int numPlayers, highScore, diceRoll;
short xCoordinate, yCoordinate;
byte ageInYears;
long cityPopulation;
-
8/12/2019 2 Data Types and Operators
15/50
Floating-Point Data Types Numbers with fractional partsType Size in Bytes Minimum Value Maximum Value
float 4 1.4E-45 3.4028235E38double 8 4.9E-324 1.7976931348623157E308
Example declarations:float salesTax;
double interestRate;double paycheck, sumSalaries;
-
8/12/2019 2 Data Types and Operators
16/50
char Data Type One Unicode character (16 bits - 2 bytes)Type Size in Bytes Minimum Value Maximum Value char 2 character character
encoded as 0 encoded as FFFF
Example declarations:char finalGrade;
char newline, tab, doubleQuotes;
-
8/12/2019 2 Data Types and Operators
17/50
boolean Data Type Two values only:
true
false Used for decision making or as "flag" variables Example declarations:
boolean isEmpty;
boolean passed, failed;
-
8/12/2019 2 Data Types and Operators
18/50
Assigning Values to Variables
Assignment operator = Value on the right of the operator is assigned to the
variable on the left Value on the right can be a literal (text representing a
specific value), another variable, or an expression (explained later)
Syntax:
dataType variableName =initialValue;
Or
dataType variable1 = initialValue1,
variable2 = initialValue2 , ;
-
8/12/2019 2 Data Types and Operators
19/50
Literals
A Literal is the source code representation of afixed value; literals are represented directly inyour code without requiring computation
int, short, byte Optional initial sign (+ or -) followed by digits 0 9
in any combination. long
Optional initial sign (+ or -) followed by digits 0 9 inany combination, terminated with an L or l .
***Use the capital L because the lowercase l can be
confused with the number 1.
http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.htmlhttp://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html -
8/12/2019 2 Data Types and Operators
20/50
Floating-Point Literals float Optional initial sign (+ or -) followed by a floating-
point number in fixed or scientific format,terminated by an F or f .
double Optional initial sign (+ or -) followed by a floating-
point number in fixed or scientific format.
Note: Commas, dollar signs, and percent signs (%)cannot be used in integer or floating-pointliterals
-
8/12/2019 2 Data Types and Operators
21/50
char and boolean Literals char
Any printable character enclosed in single quotes A decimal value from 0 65535
'\m' , where \m is an escape sequence. For example,'\n' represents a newline, and ' \t' represents a tabcharacter.
boolean
true or falseSee Example 2.2 Variables.java
-
8/12/2019 2 Data Types and Operators
22/50
Assigning the Values of OtherVariables
Syntax:
dataType variable2 =variable1;
Rules:1. variable1 needs to be defined before this
statement appears in the source code2. variable1 and variable2 need to be compatible
data types; in other words, the precision ofvariable1 must be lower than or equal to that of
variable2 .
-
8/12/2019 2 Data Types and Operators
23/50
Compatible Data TypesAny type in right column can be assigned to type in left
column:
Data Type Compatible Data Typesbyte byteshort byte, shortint byte, short, int, charlong byte, short, int, long, char
float float, byte, short, int, long, chardouble float, double, byte, short, int, long, charboolean booleanchar char
-
8/12/2019 2 Data Types and Operators
24/50
Escape Sequences To include a special character in a String , use an
escape sequenceCharacter Escape SequenceNewline \nTab \tDouble quotes \"Single quote \'Backslash \\Backspace \bCarriage return \rForm feed \f
-
8/12/2019 2 Data Types and Operators
25/50
-
8/12/2019 2 Data Types and Operators
26/50
Operators
Operators are special symbols used for: mathematical functions assignment statements
logical comparisons Examples of operators:
3 + 5 // uses + operator 14 + 5 4 * (5 3) // uses +, -, * operators
Expressions : can be combinations of variables andoperators that result in a value
-
8/12/2019 2 Data Types and Operators
27/50
Groups of Operators
There are 5 different groups of operators: Arithmetic Operators Assignment Operator Increment / Decrement Operators Relational Operators Logical Operators
-
8/12/2019 2 Data Types and Operators
28/50
Assignment Operator
Syntax:
target = expression;
expression: operators and operands that evaluateto a single value--value is then assigned to target--target must be a variable (or constant)--value must be compatible with target's datatype
-
8/12/2019 2 Data Types and Operators
29/50
Examples:
int numPlayers = 10; // numPlayers holds10numPlayers = 8; // numPlayers holds 8
int legalAge = 18;
int voterAge = legalAge;
The next statement is illegalint height = weight * 2; //weight is not
defined
int weight = 20;
and generates the following compiler error:illegal forward reference
-
8/12/2019 2 Data Types and Operators
30/50
Arithmetic OperatorsOperator Operation
+ addition
- subtraction
* multiplication
/ division
% modulus(remainder afterdivision)
-
8/12/2019 2 Data Types and Operators
31/50
Arithmetic/Assignment Operators
Java allows combining arithmetic andassignment operators into a single operator:
Addition/assignment += Subtraction/assignment = Multiplication/assignment =
Division/assignment /= Remainder/assignment %=
-
8/12/2019 2 Data Types and Operators
32/50
Arithmetic/Assignment Operators
The syntax isleftSide Op= rightSide ;
This is equivalent to:leftSide = leftSide Op rightSide ;
x%=5; x = x % 5;
x*=y+w*z; x = x*(y+w*z);
Allways it is avariable identifier. It is an arithmetic
operator.
It is either a literal | a variable identifier | an expression.
-
8/12/2019 2 Data Types and Operators
33/50
-
8/12/2019 2 Data Types and Operators
34/50
-
8/12/2019 2 Data Types and Operators
35/50
Example
int x = 3; int y = 5; boolean result ;
result = (x > y); now result is assigned the value false because 3
is not greater than 5
-
8/12/2019 2 Data Types and Operators
36/50
Logical Operators
Symbol Name&& AND|| OR
! NOT
|| T FT T T
F T F
&& T FT T F
F F F
Page 36
-
8/12/2019 2 Data Types and Operators
37/50
Exampleboolean x = true ;
boolean y = false ;boolean result;
result = (x && y);
result is assigned the value false
result = ((x || y) && x);(x || y) evaluates to true(true && x) evaluates to trueresult is then assigned the value true
O P d
-
8/12/2019 2 Data Types and Operators
38/50
Operators Precedence
Parentheses (), inside-out
Increment/decrement ++, --, from left to right
Multiplicative *, /, %, from left to right
Additive +, -, from left to right
Relational , =, from left to right
Equality ==, !=, from left to right
Logical AND &&
Logical OR ||
Assignment =, +=, -=, *=, /=, %=
-
8/12/2019 2 Data Types and Operators
39/50
Arrays An array is a list of similar things An array has a fixed:
name type length
These must be declared when the array is
created. Arrays sizes cannot be changed during the
execution of the code
-
8/12/2019 2 Data Types and Operators
40/50
3 6 3 1 6 3 4 1myArray =
0 1 2 3 4 5 6 7
myArray has room for 8 elements
the elements are accessed by their indexin Java, array indices start at 0
-
8/12/2019 2 Data Types and Operators
41/50
Declaring Arrays
int myArray[];declares myArray to be an array of integers
myArray = new int[8];
sets up 8 integer-sized spaces in memory,labelled myArray[0] to myArray[7]
int myArray[] = new int[8];
combines the two statements in one line
-
8/12/2019 2 Data Types and Operators
42/50
Assigning Values
refer to the array elements by index to storevalues in them.myArray[0] = 3;
myArray[1] = 6;myArray[2] = 3; ...
can create and initialise in one step:
int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1};
-
8/12/2019 2 Data Types and Operators
43/50
Iterating Through Arrays
for loops are useful when dealing with arrays:
for (int i = 0; i < myArray.length; i++) {myArray[i] = getsomevalue();
}
-
8/12/2019 2 Data Types and Operators
44/50
Arrays of Objects
So far we have looked at an array of primitivetypes.
integers could also use doubles, floats, characters
Often want to have an array of objects Students, Books, Loans
Need to follow 3 steps.
-
8/12/2019 2 Data Types and Operators
45/50
Declaring the Array
1. Declare the array private Student studentList[];
this declares studentList
2 .Create the arraystudentList = new Student[10];
this sets up 10 spaces in memory that canhold references to Student objects
3. Create Student objects and add them to the array:studentList[0] = new Student("Cathy","Computing");
-
8/12/2019 2 Data Types and Operators
46/50
4 6
Numeric Type Conversion
Consider the following statements:
byte i = 100;
long k = i * 3 + 4;double d = i * 3.1 + k / 2;
-
8/12/2019 2 Data Types and Operators
47/50
4 7
Conversion RulesWhen performing a binary operation involving twooperands of different types, Java automaticallyconverts the operand based on the following rules:
1. If one of the operands is double, the other isconverted into double.2. Otherwise, if one of the operands is float, theother is converted into float.
3. Otherwise, if one of the operands is long, theother is converted into long.4. Otherwise, both operands are converted into int.
-
8/12/2019 2 Data Types and Operators
48/50
4 8
Type Casting
Implicit castingdouble d = 3; (type widening)
Explicit castingint i = (int)3.0; (type narrowing)int i = (int)3.9; (Fraction part
is truncated)What is wrong? int x = 5 / 2.0;
Casting between char and
-
8/12/2019 2 Data Types and Operators
49/50
4 9
Casting between char andNumeric Types
int i = ' a ' ; // Same as int i = (int) ' a ' ;
char c = 97; // Same as char c = (char)97;
-
8/12/2019 2 Data Types and Operators
50/50