CPSC 319 Week 2 Java Basics Xiaoyang Liu xiaoyali@ucalgary.ca & Sorting Algorithms
Java Basics Variable Declarations Type Size Range boolean 1 bit true, false char 16 bits Unicode characters byte 8 bits [-128, 127] short 16 bits [-32768, 32767] int 32 bits [-2147483648, 2147483647] long 64 bits [-9223372036854775808, 9223372036854775807] float 32 bits [-3.4E38, 3.4E38] double 64 bits [-1.7E308, 1.7E308]
Java Basics Range An overflow resulting from an arithmetic operation (unless it is division by zero) is not indicated, so the programmer must be aware that, for two integers, int i = 2147483647, j = i + 1; the value of j is 2147483648. Java does not provide modifiers signed and unsigned but it has other modifiers.
Java Basics Range An overflow resulting from an arithmetic operation (unless it is division by zero) is not indicated, so the programmer must be aware that, for two integers, int i = 2147483647, j = i + 1; the value of j is 2147483648. Java does not provide modifiers signed and unsigned but it has other modifiers. Type Cast byte a, b = 1, c = 2; a = b + c;
Java Basics Range An overflow resulting from an arithmetic operation (unless it is division by zero) is not indicated, so the programmer must be aware that, for two integers, int i = 2147483647, j = i + 1; the value of j is 2147483648. Java does not provide modifiers signed and unsigned but it has other modifiers. Type Cast byte a, b = 1, c = 2; a = b + c; give a compilation error, incompatible type for =. Explicit cast is needed to convert int to byte. The addition b + c gives an integer value that must be cast to execute the assignment to the byte variable a. To avoid the problem,the assignment should be changed to a = (byte) (b + c);
Java Basics If either operand is of type double, the other is converted to double. Otherwise, if either operand is of type float, the other is converted to float. Otherwise, if either operand is of type long, the other is converted to long. Otherwise, both operands are converted to type int.
Java Basics If either operand is of type double, the other is converted to double. Otherwise, if either operand is of type float, the other is converted to float. Otherwise, if either operand is of type long, the other is converted to long. Otherwise, both operands are converted to type int. Any expression involving an int and/or a primitive lower than int (byte, short) will always result in an int. Does it mean byte + byte = int like 8 bits + 8 bits = 32 bits(which is not right!)?
Java Basics If either operand is of type double, the other is converted to double. Otherwise, if either operand is of type float, the other is converted to float. Otherwise, if either operand is of type long, the other is converted to long. Otherwise, both operands are converted to type int. Any expression involving an int and/or a primitive lower than int (byte, short) will always result in an int. Does it mean byte + byte = int like 8 bits + 8 bits = 32 bits(which is not right!)? It means that Java prefers to treat smaller data types as ints, since any modern processor has at least 32-bit words anyway. A byte + a byte gets converted to an int + and int, and the result is an int. It's easy to add bits here - the new bits are all 0. { byte a = 3; byte b = 7; b = (byte)(a + b); // Okay with cast back to byte b = a + b; // Won't compile loss of precision error
Java Basics Operators-Assignments x = y = z = 1;
Java Basics Operators-Assignments x = y = z = 1; Operators-Updating Value x = x + 1;
Java Basics Operators-Assignments x = y = z = 1; Operators-Updating Value x = x + 1; Can be shortened to: x += 1;
Operators What is the difference between prefix and postfix operators? ++n, n++, --n, and n--,
Operators What is the difference between prefix and postfix operators? ++n, n++, --n, and n--, For the prefix operator, a variable is incremented first and then an operation is performed in which the increment takes place For a postfix operator, autoincrement is the last operation performed
Operators What is the difference between prefix and postfix operators? ++n, n++, --n, and n--, For the prefix operator, a variable is incremented first and then an operation is performed in which the increment takes place For a postfix operator, autoincrement is the last operation performed What are the values of x and y? x = 5; y = 6 + ++x; x = 5; y = 6 + x++;
Operators What is the difference between prefix and postfix operators? ++n, n++, --n, and n--, For the prefix operator, a variable is incremented first and then an operation is performed in which the increment takes place For a postfix operator, autoincrement is the last operation performed What are the values of x and y? x = 5; y = 6 + ++x; x = 5; y = 6 + x++; x=6, y=12 x=6, y=11
Operators Given one integer x, how can you compute 7*x? (You cannot use multiplications and additions)
Operators Given one integer x, how can you compute 7*x? (You cannot use multiplications and additions) int tmp = x; x << 3; x = x - tmp;
Operators Given one integer x, how can you compute 7*x? (You cannot use multiplications and additions) int tmp = x; x << 3; x = x - tmp; Java allows performing operations on individual bits with bitwise operators: & (bitwise and), (bitwise or), ^ (bitwise xor), << (left shift), >> (right shift), >>> (zero filled shift right), and ~ (bitwise complement). Shorthands &=, =, ^=, <<=, >>=, and >>>= are also possible. Except for the operator >>>, the other operators are also in C/C++. The operator >> shifts out a specified number of rightmost (least significant) bits and shifts in the same number of 0s for positive numbers and 1s for negative numbers. For example, the value of m after the assignments
Decision Statements if (condition) do something; [else do something else;] if(a > b){ max = a; else max = b;
Decision Statements if (condition) do something; [else do something else;] if(a > b){ max = a; else max = b; condition? do-if-true : do-if-false; max = a > b? a : b;
Decision Statements if (condition) do something; [else do something else;] if(a > b){ max = a; else max = b; condition? do-if-true : do-if-false; max = a > b? a : b; Nested if statements switch (integer expression) { case value1: block1; break;...... case valuen: blockn; break; default: default block; switch (i) { case 5 : x + = 10; break; case 6 : x = 20; case 7 : x *= 2; break; default : x = 30; if i = 5, x =? if i = 6, x =?
Decision Statements if (condition) do something; [else do something else;] if(a > b){ max = a; else max = b; condition? do-if-true : do-if-false; max = a > b? a : b; Nested if statements switch (integer expression) { case value1: block1; break;...... case valuen: blockn; break; default: default block; switch (i) { case 5 : x + = 10; break; case 6 : x = 20; case 7 : x *= 2; break; default : x = 30; if i = 5, x = 5 if i = 6, x = 40
Input and Output Import java.io package for reading and writing data import java.io.*;
Input and Output Import java.io package for reading and writing data import java.io.*; Print anything on the screen System.out.print(message); System.out.println(message);
Input and Output Import java.io package for reading and writing data import java.io.*; Print anything on the screen (standard output) System.out.print(message); System.out.println(message); The message printed by the statement is a string. All components of the print statement are concatenated with the operator +.
Input and Output Data are read from standard input with the input stream System.in import java.io.*; public class inputtest { public static void main(string[] args) { // TODO Auto-generated method stub InputStreamReader cin = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(cin); String s = ""; try{ s = br.readline(); catch(ioexception e){ System.out.println(s);
Input and Output Reading and Writing Bytes(one at a time) import java.io.*; public class fileinput { public static void main(string[] args) throws IOException{ String finname = "in.txt"; String foutname = "out.txt"; FileInputStream fin = new FileInputStream(fInName); FileOutputStream fout = new FileOutputStream(fOutName); int i; while((i = fin.read())!= -1){ System.out.println((char)i + ""); //display characters; System.out.println(i + ""); //display ASCII values; fout.write(i); fin.close(); fout.close();
Input and Output Reading and Writing Bytes(More efficient way) import java.io.*; public class bufferstream { public static void main(string[] args) throws IOException{ String finname = "in.txt"; String foutname = "out.txt"; BufferedInputStream fin = new BufferedInputStream( new FileInputStream(fInName)); BufferedOutputStream fout = new BufferedOutputStream( new FileOutputStream(fOutName)); int i; while((i = fin.read())!= -1){ System.out.println(i + ""); fout.write(i); fin.close(); fout.close();
Input and Output Reading Lines import java.io.*; public class readline { public static void main(string[] args) throws IOException{ String finname = "in.txt"; String foutname = "out.txt"; BufferedReader fin = new BufferedReader( new FileReader(fInName)); PrintWriter fout = new PrintWriter( new FileWriter(fOutName)); String s; while((s = fin.readline())!= null){ System.out.println(s); fout.println(s); fin.close(); fout.close();
Parse Command Line Arguments All arguments are stored in args array whose type is String String[] args In your assignment, you need to parse the following parameters java Assign1 order size algorithm outputfile What is the length of your args array? What is the type of each parameter?
Parse Command Line Arguments Parse Integer int size = Integer.parseInt(args[1]);
Parse Command Line Arguments Parse Integer int size = Integer.parseInt(args[1]); Match String String order = args[0];
Parse Command Line Arguments Parse Integer int size = Integer.parseInt(args[1]); Match String String order = args[0]; if(order == "random") if(order.equals("random"))
Parse Command Line Arguments Parse Integer int size = Integer.parseInt(args[1]); Match String String order = args[0]; if(order == "random") //whether two objects are a reference to the same object if(order.equals("random")) //if the objects have the same value
Generate Random Numbers public static double random() Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range. int value = (int)(math.random()*size); Construct an integer array with length = size and fill it in with all random numbers generated with the statement above
Measuring Performance In Java, use the nanotime() method to measure the elapsed time (Note: result is in nanoseconds 10-9 s) long starttime = System.nanoTime(); somealgorithm(); long elapsedtime = System.nanoTime() - starttime; Practice: Save your random array to the file you specified (refer to the PrintWriter slide) Measure and display the elapsed time for your program
Sorting Algorithms Bubble Sort: http://youtu.be/p00xjgwzz2c?t=10s Insertion Sort: http://youtu.be/c4brhc7ktaq?t=10s Merge Sort: http://youtu.be/gcae1wnvnzm?t=10s Quick Sort: http://youtu.be/y_g9bkam6b8?t=10s Comparison: http://youtu.be/t8g-iyghpea President s Choice: http://youtu.be/k4rri_ntqc8
Code import java.io.*; public class ranarray { public static void main(string[] args) throws IOException{ String order = args[0]; int size = Integer.parseInt(args[1]); int[] array = new int[size]; String fname = args[2]; long starttime = System.nanoTime(); if(order.equals("random")){ for(int i = 0; i < size; i++){ array[i] = (int)(math.random()*size); PrintWriter fout = new PrintWriter(new FileWriter(fName)); for(integer i:array){ fout.println(i); fout.close(); long elapsedtime = System.nanoTime() - starttime; System.out.println(elapsedTime + " nanoseconds");