47
Why Java? • Free! Lots of support and use Google, Android, Oracle Java has been around for over 20 years And is only getting more popular! Platform Independent • OOP One of the few almost completely oop languages Powerful development environment – Eclipse “James Gosling invented Java, Bjarne Stroustroup invented C++, Dennis Ritchie invented C, and Bill Gates invented nothing. Yet, who’s the richest of the bunch?”

Why Java? Free! Lots of support and use – Google, Android, Oracle – Java has been around for over 20 years And is only getting more popular! Platform Independent

Embed Size (px)

Citation preview

Why Java?• Free!• Lots of support and use

– Google, Android, Oracle– Java has been around for over 20 years

• And is only getting more popular!

• Platform Independent• OOP

– One of the few almost completely oop languages

• Powerful development environment– Eclipse

“James Gosling invented Java, Bjarne Stroustroup invented C++, Dennis Ritchie invented C, and Bill Gates invented nothing. Yet, who’s the richest of the bunch?”

Start writing Java Code:EVERYTHING must be in a class

To start:1.Create a new file with the same name as the class you are going to create (and the .java extension) (e.g., NewClass.java)2.Inside the new file, create the class:

public class NewClass {

}

3.Inside the class, you can place a method called main that will run automatically when you run the file:

public class NewClass {

public static void main(String[] args) {

…Code for main function goes here

}

}

Two early/visible syntax differences

• Java uses the C/C++ family of code block syntax

• Java has type declaration as part of the syntax– You must tell the compiler what type your

variables and parameters are• The compiler sets aside space in memory ahead of

time. It must know how much space to set aside.

4

Blocksbraces must go around blocks of code

A semicolon separates each line of code.

Python• the colon (:) and indentation create blocks • newlines separate components

Racket •parens () define blocks. •Special functions over lists define a sequence of program components, (begin ...), (local ...)

public class Test { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }

Class block

Method block

• Types are included on variable and parameter declaration

public class Test { public static void main(String[] args) { int a = 5 + 10; System.out.println(a); }}

Types

type

type

6

Numerical Data Types Name Range Storage Size

byte –27 (-128) to 27–1 (127) 8-bit signed

short –215 (-32768) to 215–1 (32767) 16-bit signed

int –231 (-2147483648) to 231–1 (2147483647) 32-bit signed

long –263 to 263–1 64-bit signed (i.e., -9223372036854775808 to 9223372036854775807)

float Negative range: 32-bit IEEE 754 -3.4028235E+38 to -1.4E-45 Positive range: 1.4E-45 to 3.4028235E+38

double Negative range: 64-bit IEEE 754 -1.7976931348623157E+308 to -4.9E-324 Positive range: 4.9E-324 to 1.7976931348623157E+308

7

Numeric Operators

Name Meaning Example Result

+ Addition 34 + 1 35 - Subtraction 34.0 – 0.1 33.9 * Multiplication 300 * 30 9000 / Division 1.0 / 2.0 0.5 % Remainder 20 % 3 2

A simple Java program

Compute the area of a circle

9

Trace a Program Executionpublic class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); }}

no valueradius

allocate memory for radius

animation

10

Trace a Program Executionpublic class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); }}

no valueradius

memory

no valuearea

allocate memory for area

animation

11

Trace a Program Executionpublic class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); }}

20radius

no valuearea

assign 20 to radius

animation

12

Trace a Program Executionpublic class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); }}

20radius

memory

1256.636area

compute area and assign it to variable area

animation

13

Trace a Program Executionpublic class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; //alternative: Math.pow(radius,2) * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); }}

20radius

memory

1256.636area

print a message to the console

animation

Types• Java compiler (and interpreter) tries to be

efficient.• It sets aside space in memory ahead of time

for parameters, return values, variables.– For every variable, parameter, and return value,

you MUST specify the type!– E.g., public static int functionname(double x, String y) {

…}

15

Character Data Typechar letter = 'A'; // a new type – for a single characterchar numChar = '4'; // note the single quotes!!!

char uletter = '\u0041'; (Unicode) //4 hex numbers make a char.

char unumChar = '\u0034'; (Unicode)

Description Escape Sequence Unicode

Backspace \b \u0008

Tab \t \u0009

Linefeed \n \u000A

Carriage return \r \u000D

Backslash \\ \u005C

Single Quote \' \u0027

Double Quote \" \u0022

16

The String Type String message = "Welcome to Java"; • Strings are just an array of chars

– We’ll talk about arrays later, •+

– “operator overloaded” •Numbers get added•Strings get concatenated

– “adding” non-String types to an existing String will invoke the toString method that converts the non-String type to a String

String s = ”5” + 6;// s now has the String value “56”String r = “five” + “six”;// r now has the String value “fivesix”

Branching

18

The boolean TypeBoolean Values are: true and false

boolean b = (1 > 2);// b is the value false

boolean even = (number%2) == 0;boolean number;if (number%2 == 0) {

even = true;}else {

even = false;}

19

TIP

if (even == true) {System.out.println(“It is even.”);

}

Same as:

if (even) {System.out.println(“It is even.”);

}

20

Logical Operators

Java Name

! not

&& and

|| or

^ exclusive or

21

Conditional Operatorif (x > 0) y = 1;else y = -1;

is equivalent to

y = (x > 0) ? 1 : -1;(boolean-expression) ? expression1 : expression2

y = (true)? then y becomes expression1y = (false)? then y becomes expression 2

Types in Java:

Assume that int a = 1 and double d = 1.0. What is the result of the following expression?

a = 46 / 9;

A.46B.6C.5D.0

Types in Java:

Assume that int a = 1 and double d = 1.0. What is the result of the following expression?

a = 46 % 9 + 4 * 4 - 2;

A.8B.0C.19D.15

Types in Java:

Assume that int a = 1 and double d = 1.0. What is the result of the following expression?

a = 46 / 9 + 4 * 4 - 2;

A.8B.0C.19D.15

Types in Java:

Assume that int a = 1 and double d = 1.0. What is the result of the following expression?

d = 1.5 * 3 + a;

A.5.5B.5C.6D.6.0

Java Methods• Methods – like functions but inside of classes.

– Because everything must be in a class in Java, everything is a method

– E.g.,public static int max(int x, int y) {

int result;if (x > y) {

result = x;}else {

result = y;}return result;

}//Call methodpublic static void main(String[] args) {

System.out.println(max(3,7));}

public static int max(int x, int y) Method header:• public – available to classes other than the one it’s in.• static – don’t need to create an instance of the class to access the method (static- sticks around)• we’ll discuss these more later when we start using classes•int max – this function returns a value that is of the type int

– If a function doesn’t return a value, then the type returned is void, e.g.,public static void NoReturn(int x) {

}– The function’s name is max

•(int x, int y) – this method has 2 parameters, x, and y, and both x and y are of type int.

• int result – creating a variable called result, and it is of type int. (setting aside an int’s worth of memory space for the variable result)

• return result – the value that is inside of the variable result is what comes out of the function and is what can be used by what called the function.

public static int max(int x, int y) {int result;if (x > y) {

result = x;}

else {result = y;

}return result;

}Orpublic static int max2(int x, int y){

int result = (x>y)?x:y;return result;

}

• max(3,7)– 3 and 7 are the parameter values – 3 goes into x and 7 goes into y• System.out.println(max(3,7)); – prints out the value that is returned

from the method max, called with the values 3 and 7.• int retvalue;• retvalue = max(3,7); - we know the value being returned from the

method max is an int (because that’s how we defined the max method). So we can create a variable that is of type int to hold the value returned from max.

//Call methodpublic static void main(String[] args) {

System.out.println(max(3,7));}

– Or, as an alternative://Call methodpublic static void main(String[] args) {

int retvalue;retvalue = max(3,7);

}

Looping (Iteration)

• repeating a process– usually toward a stopping condition

• In a program this is typically accomplished by a loop counting variable, loop code, and a stopping condition

Sum numbers from 1 to 10 (Racket)

(define (sum-accum i limit total) (cond [(>= i limit) total] [else (sum-accum (+ i 1) limit (+ total i))]))

(display (sum-accum 1 10 0))

loop

Loop counting variablestopping condition

Sum numbers from 1 to 10 (Python)

def sum_accum(i, limit): total = 0 while (i < limit): total = total + i i = i + 1 return total

print (sum_accum(1, 10))

Loop code

Loop counting variable

stopping condition

Sum numbers from 1 to 10 (Java)

public static int sumAccum(int i, int limit) {int total = 0;while (i < limit) {

total = total + i; i = i + 1;

}return total;

}public static void main(String[] args){System.out.println(sumAccum(1,10));

}

Loopcode Loop counting

variable

stopping condition

Indefinite Loops• A repetition structure that executes code while a

condition is true– We don’t know ahead of time how many times the loop will

happen

import java.util.Random; // at top of file

...

int guess = 1;

Random r = new Random(); //must make an object of type random

while (guess % 7 != 0) {

guess = r.nextInt(100); //gets a random int between 0 and 100

}

System.out.println(guess);

35

while Loop Flow Chartwhile (loop-continuation-condition) {

// loop-body;

Statement(s);

}

int count = 0;

while (count < 100) {

System.out.println("Welcome to Java!");

count++;

}

Loop Continuation Condition?

true

Statement(s) (loop body)

false (count < 100)?

true

System.out.println("Welcome to Java!"); count++;

false

(A) (B)

count = 0;

Simple "dice" game (group problem)

• 2 players take turns.– Each turn: roll 3 die– Get 2 of a kind – score 10– otherwise score is the largest die roll

• simulate a game that has 2 players and continues until one of the players has 100 points

Definite Loops

• A repetition structure that executes code exactly N times– We know how many times we want it to loop

int sum = 0;for (int i = 0; i < 10; i++) { sum += i; }System.out.println(sum);

Try: • Write a class with a method that computes the

harmonic sum, which is calculated as follows:

Notes: • N is an integer, and will be the input to your method. • What type is returned?• Should you use a while or a for loop?• Make one method run from 1 to 1/n

– then make another method that runs from 1/n to 1. – Are the results different? Wanna take a guess at why?

public class HarmonicSum { public static void main (String[] args) {

System.out.println(HSLeftToRight(50000));System.out.println(HSRightToLeft(50000));

}

public static double HSLeftToRight(int maxDenom) {// for left-to-rightdouble sumL2R = 0.0;for (int n = 1; n <= maxDenom; n++) {

sumL2R += (double)(1.0/n);}return (sumL2R);

}

public static double HSRightToLeft(int maxDenom) {// for right-to-leftdouble sumR2L = 0.0;for (int n = maxDenom; n >= 1; n--) { sumR2L += (double)(1.0/n);}return (sumR2L);

}}

41

NoteIf the loop-continuation-condition in a for loop is omitted, it is implicitly true. Thus the statements given below in (a) and (b), which are infinite loops, are correct.

for ( ; ; ) { // Do something } (a)

Equivalent while (true) { // Do something }

(b)

Structural Repetition using Loops

Often used when executing code for each element in a collection of data

int[] data = {1, 2, 3, 4, 5};int sum = 0;for (int element : data) { sum += element; }System.out.println(sum);

43

Arrays• Array is a data structure that represents a collection of the

same types of data.

• A "fixed length list".

5.6

4.5

3.3

13.2

4

34.33

34

45.45

99.993

11123

double[] myList = new double[10];

myList reference myList[0]

myList[1]

myList[2]

myList[3]

myList[4]

myList[5]

myList[6]

myList[7]

myList[8]

myList[9]

Element value

Array reference variable

Array element at index 5

44

Declaring and Creating in One Stepdatatype[] arrayRefVar = new datatype[arraySize];

double[] myList = new double[10];

•The new keyword is a Java operator that creates the object. •new calls a constructor, which initializes the new object.

– Everything in java is class-based. So we need to make objects (instances) for anything that isn’t a primitive type.

45

Declaring, creating, initializing Using the Shorthand Notation

double[] myList = {1.9, 2.9, 3.4, 3.5};

This shorthand notation is equivalent to the following statements:double[] myList = new double[4];

myList[0] = 1.9;

myList[1] = 2.9;

myList[2] = 3.4;

myList[3] = 3.5;

• Can do:– int[] anArr = {1, 9, 4, 3};– int[] anArr = new int[4];anArr[0] = 1;anArr[1] = 9;anArr[2] = 4;anArr[3] = 3;

• Can’t do:– int[] anArr = new int[4];anArr = {1, 9, 4, 3};

– anArr[4] = 5; //Arrays are FIXED LENGTH!

• What if we want to add values to the end of our array?

public static int[] addingarrays(int[] arr1, int[] arr2){int x = arr1.length;int y = arr2.length;int[] newarr = new int[x+y];for (int ind=0;ind<arr1.length;ind++) { // is this the most efficient?

newarr[ind]= arr1[ind];System.out.println(newarr[ind]);

}for (int ind=0;ind<arr2.length; ind++){

newarr[x+ind] = arr2[ind];System.out.println(newarr[x+ind]);

}System.out.println(newarr); //will this work?return newarr;

}

java.util.Arraysimport java.util.Arrays;public class ArrayMethods { public static void print(int[] newarr) { System.out.println(Arrays.toString(newarr)); } // ...}

• Contains useful methods for dealing with Arrays, including:– Sort

• Arrays.sort(values);

– binarySearch• int index = Arrays.binarySearch(values,3);

– Equals• Arrays.equals(values,array2) // sees if values inside of array are equal

– Fill• int[] array = new int[5];• Arrays.fill(array,0);

– toStringNo sum!! You have to write your own.