Learning the Java Language. 2.1 Object-Oriented Programming

Similar documents
Control Flow Statements

1. Introduction to Java for JAS

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

CSEN 202 Introduction to Computer Programming

JAVA OPERATORS GENERAL

Tony Valderrama, SIPB IAP 2009

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

CONDITIONAL EXECUTION: PART 2

Introduction to Programming Using Java (98-388)

CT 229. Java Syntax 26/09/2006 CT229

CSC 1214: Object-Oriented Programming

Operators and Expressions

Tony Valderrama, SIPB IAP 2010

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Java Basic Programming Constructs

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

13 th Windsor Regional Secondary School Computer Programming Competition

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

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

Operators. Java operators are classified into three categories:

Introduction to. Android Saturday. Yanqiao ZHU Google Camp School of Software Engineering, Tongji University. In courtesy of The Java Tutorials

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

SECTION II: LANGUAGE BASICS

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

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

3. Java - Language Constructs I

Data Types. Lecture2: Java Basics. Wrapper Class. Primitive data types. Bohyung Han CSE, POSTECH

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

The Arithmetic Operators

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Operators in java Operator operands.

WA1278 Introduction to Java Using Eclipse

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

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

CHAPTER 3,4 & 5. Contents:

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

Object-Oriented Programming

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

CS260 Intro to Java & Android 03.Java Language Basics

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Prof. Navrati Saxena TA: Rochak Sachan

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

1. Download the JDK 6, from

JAVA Programming Fundamentals

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

A Java program contains at least one class definition.

CS313D: ADVANCED PROGRAMMING LANGUAGE

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

A flow chart is a graphical or symbolic representation of a process.

Index COPYRIGHTED MATERIAL

Outline. Java Compiler and Virtual Machine. Why Java? Naming Conventions. Classes. COMP9024: Data Structures and Algorithms

CS 231 Data Structures and Algorithms, Fall 2016

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Getting started with Java

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

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

.Net Technologies. Components of.net Framework

Expressions & Flow Control

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

1 Shyam sir JAVA Notes

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

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

Course Outline. Introduction to java

Program Fundamentals

Array. Prepared By - Rifat Shahriyar

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

CS 106 Introduction to Computer Science I

Java Primer 1: Types, Classes and Operators

COP 3330 Final Exam Review

Lexical Considerations

Contents. iii Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services August 1998, Revision B

S.E. Sem. III [CMPN] Object Oriented Programming Methodology

3. Java - Language Constructs I

1.00 Lecture 4. Promotion

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

COMP6700/2140 Operators, Expressions, Statements

Chapter 1 Introduction to Java

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

1007 Imperative Programming Part II

9 Working with the Java Class Library

Week 6: Review. Java is Case Sensitive

Getting started with Java

Zheng-Liang Lu Java Programming 45 / 79

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

STRUCTURING OF PROGRAM

CPSC 319. Week 2 Java Basics. Xiaoyang Liu & Sorting Algorithms

Software Practice 1 Basic Grammar

Software Programming Objectives

SRIVIDYA COLLEGE OF ENGG & TECH INTRODUCTION TO OOP AND JAVA FUNDAMENTALS SVCET. Ada 95 Fortran 2003 PHP since v4, greatly enhanced in v5

Introduction to Java

Session 3. Basic Java Data Types, Control Structures. 8 primitive or built-in data types

Declaration and Memory

Chapter 3: Operators, Expressions and Type Conversion

Informatics Ingeniería en Electrónica y Automática Industrial

Transcription:

Learning the Java Language 2.1 Object-Oriented Programming

What is an Object? Real world is composed by different kind of objects: buildings, men, women, dogs, cars, etc. Each object has its own states and behaviors Behaviors Changing Gear Color = Red Brand = Ferrari Speed = 200 mph Gear = 4 States Steering Accelerating Braking 2

What is a Software Object? Software designers use the same idea to ease programmer to develop their software A software is also composed by different kind of software objects Each software object also has its own states and behaviors Method (Behavior) Press ( ) Variables (States) Color = Grey Size = 2cm x 2cm Shape = Rectangular (protruded) 3

Encapsulation Hiding information within an object s nucleus Provide a public interface for interacting with it Advantages to software developers Modularity: An object can be easily passed around in the system (Otherwise, you need to think about how many files you need to bundle together to pass to your friends) Information hiding: Users need not go into details of the object before using the object (E.g., you don t need to know the circuit of a TV set if you want to watch TV) Safety: Users of the object will not direct access the internal state of the object. This reduces the possibility of erroneous situation 4

What is a Class? A Class is a blueprint or prototype that defines the variables and methods common to all objects of a certain kind Every object of a Class is just an instance of that class Benefit - Reusability This arrangement saves effort in developing a number of objects of the same kind Usually an object is used a number of times in an application 5

The Button Class: Method Press ( ) Variables Color = Grey Size = 2cm x 2cm Shape = Rectangular (protrude) Instantiation Instantiation Instance of Button Class Instance of Button Class 6

What is Inheritance? A Class often has Subclasses which give more specific description of the object All subclasses inherit all states of the parent class Button Button PlaySound Button PlayVideo Button Document 7

Method Press ( ) Variables Color = Grey Size = 2cm x 2cm Shape = Rectangular (protrude) Button Class Play Sound Button Subclass Inherit all variables and methods Add other variables and methods Override some superclass variables and methods Variables Superclass variables Method Color = Grey with Dark Superclass methods Grey icon set(para) *Action = para* Overriding 8

We can have more than one level of inheritance Button Button PlaySound Method Superclass methods set(para) Variables Superclass variables *Action = Applause* **loudness = para** Button Applause Overriding 9

Benefit of Inheritance We need not re-define every aspect of a class from very beginning again All we need to do is to find out what in addition the subclass is different from the parent class 10

What is a Message? Software objects interact and communicate with each other by sending messages Method Press () Variables Color Size loudness Action Shape Play Method Message (Applause) Variables 11

Java is an OO language /** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */ class HelloWorldApp { public static void main(string[] args) { System.out.println("Hello World!"); //Display the string. Method Main(String[] args) Variables HelloWorldApp Class 12

import java.applet.applet; import java.awt.graphics; public class HelloWorld extends Applet { public void paint(graphics g) { g.drawstring("hello world!", 50, 25); Applet Method Applet Class Variables Method paint(graphics g) Variables HelloWorld Subclass 13

Exercise 1 Make use of the Java Workshop 2.0 to create a project to run the applet HelloWorld The result should look like the one on the right 14

Exercise 2 Make use of the Java Workshop 2.0 to create a project to run the Standalone application Count It counts the no. of characters in an ASCII file Try to run Count on any ASCII file to count the no. of characters import java.io.*; public class Count { public static void countchars(inputstream in) throws IOException { int count = 0; while (in.read()!= -1) count++; System.out.println("Counted " + count + " chars."); public static void main(string[] args) throws Exception { if (args.length >= 1) countchars(new FileInputStream(args[0])); else System.err.println("Usage: Count filename"); 15

Learning the Java Language 2.2 The Nuts and Bolts 16

Basic Constructs of a Java Program a. Classes, Methods and Objects b. Variables and Data Types c. Operators d. Expressions e. Control Flow Statements f. Arrays and Strings 17

A. Classes, Methods and Objects Classes define the states and behaviors of objects The states of an object are defined by its variables The behaviors of an object are defined by its methods The class Count has two methods: countchars and Main Every Java program must have a Main method It is the start of the program import java.io.*; public class Count { // countchars method omitted // public static void main(string[] args) throws Exception { if (args.length >= 1) countchars(new FileInputStream(args[0])); else System.err.println("Usage: Count filename"); 18

A method often needs objects from other classes to help its operation The countchars method processes the object named in, which belongs to the InputStream class One of the methods contained in the InputStream class is read It will read the data of the stream one-by-one import java.io.*; public class Count { public static void countchars(inputstream in) throws IOException { int count = 0; while (in.read()!= -1) count++; System.out.println("Counted " + count + " chars."); // main method omitted // Note: we only refer to the read method of a particular object named in. We do not refer to other objects of this class 19

Exercise: Rename the method main to start, note the error message when building the project 20

B. Variables and Data Types Variables are entities that act or are acted upon in the software object In the method countchars, two variables, in and count, are defined A variable must be declared once in a program A variable declaration always contains two components Type and Name import java.io.*; public class Count { public static void countchars(inputstream in) throws IOException { Type Name int count = 0; while (in.read()!= -1) count++; System.out.println("Counted " + count + " chars."); // main method omitted // 21

Data types - Two categories: primitive and reference Primitive Types - usually contains a single value of particular size and format - hardware independent Type Size/Format Description Integers byte 8-bit two s complement Byte-length integer short 16-bit two s complement Short integer int 32-bit two s complement Integer long 64-bit two s complement Long Integer Real Numbers float 32-bit IEEE 754 Single-precision floating-point double 64-bit IEEE 754 Double-precision floating-point Other Types char 16-bit Unicode character A single character boolean true or false A boolean value (true or false) 22

Arrays, classes, and interfaces are reference types A reference type variable is a reference to the actual value or set of values represented by the variable For example: Just like the address of your friend The address is not your friend, it is just a way to reach your friend Count is primitive type variable in is reference type variable import java.io.*; public class Count { public static void countchars(inputstream in) throws IOException { int count = 0; while (in.read()!= -1) : // main method omitted // 23

Scope A variable s scope is the block of code within which the variable is accessible The location of the variable declaration within the program determines its scope Depending on the locations, a variable can be categorized into: Member variable Local variable Method parameter Exception-handler parameter 24

25

In the Count class, there is no Member Variable In countchars, in is method parameter Its scope includes In countchars, count is local variable Its scope includes No exception handling parameter is found import java.io.*; public class Count { public static void countchars(inputstream in) throws IOException { int count = 0; while (in.read()!= -1) count++; System.out.println("Counted " + count + " chars."); public static void main(string[] args) throws Exception { : 26

Exercise : Modify the following statement in the Count class int Count = 0; to int Count = 10000; Note the output when executing the program 27

Exercise : Identify the member variables, method parameters, local variables, exception handling parameters of the following program and determine their scopes import import java.io.*; class class Parent Parent {{ public public int int anum anum = 2 ;; public public int int increment (int (int bnum) bnum) {{ return return (bnum (bnum + 1); 1); public public class class Child Child extends extends Parent{ Parent{ int int anum anum ;; public public Child Child () (){{ this.anum = increment( super.anum); public public static static void void main main (String[] args) args) {{ Child Child t t = new new Child(); System.out.println("Result = " + t.anum); 28

C. Operators The operators in Java can be divided into 4 categories arithmetic relational and conditional bitwise and logical assignment These operators can be unary e.g. count++; // arithmetic operator: autoincrement count or binary e.g. count = 0; // assignment operator: assign 0 to count or tertiary e.g. expr? op1 : op2 //if expr is true, then do op1, otherwise do op2 29

Java arithmetic operators Operator Use Description + op1 + op2 Adds op1 and op2 - op1 op2 Subtracts op2 from op1 * op1 * op2 Multiplies op1 and op2 / op1 / op2 Divide op1 by op2 % op1 % op2 Computes the remainder of dividing op1 by op2 The + operator can also be used to concatenate strings e.g. System.out.println ( Counted + count + chars. ); The ++ and -- operators are the shorthand of increment by 1 and decrement by 1 e.g. count++; // equivalent to count = count + 1; 30

Java relational operators Relational Use Return true if... Operator > op1 > op2 op1 is greater than op2 >= op1 >= op2 op1 is greater than or equal to op2 < op1 < op2 op1 is less than op2 <= op1 <= op2 op1 is less than or equal to op2 == op1 == op2 op1 and op2 are equal!= op1!= op2 op1 and op2 are not equal instanceof op1 instanceof op2 op1 and op2 are assignment compatible 31

Java conditional operators Conditional Use Return true if... Operator && op1 && op2 op1 and op2 are both true; conditionally evaluates op2. op1 op2 either op1 or op2 is true; conditionally evaluates op2.! op1! op2 op1 is false & op1 & op2 op1 and op2 are both true; always evaluates op1 and op2. op1 op2 either op1 or op2 is true; always evaluates op1 and op2. E.g. a = 0; b = 0; c = 0; if (a++ == 0 && b++ == 0) { c = 10; Answer: a = 1; b = 0; c = 0. E.g. a =0; b = 0; c = 0; if (a++ == 0 & b++ == 0) {c = 10; Answer: a = 1; b = 1; c = 0. 32

Java bitwise and logical operators Operator Use Operation >> op1 >> op2 Shifts bits of op1 right by distance op2 << op1 << op2 Shifts bits of op1 left by distance op2 >>> op1 >>> op2 Shifts bits of 1 right by distance op2 (unsigned) & op1 & op2 Performs the bitwise and.. op1 op2 Performs the bitwise or. ^ op1 ^ op2 Performs the bitwise xor. ~ ~ op1 Performs the bitwise complement. E.g. int a = -2; a = a >> 1; // a = 111... 110; a >>1 = 111... 111; Answer: a = -1. E.g. int a = -2; a = a >>> 1; // a = 111... 110; a >>> 1 = 011... 111 Answer: a = 2,147,483,647. 33

The operators & and are bitwise logical operators They can be applied to different types of variables E.g. boolean a = true; a = false; c = a & b; Answer: c = false. E.g. byte a = 1; b = 2; c = a & b; // a = 00000001; b = 00000010; Answer: c = 0 // c = a & b = 00000000. 34

Java assignment operators Java provides several shortcut assignment operators Operator Use Equivalent to += op1 += op2 op1 = op1 + op2 -= op1 -= op2 op1 = op1 - op2 *= op1 *= op2 op1 = op1 * op2 /= op1 /= op2 op1 = op1 / op2 %= op1 %= op2 op1 = op1 % op2 &= op1 &= op2 op1 = op1 & op2 = op1 = op2 op1 = op1 op2 ^= op1 ^= op2 op1 = op1 ^ op2 <<= op1 <<= op2 op1 = op1 << op2 >>= op1 >>= op2 op1 = op1 >> op2 >>>= op1 >>>= op2 op1 = op1 >>> op2 35

Exercise: Modify the program of Count such that you will print out a message to indicate the total number of characters is an even or odd number. Hint: Add an if statement to test the total number of characters is odd or even Test can be done by getting the remainder when the character number is divided by 2 36

D. Expressions An expression is a series of variables, operators, and method calls that evaluates to a single value E.g. count++; // variable: count; operators: ++; return count = count +1 E.g. in.read(); // method call: read(); result: return of in.read() A Java statement can comprise several expressions E.g. in.read()!= -1; // Two expressions in this statement The evaluation of expression is usually from left to right E.g. in.read()!= -1; // in.read() is evaluated first followed by the // relational operator!= The order can be changed due to the precedence of operators E.g. x + y / 100; // division will do first and then addition E.g. (x + y) / 100; // addition done first due to the ( ) 37

E. Control Flow Statements The while statement performs some actions while a certain condition remains true General syntax while (expression) { statement; // do statement if expression is true The { can be omitted if the statement has only one statement import java.io.*; public class Count { public static void countchars(inputstream in) throws IOException { int count = 0; while (in.read()!= -1) count++; System.out.println("Counted " + count + " chars."); // main method omitted // 38

Besides while, Java supports several other control flow statements Type of Statement Decision-making Loop Exception Branching Keyword if-else, switch-case for, while, do-while try-catch-finally, throw break, continue, label:, return Normal program execution is from up to down sequentially These statements change the flow of program execution depended on the condition 39

Decision Making if-else statement is particularly suitable for making decision based on a ranges of values or conditions E.g. int testscore; char grade; if (testscore >= 90) { grade = 'A'; else if (testscore >= 80) { grade = 'B'; else if (testscore >= 70) { grade = 'C'; else if (testscore >= 60) { grade = 'D'; else { grade = 'F'; 40

switch-case statement is particularly suitable for making decision based on a single value. E.g., int month; switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; 41

The above example can also be implemented by if-else statement. However, it will be much longer int month;... if (month == 1) { System.out.println("January"); else if (month == 2) { System.out.println("February"); : : else if (month == 11) { System.out.println( November"); else if (month == 12) { System.out.println( December");... 42

The switch-case statement can combine with the break or default statements. E.g., int month, numdays; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numdays = 31; break; case 4: case 6: case 9: case 11: numdays = 30; break; case 2: if ( ((year % 4 == 0) &&!(year % 100 == 0)) (year % 400 == 0) ) numdays = 29; else numdays = 28; break; default: System.out.println( Hey, that s not a valid month! ); break; 43

Loop Statements Java supports three loop statements while, for, and do-while For loop is useful when we know the constraints of the loop. E.g., // calculate the factorial 10 // int i; int length = 10; int fac = 1; for (i = 1; i <= length; i++) { fac *= i; The loop will stop when i = 11 44

The do-while loop is less commonly used It is useful if the loop has to do at least once It does the statement before testing the condition For example, the countchars method can be modified as follows: int c; InputStream in;... do { c = in.read();... while (c!= -1); It is exactly the same as the while loop used before 45

Branching Statements Java supports three branching statements break, return (more commonly used) and continue (less used) The break statements have labeled or unlabeled form. E.g., // calculate the factorials of 3,5,7,9,11; Quit if > 1048576 int i, j, fac = 1; factorial: Cannot use break for (j = 3; j <= 11; j+=2) { fac = 1; here since break will for (i = 1; i<=j; i++) { only break the inner fac *= i; for for loop if (fac > 1048576) { System.out.println( Too big ); break factorial; System.out.println( Factorial of +j+ = +fac); 46

Exercise: Build the program on the last page. Note the results. Modify the statement break factorial to break. Execute the program again. Note the results. Do you get the correct results? Why? 47

F. Arrays and Strings Like other languages, Java allows one to collect and manage multiple values through an array object Declaration of array is simple, e.g. int [] arrayofints; // arrayofints is an array of integers Note that just declaration is not enough in order to use an array. One needs to allocate memory for it Memory can be allocated to array using the new operator. E.g. int [] arrayofints = new int[10]; // arrayofints is an array of integers with 10 elements 48

Now, you can use it. E.g. for (int j = 0; j <= arrayofints.length; j ++) { arrayofints[j] = j; System.out.println("[j] = " + arrayofints[j]); Result: [0] = 0 [1] = 1 : [arrayofints. length] = arrayofints. length Note that length is a property provided for all Java arrays It gives the number of elements of an array 49

An array of string called args is passed to the main method The Java runtime allocates the space for the args array import java.io.*; public class Count { // countchars method omitted // public static void main(string[] args) throws Exception { if (args.length >= 1) countchars(new FileInputStream(args[0])); else System.err.println("Usage: Count filename"); String str A sequence of characters str t e s t. t x t String [ ] args Many sequences of characters args[0] args[1] args[2] t e s t. t x t t s t 1 2 3 t 50

Exercise: Modify the program of Count such that it will show the number of characters of two files. Both the filename and its number of characters are printed out on the screen. The filenames are input in the command line. 51