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

Similar documents
Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Zheng-Liang Lu Java Programming 45 / 79

JAVA OPERATORS GENERAL

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

Java Bytecode (binary file)

Introduction to Programming Using Java (98-388)

Program Fundamentals

Prof. Navrati Saxena TA: Rochak Sachan

A variable is a name that represents a value. For

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

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

CS 11 java track: lecture 1

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Java Programming Language. 0 A history

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

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

COMP Primitive and Class Types. Yi Hong May 14, 2015

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

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

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

13 th Windsor Regional Secondary School Computer Programming Competition

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

Chapter 3: Operators, Expressions and Type Conversion

CSC 1214: Object-Oriented Programming

Course Outline. Introduction to java

Introduction Basic elements of Java

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

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

Programming with Java

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

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

1 Shyam sir JAVA Notes

CS313D: ADVANCED PROGRAMMING LANGUAGE

JAVA Programming Fundamentals

Java Basic Programming Constructs

CS 231 Data Structures and Algorithms, Fall 2016

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

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

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

Pace University. Fundamental Concepts of CS121 1

Section 2: Introduction to Java. Historical note

Operators. Java operators are classified into three categories:

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

PROGRAMMING FUNDAMENTALS

CS11 Java. Fall Lecture 1

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections

1007 Imperative Programming Part II

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

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

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

CMSC131. Introduction to your Introduction to Java. Why Java?

Computer Programming, I. Laboratory Manual. Final Exam Solution

Values and Variables 1 / 30

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

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

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

CSI33 Data Structures

Fundamentals of Programming

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Goals. Java - An Introduction. Java is Compiled and Interpreted. Architecture Neutral & Portable. Compiled Languages. Introduction to Java

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

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

Object-Oriented Programming

Basic Operations jgrasp debugger Writing Programs & Checkstyle

3. Java - Language Constructs I

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

The Arithmetic Operators

Advanced Computer Programming

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

Fundamental of Programming (C)

A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1

Expressions & Flow Control

Chapters 1-4 Summary. Syntax - Java or C? Syntax - Java or C?

Chapter. Let's explore some other fundamental programming concepts

Operators and Expressions

1 Introduction Java, the beginning Java Virtual Machine A First Program BlueJ Raspberry Pi...

ECE 122 Engineering Problem Solving with Java

Inf1-OOP. Textbooks. Who and What. Organizational Issues. Why Java? Course Overview. Hello, World! in Java. Ewan Klein, Perdita Stevens

Inf1-OOP. Textbooks. Who and What. Organisational issues. Why Java? Course Overview. Hello, World! in Java

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Introduction to Java

Java Identifiers, Data Types & Variables

Basics of Java Programming

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Arithmetic and Bitwise Operations on Binary Data

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

Object Oriented Software Design

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

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

SECTION II: LANGUAGE BASICS

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Programming Language Basics

Computers Programming Course 6. Iulian Năstac

Transcription:

OOP in Java 1

Outline 1. Getting started, primitive data types and control structures 2. Classes and objects 3. Extending classes 4. Using some standard packages 5. OOP revisited Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail. 2

Recommended text The Java Programming Language Third Edition by Arnold, Gosling and Holmes Addison Wesley Gosling created the Java language In the spirit of C and C++ Programming Languages 3

What you need to know already What compiling and interpreting mean Some knowledge of C or Python 4

Getting started at home Just follow these steps explanations later Look at java.sun.com for what is available Download and install the JDK currently version 8 This will install software needed Create a directory where you will save your Java programs call the folder JavaProgs 5

Keeping Going Start vim or NotePad and enter the program on the next slide. Save it with the filename First.java must be this name. Put quotes around it to make sure Notepad does not put.txt on the end. Note CAPITAL F. Save it in your JavaProgs folder: 6

The first program public class First { public static void main(string[] args) { System.out.println( Hugh Murrell ); System.out.println( 73156286554"); } } 7

Then.. In a terminal window, navigate to your JavaProgs folder Use cd to change directory. 8

Compile it The compiler is called javac, so type in: javac First.java Then run it like this: java First 9

Explanations.. All Java source code files are called Something.java You give this to the javac compiler This produces a file called Something.class This is in bytecode This can be interpreted by the java interpreter 10

More explanations Each source code file defines a class The name of the class it defines (First in our case) must match the filename hence First.java This is compiled to a bytecode file named First.class Java is case-sensitive (like C) Classes should start with a capital letter. So the file must be called First.java and not first.java 11

Practical Exercise In your prac session on Friday you will have to, type in, compile and run a HelloWorld.java program that prints your name and student number. and then adapt your program to solve the Whiskey problem. see website for details. 12

Features of Java Java is a general purpose high level language Core Java is well-defined and stable Versions are useful in many situations desktop, server, embedded, mobile etc Java is a trademark of Sun Microsystems Java is cross -platform 13

More features Java is a pure object-oriented language. No functions, no global variables Unlike C++, which is C with objects Java is designed to make it hard to write programs which will crash No pointers Strongly typed, Compiler will not compile doubtful code Programmer must write code that catches exceptions Run-time checks eg array bounds exceptions Slower than C or C++ (not much), but less chance of crash 14

Types Recall data type from C int, char double etc Java has 2 kinds of types: Primitive types Reference types 15

Primitive types These are simple types like char, double, int Similar to C Main difference the sizes of these types are defined eg an int is 4 bytes Each hardware platform has its own 'virtual machine' Which all look the same So primitive types can all have the same data sizes All chars use UNICODE character set - so characters are 2 bytes long 16

Reference types Reference type variables are objects Objects belong to classes Objects made by a constructor 17

Primitive types first We will look at primitive types first and control structures (loops and ifs) Then look at classes and objects 18

Program format public class Testing { public static void main(string[] args) { // find the area of a circle.. double radius = 5.0; double area; area = 3.1416 * radius * radius; } System.out.println("Area = " + area); } Use this format to start with In file Testing.java Code goes here Explain rest later 19

Variables - declaring and assigning public class Testing { public static void main(string[] args) { // find the area of a circle.. double radius = 5.0; double area; area = 3.1416 * radius * radius; System.out.println("Area = " + area); } } // starts a line comment double area declares a variable called area of type double double radius = 5.0; declares and initializes a variable variables can be declared anywhere in a block { } statements end in ; like C and C++ 20

Console output System.out.println("Area = " + area); This takes a single string argument but.. The + causes area to be converted to the equivalent string, and concatenated with the left hand operand so we get "Area = 5.72" or whatever System.out.print stays on same line 21

Primitive data types - numeric Name Range Size byte -2 7 to 2 7-1 (-128 to +127) 8 bits short -2 15 to 2 15-1 ( ± 32 000 ) 16 bits int -2 31 to 2 31-1 ( ± 2 500 million ) 32 bits long -2 63 to 2 63-1 (very big!!) 64 bits float about ± 10 38, 6/7 sig digits 32 bits double ± 10 308, 14/15 sig digits 64 bits Java data type sizes are platform independent All are signed Top four are integer, bottom two are floating point Variables of these types declared like short a,b,c; or initialised when declared double x = 1.502; 22

Numeric data types Can get overflow eg int i = 64000; int n = i * i ; Specify type of constant like x = 1000L; // defaults to integer f = 1.0F; // force float - defaults to double x = 0x1FF; // hex Operators + - * / % is mod = remainder eg 13 % 4 is 1 Short cut same as C += x+=8; same as x = x + 8; -= x-=8; same as x = x - 8; *= x*=8; same as x = x * 8; /= x/=8; same as x = x / 8; %= x%=8; same as x = x % 8; 23

Overflow Exercise Use code to produce overflow as in the previous slide Find out what happens when you compile/run it. 24

Two types of division float f = 1.0 / 2.0; // floating point int i = 1 / 2; // i is 0 if both operands are integer, / is integer version - it gives the quotient and discards the remainder So / is overloaded different versions, same name 25

x++; is the same as x = x + 1; y--; is the same as y = y - 1; post-increment is like Increment and decrement a = b++; which first assigns b to a then increments b pre-increment is a = ++b; which first increments b then assigns the new value to a 26

Type casts Assigning a small type to a larger type is no problem eg int i; long x; i = 32; x = i; OK because x more bits than i But reverse gives possible loss of precision eg int i; long x; x = 32; i = x; // gives compile error Problem solved by a type cast ie i = (int) x; 27

Type cast exercise Try out int i; long x; x = 32; i = x; In a program. Fix it as in the previous slide 28

Char type char is for a single character, like char c = A ; c++; note single quotes makes c = B Strings are different - see later Java uses Unicode not ASCII - 16 bits per character. 29

boolean type If a variable is declared to be boolean, it is restricted to 2 values - true and false boolean result; result = true; result = ( x > y ); result is true if x is greater than y also < <= >= ==!= == not the same as = && and or! not result = ( x > y ) && ( y < 5 ); result is true if x is greater than y and y is less than 5 && and are short-cut operators 30

bitwise operators & is bitwise AND (like both) is bitwise OR (like either ) ^ is XOR (like not equal) ~ is NOT eg if x = 9 1001 and y = 10 1010 x & y is 8 1000 x y is 11 1011 x ^ y is 3 0011 ~ 0xFFFFFFFE is 1 inverting 11111111110 31

bit shift operators >> is shift right eg if x = 7 or in binary 0000 0111 x >> 1 is 0000 0011 << is shift left so x << 1 is 0000 1110 = 14 32

Try out this code: int i = 6; System.out.println(i&1); i>>=1; System.out.println(i&1); i>>=1; System.out.println(i&1); Explain what you get Bit shift exercise 33

precedence 2 * 3 + 4 is 10 not 14 2*(3+4) is 14 Highest ++ -- * / % + - < <= > >= ==!= && Lowest = += -= *= /= %= Use brackets when in doubt 34

Control - if for example if ( x== 5 ) { y = 2; a++; } else c++; round brackets around boolean expression indentation no then as in Visual Basic block { } around several steps to do no block if just one step - if (x<4) a=4; else can be omitted if not needed 35

if example - validation for example if ( ( age>0 ) && ( age < 130 ) ) System.out.println( age is valid ); else { System.out.println( age is invalid );.. code to deal with error.. } beware of if ( x==5 ); y = 2; 36

switch - I used where many alternative actions are possible example - switch (y) { case 5: a = 7; case 9: b = 3; case 4: a = 8; default: z = 2; } y can be expression (like x + 4) but must be integral the 5, 9, 4 etc must be constants default is optional 37

switch - II the action falls through - when one case is triggered, all the following options execute to the end of the switch so often combine with break - example - switch (y) { case 5: a = 7; break; case 9: b = 3; break; case 4: a = 8; break; } include final break - not essential but good practice, since if add further option do not need to go back and add break to previous 38

Conditional operator? ; example x = ( y > 4 )? 7 : 3; if y is greater than 4, x becomes 7, and otherwise, it becomes 3 in general a? b : c b is evaluated if a is true, c if it is not example int x =9, y = 10, a; a = (x > 9)? x++ : y++ ; after this a = 10, y is 11, x is still 9 39

loops - while loops repeat blocks of code - called iteration example - output the numbers 3, 6, 9,... 99 x = 3; while ( x<102 ) { System.out.println( x ); x += 3; } in general, while (boolean expression) statement or block to repeat need to initialise variables may loop zero times if false first time use indentation 40

loops - do while example - output the numbers 3, 6, 9,... 99 x = 3; do { System.out.println( x ); x += 3; } while ( x<102 ) in general, do statement or block to repeat while (boolean expression) unlike a while, it will execute the loop at least once 41

loops - for example - output the numbers 3, 6, 9,... 99 for ( x = 3; x<102; x+=3 ) System.out.println(x); in general for ( <initialisation> ; <loop while true>; <change every time> ) < statement or block to repeat > may loop zero times add up the integers 1 + 2 + 3 +...100 int t = 0; int x; for ( x = 1; x<101; x++) t += x; System.out.println( t ); 42

loops - for - II can use statement list, like int t; int x; for ( x = 1, t = 0; x<101; x++) t+=x; System.out.println(t); can omit any part, (retain separating ; ) like int t = 0; int x = 1; for ( ; x<101; x++) t+=x; System.out.println(t); for (; ; ) loops forever 43

can declare variable in for, like int t = 0; for ( int x = 1; x<101; x++) t+=x; System.out.println(t); in this case the scope of the variable is limited to the for statement do not do this - for ( int x = 1; x<101; x++); t+=x; loops - for - III 44

Arrays - I An array is a set of boxes (elements) each labelled with a number (index) Arrays are declared and created as int [ ] numbers = new int [ 100 ]; which makes an array of 100 integers called numbers or do it in 2 steps int [ ] numbers; //declare it numbers = new int [ 100 ]; // create it or initialise it int [ ] numbers = { 4, 2, 1, 3, 5 }; can have arrays of anything 45

Arrays - II Array elements referred to like numbers [4] = 18; Multi-dimensional arrays created and used like int [ ] [ ] table = new int [5] [10]; table[3][4]=7; Array element numbering starts at 0 so int [ ] numbers = new int [ 100 ]; creates 100 elements, from numbers[0] to numbers[99] array bounds are checked at compile time and run time 46

int [ ] numbers = new int [5]; //.. put some numbers in the array, then...sort them Arrays - sorting // a bubble sort.. for ( int i = 0; i < 5; i++ ) for ( int j = 0; j < 4-i; j++ ) if ( numbers[ j ] > numbers[ j+1] ) { // swap them int temp; temp = numbers[ j ]; numbers[ j ] = numbers[ j+1 ]; numbers[ j+1 ] = temp; }; 47

Array exercise Declare an array of 10 doubles Fill the array with random numbers (use Math.random(); ) Print them out Sort them Print them out 48