CP1270. Programming Fundamentals

Similar documents
Pace University. Fundamental Concepts of CS121 1

CS 231 Data Structures and Algorithms, Fall 2016

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Programming with Java

Full file at

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

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Introduction to Programming Using Java (98-388)

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

Java is an objet-oriented programming language providing features that support

Object Oriented Software Design

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

AP Computer Science A

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

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Course Outline. Introduction to java

COE 211/COE 212 Computer/Engineering Programming. Welcome to Exam II Thursday December 20, 2012

DM550 Introduction to Programming part 2. Jan Baumbach.

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013


CS11 Java. Fall Lecture 1

Computer Components. Software{ User Programs. Operating System. Hardware

BASIC ELEMENTS OF A COMPUTER PROGRAM

Introduction to Java Applications

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Simple Java Reference

COMP 202 Java in one week

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

CMPT 125: Lecture 3 Data and Expressions

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Loops. CSE 114, Computer Science 1 Stony Brook University

Java+- Language Reference Manual

Index COPYRIGHTED MATERIAL

Object-Oriented Programming

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

WOSO Source Code (Java)

CMPS 12A Winter 2006 Prof. Scott A. Brandt Final Exam, March 21, Name:

Zheng-Liang Lu Java Programming 45 / 79

Last Class. While loops Infinite loops Loop counters Iterations

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

CS 170 Exam 2. Version: A Fall Name (as in OPUS) (print): Instructions:

COMP 202. Java in one week

Primitive Data, Variables, and Expressions; Simple Conditional Execution

COE318 Lecture Notes Week 4 (Sept 26, 2011)

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

STUDENT LESSON A12 Iterations

A variable is a name for a location in memory A variable must be declared

Chapter 1 Introduction to java

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

CSE 114 Computer Science I

Introduction to Computer Science Unit 2. Notes

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Introduction to Java & Fundamental Data Types

1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207

c) And last but not least, there are javadoc comments. See Weiss.

COE 212 Engineering Programming. Welcome to Exam II Monday May 13, 2013

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

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

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

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

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

COMP6700/2140 Data and Types

Fundamental of Programming (C)

CS 106 Introduction to Computer Science I

Section 004 Spring CS 170 Exam 1. Name (print): Instructions:

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

DM503 Programming B. Peter Schneider-Kamp.

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

APCS Semester #1 Final Exam Practice Problems

CS212 Midterm. 1. Read the following code fragments and answer the questions.

COE 212 Engineering Programming. Welcome to Exam II Thursday April 21, Instructors: Dr. Salim Haddad Dr. Joe Tekli Dr. Wissam F.

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

ICSE Class 10 Computer Applications ( Java ) 2014 Solved Question Paper

Java Bytecode (binary file)

AP CS Unit 3: Control Structures Notes

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Elementary Programming

Chapter 4: Control Structures I

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

ECE 122 Engineering Problem Solving with Java

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Visual C# Instructor s Manual Table of Contents

Mr. Monroe s Guide to Mastering Java Syntax

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Program Fundamentals

Important Java terminology

Array. Prepared By - Rifat Shahriyar

Place your name tag here

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Chapter 2: Data and Expressions

CEN 414 Java Programming

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2

Transcription:

CP1270 Programming Fundamentals

WHO AM I? INSTRUCTOR: Dr. Branko Bronco Cirovic

WHERE AM I? OFFICE : ET338 PHONE : 758-7091 EMAIL : branko.cirovic@cna.nl.ca WEBSITE(s) : http://branko-cirovic.appspot.com

TOPICS Introduction: algorithms and computation Java language, compiler, virtual machine, I/O Java: variables, types, assignment statement and arithmetic Java: decision making - if, if else and switch controls Java: iteration ( loops ) - while, for, do while Java: methods Java: arrays and strings

EVALUATION Labs: 30% Midterm exam: 30% Final exam: 40%

PROGRAMMING - WHAT IS IT? Computer Program is a... suitable representation of an Algorithm Algorithm - finite sequence of executable, unambiguous instructions that would ultimately terminate and produce solution to a symbol manipulation problem.

ALGORITHMS Do they solve problems of hunger, wars, homelessness, diseases? Didn t think so... So what kind of problems are symbol manipulation problems? Examples: sort unsorted list of integers, reverse a word, find shortest distance between nodes in a graph, determine if bird hit the pig or not etc. Good news: there are infinitely many algorithms - plenty of work for plenty of people for a very long amount of time!

EXECUTABLE INSTRUCTIONS? 1 Draw a straight-line segment between two points with coordinates ( 0, 0 ) and ( 1, 3 ) 3 2 1 1 2 3 4 2 Draw a straight-line segment between two points with coordinates ( 2, 2 ) and ( 4, 0 ) 3 2 1 1 2 3 4 3 Draw circle with radius 2 and centre at the intersection of previous two line segments?

UNAMBIGUOUS INSTRUCTIONS? 1. Set the value of variable n to 10 2. Execute either step 3 or 4 Which one? 3. Set the value of variable i to 2 4. Skip ahead How far? 5. Divide n by i

TERMINATION? 1. Go to ATM machine 2.Withdraw 20 dollars 3. Give money to your instructor 4.Go to step 1

JAVA Developed by James Gosling at Sun Microsystems in 1995 General purpose, object-oriented programming language Source code compiles into byte-code Byte-code is then executed by Java Virtual Machine ( JVM ) Advantage: portable to any platform / OS Disadvantage: slower execution

JRE Java Runtime Environment Java API classes Java Virtual Machine Operating System ( Windows, Mac, Linux, Unix etc ) Hardware ( Intel, Motorola, Alpha etc )

Hello.java public class Hello { public static void main(string[] args) { System.out.println("Hello Java");

COMPILE AND RUN In order to compile Hello.java, at command line type: javac Hello.java If you don t have any syntax errors, new file is created in the same directory - Hello.class ( byte-code ). In order to execute it, start JVM by typing at command line: java Hello

ANALYSIS - class Hello public class Hello { Any program in Java must be encapsulated in at least one class. Attribute public denotes that class is accessible by anyone. The name of a publicly declared class must be the same as file s prefix - Hello.java Curly braces { denote the body of the class.

ANALYSIS - main public static void main(string[] args) { Any stand-alone Java application must have the main method - the entry point of execution. main method is public, i.e. it can be accessed by anyone. main method is static, i.e. it belongs to the class, not to class instance. main method s return type is void, i.e. it does not return any values.

ANALYSIS - main main method s argument is array of strings: String[] args. Curly braces { denote the body of the main method. System.out.println("Hello Java"); belongs to the main method - it sends string "Hello Java" to standard output ( screen ).

VARIABLES Variable, in computer science, refers to a memory location with associated symbolic name ( identifier ) which contains a value. The value of a variable may change during the program execution. In order to declare a variable in Java, we need to specify variable s data type and identifier.

DATA TYPES There are eight primitive data types in Java: Type Description boolean unsigned 8-bit integer ( true / false ) byte signed 8-bit integer char unsigned 16-bit integer ( Unicode ) short signed 16-bit integer int signed 32-bit integer long signed 64-bit integer float 32-bit floating point double 64-bit floating point

IDENTIFIERS Legal identifiers in Java are strings ( words ) which must begin with a letter, underscore ( _ ) or a dollar sign ( $ ), followed by any combination of letters, digits, dollar signs and underscores. Identifiers must not be Java reserved words. Java is a case - sensitive language, i.e., x and X represent two different identifiers. Once the variable has been declared, it must not be redeclared.

VARIABLE DECLARATION In Java, variables are declared as: <type> <identifier>; Examples of variable declaration: int number; char letter; double real; Once declared, values can be assigned to variables.

ASSIGNMENT STATEMENT Assignment statement in Java has the form: <identifier> = <value>; Examples of assignment statement: number = 2; letter = a ; real = 3.14159; It is important that types of values coincide with the declared types of variables, i.e., number = 2.5; would result in an error.

Assignment.java public class Assignment { public static void main(string[] args) { int number; char letter; double real; number = 2; letter = 'a'; real = 3.14159; System.out.println("number: " + number); System.out.println("letter: " + letter); System.out.println("real: " + real);

ASSIGNMENT THROUGH INPUT Values can be assigned to declared variables through input ( STDIN - keyboard ) There are many different ways to accomplish this task. Probably the easiest one is to use the Scanner class defined in java.util.* library. Values can be declared and assigned value in a single line, as in int n = 1; or int n = s.nextint(); ( input )

Input.java import java.util.*; public class Input { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter integer: "); int n = s.nextint(); System.out.print("Enter real: "); double d = s.nextdouble(); System.out.print("Enter character: "); char c = s.next().charat(0); System.out.println(n + " " + d + " " + c);

TYPECASTING Java promotes higher types to lower types, i.e., double to float, float to int, int to char. ( implicit typecasting ). For example, the value of expression 3.14 + 2 + a is 102.14 Why? Because ASCII value of a is 97! Explicit typecasting : the value of 5 / 2 is 2. On the other hand, the value of (double) 5 / (double) 2 is 2.5

ARITHMETIC There are five arithmetic operators in Java: Operation Operator Example Addition + 5 + 2 Subtraction - 5-2 Multiplication * 5 * 2 Division / 5 / 2 Modulus ( remainder ) % 5 % 2

ARITHMETIC Rules of Operator Precedence Operators in expressions contained within pairs of parentheses are evaluated first. Multiplication, Division and Modulus are applied next, evaluated from left to right. Addition and Subtraction are applied last, evaluated from left to right.

EXAMPLE Evaluate expression: z = (2 + 5) * 3 / 6 - (5 % 4) z = 7 * 3 / 6-1 ( Parentheses ) z = 21 / 6-1 ( Multiplication, LR ) z = 3-1 ( Division ) z = 2 ( Subtraction )

Arithmetic.java import java.util.*; public class Arithmetic { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter a: "); int a = s.nextint(); System.out.print("Enter b: "); int b = s.nextint(); int sum = a + b; int dif = a - b; int pro = a * b; int quo = a / b; int rem = a % b;

Arithmetic.java ctd System.out.println("Sum: " + sum); System.out.println("Difference: " + dif); System.out.println("Product: " + pro); System.out.println("Quotient: " + quo); System.out.println("Reminder: " + rem);

JAVA MATH LIBRARY More complex mathematical operations are provided by the Math class. The class provides methods for performing numeric operations such as trigonometric functions, exponential, power, logarithm, square root etc. Class also defines two constants: E = 2.71828 ( the base of natural logarithm ) and PI = 3.14159 ( the ratio of the circumference of a circle to its diameter ).

TestMath.java import java.util.*; public class TestMath { public static void main(string[] args) { Scanner s = new Scanner(System.in); int power, base, exp; System.out.print("Enter base: "); base = s.nextint(); System.out.print("Enter exponent: "); exp = s.nextint(); power = Math.pow(base, exp); System.out.println("Power: " + power);

DECISION MAKING So far we have learned about variables, types, assignment statement and simple arithmetic. How would one handle problems like: if bird hit the pig and if the pig was the last one, compute score and move to the next level? For this type of problems we need flow control structures ( decision making ) Java has three types of control structures: if, if else and switch

THE if STATEMENT In the form of a flowchart, the if statement looks like: true BE false Where BE is a boolean expression, i.e. it can be evaluated to true / false // code So, if BE is evaluated to true, associated code is executed. Otherwise, control is simply passed to the joint.

BOOLEAN EXPRESSIONS Named after English mathematician, logician and philosopher, George Boole ( 1815-1864 ). They are expressions that can be evaluated to true or false. In Java, Boolean expressions are constructed from variables, constants, relational operators and logical connectives.

RELATIONAL OPERATORS Operator Meaning > Greater than < Less than == Equal to!= Not equal to >= Greater than or equal <= Less than or equal

LOGICAL CONNECTIVES Connective Meaning! Not && And Or b!b 0 1 1 0 a b a && b 0 0 0 0 1 0 1 0 0 1 1 1 a b a b 0 0 0 0 1 1 1 0 1 1 1 1

LOGIC Rules of Connective Precedence Connectives in expressions contained within pairs of parentheses are evaluated first. Not connective has the highest precedence and is applied first. Evaluation is from from left to right. And connective is applied next. Or connective has the lowest precedence and is applied last.

EXAMPLE Assume a = true, b = false and c = true. Evaluate expression: d =!a && (b c) d =!true && (false true) ( Parentheses, Or ) d =!true && true ( Not ) d = false && true ( And ) d = false

if SYNTAX Code associated with if statement consists of a single instruction: if(<boolean Expression>) // instruction; Code associated with if statement consists of multiple instructions: if(<boolean Expression>) { // instruction_1;... // instruction_n;

Multiple.java import java.util.*; public class Multiple { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter n: "); int n = s.nextint(); if(n % 10 == 0) System.out.println(n + " is multiple of 10");

THE if else STATEMENT if else is similar to plain if statement: true // code A BE false // code B The difference is that, if Boolean expression is evaluated to false, different code is executed ( code B ).

if else SYNTAX Code associated with if / else statement consists of a single instruction: if(<boolean Expression>) // instruction_a; else // instruction_b;

if else SYNTAX Code associated with if /else statement consists of multiple instructions: if(<boolean Expression>) { // instruction_a1;... // instruction_an; else { // instruction_b1;... // instruction_bn;

Multiple.java import java.util.*; public class Multiple { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter n: "); int n = s.nextint(); if(n % 10 == 0) System.out.println(n + " is multiple of 10"); else System.out.println(n + " is not multiple of 10");

NESTED if else true n<0 false negative true n>0 false positive zero

Vowels.java import java.util.*; public class Vowels { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter letter: "); char c = s.next().charat(0); if(c == 'a') System.out.println(c + " is a vowel."); else if(c == 'e') System.out.println(c + " is a vowel.");

Vowels.java ctd else if(c == 'i') System.out.println(c + " is a vowel."); else if(c == 'o') System.out.println(c + " is a vowel."); else if(c == 'u') System.out.println(c + " is a vowel."); else System.out.println(c + " is not a vowel.");

switch CONTROL A sequence of nested if - else statements that compares a single enumerated value ( byte, short, char, int, String ) against several constant alternatives can be implemented as a switch statement: switch(n) { case 1 : // code; break; case 2 : // code; break;... case n : // code; break; default : // code; break;

Vowels.java import java.util.*; public class Vowels { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter letter: "); char c = s.next().charat(0); switch(c) { case 'a' : System.out.println("Vowel"); break; case 'e' : System.out.println("Vowel"); break; case 'i' : System.out.println("Vowel"); break; case 'o' : System.out.println("Vowel"); break; case 'u' : System.out.println("Vowel"); break; default : System.out.println("Not a vowel"); break;

ITERATION ( LOOPS ) When you Google something, how many results do you get? Well, that depends on what we are looking for: qeqwddfd 13!!! dfg $%#^&* -+=kk - did not match any documents www - About 25,270,000,000 results (0.25 seconds)

ITERATION ( LOOPS ) So far, our computations took constant number of steps to produce results, no matter what the size of the input was. Many times, the number of steps required to carry out computation is not constant - it depends on the size of input. Because of this, we need iterative structures ( loops ) - while, for and do while.

while LOOP BE true // code false In the form of a flowchart, the while loop looks like: As long as boolean expression is evaluated to true, body of the loop is executed. Once this condition fails, control is passed to the code outside of loop.

while SYNTAX The while loop syntax in Java is: while(<boolean Expression>) { // code In most applications, it is important to ensure that Boolean Expression will eventually become false and therefore prevent infinite iteration.

While.java import java.util.*; public class While { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter n: "); int n = s.nextint(); int i = 1; while(i <= n) { System.out.print(i + " "); i++; System.out.println();

Prime.java import java.util.*; public class Prime { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter n: "); int n = s.nextint(); int count = 0; int i = 1; while(i <= n) { if(n % i == 0) count++; i++; if(count == 2) System.out.println(n + " is prime."); else System.out.println(n + " is not prime");

NUMBER OF ITERATIONS In both examples, While.java and Prime.java, the body of the loop is executed n times, where n is the size of input. Quite often, we cannot predict the number of time the body of the while loop will be executed. Interesting example is the computation of the greatest common divisor. Recall that gcd( a, b ) is the greatest integer that divides both, a and b.

GCD - ALGORITHM m n r = m % n m n r = m % n 4 2 0 5 3 2 3 2 1 m n r = m % n 12 8 4 2 1 0 8 4 0

Gcd.java import java.util.*; public class Gcd { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter m: "); int m = s.nextint(); System.out.print("Enter n: "); int n = s.nextint();

Gcd.java ctd int r = m % n; while(r!= 0) { m = n; n = r; r = m % n; System.out.println("gcd: " + n);

for LOOP init BE false init - initializes loop index variable ( e.g. i = 1 ). Executed once. control true // code As long as boolean expression is true, the body of the loop is executed. Last statement in the body of the loop is control - it controls the loop index variable ( e.g i++).

for SYNTAX The for loop syntax in Java is: for(init; <Boolean Expression>; control) { // code For loop is typically used when we know in advance the number of iterations.

FIBONACCI SEQUENCE Fibonacci sequence are the numbers in the following integer sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,... By definition, the first two integers in the sequence are 1 and each subsequent integer is the sum of the previous two. Leonardo Fibonacci, Italian mathematician (1170-1250)

FIBONACCI SEQUENCE previous temp next 1 0 1 0 1 1 1 1 2 1 2 3 2 3 5 3 5 8 5 8 13

Fibonacci.java import java.util.*; public class Fibonacci { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter n: "); int n = s.nextint(); int prev = 1; int temp = 1; int next; for(int i = 1; i <= n; i++) { next = prev + temp; System.out.print(next + " "); prev = temp; temp = next; System.out.println();

do while LOOP true // code BE false Similar to while loop, except that body of the do-while must be executed at least once. The last statement in do-while loop is Boolean Expression. As long as it evaluates to true, control is passed back to the first line of code.

DoWhile.java import java.util.*; public class DoWhile { public static void main(string[] args) { int a, b; Scanner s = new Scanner(System.in); do { System.out.print("Enter a: "); a = s.nextint(); System.out.print("Enter b: "); b = s.nextint(); while(a < b);

METHODS Do we build buildings by getting huge chunk of stone or wood and then carve them inside out? Doable ( Al Khazneh ا%$#نة ), but... As foundation, floors, walls, rafters are basic building blocks in civil engineering, so are methods in Computing!

METHODS A method is enclosed group of statements ( assignment, flow control, iteration ) that has: Name - any legal identifier as in the case of variable names, but good coding conventions restrict method names furthermore: - method name should be a verb in lower case or - multi-word name that begins with a verb in lowercase, followed by adjectives, nouns etc. Examples: run, runfast, getbackground, isempty

METHODS Modifiers - specify methods accessibility ( public, private, static ) - more about this in CP1340. In this course, all our methods will be public static - i.e., class methods accessible by anyone. Return type - methods can return no value ( void ) or a single value whose type must be specified ( int, double, boolean, char etc. ) Argument list - list of parameters including their names and types that can be passed to a method.

METHOD S SIGNATURE Defined as [public private protected] [static] [return-type] name([type] arg1, [type] arg2,...) { // body Examples: public static void main(string[] args) public static boolean isprime(int n) public static int gcd(int m, int n)

Area.java public class Area { public static void main(string[] args) { int w = 2; int h = 3; int a = area(w, h); System.out.println("area: " + a); public static int area(int w, int h) { int ar = w * h; return ar;

ARGUMENTS PASSING a = 6 public static void main(string[] args) { int w = 2; int h = 3; int a = area( w, h ); 2 3 public static int area(int w, int h ) { int ar = w * h; return ar; ar = 2 * 3 = 6

Primes.java public class Primes { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter n: "); int n = s.nextint(); if(isprime(n)) System.out.println(n + " is prime."); else System.out.println(n + " is not prime.");

Primes.java ctd public static boolean isprime(int n) { int count = 0; for(int i = 1; i <= n; i++) { if(n % i == 0) count++; if(count == 2) return true; else return false;

PrimeSequence.java import java.util.*; public class PrimeSequence { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter n: "); int n = s.nextint(); generateprimes(n);

PrimeSequence.java ctd public static void generateprimes(int n) { int number = 2; int count = 1; while(count <= n) { if(isprime(number)) { System.out.print(number + " "); count++; number++; System.out.println();

PrimeSequence.java ctd public static boolean isprime(int n) { int count = 0; for(int i = 1; i <= n; i++) { if(n % i == 0) count++; if(count == 2) return true; else return false;

SCOPE OF VARIABLES Scope of variable refers to location where variable is declared. Variables declared within method, including parameter list, are method variables - they are visible, accessible and modifiable within a method only. Variables declared within a class, but outside of any method are class variables - they are visible, accessible and modifiable by any method that belongs to the same class.

Scope.java public class Scope { static int x = 1; // class variable public static void main(string[] args) { x++; System.out.println("main:x = " + x); int w = 5; // method variable System.out.println("main:w = " + w); a(w); System.out.println("main:w = " + w); System.out.println("main:x = " + x); public static void a(int w) { x--; w++; System.out.println("a:w = " + w);

CALL BY VALUE Any identifier in Java has two values associated with it: Actual value assigned to a variable. Memory location - place in memory where assigned value resides. int n = 10; memory location (e.g. 272d7a10), assigned by compiler value is 10, assigned by developer

Scope.java - ANALYSIS class Scope int x = 1; main() { x++; int w = 5; a(w); a(int w) { x--; w++;... Memory x 12 w 5 w 56 addresses ( arbitrary ) 272d2708 272d270c 272d2710 272d2714 272d2718 272d271c 272d2720 272d2724 272d2728

RECURSION Recursive method is a method that calls itself either directly or indirectly ( through another method ). It consists of: One or more base cases - trivial cases for which method returns discrete value. One or more nontrivial cases for which method returns a call to itself. In order to avoid infinite recursion, nontrivial cases should return slightly simpler or smaller call.

EXAMPLE Factorial function can be recursively defined as: f( x ) =! "# 1 x f(x - 1) if x = 1 otherwise So, f( 1 ) represents the base case - function simply returns 1, i.e. f ( 1 ) = 1. On the other hand, f ( 3 ), for example, is nontrivial call. Recursion than proceeds as: f( 3 ) = 3 f( 2 ) = 3 2 f( 1 ) = 3 2 1 = 3 2 = 6

Factorial.java import java.util.*; public class Factorial { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter n: "); int n = s.nextint(); System.out.println(n + "! = " + f(n)); public static int f(int n) { if(n == 1) return 1; else return n * f(n - 1);

EXAMPLE Recall Fibonacci sequence. It can be recursively defined as: f( x ) =! "# 1 f(x - 1) + f(x - 2) if x = 1 or x = 2 otherwise Here we have two base cases, when argument x is either 1 or 2, i.e. f( 1 ) = 1 and f( 2 ) = 1, reflecting the fact that first two integers in the sequence are 1, 1. Nontrivial case, say f( 4 ) is evaluated as: f( 4 ) = f( 3 ) + f( 2 ) = f( 2 ) + f( 1 ) + 1 = 1 + 1 + 1 = 3

RecFibo.java public class RecFibo { public static void main(string[] args) { for(int i = 1; i <= 10; i++) System.out.print(rf(i) + " "); System.out.println(); public static int rf(int n) { if(n == 1 n == 2) return 1; else return rf(n - 1) + rf(n - 2);

ARRAYS - MOTIVATION How would one write Java code to compute average mark on midterm? int grade0, grade1, grade2,..., grade13; // get grades // compute sum sum = grade0 + grade1 +... + grade13; Very tedious. What if we have to compute the average of 100 or 1000 marks?

ARRAYS An Array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. Array is declared as: type[] name = new type[size]; The new operator requests memory allocation and stores returned address in array s name. For example, int[] a = new int[10]; creates an array of integers whose length is 10.

ARRAYS Pictorially, int[] a = new int[10]; can be represented as: First index ( 0 ) 0 1 2 3 4 5 6 7 8 9 Indices Array a of integers whose size is 10 Element ( integer ) at index 8

ARRAYS When array is allocated, its values are automatically initialized to zeros for numeric data types and false for boolean type. Arbitrary values can be assigned by either specifying array s name, index and value as in: int[] n = new int[3]; n[0] = 5; n[1] = 2; n[2] = 4; Or by assigning values at time of allocation as in: int[] n = {5, 2, 4;

ARRAYS In either case, resulting array is: 0 1 2 n 5 2 4 Each array has field length associated with it. It stores the number of values in the array. Continuing with the previous example, the value of n.length is 3.

Arrays.java public class Arrays { public static void main(string[] args) { int[] n = new int[3]; System.out.print("Array of integers: "); for(int i = 0; i < n.length; i++) System.out.print(n[i] + " "); System.out.println(); char[] c = {'a','b','c','d'; System.out.print("Array of characters: "); for(int i = 0; i < c.length; i++) System.out.print(c[i] + " "); System.out.println();

Arrays.java ctd double[] d = new double[5]; System.out.print("Array of real numbers: "); for(int i = 0; i < d.length; i++) { int rnd = (int) (Math.random() * 10000); d[i] = rnd / 100.0; System.out.print(d[i] + " "); System.out.println();

FIND MINIMUM Given array of integers, find the smallest value in the array. The algorithm proceeds as follows: [1] Assume min = 5 0 1 2 3 4 n 5 2 4 1 3 [2] 2 < 5 ( true ) min = 2 [3] 4 < 2 ( false ) min = 2 [4] 1 < 2 ( true ) min = 1 [5] 3 < 1 ( false ) min = 1

FindMin.java public class FindMin { public static void main(string[] args) { int[] n = new int[10]; for(int i = 0; i < n.length; i++) { n[i] = (int)(math.random() * 100); System.out.print(n[i] + " "); System.out.println(); int min = n[0]; int loc = 0; for(int i = 1; i < n.length; i++) { if(n[i] < min) { min = n[i]; loc = i; System.out.println(min + " at: " + loc);

ARRAYS AND METHODS Assume that we declared and initialized array: int[] n = {5, 2, 4; What would be the output of System.out.println(n); It is something like [I@272d7a10 And what the ***k is [I@272d7a10? It is the address of the first item in the array!

ARRAYS AND METHODS Method that takes array as an argument might have the prototype: public static int f(int[] n) Method call would consist of specifying method s name and argument as in f(n). Argument is array s name, i.e. the address of the first entry in the array. The consequence of such a call is that any changes made to the array in called method will be reflected in calling method.

Scramble.java public class Scramble { public static void main(string[] args) { int[] n = {1, 2, 3, 4, 5; print(n); scramble(n); print(n); public static void print(int[] n) { for(int i = 0; i < n.length; i++) System.out.print(n[i] + " "); System.out.println(); public static void scramble(int[] n) { for(int i = 0; i < n.length; i++) n[i] = (int)(math.random() * 5 + 1);

CALL BY REFERENCE Recall that any identifier in Java has two values associated with it: the actual value assigned to identifier and memory address where that value is stored. Since array s name stores the address of the first entry in the array, when we call a method passing array s name as an argument, we actually pass that memory address. Such calls are called calls by reference.

CALL BY REFERENCE int[] n = {1, 2, 3; main() { f(n); Function call f(n) passes 272d270c as argument. f(int[] n) { n[0] = 4; addresses ( arbitrary ) Memory 272d2708! 272d270c 41 "# 272d2710 2 272d2714 3 272d2718 Function f now has the access to the same memory segment.

SEQUENTIAL SEARCH Given array of integers and a target value, decide whether or not target value is in the array. Assume that int[] n = {5, 2, 4, 1, 3; and target is 1. The algorithm proceeds as follows: [1] 5 == 1 ( false ) 0 1 2 3 4 n 5 2 4 1 3 [2] 2 == 1 ( false ) [3] 4 == 1 ( false ) [4] 1 == 1 ( true )

SequentialSearch.java import java.util.*; public class SequentialSearch { public static void main(string[] args) { int[] n = {5, 2, 4, 1, 3; Scanner s = new Scanner(System.in); System.out.print("Enter target: "); int target = s.nextint(); if(find(n, target)) System.out.println(target + " is in the array."); else System.out.println(target + " is not in the array.");

SequentialSearch.java ctd public static boolean find(int[] n, int target) { boolean found = false; for(int i = 0; i < n.length &&!found; i++) { if(n[i] == target) found = true; return found;

INSERTION SORT Input: unsorted array of integers Output: sorted array of integers ( ascending order )

InsertionSort.java public class InsertionSort { public static void main(string[] args) { int[] n = new int[10]; generatenumbers(n); print(n); sort(n); print(n);

InsertionSort.java ctd public static void generatenumbers(int[] n) { for(int i = 0; i < n.length; i++) { n[i] = (int)(math.random() * 100); public static void print(int[] n) { for(int i = 0; i < n.length; i++) System.out.print(n[i] + " "); System.out.println();

InsertionSort.java ctd public static void sort(int[] n) { for(int i = 1; i < n.length; i++) { int pivot = n[i]; for(int j = i - 1; j >= 0; j--) { if(pivot < n[j]) { int temp = n[j + 1]; n[j + 1] = n[j]; n[j] = temp;

BINARY SEARCH Sequential search, in the worst case scenario ( i.e., target is not in the array or the last entry in the array ), takes n comparisons, where n is the array s length. If array is sorted, search can be drastically improved. The idea behind the binary search is to represent array as a binary tree-like structure.

BINARY SEARCH 0 1 2 3 4 5 6 1 2 3 4 5 6 7

BINARY SEARCH 0 1 2 3 4 5 6 Assume target is 7. Start in the middle, where middle = ( start + end ) / 2. Start index is 0, end index 4 is 6. So, middle = 3. 1 2 3 6 5 7 Since 7 > 4, new start is middle + 1 ( 4 ) and new middle = ( 4 + 6 ) / 2 = 5. Since 7 > 6, new start is middle + 1 ( 6 ) and new middle = ( 6 + 6 ) / 2 = 6.

BINARY SEARCH 0 1 2 3 4 5 6 target = 3. middle = ( 0 + 6 ) / 2 = 3 2 4 6 3 < 4 end = middle - 1 = 2 middle = ( 0 + 2 ) / 2 = 1 1 3 5 7 3 > 2 start = middle + 1 = 2 middle = ( 2 + 2 ) / 2

BINARY SEARCH 0 1 2 3 4 5 6 4 2 6 1 3 5 7 target = 0. middle = ( 0 + 6 ) / 2 = 3 0 < 4 end = middle - 1 = 2 middle = ( 0 + 2 ) / 2 = 1 0 < 2 end = middle - 1 = 0 middle = ( 0 + 0 ) / 2 = 0 0 < 1 end = middle - 1 = -1 start > end! Not found.

BinarySearch.java import java.util.*; public class BinarySearch { public static void main(string[] args) { int[] n = {1, 2, 3, 4, 5, 6, 7; Scanner s = new Scanner(System.in); System.out.print("Enter target: "); int target = s.nextint(); if(binsearch(n, target)) System.out.println(target + " is in the array."); else System.out.println(target + " is not in the array.");

BinarySearch.java ctd public static boolean binsearch(int[] n, int target) { int start = 0; int end = n.length - 1; int middle = (start + end) / 2; boolean found = false; while(start <= end &&!found) { if(target == n[middle]) found = true;

BinarySearch.java ctd else if(target < n[middle]) { end = middle - 1; middle = (start + end) / 2; else { start = middle + 1; middle = (start + end) / 2; return found;

2-DIMENSIONAL ARRAYS 2-Dimensional arrays ( in general n-dimensional arrays ) are arrays whose entries are arrays themselves. n[0] 0 1 1 2 0 1 2 3 So, n[0][0] = 1, n[0][1] = 2, n[1][0] =3, n[1][1] = 4 etc. n[1] 3 4 5 6 In Java, lengths of subarrays need not be the same. n[2] 0 1 2 7 8 9

MultArray.java public class MultArray { public static void main(string[] args) { int[][] a = { { 1, 2, { 3, 4, 5, 6, { 7, 8, 9 ; print(a);

MultArray.java ctd public static void print(int[][] a) { for(int i = 0; i < a.length; i++) { for(int j = 0; j < a[i].length; j++) { System.out.print(a[i][j] + " "); System.out.println();

STRINGS java.lang.string is a built-in class ( API ) that represents character strings, i.e. words. Strings are immutable objects, i.e., they cannot be changed after they are created. In order to create strings, one has to invoke constructor method. Constructor is a special method which has the same name as the class it belongs to.

STRING CONSTRUCTORS The most common String constructors are: String s1 = new String(); - creates an empty string. Its length is zero. String s2 = new String("Giddy up!"); - creates a string object representing the same sequence of characters as in its argument. String s3 = new String(ca); - creates a string object representing the sequence of characters contained in character array argument ( ca ).

CONSTRUCTORS In general, objects in Java are created through constructors. Unlike regular methods, constructors are invoked once and only once - at the time of object creation. Object o = new Object(arg); creates a new object. The new operator requests memory allocation and stores returned address in object s name. Name ( address ) Data field(s) Constructor(s) Method(s)

StringConstructors.java public class StringConstructors { public static void main(string[] args) { String s1 = new String(); String s2 = new String("Giddy up!"); char[] ca = {'a','b','c'; String s3 = new String(ca); String s4 = new String(ca, 1, 2); System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s4);

STRING METHODS Once String is constructed, we can use methods provided in the String class. Some of the most commonly used String methods are: public int length() - Returns the length of this string. public char charat(int index) - Returns the character at specified index. public int indexof(char c) - Returns the index within this string of the first occurrence of the specified character.

STRING METHODS public boolean equals(object obj) - Compares this string to specified object. public String substring(int index) - Returns a new string that is a substring of this string starting at index index. public char[] tochararray() - Converts this string to a new character array.

STRING METHODS public String tolowercase() - Returns a new string which is this string with all characters converted to lowercase. public String touppercase() - Returns a new string which is this string with all characters converted to uppercase. public String concat(string str) - Returns a new string which is concatenation of this string and the specified string.

StringMethods.java public class StringMethods { public static void main(string[] args) { String s = new String("abcde"); int length = s.length(); System.out.println(s + " has " + length + " characters "); char c = s.charat(1); System.out.println("Second character: " + c); int pos = s.indexof('e'); System.out.println("The index of e is " + pos);

StringMethods.java ctd char[] chs = s.tochararray(); for(int i = 0; i < chs.length; i++) System.out.println(chs[i]); String p = new String("XYZ"); System.out.println(s + " " + p); if(s.equals(p)) System.out.println("same data fields"); else System.out.println("different data fields");

StringMethods.java ctd if(s == p) System.out.println("Same references"); else System.out.println("Different references"); String subs = s.substring(2); System.out.println("Substring: " + subs);

StringMethods.java ctd String ccs = s.concat(p); System.out.println("s concat p: " + ccs); String lcs = p.tolowercase(); System.out.println("Lowercase: " + lcs); String ucs = s.touppercase(); System.out.println("Uppercase: " + ucs);

== VS equals String s1 = new String("abc"); s1 (@ff0add00) == ( false ) String s2 = new String("abc"); s2 (@ff0addbc) abc Constructors Methods equals ( true ) abc Constructors Methods

STRING REFERENCES String s1 = new String("abc"); String s2 = s1; s1 (@ff0add00) == ( true ) abc s2 (@ff0add00) Constructors Methods

REVERSE STRING index = 0, length = 5, target index = 4 = 5-1 - 0 0 1 2 3 4 a b c d e index = 1, length = 5, target index = 3 = 5-1 - 1 index = 2, length = 5, target index = 2 = 5-1 - 2 index = 3, length = 5, target index = 1 = 5-1 - 3 index = 4, length = 5, target index = 0 = 5-1 - 4

Reverse.java import java.util.*; public class Reverse { public static void main(string[] args) { System.out.print("Enter word: "); Scanner s = new Scanner(System.in); String word = s.next(); String reversedword = reverse(word); System.out.println(reversedWord);

Reverse.java ctd public static String reverse(string word) { int length = word.length(); char[] ca = new char[length]; for(int i = 0; i < length; i++) { ca[i] = word.charat(length - i - 1); return new String(ca);

Palindrome.java import java.util.*; public class Palindrome { public static void main(string[] args) { System.out.print("Enter word: "); Scanner s = new Scanner(System.in); String word = s.next(); if(ispalindrome(word)) System.out.println(word + " is palindrome"); else System.out.println(word + " is not palindrome");

Palindrome.java ctd public static boolean ispalindrome(string word) { String rword = reverse(word); if(rword.equals(word)) return true; else return false;

Palindrome.java ctd public static String reverse(string word) { int length = word.length(); char[] ca = new char[length]; for(int i = 0; i < length; i++) { ca[i] = word.charat(length - i - 1); return new String(ca);

COMMAND-LINE ARGUMENTS Recall the main method s signature: public static void main(string[] args) What are main method s arguments? Array of strings: String[] args Similarly as we pass argument to javac ( i.e. filename containing the source code ), we can pass command-line arguments to any Java program having the main method.

Cla.java public class Cla { public static void main(string[] args) { for(int i = 0; i < args.length; i++) { System.out.println("CLA " + i + " : " + args[i]); Compile and run: java Cla Now run as: java Cla one two three Command line arguments one, two and three are internally stored as args[0], args[1] and args[2]

FILES Java File class is used as abstract representation of a file. Constructor takes a pathname to a file as argument as in : File f = new File(args[0]); Java class FileReader can now be used to read the content of a file : FileReader in = new FileReader(f); Method in.read(data) reads the content of a file f and stores it in a character array data whose length is the length of file - f.length().

ReadFile.java import java.io.*; public class ReadFile { public static void main(string args[]) throws IOException { if(args.length == 0) System.out.println("usage: java ReadFile filename"); else { File f = new File(args[0]); readfile(f);

ReadFile.java ctd. public static void readfile(file f) throws IOException { FileReader in = new FileReader(f); int size = (int) f.length(); char data[] = new char[size]; in.read(data); in.close(); String s = new String(data); System.out.print(s);

FILES Similarly, Java class FileWriter can be used to write to a file : FileWriter out = new FileWriter(f); Method out.write(data) writes string data into a file specified by File s constructor. If the file does not exist, it will be created as well.

WriteFile.java import java.io.*; public class WriteFile { public static void main(string args[]) throws IOException { if(args.length == 0) System.out.println("usage: java ReadFile filename"); else { File f = new File(args[0]); writefile(f);

WriteFile.java ctd public static void writefile(file f) throws IOException { FileWriter out = new FileWriter(f); String s = "This is a FileWriter"; out.write(s); out.close();