CPSC 319. Week 2 Java Basics. Xiaoyang Liu & Sorting Algorithms

Similar documents
Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Expressions & Flow Control

CSC 1214: Object-Oriented Programming

CS2141 Software Development using C/C++ C++ Basics

JAVA OPERATORS GENERAL

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Zheng-Liang Lu Java Programming 45 / 79

Darshan Institute of Engineering & Technology for Diploma Studies

SECTION II: LANGUAGE BASICS

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Agenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

CSC 1214: Object-Oriented Programming

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Operators in java Operator operands.

Object-Oriented Programming Design. Topic : Streams and Files

Chapter 3: Operators, Expressions and Type Conversion

Byte and Character Streams. Reading and Writing Console input and output

HST 952. Computing for Biomedical Scientists Lecture 8

JAVA Programming Fundamentals

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

3. Java - Language Constructs I

Operators and Expressions

PIC 20A Streams and I/O

Java Basic Programming Constructs

1.00 Lecture 30. Sending information to a Java program

1993: renamed "Java"; use in a browser instead of a microwave : Sun sues Microsoft multiple times over Java

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Reading and Writing Files

Introduction to Programming Using Java (98-388)

Operators. Java operators are classified into three categories:

needs to be reliable, easy to change, retarget efficiency is secondary implemented as interpreter, with virtual machine

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output

Data Types and the while Statement

CS313D: ADVANCED PROGRAMMING LANGUAGE

Getting Started in Java. Bill Pugh Dept. of Computer Science Univ. of Maryland, College Park

Declaration and Memory

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Lesson 3: Accepting User Input and Using Different Methods for Output

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

Prof. Navrati Saxena TA: Rochak Sachan

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Learning the Java Language. 2.1 Object-Oriented Programming

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

Programming. Syntax and Semantics

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

PROGRAMMING FUNDAMENTALS

A flow chart is a graphical or symbolic representation of a process.

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Object Oriented Software Design

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

CS 251 Intermediate Programming Java I/O Streams

I/O Streams. Object-oriented programming

CMPT 125: Lecture 3 Data and Expressions

Streams and File I/O

1 Shyam sir JAVA Notes

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Full file at

IT101. File Input and Output

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Workbook 2. Remember to check the course website regularly for announcements and errata:

CT 229. Java Syntax 26/09/2006 CT229

Computational Expression

Data Types and Variables in C language

Arithmetic and Bitwise Operations on Binary Data

Informatics Ingeniería en Electrónica y Automática Industrial

Programming Languages and Techniques (CIS120)

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Au

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Sp

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Arithmetic and Bitwise Operations on Binary Data

1. Download the JDK 6, from

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

e) Implicit and Explicit Type Conversion Pg 328 j) Types of errors Pg 371

Programming with Java

Character Stream : It provides a convenient means for handling input and output of characters.

Getting started with Java

ECE 122 Engineering Problem Solving with Java

Array. Prepared By - Rifat Shahriyar

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

The Java language has a wide variety of modifiers, including the following:

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

CSEN 202 Introduction to Computer Programming

2/5/2018. Expressions are Used to Perform Calculations. ECE 220: Computer Systems & Programming. Our Class Focuses on Four Types of Operator in C

Simple Java Reference

Exercises Software Development I. 05 Conversions and Promotions; Lifetime, Scope, Shadowing. November 5th, 2014

Transcription:

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");