Top Banner
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?”
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.

Dec 26, 2015

Download

Documents

Domenic West
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 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.

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?”

Page 2: 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.

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

}

}

Page 3: 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.

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.

Page 4: 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.

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

Page 5: 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.

• 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

Page 6: 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.

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

Page 7: 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.

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

Page 8: 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.

A simple Java program

Compute the area of a circle

Page 9: 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.

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

Page 10: 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.

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

Page 11: 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.

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

Page 12: 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.

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

Page 13: 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.

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

Page 14: 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.

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) {

…}

Page 15: 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.

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

Page 16: 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.

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”

Page 17: 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.

Branching

Page 18: 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.

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;}

Page 19: 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.

19

TIP

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

}

Same as:

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

}

Page 20: 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.

20

Logical Operators

Java Name

! not

&& and

|| or

^ exclusive or

Page 21: 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.

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

Page 22: 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.

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

Page 23: 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.

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

Page 24: 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.

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

Page 25: 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.

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

Page 26: 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.

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

Page 27: 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.

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.

Page 28: 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.

• 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;

}

Page 29: 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.

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

}

Page 30: 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.

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

Page 31: 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.

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

Page 32: 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.

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

Page 33: 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.

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

Page 34: 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.

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

Page 35: 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.

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;

Page 36: 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.

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

Page 37: 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.

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

Page 38: 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.

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?

Page 39: 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.

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

}}

Page 40: 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.

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)

Page 41: 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.

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

Page 42: 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.

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

Page 43: 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.

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.

Page 44: 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.

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;

Page 45: 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.

• 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!

Page 46: 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.

• 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;

}

Page 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.

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.