Numeric Processing in Java P E M R O G R A M A N B E R O R I E N T A S I O B J E K NIKO IBRAHIM, MIT UNIVERSITAS KRISTEN MARANATHA
Lecture s Outline NUMBERS IN JAVA Primitives types Swapping pattern Debugging with System.out.println() Operators and Expressions Mixed types Math Class PROGRAMMING WITH NUMBERS Assignment statement revisited Decrement and Increment operator Circular counting Random numbers Example: balance
Primitive Types (revisit) Java memiliki beberapa primitive types yang bersifat built-in, dan tidak memerlukan pendefinisian kelas untuk menggunakannya. Primitive Types tersebut dapat berupa: karakter (char) bilangan bulat (int) bilangan desimal (float) Primitive Types bukanlah Objek!, sehingga tidak memiliki atribut, method, ataupun constructor. Beberapa primitive types yang sering dipakai: numeric types: byte, short, int, long, float, double non-numeric types: char, boolean (more later...)
INTEGERS Bilangan bulat (Integer) di Java dapat berupa salah satu berikut: byte short int long Yang paling umum dipakai adalah int Bilangan integer tidak boleh ada spasi ataupun koma Contoh: 1001-25 Tipe byte dan short jarang digunakan
Real (Floating Point Number) Bilangan desimal atau pecahan seringkali disebut sebagai Real atau floating-point numbers. Ada dua jenis bilangan Real, yaitu: float double Yang paling umum dipakai adalah double Bilangan pecahan disimpan dengan tingkat akurasi yang terbatas Operasi aritmatika terhadap bilangan pecahan menghasilkan nilai pendekatan Contoh bilangan desimal: 23.89 0.0032 Dapat menggunakan notasi ilmiah E Contoh: 5100 = 5.1E+3 0.221 = 2.2e-2
Tabel Tipe Bilangan Type Storage Min Value Max Value byte 8 bits -128 127 short 16 bits -32,768 32,768 int 32 bits -2,147,483,648 2,147,483,647 long 64 bits -9,223,372,036,854,775,808 9,223,372,036,854,775,807 float 32 bits approx. -3.4E+38 approx. 3.4E+38 double 64 bits approx. -1.7E+308 approx. 1.7E+308
Konstanta Konstanta atau constant (seringkali disebut juga literals) adalah variabel yang hanya di-assign sekali Untuk mendefinisikan konstanta di Java, kita gunakan kata final Contoh: final float PI = 3.14159; final int LIFE = 42; Konstanta digunakan untuk menyimpan nilai yang tidak boleh diubah di dalam program Konstanta juga membuat kode program lebih mudah dibaca Apabila perlu pengubahan nilai konstanta, cukup diubah di satu tempat yaitu pada tempat pendefinisian konstanta tersebut (change only in one spot) Biasanya konstanta dituliskan dengan huruf besar semua, misal: MAX_LOAD, LIFE_TIME, PI, dll.
Primitive vs Reference Reference variable refers to (points to) an object null if not initialized instantiate object to initialise Example: AOval face = new AOval(); AWindow papan = new AWindow(); Primitive variable contains a value Example: int counter = 25; float harga = 1000.50
MIXED TYPES Two or more different numeric types involved Example: 12 + 7.04 =? safe conversions widening: no information lost (wider type value can represent any narrower type value) Java uses automatic widening: of all the types used in the expression, the results type is the last type (reading left to right) on the list: int < long < float < double Example: 7.0/2 evaluates as 7.0/2.0 producing double double + float = double no automatic narrowing (unsafe! lost of data/precision) - can only be forced, using for example casting
Casting casting (forced conversion) - adalah suatu cara untuk memaksa perubahan tipe Dengan melakukan casting, kita mungkin akan kehilangan informasi (misalnya adanya penhapusan nilai pecahan di belakang koma) Sintaks: (type) expression Contoh: nilai = (int) 12.78; mengasilkan: nilai = 12; Contoh lain: int i = 5.5; // illegal! (5.5 is a float type number, not an integer) casting must be used - otherwise the compiler will produce error Cara yang benar adalah: int i = (int)5.5;
MATH CLASS Java memiliki standard library yang berhubungan dengan operasi matematika, yang disimpan dan dikelompokkan ke dalam kelas MATH (MATH CLASS) Kelas MATH ini memiliki method-method yang umum sekali digunakan untuk melakukan perhitungan matematika Beberapa penggunaan kelas MATH: conversions Math.abs(), Math.round(),... Contoh: Math.abs(-10) akan menghasilkan nilai 10 functions of all kinds Math.sin(), Math.cos(), Math.tan(),... Math.log(), Math.exp(), Math.sqrt(),... Contoh: Math.sqrt(9) akan menghasilkan nilai 3 others Math.random() menghasilkan nilai acak antara 0 s/d 1 (0 tidak termasuk) Misal: 0.1, 0.7, 1.0, dll Terdapat juga nilai constants, seperti: Math.PI, Math.E
DEBUGGING WITH System.out.println() Debugging adalah suatu proses untuk menghilangkan eror-eror yang terdapat pada program. debugging means removing programming errors Java memiliki sebuah objek yang disebut System.out yang berguna untuk menampilkan sesuatu System.out.println() adalah suatu method yang biasa digunakan untuk menampilkan informasi mengenai suatu objek atau tipe data tertentu. The println() method memiliki sebuah parameter. Parameter ini dapat berupa primitive type ataupun objek reference Contoh: System.out.println(harga); System.out.println(leftEye); BlueJ Terminal Window akan menampilkan nilai (jika primitive type) atau deskripsi objek (if a reference was passed) useful for finding errors in programs - provide information such as: which methods have been called the values of parameters and local variables the order in which methods have been called comment out System.out.println() statements once the program seems correct
Contoh 1 Misalnya kita memiliki kode sbb: win = new AWindow(100,100,300,150); oval = new AOval(90,20,70,30); System.out.println(win); System.out.println(oval); The BlueJ Terminal Window shows the object properties:
Contoh 2: Swapping Pattern passing primitives to println() public class Swap { public Swap(){ private int x = 26; private int y = 45 ; //print out some values or messages System.out.println("Before swapping..."); System.out.println("x = " + x +", y = " + y) ; // the 'swap' pattern int temp ; //need a temporary storage temp = x ; x = y ; y = temp ; //print it out again to see the difference System.out.println("After swapping..."); System.out.println("x = " + x +", y = " + y) ;
Hasil Contoh 2
Brain Teaser 1: Analyse This
Brain Teaser 2: What value?
ASSIGNMENT STATEMENT Assignment dilakukan dengan menggunakan operator = Nilai disisi kanan di-copy-kan ke sisi kiri Ada perbedaan antara assignment untuk primitive dengan reference primitives: straightforward operation A = B berarti nilai yang disimpan di variabel/ekspresi B dikopikan ke variable A references: can add surprises! Terjadi: aliasing phenomenon A = B berarti kedua A dan B menunjuk ke (pointing to) objek yang sama, yaitu objek yang sedang ditunjuk oleh B. Apa konsekuensinya?
Contoh 3: aliasing public class Number{ private int value; public Number(int value){ this.value = value; //using 'this' the same identifier may be used public int getvalue(){ return value; public void setvalue(int val){ value = val; //no need for 'this' here because we re using different names public class Assignment{ private Number n1,n2; public Assignment(){ n1 = new Number(12); n2 = new Number(100); n1 = n2; //aliasing occurs here n1.setvalue(28); // QUESTION: What is the value for n2 now? System.out.println(n2.getValue());
CIRCULAR COUNTING Problem Anda memerlukan sebuah variabel untuk menghitung bilangan secara terurut berdasarkan range tertentu dari range paling rendah ke range paling tinggi. Penghitungan terus berulang, artinya saat penghitungan mencapai range tertinggi, maka akan kembali menghitung dari range yang terendah. Misal: range 1 s/d 5, step = 1 Circular Counting: 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, dst. Solution The simplest case (which is also quite common) is when the sequence begins at 0, has a step size of 1, and contains n values (which means that the range is 0 to n-1). In this case, compute the new value for the variable using the assignment: v = (v + 1) % n; As long as v+1 remains less than n, the remainder when it is divided by n will be the same value, thus ensuring that the successive values will increase by one each time. But when v reaches n - 1 (the final value in the sequence), v+1 will equal n and the remainder (and hence the next value) will be zero. In the general case, the new value for the variable is given by the assignment: v = min + (v - min + step) % (max - min + 1) where max and min are the largest and smallest values in the sequence and step is the step size.
Brain Teaser: What is the output? Formula: v = min + (v - min + step) % (max - min + 1) Starting from: v = 4 min = 3 max = 20 step = 5 Result:? 9,14,19,6,11,16,3,8,13,18,5,10,15,20,7,12,17,4, 9,14,19,6,11,16,3,8,13,18,5,10,15,20,7,12,17,4, 9,14,19,6,11,...
Testing Code public class circular{ private int v,min,max,step; public circular() { // initialise instance variables v = 4; min = 3; max = 20; step = 5; for (int i = 0; i <= 40; i++){ v = min + (v - min + step) % (max - min + 1); System.out.print(v + ",");
RANDOM NUMBERS Problem: You need to generate a number that lies within a specified range, but whose actual value is unpredictable. Every time you generate the number, you expect to get a different result. Solution: 1 + (int)(math.random() * n); //integer within the range 1..n min + Math.random() * (max - min) //float in range min..max To generate an unpredicable integer value in the range min to max, use the expression: min + (int)(math.random() * (max - min + 1)) Since the Math.random() method returns a floating point value between 0 and 1, the right-hand parenthesis produces a floating point value between 0 and (max-min+1). Casting this value to an int throws away any fractional component, thus producing an integer in the range 0 to max-min, which means that the overall value is in the range min to max.
Contoh 4: Randomizer public class random { private int v, min=10, max=25; public random() { for (int i = 0; i <= 10; i++){ //generate random number: v = min + (int)(math.random()*(max-min + 1)); //print the random numbers: System.out.print(v + ", "); Result Example(could be different for each runs): 11, 21, 18, 14, 12, 22, 12, 11, 13, 20, 18,
Latihan Silahkan mengerjakan ke-4 contoh soal yang diberikan. Silahkan modifikasi kode untuk improvisasi dan latihan sebelum praktikum.