CompSci 230 S2 2015 Software Construction Introduction to Java.

48
CompSci 230 S2 2015 Software Construction Introduction to Java

Transcript of CompSci 230 S2 2015 Software Construction Introduction to Java.

CompSci 230 S2 2015Software Construction

Introduction to Java

2

Today’s Agenda Topics:

How does Java compare with Python? Hello World in Java and Python Setting Up and Getting Started in Java Programming

Notepad++, TextPad, Eclipse Java Syntax

Reading: The Java Tutorials

http://docs.oracle.com/javase/tutorial/ Welcome to Java for Python Programmers

http://interactivepython.org/courselib/static/java4python/index.html

01

3

How does Java compare with Python? Java:

Python:

Java programs are “robust” if they are well-tested: reliable behaviour. Python is not a strongly-typed language, so a method can produce strange

results if given an unexpected input. More difficult to test, so less “robust”?

Simple Architecture neutral

Object oriented Portable

Distributed High performance(?)

Multithreaded Robust (as defined by Gosling)

Dynamic Secure

Simpler than Java Architecture neutral

Object oriented Portable

Distributed Adequate performance

Multithreaded Less robust?

More dynamic than Java More difficult to secure?

01

4

Python Vs Java Python:

the syntax is sparse, and clear. the underlying model of how objects and variables work is

very consistent. You can write powerful and interesting programs without a

lot of work. Java:

For very large programs Java and C++ are going to give you the best performance.

Maintainability is very important too.

01

5

Dynamic vs Static Typing It is the way that each language handles variables.

Java forces you to define the type of a variable when you first declare it and will not allow you to change the type later in the program. This is known as static typing.

Python uses dynamic typing, which allows you to change the type of a variable, by replacing an integer with a string.

Pros & Cons Dynamic typing is easier for the novice programmer to get to grips

with without worrying too much about their types

However, Static typing reduces the risk of undetected errors plaguing your program It is easy to misspell a variable name and accidentally create a whole new

variable

01

6

Braces vs Indentation Python:

uses indentation to separate code into blocks Java:

uses curly braces to define the beginning and end of each function and class definition

01

7

Speed vs Portability Java:

It can be used to create platform-independent applications. Any computer or mobile device that is able to run the Java virtual

machine can run a Java application

Python: You need a compiler that can turn Python code into code

that your particular operating system can understand. But, Java programs run more slowly than Python

programs.

01

8

Python vs Java: Which is Easier to Use? Most programmers agree that Python is an easier

language for novice programmers to learn. You will progress faster if you are learning Python as a

first language than Java. However, the popularity of Java means that learning

this powerful language is essential if you want to develop apps for Android, for example.

01

9

Java: A Compiled and Interpreted Language

“In the Java programming language, all source code is first written in plain text files ending with the .java extension. “Those source files are then compiled into .class files by the javac compiler.

“A .class file does not contain code that is native to your processor; “it instead contains bytecodes — the machine language of the Java Virtual

Machine (Java VM). “The java launcher tool then runs your application [by interpreting its

bytecode on] an instance of the Java Virtual Machine.” Source: http://

docs.oracle.com/javase/tutorial/getStarted/intro/definition.html01

10

Java – a mixed system

Java source code (MyProgram.java) Java byte code (MyProgram.class)

javac.exe

java.exejava.exe java.exe

Computer 1 Computer 2 Computer 3

01

11

Hello World program Note: Python has a command-line interface which will

execute a single line of code immediately after you type it

Python Source code: Hello.py Print the Hello World! message

Java Source code: Hello.java Print the Hello World! messagepublic class Hello {

public static void main(String[] args) { System.out.println("Hello world!"); }}

def main():print("Hello world!")

main()Python

Java Output

01

12

Setting up your computer Installing Java:

http://www.oracle.com/technetwork/java/javase/downloads/index.html Choose Java SE Downloads -> Java Platform (JDK) 8u45 Click “Accept License Agreement” Choose Platform and the version number (JDK 8 or jdk1.8.0_45)

There are several equivalent names Java Standard Edition Development Kit Java SE Development Kit JDK

Usually Java is installed in the "Program Files" folder in the C drive of your computer.

Have you installed the JDK correctly? Type “cmd” in the start menu Enter “java -version“ in the command prompt window. It should print

the version information.01

13

Setting up your computer You can use any IDE (Example: Notepad++, Textpad,

Eclipse, etc) Please check our course website to get information regarding

to setting up Notepad++ and textpad for Java programming You can add commands to compile and run java programs

All Java files have the extension .java. Our programs will consist of TWO source files:

To compile Java programs we use the javac command,

To run an application we use the java command, e.g.

javac MyProgram.java

java MyApplication

javac MyApplication.java

contains the instructions describing what we want the program to do

starts our program (a bit like a starter motor in a car)

MyProgram.javaMyApplication.java

01

14

Java programs don't run. You may have problem in your Path variable on your

system. Check the following

In the start menu, type “cmd” Type “javac” + press ENTER key It should display “Usage: javac… “ Otherwise, follow the steps below:

How to fix it: Go to the C drive, open the Program Files folder, open the

Java folder and open the jdk version folder (jdk1.8.x_x) and open the bin folder: Check that java.exe and javac.exe are in this folder

Now copy the path to the JDK version you are running, e.g. C:\Program Files\Java\jdk1.8.0_45\bin

01

15

Java programs don't run. (con’t) Type “System” in the start menu and choose System from Control Panel Click “Advanced system settings” on the left menu Select the “Advanced” tab and click "Environment Variables“ button

Edit the Path System variable Insert the path to your JDK after one of the first ";". Your path must be between two ";".

…;SYSTEMROOT%\System32; C:\Program Files\Java\jdk1.8.0_45\bin

01

16

Structure of a Java program Important Rules:

Every Java program must define a class, all code is inside a class.

Everything in Java must have a type Every Executable Java program must have a function

called public static void main(String[] args) And contains the statements (commands) to be executed.

public class MyApplication { public static void main(String[] args) { MyProgram p = new MyProgram(); p.start(); }}

public class MyProgram { public void start() { System.out.println("Start!"); }}

Class name Method

name

01

17

Structure of a Java program public static void main(String[] args):

the following lines look similar but are in fact treated by Java as completely different methods

public void main(String[] args) public static void main(String args) public static void main() void main(String args)

public indicates to the Java compiler that this is a method that anyone can call

static tells Java that this is a method that is part of the class, but is not a method for any one instance of the class

void tells the Java compiler that the method main will not return a value

args: It is a parameter list for the main method. It is an array of Strings01

18

Syntax syntax: The set of legal structures and commands

that can be used in a particular language. Every basic Java statement ends with a semicolon ; The contents of a class or method occur between { and

}

syntax error (compiler error): A problem in the structure of a program that causes the compiler to fail. Missing semicolon Too many or too few { } braces Illegal identifier for class name Class and file names do not match ...

01

19

Syntax error example1 public class Hello {2 pooblic static void main(String[] args) {3 System.owt.println("Hello, world!")_ 4 }5 }

Compiler output: Hello.java:2: <identifier> expected pooblic static void main(String[] args) { ^ Hello.java:3: ';' expected } ^ 2 errors

The compiler shows the line number where it found the error.

The error messages can be tough to understand!01

20

Comments Comments:

Ignored by the compiler Aimed at people who read the code

Inline comments All text until end of line is ignored e.g.

Multi-line comments All text between start and end of comment is ignored e.g.

//comment goes here

/* comment goes

in this space,

here */

01

21

Data Types Python:

Integers are objects, floating point numbers are objects, lists are objects, everything

Java: Most basic data types like integers and floating point numbers

are not objects. They are called primitive data types. Operations on the primitives are fast

There are eight primitive types :

Integers (whole numbers): Floating-point numbers (decimal numbers): Characters (symbol in character set (text)): boolean (true or false values):

byte, short, int,long, float, double, char, boolean

01

22

Range of values allowed Values stored by integer and floating point types:

Note: float and double use scientific notation

byte 8 bits -128 127

short 16 bits -32 768 32 767

int 32 bits -2 147 483 648 2 147 483 647

long 64 bits -9 223 372 036 854 775 808 9 223 372 036 854 775 807

double 64 bits +/- 4.9 E-324 +/- 1.8 E+308

Type Size Minimum Value Maximum Value

float 32 bits +/- 1.4 E-45 +/- 3.4 E+38

01

23

Declare and initialise a variable Java is a statically typed language.

the association between a variable and the type of object the variable can refer to is determined when the variable is declared

Once the declaration is made it is an error for a variable to refer to an object of any other type.

X

3int x = 3;

int x;

x = 3;

double percentagePassing101, percentagePassing105;

boolean isTheLectureOverYet;

x = 3.5;

01

24

Printing variables A variable can be used anywhere that a literal can be

used. We can print out the value stored in a variable using

the System.out.println() statement, e.g.

Or using System.out.print() Note: The println method prints a string and adds a newline

character at the end.

2323number

System.out.println(number);

int number = 23;System.out.println(number);

int number = 23;System.out.print("Hello World!");System.out.print(number);

Hello World!23

int number = 23;System.out.println("Hello World!");System.out.println(number);

Hello World!23

01

25

Symbolic constants – final A symbolic constant is like a variable, except that the

value it stores cannot change once it is initialised.

Use the following style guidelines for naming symbolic constants: use all upper case letters separate multiple words with an underscore

final int DAYS_IN_YEAR = 365;final double GST_RATE = 0.125; DAYS_IN_YEAR = 30;

01

26

Strings Python:

String literals are formed using either the single quotes or the double quotes as delimiters. Java:

String literals are formed using the double quotes as delimiters. Character literals are formed using the single quotes as delimiters.

Java strings do not support a slicing operator. Java uses method calls where Python uses Operators.

Python Java Description

str[3] str.charAt(3) Return character in 3rd position

str[2:5] str.substring(2,5) Return substring from 2nd to 4th

len(str) str.length() Return the length of the string

str.find('x') str.indexOf('x') Find the first occurrence of x

str.split() str.split('\s') Split the string on whitespace into a list/array of strings

str.split(',') str.split(',') Split the string at ',' into a list/array of strings

str + str str.concat(str) Concatenate two strings together

str.strip() str.trim() Remove any whitespace at the beginning or end

String greeting = "Hello World!";char c = 'H';

01

27

String Concatenation Both Python and Java use the concatenation operator

+ to join two strings to form a third, new string Python:

Operands of other types must be converted to strings before they can be concatenated

Java: If one of the operands is a string, the other operand can be of any

type.

result = "35" + " pages long."result = str(35) + " pages long."

String result;result = "35" + " pages long." ;result = 35 + " pages long.";

01

28

Type Conversion Python:

Numeric types can be converted to other numeric types by using the appropriate type conversion functions. The function’s name is the name of the destination type.

Java: Numeric types can be converted to other numeric types by

using the appropriate cast operators. A cast operator is formed by enclosing the destination type name in parentheses.

int(3.14)float(3)

int x = (int) 3.14;double y = (double) 3;char p = (char) 65;int q = (int) 'a';

33.0A97

01

29

import Python:

A module is imported using the form:

Java: A package resource is imported using the form:

The resource is then referenced without the package name as a qualifier.

import <module name>from <module name> import <resource name>

import <package name>.<resource name>;

import math

print(math.sqrt(2), math.pi)

import java.util.*;

...ArrayList<String> names = new ArrayList<String>();

01

30

The Random class A Random object generates pseudo-random numbers.

Class Random is found in the java.util package.

Examples: To get a random number from 0 to 9 inclusive

To get a number in arbitrary range [min, max] inclusive:

Method name

Description

nextInt(max)

returns a random integer in the range [0, max)in other words, 0 to max-1 inclusive

nextDouble()

returns a random real number in the range [0.0, 1.0)

Random rand = new Random();int randomNumber = rand.nextInt(10);

Random rand = new Random();int size_of_range = max - min + 1;int n = rand.nextInt(size_of_range) + min;

01

31

Lists Vs Arrays Arrays In Java:

It is a sequence of elements of the same type. Each element is accessed in constant time using an index position. Unlike a list, an array’s length is fixed when it is created and cannot be

changed. Moreover, the only operations on an array are access or replacement of elements via

subscripts. Like other data structures, arrays are objects and thus are of a reference

type. The type of an array is determined by its element type, which is specified

when the array is instantiated. Default values:

Each array element in ages (int) has a default value of 0. Each array element in names (string) has a default value of null

The length of an array can be obtained from the array object’s length variable for loop can be used just to reference the elements in an array:

int[] ages = new int[10];String[] names = new String[10];

System.out.println(names.length);for (String name: names) System.out.println(name);

ages[0] = 21;+ve

index only

01

32

ArrayLists Lists in Python:

A list is a mutable sequence of 0 or more objects of any type. The len function returns the number of elements in a list. The subscript operator ([]) accesses an element at a given

position. (+ve or –ve index) ArrayLists in Java:

The type is determined when the ArrayList is instantiated. Examples:

Names can contain only strings, whereas the second ArrayList can contain only instances of class Integer. The class Integer is a wrapper class, which allows values of type int to be

stored in an ArrayList. When an int is inserted, the JVM wraps it in an Integer object. When an

Integer object is accessed, the int value contained there is returned.

ArrayList<String> names = new ArrayList<String>();ArrayList<Integer> ages = new ArrayList<Integer>();

ages.add(63);ages.set(0, ages.get(0) + 1);

+ve index only

01

33

Boolean and Relational, Logical Operators The type boolean includes the constant values true

and false The relational operators are ==, !=, <, >, <=, and

>=. The logical operators:

Python: The logical operators are not, and, and or Comparison operators can be chained

Java: The logical operators are ! (not) && (and), and || (or).

value > 10 and value < 10010 < value < 100

value > 10 && value < 100value >= 10 || value == 5

01

34

Control Flow Conditionals

Conditional statements in Python and Java are very similar Simple if

if-else

The statements in the consequent and each alternative are marked by curly braces ({}). When there is just one statement, the braces may be omitted.

Each Boolean expression is enclosed in parentheses.

if condition: statement1 ...

if (condition) { statement1; ...}

if condition: statement1 ...else: statement1 ...

if (condition) { statement1; ...} else { statement1; ...}

01

35

Control Flow (con’t) Conditionals

Nested if-elseif grade < 60: print 'F'elif grade < 70: print 'D'elif grade < 80: print 'C'elif grade < 90: print 'B'else: print 'A'

if (grade < 60) { System.out.println('F');} else if (grade < 70) { System.out.println('D');} else if (grade < 80) { System.out.println('C');} else if (grade < 90) { System.out.println('B');} else System.out.println('A');

01

36

Control Flow Loops

for + range (Python) The variable picks up the value of each element in the iterable

object and is visible in the loop body The range function provides you with a wide variety of options for

controlling the value of the loop variable for (Java)

The Java for loop is really analogous to the last option giving you explicit control over the starting, stopping, and stepping in the three clauses inside the parenthesis.

for i in range(10): print i

for (start clause; stop clause; step clause) { statement1; ...}

range(stop)range(start,stop)range(start,stop,step)

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

Note: “i” is only visible within the loop

01

37

Control Flow for - visiting each element in an iterable object

Python:

Java:

while:

do-while: This ensures that a loop will be executed at least one time

for <variable> in <iterable>: <statement> ...

for (<type> <variable> : <iterable>){ <statement>; ...}

for s in aListOfStrings: print(s)

for (String s : aListOfStrings){ System.out.println(s);}

while condition: statement1 statement2 ...

while (condition) { statement1; statement2; ...}

do { statement1; statement2; ...} while (condition);

01

38

File I/O Python:

The input function displays its argument as a prompt and waits for input When the user presses the Enter or Return key, the function returns a

string representing the input text. Java:

The Scanner class is used for the input of text and numeric data from the keyboard.

The programmer instantiates a Scanner and uses the appropriate methods for each type of data being input.

name = input("Enter your name: ")age = int(input("Enter your age: "))

Scanner in = new Scanner(System.in);fahr = in.nextDouble();

Return type

Method Name

Description

boolean hasNext() returns true if more data is present

boolean hasNextInt() returns true if the next thing to read is an integer

String next() returns the next thing to read as a String

int nextInt() returns the next thing to read as an integer

… 01

39

Example: Your BMI (body mass index) is considered healthy if it is in the range 19 – 25.

Write a program that prompts the user to enter their height and weight. Your program should then calculate the user’s BMI using the following

formula:

Use Math.pow() to square the height.public class ExampleApp { public static void main(String[] args) { MyExample p = new MyExample(); p.start(); }}

import java.util.Scanner;public class MyExample { public void start() { Scanner in = new Scanner(System.in); System.out.print("Enter your weight in kgs: "); double weight = in.nextDouble(); System.out.print("Enter your height in metres: "); double height = in.nextDouble(); double bmi = weight / (height * height); System.out.print("Your BMI is: "); System.out.println(bmi); }}

𝒃𝒎𝒊=𝒘𝒆𝒊𝒈𝒉𝒕 𝒊𝒏𝒌𝒈𝒔

(𝒉𝒆𝒊𝒈𝒉𝒕 𝒊𝒏𝒎𝒆𝒕𝒓𝒆𝒔 )2

Enter your weight in kgs: 61.45Enter your height in metres: 1.64Your BMI is: 22.84726353361095

01

40

Arguments for the method main The heading for the main method shows a parameter that is an array

of Strings:

When you run a program from the command line, all words after the class name will be passed to the main method in the args array.

The following main method in the class TestArray will print out the first two arguments it receives:

public static void main(String[] args) { ...}

>java TestArray Hello World

public static void main(String[] args) { for (int i=0; i<args.length; i++) System.out.println(args[i]);}

>java TestArray Hello WorldHelloWorld

Output:

public static void main(String[] args) { ...}

>java TestArray Hello World

public static void main(String[] args) { for (int i=0; i<args.length; i++) System.out.println(args[i]);}

01

41

Multidimensional Arrays Multidimensional Arrays

Arrays with more than one index number of dimensions = number of indexes

Multidimensional arrays in Java are implemented as arrays of arrays Examples:

Two-dimensional arrays A two-dimensional array can be thought of as a table of values, with

rows and columns A two-dimensional array element is referenced using two index

values Example:

int[][][] threeD = new int [2][3][4];int[][][][] fourD = new int [2][3][768][1024];

int[][] x = new int[5][7]; 7 columns:

5 rows

01

42

2-Dimensional Arrays

1 2 3

4 5 6

Declaration & Initialization 2-D arrays Syntax for 2-D arrays is similar to 1-D arrays

<type>[][] <name> = new <type>[rows][columns]; Example 1:

The array should have five rows and seven columns The real picture:

Example 2:

The array has 4 rows. 2-D Array Initializer

You can also initialize at declaration with 2D array literal Use nested comma separated lists, enclosed in {}’s

int[][] x = new int [4][];

int[][] x = new int[5][7];

int[][] y = { {1,2,3}, {4,5,6}};

01

43

Creating Multidimensional Arrays We can use existing arrays for initialization

a3 does not store copies of a1 and a2 in Array3[0] and a3[1] respectively

Instead it stores reference to a1 and a2

If we change the value of a1[1], we also change the value of a3[0][1]

To create copies of an existing 1-dimensional arrays, we can use the clone method

int[] a1 = {10,12,14};int[] a2 = {20,22,24};int[][] a3 = {a1, a2};

a1[1] = 0;System.out.println(a3[0][1]);

int[][] a4={a1.clone(), a2.clone()};

0 10

1 12

2 14

a1

0 20

1 22

2 24

a2

0

1

a3

0

1

10

12

14

20

22

24

a4

0 10

1 12

2 14

a1

0 20

1 22

2 24

a2

01

44

Length Variables Syntax:

arrayName.length returns the number of rows in the array

arrayName[rowToGet].length returns the number of columns in row “rowToGet”

Note: If x is a rectangular array, all rows have the same length

int[][] x = new int[5][7];System.out.println(x.length);System.out.println(x[0].length); 5

7

Output:

System.out.println(x[0].length);System.out.println(x[1].length);System.out.println(x[2].length);

777

Output:

01

45

Using 2D Arrays Accessing elements

To access elements, we use pretty much the same technique as a 1D array

Initialization & Printing Nested loops are used to initialize array elements and print out

values Algorithm:

Starting from the first row (0th) to the last row (n-1) – outer loop For each row, starting from the first column (0th) to the last column (m-1) – inner

loop Print out the value

int[][] y = { {1,2,3}, {4,5,6}}; for (int row = 0; row < y.length; row++) { for (int col = 0; col < y[row].length; col++) System.out.print(y[row][col] + " "); System.out.println();}

System.out.println(myArr[rowToGet][colToGet]);

Use y.length to navigate the last

row

Use y[row].length to navigate the last column of

each row

01

46

Cloning of Multi-D Arrays It is shallow clone only Remember that multi-dimensional arrays in Java are arrays of arrays.

Cloning only generates a copy of the root array

Note: a5[0] and a5[1] from an 1-dimensional array that store the memory location m0 and m1 of two 1-dimensional arrays. If we clone a5, then we only create a new 1-dimensional array that stores m0 and m1.

int[][] a5 = {{10,12,14}, {20,22,24}};int[][] a6 = a5.clone();

0

1

a5

0

1

10

12

14

20

22

24a6

01

47

Ragged Arrays

3 2

Ragged arrays have rows of unequal length Each row has a different number of columns, or

entries Declaration & Initialization a ragged array

Syntax: <type>[][] <name> = new <type>[rows][]; <name>[0] = new <type>[colCountForRow1]; ...

Array Initializer 0

1

2

int[][] b = {{3,2}, {3,2,1}, {1}};

int[][] b;b = new int[3][];b[0] = new int[2];b[1] = new int[3];b[2] = new int[1];

3 2 1

1

0

1

2

0 0

0 0 0

0

b

b

01

48

Using Ragged Arrays Length Variables:

arrayName.length returns the number of rows in the array arrayName[rowToGet].length returns the number of columns in row

“rowToGet” Example:

b.length = 3 b[0].length returns 2 b[1].length returns 3 b[2].length returns 1 b[3].length <- ERROR

Initialization & Printing Nested loops are used to initialize array elements and print out values Note: You must use y[row].length to get the number of columns in each row.

The number may not be the same for all rows.

for (int row = 0; row < y.length; row++) { for (int col = 0; col < y[row].length; col++) System.out.print(y[row][col] + " "); System.out.println();}

int[][] y = {{3,2}, {3,2,1}, {1}};

01