Upload
milhcbt1790
View
172
Download
3
Embed Size (px)
DESCRIPTION
PBO 1-B pdf
Citation preview
Object-Oriented Programming with Java
Java Type Manipulation
ImanLHakim
Agenda
• What is Data • How Computer Stores Data • Java Data Type • Primitive Type • Primitive Data Conversion (Casting) • Arithmetic of Primitive Data • Wrapper Class of Primitive Data Type • Reference Type • Reference Type Casting • Object Class as Parents of all Java Classes • Immutable String and Mutable String • Basics String Operation and Regular Expression
What is Data
• The term data refers to qualitative or quantitative attributes of a variable or set of variables. Data (plural of "datum") are typically the results of measurements and can be the basis of graphs, images, or observations of a set of variables. Data are often viewed as the lowest level of abstraction from which information and then knowledge are derived. Raw data, i.e. unprocessed data, refers to a collection of numbers, characters, images or other outputs from devices that collect information to convert physical quantities into symbols. Wikipedia
• We use Computer to process data.
How Computer Stores Data
• Data stored in computer memory or storage in binary format.
• Computer only recognize binary type of data.
• It is Computer Programming Language and other programs that help us classified data into varieties type
Java Data Types
Typ
e
Reference
Class
Interface
Array
Primitive
Numeric
Floating Point
float (signed)
double (signed)
Integral
byte (signed)
short (signed)
int (signed)
long (signed)
char (unsigned)
Boolean
Return address
Integral Data Type
Data Type Value Default
Value Size Range
Char Unicode
character \u0000 16 bits \u0000 to \uFFFF
Byte Signed integer 0 8 bits -128 to 127
Short Signed integer 0 16 bits -32768 to 32767
Int Signed integer 0 32 bits -2147483648 to
2147483647
long Signed integer 0 64 bits
-9223372036854775808
to
9223372036854775807
Integral Literal IntegerLiteral: DecimalIntegerLiteral HexIntegerLiteral OctalIntegerLiteral DecimalIntegerLiteral: DecimalNumeral IntegerTypeSuffixopt HexIntegerLiteral: HexNumeral IntegerTypeSuffixopt OctalIntegerLiteral: OctalNumeral IntegerTypeSuffixopt IntegerTypeSuffix: one of l L DecimalNumeral: 0 NonZeroDigit Digitsopt Digits: Digit Digits Digit Digit: 0 NonZeroDigit NonZeroDigit: one of 1 2 3 4 5 6 7 8 9 HexNumeral: 0 x HexDigits 0 X HexDigits HexDigits: HexDigit HexDigit HexDigits HexDigit: one of
0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F OctalNumeral: 0 OctalDigits OctalDigits: OctalDigit OctalDigit OctalDigits OctalDigit: one of 0 1 2 3 4 5 6 7
Sample byte Literals
byte b1 = 015; byte b2 = 15; byte b3 = 0x15;
byte b4 = 0X15; byte b5 = -015; byte b6 = -15;
byte b7 = -0x15; byte b8 = -0X15;byte b9 = 127;
byte b10 = -128;
// byte b11 = 128;
//Type mismatch: cannot convert from int to byte
// byte b12 = -129;
//Type mismatch: cannot convert from int to byte
byte b13 = (byte) 128; // konversi tipe eksplisit
byte b14 = (byte) -129; // konversi tipe eksplisit
Sample short Literals
short s1 = 015; short s2 = 15; short s3 = 0x15;
short s4 = 0X15; short s5 = -015; short s6 = -15;
short s7 = -0x15; short s8 = -0X15; short s9 = 32767;
short s10 = -32768;
// short s11 = 32768; //Type mismatch: cannot
// convert from int to short
// short s12 = -32769; //Type mismatch: cannot
// convert from int to short
short s13 = (short) 32768; // konversi tipe eksplisit
short s14 = (short) -32768;// konversi tipe eksplisit
Sample int Literals
int i1 = 0555; int i2 = 555; int i3 = 0xFAfa; int i4 = 2147483647;
//int i5 = 2147483648;//The literal 2147483648 of type int is out of range
//int i6 = 2147483648L; //Type mismatch: cannot convert from long to int
int i7 = (int) 2147483648L; // konversi tipe eksplisit
int i8 = (int) 2147483649L; // konversi tipe eksplisit
int i9 = (int) 2147483650L; // konversi tipe eksplisit
int i10 = (int) 4294967294L;// konversi tipe eksplisit
int i11 = (int) 4294967295L;// konversi tipe eksplisit
int i12 = (int) 4294967296L;// konversi tipe eksplisit
int i13 = (int) 4294967297L;// konversi tipe eksplisit
int i14 = (int) 4294967298L;// konversi tipe eksplisit
int i15 = (int) 8589934593L;// konversi tipe eksplisit
Sample long Literals
long l1 = 0555;
long l2 = 555;
long l3 = 0xFAfa;
// long l4 = 2147483648;
//The literal 2147483648 of
// type int is out of range
long l5 = 2147483648L;
// long l6 = 9223372036854775808L; //The literal
// 9223372036854775808L of type long is out of range
Floating-Point Data type
Type Contains Default Size Range
Float IEEE 754
floating point 0.0 32 bits
1.4E-45 to
3.4028235E+3
8
double IEEE 754
floating point 0.0 64 bits
4.9E-324 to
1.7976931348
623157E+308
Float Literal FloatingPointLiteral: DecimalFloatingPointLiteral HexadecimalFloatingPointLiteral DecimalFloatingPointLiteral: Digits . Digitsopt ExponentPartopt FloatTypeSuffixopt . Digits ExponentPartopt FloatTypeSuffixopt Digits ExponentPart FloatTypeSuffixopt Digits ExponentPartopt FloatTypeSuffix ExponentPart: ExponentIndicator SignedInteger ExponentIndicator: one of e E SignedInteger: Signopt Digits Sign: one of + - FloatTypeSuffix: one of f F d D HexadecimalFloatingPointLiteral: HexSignificand BinaryExponent FloatTypeSuffixopt HexSignificand: HexNumeral HexNumeral . 0x HexDigitsopt . HexDigits 0X HexDigitsopt . HexDigits BinaryExponent: BinaryExponentIndicator SignedInteger BinaryExponentIndicator:one of p P
Sample float Literals
float f1 = 1e1f; float f2 = 2.f;
float f3 = .3f;
float f4 = 0f; float f5 = 3.14f;
float f6 = 6.022137e+23f;
//float f7 = .394;/* ^Type mismatch:
cannot convert from double to float*/
float f8 = 0xfff;//last f for float
float f9=0Xf.aP1F;/*(15+10/16ths)*
2^1= 31.25 */
Sample double Literals
double d1 = 0XaP0; // 10 * 2^0 = 10
double d2 = 0XfP2D; // 15 * 2^2 = 60
//double d3 = .98P2;
/* ^Syntax error on token "P2", delete
this token*/
double d4 = 'x';
//implisit conversion char -> double
double d5 = 232;
//implisit conversion int -> double
char Literal
Seq Keterangan
\n Newline (\u000A)
\t Tab (\u0009)
\b Backspace (\u0008)
\r Return (\u000D)
\f Form feed (\u000C)
\\ Backslash itself (\u005C)
\' Single quote (\u0027)
\" Double quote (\u0022)
\ddd Sebuah karakter ASCII, dimana setiap d diganti dengan angka oktal antara 0-
377, jumlah angka oktal tidak mesti 3. contoh ‘\62’, ‘\134’
\uxxx
x
Sebuah karakter Unicode, dimana setiap x diganti angka hexadesimal, jumlah
angka hexadesimal harus selalu 4. contoh ‘\x0012’, ‘\xBAba’.
CharacterLiteral: ' SingleCharacter ' ' EscapeSequence ' SingleCharacter: InputCharacter but not ' or \
Sample char Literal
char c1 = 'a'; char c2 = '2';
// char c3 = '76'; //Invalid character constant
// char c4 = '''; //Invalid character constant
char c5 = '\'';
// char c6 = '\'; //Invalid character constant
char c7 = '\76';
// char c8 = '\U0032';//Invalid escape sequence
// (valid ones are \b \t \n \f \r \" \' \\ )
char c9 = '\u0032'; char c10 = '\10';
char c11 = '\u20AC';
char c12 = '\377'; char c13 = '\uffff';
boolean Literal
• boolean only have true and false
• Unlike C/C++, java does not have boolean literal 1 or 0 (zero).
Java Operators
Precedence Operator Description Association
1 ++,-- Postincrement, Postdecremet R L
2 ++,-- Preincrement, Predecrement R L
+,- Unary plus, unary minus R L
~ Bitwise compliment R L
! Boolean NOT R L
3 New Create object R L
(type) Type cast R L
4 *,/,% Multiplication, division, remainder L R
5 +,- Addition, subtraction L R
+ String concatenation L R
6 <<, >>, >>> Left shift, right shift, unsigned right shift L R
7 <, <=, >, >= Less than, less than or equal to, greater than, greater
than or equal to L R
Instanceof Type comparison L R
Java Operators (cont…)
Precedence Operator Description Association
8 ==, != Value equality and inequality L R
==, != Reference equality and inequality L R
9 & Boolean AND L R
& Bitwise AND L R
10 ^ Boolean XOR L R
^ Bitwise XOR L R
11 | Boolean OR L R
| Bitwise OR L R
12 && Conditional AND L R
13 || Conditional OR L R
14 ?: Conditional Ternary Operator L R
15
=,+=,-=, *=,/
=,%=,&=,^=, |=,
<<=, >> =, >>>=
Assignment Operators R L
Exercise
• Create sample java code that use all operator above except “Create object”, “Type Cast”, “Object Comparation”
Primitive Data Convertion
Convert Convert to:
from: boolean byte short char int long float double
boolean - N N N N N N N
byte N - Y C Y Y Y Y
short N C - C Y Y Y Y
char N C C - Y Y Y Y
int N C C C - Y Y* Y
long N C C C C - Y* Y*
float N C C C C C - Y
double N C C C C C C -
Wrapper Class of primitives
• Each primitive type has wrapper class • Each class has fields and method to ease data manipulation • Since JDK 1.5 between primitive and wrapper converted
automatically, these call auto boxing (primitive wrapper), auto unboxing ( wrapper primitive)
Primitive Wrapper class
boolean java.lang.Boolean
char java.lang.Character
byte java.lang.Byte
short java.lang.Short
int java.lang.Integer
long java.lang.Long
float java.lang.Float
double java.lang.Double
Common Used Methods of Wrapper Class
• Y. xValue()Returns the x value of this y object. • Y.parseX(String s)Returns a new X initialized to
the value represented by the specified String s. • Y.valueOf(X x) Returns a Y instance
representing the specified x value. • Y.toXString()Returns a string representation of
the integer argument as an unsigned integer in base X.
• Y.toString()Returns a string representation of this Y object.
Common Used Fields of Wrapper Class
• X.MAX_VALUE maximal value of type X
• X.MIN_VALUE minimal value of type X
• D.NaN A constant holding a Not-a-Number (NaN) value of type D (Double or Float).
Simplified Memory Layout of Primitive Reference Type
float pi = 3.1415926 ; Student s1 = new Student(“iman”, 19); Student s2 = new Student(“Angust”, 14);
V -Table
Student
pi = 3.1415926
s1
s2
Student
SCHOOL=“ITT”
Class definition and static member value
public class Student{ public static String SCHOOL = “IIT”; public String name; public int age; public Student (String name, String age){ this.name = name; this.age = age } }
s2
name = “Angust”
age = 14
s1
name = “iman”
age = 19
Type Casting
• Let an object with type X acts as object with Type Y. • Java understands two types of casting
– Implicit or up casting , done automatically – Explicit or down casting, done manually
//let’s say X is abstract class X x1 = new Y();//implicit (up) casting YX X x2 = new Z();//implicit (up) casting Z X Y y1 = new Y(); Z z1 = new Z(); Y y2 = (Y) x1;//explicit (down) casting XY Z z2 = (Z) x2;//explicit (down) casting ZZ
Introducing java.lang.Object Class
• Class java.lang.Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
• Some of java.lang.Object’s methods highly recommended to be implemented by its descendent.
Important java.lang.Object’s Methods
Return Type Method Signature
protected Object clone() Creates and returns a copy of this object.
boolean equals(Object obj) Indicates whether some other object is "equal to" this one.
int hashCode() Returns a hash code value for the object.
String toString() Returns a string representation of the object.
Class<?> getClass() Returns the runtime class of this Object.
Copying Object
Shallow copy
X x1 = new X();
X x2 = x1;//copy x1x2;
x1 == x2;//true
x1.getClass() ==
x2.getClass(); //true
Deep copy (clone)
X x1 = new X();
X x2= x1.clone();//copy xx2;
x1 != x2;//true
x1.getClass() ==
x2.getClass(); //true
See Item 11: Override clone judiciously of Bloch, Joshua (2008), Effective Java (2 ed.), Addison-Wesley.
Comparing Objects
• Use equals() method to compare reference type, don’t use == operator. • Implement equals() method on every class that it’s instances not (object)
always unique, or may compared. • The equals method implements an equivalence relation. It is:
– Reflexive: For any non-null reference value x, x.equals(x) must return true. – Symmetric: For any non-null reference values x and y, x.equals(y) must return
true if and only if y.equals(x) returns true. – Transitive: For any non-null reference values x, y, z, if x.equals(y) returns true
and y.equals(z) returns true, then x.equals(z) must return true. – Consistent: For any non-null reference values x and y, multiple invocations of
x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
– For any non-null reference value x, x.equals(null) must return false.
• Always override hashCode() when you override equals. ~ Bloch, Joshua (2008), Effective Java (2 ed.), Addison-Wesley.
Make Object Easy to Observe
• Implement toString to make your class much
more pleasant to use.
• The toString method is automatically invoked
when an object is passed to println, printf, the
string concatenation operator, or assert, or
printed by a debugger.
String
• The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.
• Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings.
• The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.
• The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.
Regular Expresion
• In computing, a regular expression, also referred to as regex or regexp, provides a concise and flexible means for matching strings of text, such as particular characters, words, or patterns of characters. A regular expression is written in a formal language that can be interpreted by a regular expression processor, a program that either serves as a parser generator or examines text and identifies parts that match the provided specification. ~ wikipedia
Regex in Java
• Since Java 1.4 we can perform textual pattern matching with regex. • Java provides Pattern and Matcher classes of the java.util.regex
package. • String class has some regex methods below
Return Type Method Signature
boolean matches(String regex) Tells whether or not this string matches the given regular expression.
String replaceAll(String regex, String replacement) Replaces each substring of this string that matches the given regular expression with the given replacement.
String replaceFirst(String regex, String replacement) Replaces the first substring of this string that matches the given regular expression with the given replacement.
String[] split(String regex) Splits this string around matches of the given regular expression.
String[] split(String regex, int limit) Splits this string around matches of the given regular expression.
Assignment
• Create Text Base Reverse Polish notation (RPN) Calculator Application with addition, subtraction, multiplication and division operators.
and Remember…..