cc316: object oriented programming - manal helal

76
OOP in Java : © W. Milner 2005 : Slide CC316: Object Oriented Programming Dr. Manal Helal, Fall 2015. http://moodle.manalhelal.com/course/view.php?id=15 Lecture 1: Introduction to Java

Upload: others

Post on 22-Apr-2022

19 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

CC316: Object Oriented Programming

Dr. Manal Helal, Fall 2015.http://moodle.manalhelal.com/course/view.php?id=15

Lecture 1: Introduction to Java

Page 2: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Course Description• This course introduces JAVA to students as an example of an object

oriented programming language. The course starts with a briefing on Java history and the classifications of different Java editions.

• The concepts of classes and objects are introduced followed by a description of various types of class members. The course describes the concepts of abstraction and encapsulation and how to apply these concepts when creating classes.

• The course describes the object-oriented relationships: association, aggregation, composition, inheritance and implementation. Also the concept and role of polymorphism are introduced covering method overloading, method overriding, and dynamic method dispatching. Exception handling and the usage of Java API are presented with a concern to using javax.swing to build GUI applications.

Page 3: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Course Learning Objectives• Understand object oriented design principles and programming using Java as

an OOP language.• Using Java API (Math , String, Date, ArrayList, I/O, File,… etc.)• Understand method definition, invocation, overloading, encapsulation and

information hiding.• Understand the class members, access modifiers, and Object instantiation.• Understand object oriented relations (associations, aggregation, composition,

inheritance and interface, .... etc).• Understand class inheritance, reusability, method overriding, and

polymorphism.• Understand abstraction, interfaces and inner classes.• Build user interfaces using Java swing package, and event driven

programming.• Handle runtime exceptions.• Create simple software system using Java.

Page 4: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Coure Outline1. Revision of Problem Solving & Introduction to Java Language - Ch 1, 2, 3, 4, 6, 7.2. Introduction to OOP in Java3. Methods in Java - Ch 5.4. Objects and Classes - Ch 8.5. Thinking in Objects (Ch 9, 10).6. Revision7. Midterm Exam8. Inheritance & Polymorphism - Ch 11.9. Inheritance & Polymorphism Cont’d - Ch 11.10.GUI - Ch 12.11.Abstract Classes & Interfaces - Ch 15.12.Event Driven Programming - Ch 1613.Exception Handling & Text I/O- Ch 14.14. Revision 15.Projects Presentations16.Final Exam

Page 5: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Grading Scheme•Week 7

Quiz 1 5%Assignment 1 5%Midterm 1 20%

•Week 12Quiz 2 5%Assignment 2 5%Midterm 2 10%Project 10%

•Final Exam 40%

Grading scale A+ = [95%, ∝) A = [90%, 95%) A- = [85%, 90%) B+ = [80%, 85%) B = [75%, 80%) B- = [70%, 75%)C= [65%, 70%) C = [60%, 65%)C-= [55%, 60%) D = [50%, 55%)

Page 6: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Textbook & References

• Y Daniel Liang, Introduction to JAVA Programming, 9th Edition, Prentice Hall, 2013.

• References

• Herbert Schildt, Java: The Complete Reference, 7th Edition, McGraw-Hill Osborne Media.

• Harvey M. Deitel, Paul J. Deitel, Java How to Program, 7th Edition, Prentice Hall.

Page 7: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Rules

• Course Web site: http://moodle.manalhelal.com/course/view.php?id=15.

• Attendance

• Attendance is a must in all CCIT courses. A consecutive 3 absences will result in course forced withdrawal. 2 sections/labs count for 1 lecture. For example, a student absent for 2 lectures & 3 labs will be withdrawn. Medical and other excuses should be submitted to the department.

• Academic Honesty

• First academic honesty preaching will result in a disciplinary action ranging from zero mark in the graded activity and up to forced course withdrawal or forced academy dismissal, as regulated by AASTMT policies. This includes copied assignments/projects, exam cheating of all types, inadequate individual participation in teamwork – more on course Description Document, and College and Academy Hand-Books.

Page 8: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Studying Plan & Teaching Method• Every lecture is accompanied with source code examples that are zipped and

uploaded with the lecture slides on Moodle course website. These examples are expected to be read, understood, and executed in your machine.

• Every lecture is followed with practice problems in labs and sections to be attempted guided by the TA, then a small assignment, that is very easy to finish if you execute all samples, and revise the theoretical content of the lecture.

• Asking questions are encouraged in this preference order:

• In office hours,

• then finally in lecture and section times to avoid lengthy interruptions and delay in course contents.

• Please don’t accumulate material without full understanding and use the lecturer and the TA as much as you can to do your best.

• Understanding theoretical concepts in lectures, running all examples, doing all assignments, and engaging in a good project, are the methods to study for the lab quizzes and the open-book midterm and final exams.

Page 9: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Lecture Learning Objectives

• Differentiate between the different Java Editions.

• Describe Java Characteristics.

• Install JDK, compile and run your first java program.

• Revise Problem Solving using Java Language.

Page 10: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

What you need to know already

• What compiling and interpreting mean

• Some knowledge of C, or other programming language.

• Much Java syntax is like C, so

• We’ll say ‘it’s like C except that..’

Page 11: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Getting Started

• Just follow these steps – explanations later:

• Look at http://www.oracle.com/technetwork/java/index.html for what is available

• You need Java SE = Java Standard Edition

• Download and install the JDK – currently 8.0 Update 6

• This will install software needed in

• C:\Program files\java

• Create a directory where you will save your Java programs – call the folder JavaProgs

Page 12: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Keep Going

• Start NotePad and enter the program on the next slide.

• Save it with the filename “First.java” – must be this name. Put quotes around it – make sure Notepad does not put .txt on the end.

• Note CAPITAL F.

• Save it in your JavaProgs folder:

Page 13: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

The first program

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

System.out.println("Hello world");}

}

Page 14: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Then..

• Switch to the command prompt (Start Programs Accessories Command Prompt) and navigate to your JavaProgs folder

• Use cd to change directory. cd.. Moves ‘up’ a level.

• You should have something like:

Page 15: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Compile it• The compiler is called javac. You’ll need to include the path to it, so

type in:

• After this, get this line back using the up and down arrow keys.

• Then run it like this:

Page 16: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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

Page 17: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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

Page 18: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Exercise• Change the file First.java so it defines a class called Second –

and save it as Second.java

• Change it so it outputs ‘my second program’ instead of ‘Hello world’

• Compile and run it.

Page 19: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide 19

Why Java?

The answer is that Java enables users to develop and deploy applications on the Internet for servers, desktop computers, and small hand-held devices. The future of computing is being profoundly influenced by the Internet, and Java promises to remain a big part of that future. Java is the Internet programming language.

Java is a general purpose programming language. Java is the Internet programming language.

Page 20: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Java, Web, and Beyond

• Java can be used to develop Web applications.

• Java Applets

• Java Servlets

• Java Server Pages (JSP)

• Java can also be used to develop applications for hand-held devices such as Tablets and cell phones

20

Page 21: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Examples of Java’s Versatility (Applets)

21

Page 22: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

PDA and Cell Phone

22

Page 23: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Java’s History

23

http://www.oracle.com/technetwork/java/javase/overview/javahistory-index-198355.html

Page 24: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Java Features• 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 (Oracle Now)

• Java is cross -platform

Page 25: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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

• Compiler will not compile doubtful code

• Programmer must write code that ‘catches exceptions’

• Run-time checks e.g. array bounds exceptions

Page 26: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Characteristics of Java

26

Java is partially modeled on C++, but greatly simplified and improved. Some people refer to Java as "C++--" because it is like C++ but with more functionality and fewer negative aspects.

• Java Is Simple

• Java Is Object-Oriented

• Java Is Distributed

• Java Is Interpreted

• Java Is Robust

• Java Is Secure

• Java Is Architecture-Neutral

• Java Is Portable

• Java Is Multithreaded

• Java Is Dynamic

http://www.cs.armstrong.edu/liang/intro9e/supplement/JavaCharacteristics.pdf

Page 27: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Characteristics of Java

27

• Java Is Simple

• Java Is Object-Oriented

• Java Is Distributed

• Java Is Interpreted

• Java Is Robust

• Java Is Secure

• Java Is Architecture-Neutral

• Java Is Portable

• Java Is Multithreaded

• Java Is Dynamic

Java is inherently object-oriented. Although many object-oriented languages began strictly as procedural languages, Java was designed from the start to be object-oriented. Object-oriented programming (OOP) is a popular programming approach that is replacing traditional procedural programming techniques.

One of the central issues in software development is how to reuse code. Object-oriented programming provides great flexibility, modularity, clarity, and reusability through encapsulation, inheritance, and polymorphism.

Page 28: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Characteristics of Java

28

• Java Is Simple

• Java Is Object-Oriented

• Java Is Distributed

• Java Is Interpreted

• Java Is Robust

• Java Is Secure

• Java Is Architecture-Neutral

• Java Is Portable

• Java Is Multithreaded

• Java Is Dynamic

Distributed computing involves several computers working together on a network. Java is designed to make distributed computing easy. Since networking capability is inherently integrated into Java, writing network programs is like sending and receiving data to and from a file.

Page 29: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Characteristics of Java

29

• Java Is Simple

• Java Is Object-Oriented

• Java Is Distributed

• Java Is Interpreted

• Java Is Robust

• Java Is Secure

• Java Is Architecture-Neutral

• Java Is Portable

• Java Is Multithreaded

• Java Is Dynamic

You need an interpreter to run Java programs. The programs are compiled into the Java Virtual Machine code called bytecode. The bytecode is machine-independent and can run on any machine that has a Java interpreter, which is part of the Java Virtual Machine (JVM).

Page 30: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Characteristics of Java

30

• Java Is Simple

• Java Is Object-Oriented

• Java Is Distributed

• Java Is Interpreted

• Java Is Robust

• Java Is Secure

• Java Is Architecture-Neutral

• Java Is Portable

• Java Is Multithreaded

• Java Is Dynamic

Java compilers can detect many problems that would first show up at execution time in other languages.

Java has eliminated certain types of error-prone programming constructs found in other languages.

Java has a runtime exception-handling feature to provide programming support for robustness.

Page 31: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Characteristics of Java

31

Java implements several security mechanisms to protect your system against harm caused by stray programs.

• Java Is Simple

• Java Is Object-Oriented

• Java Is Distributed

• Java Is Interpreted

• Java Is Robust

• Java Is Secure

• Java Is Architecture-Neutral

• Java Is Portable

• Java Is Multithreaded

• Java Is Dynamic

Page 32: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Characteristics of Java

32

• Java Is Simple

• Java Is Object-Oriented

• Java Is Distributed

• Java Is Interpreted

• Java Is Robust

• Java Is Secure

• Java Is Architecture-Neutral

• Java Is Portable

• Java Is Multithreaded

• Java Is Dynamic

Write once, run anywhere

With a Java Virtual Machine (JVM), you can write one program that will run on any platform.

Page 33: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Characteristics of Java

33

• Java Is Simple

• Java Is Object-Oriented

• Java Is Distributed

• Java Is Interpreted

• Java Is Robust

• Java Is Secure

• Java Is Architecture-Neutral

• Java Is Portable

• Java Is Multithreaded

• Java Is Dynamic

Because Java is architecture neutral, Java programs are portable. They can be run on any platform without being recompiled.

Page 34: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Characteristics of Java

34

• Java Is Simple

• Java Is Object-Oriented

• Java Is Distributed

• Java Is Interpreted

• Java Is Robust

• Java Is Secure

• Java Is Architecture-Neutral

• Java Is Portable

• Java Is Multithreaded

• Java Is Dynamic

Multithread programming is smoothly integrated in Java, whereas in other languages you have to call procedures specific to the operating system to enable multithreading.

Page 35: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Characteristics of Java

35

• Java Is Simple

• Java Is Object-Oriented

• Java Is Distributed

• Java Is Interpreted

• Java Is Robust

• Java Is Secure

• Java Is Architecture-Neutral

• Java Is Portable

• Java Is Multithreaded

• Java Is Dynamic

Java was designed to adapt to an evolving environment. New code can be loaded on the fly without recompilation. There is no need for developers to create, and for users to install, major new software versions. New features can be incorporated transparently as needed.

Page 36: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

JDK Versions

• JDK 1.02 (1995)

• JDK 1.1 (1996)

• JDK 1.2 (1998)

• JDK 1.3 (2000)

• JDK 1.4 (2002)

• JDK 1.5 (2004) a. k. a. JDK 5 or Java 5

• JDK 1.6 (2006) a. k. a. JDK 6 or Java 6

• JDK 1.7 (2011) a. k. a. JDK 7 or Java 7

• JDK 1.8 (2014) a. k. a. JDK 8 or Java 836

Page 37: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

JDK Editions• Java Standard Edition (Java SE)

Java SE can be used to develop client-side standalone applications or applets.

• Java Enterprise Edition (Java EE)

Java EE can be used to develop server-side applications such as Java servlets and Java ServerPages.

• Java Micro Edition (Java ME).

Java ME can be used to develop applications for mobile devices such as cell phones.

• This book uses Java SE to introduce Java programming. 37

Page 38: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Popular Java IDEs

• NetBeans Open Source by Sun (Oracle now). Most suitable to Java EE for web applications

• Eclipse Open Source by IBM. Most suitable for Java SE and this course.

• Exercise: Prepare your development machine at home, including Eclipse and JDK 8 today. Ask the TAs and lab technicians for help if required.

38

Page 39: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Types

• Recall data type from C – int, char double etc

• Java has 2 kinds of types:

• Primitive types

• Reference types

Page 40: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Primitive types• These are simple types like char, double, int

• Similar to C

• Main difference – the sizes of these types are defined for example an int is 4 bytes

• Each hardware platform has its own 'virtual machine'

• Which all look the same

• So can all have the same data sizes

• All chars use UNICODE character set - so characters are 2 bytes long

Page 41: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Reference types• Reference type variables are objects

• Objects belong to classes

• Objects made by a constructor

Page 42: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Primitive types first• We will look at primitive types first

• and control structures (loops and ifs)

• Then look at classes and objects

Page 43: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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 withIn file Testing.javaCode goes hereExplain rest later

Page 44: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Variables - declaring and assigning

• // starts a line comment

• double radius = 5.0; declares and initialises a variable

• double area declares a variable called area of type double

• variables can be declared anywhere in a block { }

• statements end in ; like C and C++

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

} }

Page 45: CC316: Object Oriented Programming - Manal Helal

45

Primitive data types - numericName Range Sizebyte -27 to 27-1 (-128 to +127) 8 bits

short -215 to 215-1 ( ± 32 000 ) 16 bits

int -231 to 231-1 ( ± 2 500 million ) 32 bits

long -263 to 263-1 (very big!!) 64 bits

float about ±1038, 6/7 sig digits 32 bits

double ±10308, 14/15 sig digits 64 bits

Java data type sizes are platform independent

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;

Page 46: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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 = 511 Decimal (1*16^2 + 15*16^1 + 15 * 16^0

Find out what happens when you compile/run

these 2 lines.

Page 47: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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

Page 48: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Type cast exercise

• Try out• int i;• long x;• x = 32;• i = x;

• In a program, and try to compile and run first.

• Fix it as in the previous slide

Page 49: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Char type

• char is for a single character, like

• char c = ‘A’;// note single quotes

• c++; makes c = ‘B’

• Strings are different - will see later

• Java uses Unicode not ASCII - 16 bits per character.

import java.applet.*; import java.awt.*;

public class TestApplet extends Applet { public void paint(Graphics g) {

char c; Font f = new Font("Arial Unicode MS",Font.PLAIN,20); g.setFont(f); c = '\u098a'; // Unicode constant g.drawString("Some Bengali: " + c,10,30 );

} }

Page 50: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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 =

• && is and || is or ! is not

• result = ( x > y ) && ( y < 5 );result is true if x is greater than y and y is less than 5

Page 51: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Operators

• Operators + - * / as usual

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

51

Page 52: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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

Page 53: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Increment and decrement• x++; is the same as x = x + 1;

• y--; is the same as y = y - 1;

• post-increment is like:

a = b++;which first assigns b to athen increments b

• pre-increment is: a = ++b;which first increments b then assigns the new value to a

Page 54: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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

• (~ 0000 0001) is 1 inverting it results in: 1111 1110

Page 55: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

bit shift operators

• >> is shift righteg if x = 7 or in binary 0000 0111 x >> 1 is 0000 0011

• << is shift left so x << 1 is 0000 1110 = 14

Page 56: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Bit shift exercise

• 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

Page 57: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Operator Precedence• 2 * 3 + 4 is 10 not 14

• 2*(3+4) is 14

• Highest ++ -- Lowest = += -= *= /= %=

* / % Use brackets when in doubt

+ -

< <= > >=

== !=

&&

||

Page 58: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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

Page 59: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

I/O (Input / Output)

// Create a Scanner

Scanner input = new Scanner(System.in);

// Prompt the user to enter a number

System.out.print("Enter a number : ");

int number = input.nextInt();

System.out.println("You entered " + number);

Page 60: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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

Page 61: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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;

Page 62: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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

Page 63: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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

Page 64: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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

Page 65: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

loops - while• loops repeat blocks of code - called iterationExample - 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

Page 66: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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

Page 67: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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

Page 68: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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

Page 69: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

loops - for - III• 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;

Page 70: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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

Page 71: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

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

int [ ] numbers = new int [ 100 ]; creates 100 elements, from numbers[0] to numbers[99]

• array bounds are checked at compile time and run time

Page 72: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Arra

ys -

sorti

ng int [] numbers = new int [5]; //.. put some numbers in the array, then...sort them

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

Page 73: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Array exercise

• Declare an array of 100 doubles

• Fill the array with random numbers (use Math.random(); )

• Print them out

Page 74: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Assignment 1a

• Due date lab day after 2 weeks, 11:30 PM, file name should be:ass1a_YourID.java

• 2.3  (Convert feet into meters) Write a program that reads a number in feet, converts it to meters, and displays the result. One foot is 0.305 meter. Here is a sample run:

Enter a value for feet: 16.5

16.5 feet is 5.0325 meters

Page 75: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Assignment 1b

• Due date Thursday, 6 March 2014, 11:30 PM, file name should be:ass1b_YourID.java

• 3.5 (Find future dates) Write a program that prompts the user to enter an integer for today’s day of the week (Sunday is 0, Monday is 1, . . ., and Saturday is 6). Also prompt the user to enter the number of days after today for a future day and dis- play the future day of the week. Here is a sample run:

Enter today's day: 1

Enter the number of days elapsed since today: 3

Today is Monday and the future day is Thursday

Page 76: CC316: Object Oriented Programming - Manal Helal

OOP in Java : © W. Milner 2005 : Slide

Assignment 1c

• Due date Thursday, 6 March 2014, 11:30 PM, file name should be:ass1c_YourID.java

• **4.7 (Financial application: compute future tuition) Suppose that the tuition for a university is $10,000 this year and increases 5% every year. Write a program that computes the tuition in ten years and the total cost of four years’ worth of tuition starting ten years from now.