core concepts of programming - york u

22
Object-Based Programming: JAVA Fundamentals Summary Page 1 of 23 Core Concepts of Programming Programming deals with real world objects and convert them into data that can be manipulated using a programming language. A video store objects include: 1. The Store 2. The Movies 3. The People Java allows us to model the objects by creating classes: Classes are "blue prints" that define - an object's properties such as movie titles, directors, etc. and its behavior, e.g.; how these movies 'behave', e.g., rented or bought; The core concepts are essential for making these real world objects into classes that you can work with in programming. Data types Variables Objects Classes Methods Method parameters Return types and values Creating objects Accessors and Mutators Data Types Different data types can be used in various ways depending on the type. Strings are used to form words; sentences, etc. that require sequence of characters or values wrapped in double quotes ("…") Derives from the Java String class String literals can contain any valid Unicode characters: alpha-numeric and symbols or no characters at all (null). A string literal cannot span multiple lines but can be concatenated using the "+" sign

Upload: others

Post on 20-Jan-2022

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 1 of 23

Core Concepts of Programming • Programming deals with real world objects and convert them into data that can be manipulated

using a programming language.

A video store objects include:

1. The Store

2. The Movies

3. The People

Java allows us to model the objects by creating classes:

Classes are "blue prints" that define -

• an object's properties such as movie titles, directors, etc. and

• its behavior, e.g.; how these movies 'behave', e.g., rented or bought;

The core concepts are essential for making these real world objects into classes that you can work with

in programming.

• Data types

• Variables

• Objects

• Classes

• Methods

• Method parameters

• Return types and values

• Creating objects

• Accessors and Mutators

Data Types

• Different data types can be used in various ways depending on the type.

Strings are used to form words; sentences, etc. that require sequence of characters or values

wrapped in double quotes ("…")

• Derives from the Java String class

• String literals can contain any valid Unicode characters: alpha-numeric and symbols or no

characters at all (null).

• A string literal cannot span multiple lines but can be concatenated using the "+" sign

Page 2: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 2 of 23

• There are also certain special characters in Java require escape sequences for display

using the backslash-symbol combination:

\b - backspace \t – tab \n – newline \r - carriage return;

\" – 2x quote \' - 1x quote \\ - backslash

// Displaying double quotes

System.out.println( "The first little piggy said " +

"\"Not by the hair of my chinny chin chin!\"")

More things you can do with strings:

String greeting = "Hello!"

// Change the case

System.out.println(greeting.toUpperCase())

System.out.println(greeting.toLowerCase())

String phrase = "Time flies like an arrow."

// Extract a part of a string (substring) using the starting and ending index values

String substring = phrase.substring(5, 10);

// Output the extracted string

System.out.println(substring);

// Replace a substring

String phrase2 = phrase.replace("arrow", "air plane");

// Check for matching substring

If (substring.equals( "flies" )) {

System.out.println( "Matching string exists in the phrase." );

} else {

System.out.println( "No Matching string exists in the phrase." );

}

}

Numbers are primitive type, i.e., there is no associated class behind them – literal

• Integers (+/-, 0 whole numbers) – do not use commas

• Doubles – floating point - use decimal form

• Exponentiation – e.g., 12.0E2 = 144.0

• Boolean – TRUE / FALSE

• When doing calculations, remember the order of operations.

Page 3: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 3 of 23

Casting Casting converts one data type to another data type

public class TypeCasting {

public static void main(String[] args) {

double dNum = 34.59; // double value

int iNum = (int) dNum; // place the type spec (int) to

// convert double to integer

System.out.println(iNum);

String sNum = "50"; // string value

iNum = Integer.parseInt(sNum); // parseInt method in Interger class

// converts string to integer

System.out.println(iNum);

}

}

Variables • Variables allow storing values in memory and make it easy to reuse stored values

• We had to learn about types before we can work with variables because creating a new variable

requires declaring the type of value to be stored.

Variable Identifiers

• Variable names are case-sensitive

• Begin with a lower-case letter only and

• for the rest of the name letters, numbers, underscore and dollar sign are allowed – but most

do not use the $ by convention

• Reserved words are obviously NOT allowed

String Variable Declaration

Consists of three components:

1. Type – e.g. String, int, double, boolean, etc.

2. identifier/name – e.g. myCourses - Use camel-case for names with multiple words

3. contents assigned - e.g. "ITEC 1620"

Page 4: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 4 of 23

Assigning Variables Examples:

// Create String variables and assign values

String motto = "Do the best!";

String newMotto = "Be the best!" ;

// Reassign a variable

newMotto = "Do the best and be the best!" ;

// Output the reassigned content

System.out.println(newMoto);

// Integer variable

int year = 2014

// Double variable

double pi = 3.14

// Variable within a variable

int nextYear = year + 1

Static Variables • Static variables a.k.a. class variables belong to a class;

• Used to hold a value that may be common to all instances of a class; they are not instances of

the class

Public class HockeyTourney {

// these are instance variables

private String team1

private String team2

// this is a static variable belonging to the class

private static int gamesPlayed = 0;

Objects, Classes and Methods

Objects are values that refer to an instance of a class that can be manipulated using one of its

methods.

• Objects can represent anything.

• An instance of a class is an object of that class.

• Class is a way to package an object and define the properties and methods of that object.

Page 5: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 5 of 23

Method contains instructions for how to manipulate the object. (Java API or defined somewhere

else.)

• Only methods defined within a class can be called or invoked.

• To call or invoke a method on an object use the "dot notation".

• This statement returns the count of characters in the motto string, and store the integer

value to a variable named mLength

int mLength = motto.length();

Static Method • Static methods do not require an object to call the method

• Use the class name and dot notation to call static methods

• Static method cannot access regular instance variables or methods directly without an object

public class HockeyTourney {

public static int getTotalGamesPlayed() {

// Method codes

}

}

// Calling a static method

HockeyTourney.getTotalGamesPlayed();

Creating a static method Example: Creating our HockeyTourney class will follow these stages in the process:

1. Declare variables – instance & static

2. Build a constructor

3. Create methods – normal and static

4. Fill in data

5. Generate the output

1. To start, at the top of the class create some instance variables to hold the team names

Public class HockeyTourney {

private String team1 // instance variable

private String team2 // instance variable

and a static variable to hold the count of games played.

private static int gamesPlayed = 0; // static variable

Page 6: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 6 of 23

• The static variable, gamesPlayed is also assigned a default value so that each time a new

hockey game object is constructed, the static variable's value is incremented for tracking the

total # of games played.

• This variable now belongs to the class and not the instance of the class which are individual

games.

2. Next build a constructor to set up our instance and static variables …

• This constructor accepts parameters passed to it representing the 2 teams.

• The name of the constructor is the same as our class name.

public HockeyTourney (String teamOne, String teamTwo) {

team1 = teamOne;

team2 = teamTwo;

gamesPlayed++; // increment static variable each time

// a game object is created

3. Now we create a method we can use to get the names of the teams that are playing in the game.

• After our main method, create the new methods.

• The getTeams method returns a string that outputs the teams playing the game using

concatenations.

public String getTeams() {

return "Today's match is the " + team1 + "vs. the " + team2;

• The getGamesPlayed gives us how many games have been played by returning the value of the

gamesPlayed static variable.

public static int getGamesPlayed() {

return gamesPlayed;

}

4. The HockeyTourney class is completed. We can try it out by filling in our main method with games.

• To create some HockeyTourney objects, start with its type: HockeyTourney; its identifier:

game1; then call the constructor by passing it some team names.

public static void main(String[] args) {

hockeyTourney game1 = new HockeyTourney("Blades", "Howlers");

hockeyTourney game2 = new HockeyTourney("Jets", "Cougars")

Page 7: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 7 of 23

5. Each game object has its own set of team1 and team2 instance variables to output the names of

the teams playing in each game.

System.out.println(game1.getTeams());

System.out.println(game2.getTeams());

• Now we can call our static method to get the total number of games played.

• To access the static method, only the call to the class name and the dot notation is required, no

object – HockeyTourney.getGamesPlayed() – so to display the value:

System.out.println(HockeyTourney.getGamesPlayed());

// HockeyTourney Class – output team pairs and the total number of

// games played – Using static variable and method example

Public class HockeyTourney { //variables

private String team1

private String team2

private static int gamesPlayed = 0; // static variable

public HockeyTourney (String teamOne, String teamTwo) { // constructor

team1 = teamOne;

team2 = teamTwo;

gamesPlayed++;

public static void main(String[] args) {

hockeyTourney game1 = new HockeyTourney("Blades", "Howlers"); // game data

hockeyTourney game2 = new HockeyTourney("Jets", "Cougars")

System.out.println(game1.getTeams()); // method calls

System.out.println(game2.getTeams());

System.out.println(HockeyTourney.getGamesPlayed());

public String getTeams() { // normal method

return "Today's match is "+team1+"vs. "+team2;

}

Public static int getGamesPlayed() { // static method

return gamesPlayed;

}

Page 8: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 8 of 23

Parameters vs. Arguments A Parameter is some type of input that the method requires to execute its instructions.

• For Example, the println method is defined as accepting one parameter of type String named x.

Public void println(String x)

• x is a variable that contains whatever is passed into the method

• the x variable in this case is referred to as a parameter; not as an argument

The term parameter refers to the method's definition of the parameter; the term argument is used

when the method is invoked or called

• these arguments or parameters are called "explicit" parameters

• there is also an "implicit" parameter – the object on which the method is called.

System.out.println("string");

• The System.out object is the implicit parameter needed to call the println method

• The input, "string" passed onto the println method is the explicit parameter

• Some methods require a single parameter; some require multiple parameters; some require

none

Method Return Types and Values Recall the expression: Int length = motto.length();

• the String class' length method returned the integer character count and allowed us to store

that value to the variable 'length'; this is called the "return value"

• Methods can have return types and the type is defined when the method is declared

• Knowing what a method returns back is important in knowing how to use a method

• As per Java API, the definition of the length method is:

public int length()

• The int indicates that this method will return a value of the type integer which can then be

stored in a variable.

• Here is a more succinct expression to assign itemLength to the return value of item.length() call:

int itemLength = item.length();

Page 9: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 9 of 23

To summarize:

• A parameter is an input that is passed to a method.

• A method's definition of what the method accepts, is called a parameter.

– Implicit parameter is the object that you call your method on

– Explicit parameter is the input that is passed into the method as an argument.

• An argument is passed to a method that requires a parameter when you invoke a method

• Methods can have return types and values –

– A return type is declared when a method is defined

– A value of the return type is returned when the method is completed

Instantiating Objects • Although System.out and String do not require instantiation processes but most objects in Java

require instantiating a new object, i.e., creating a new instance or an object of that class, before

working with it.

• Classes are stored in packages, i.e., collection of classes.

Constructors

A constructor method is a special method inside of a class;

• Named the same as the class

• Invoked to create/construct a new object from that class.

• Has no return type

• Cannot be called on an object as we do with the String class' length() method

• Can only be used with the new operator

String name;

name = new String("Ariel");

• After the new operator creates the object, name, a String constructor is invoked to set it up

initially.

• Then we can use the dot operator to access its methods

count = name.length() //object reference

Page 10: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 10 of 23

Accessors and Mutator Methods

Accessor methods (getters) are methods that only retrieve and return data about the object.

public String getName()

{

return name;

}

Mutator methods (setters) do manipulate the object by changing its internal data.

public void setName(String grade)

{

name = grade;

}

Defining a Private Implementation:

Instance Variables • When working with classes, we can create an object from a class and invoke that class' methods

that manipulate the object's data.

• But, we need some location to store that data.

• Instance variables are variables that each instance of a class, or object, will have access to in

order to store data

Instance Variables have 4 Components similar to regular variables:

1. Access Specifier

2. Type

3. Identifier

4. Contents

Access Specifier specifies which parts of our program are allowed to directly modify or use an instance

variable, method, or class.

Access Specifier Types

1. Public – the instance variable, method or class is accessible from everywhere

2. Private – … accessible from its own class

3. Protected – … accessible in its own package or subclasses (not covered in this course)

• In the below, the instance variable comes into play and defines it to hold the balance value.

public class BankAccount {

private int balance; //specify a property of the class BankAccount

}

Page 11: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 11 of 23

• Each time we create an instance of the BankAccount, that object will have its own balance value

stored for it.

Typically, instance variables are placed at the top inside the class

• start with the access specifier, e.g., private, so that only this class can directly manipulate this

instance variable

• then the type, e.g., int

• then the identifier – its name, e.g., balance

Note in the above example, there is no content – contents are typically set in the constructor

method or through another method.

In most cases, private instance variable specifiers should be used to deal with internal data used by your

objects:

increase reliability of the program by preventing the use of data in unexpected ways and break

your program

private implementation forces the use of Public Interface (method written to allow users to

manipulate your data properly)

Interface: an abstract class provides a template for further development.

• The purpose of an abstract class is to provide a common interface.

Public Interface consists of the methods that will be available to access and manipulate the data that

is stored in instance variables.

Encapsulation refers to hiding your instance variable from public use while providing methods to

access them.

• Makes your class easier for others to use because they don't have to worry about the internal

data of your class.

• users can just call the methods available to achieve their goals

Constant (variable)

• the value of a constant cannot be changed after being created, i.e., the value is final

• The keyword "final" is used to declare a constant.

• You can create static constants or instance constants.

public class Constants {

private static final String lastLecture = "December 3"

public static void main(String[] args) {

final String examDay = "December 22";

}

}

Page 12: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 12 of 23

Variable Scope

• The scope of a variable determines its accessibility

• Instance variables are accessible to all your methods

• A local variable created inside of a method is only available inside that method

• Local variables created inside of "if" statements or a for loop and other blocks of code are only

available inside of that statement.

The Scanner Class

• We can accept basic user input using the Scanner class.

• To begin accepting user input, the Scanner class must first be imported.

import java.util.Scanner // Java's util.Scanner package

Creating A Scanner Object

• We create a scanner object where the constructor accepts a parameter that indicates the source

of the input

Scanner input = new Scanner(System.in);

• The System.in object is by default keyboard input

• After the new operator creates the object, a constructor is invoked to help set it up initially.

• Now, provide a prompt for user input:

System.out.println("Enter the name of the movie.");

• Now use the Scanner's input object and call its nextLine method to take in an entire line of input

as sequence of characters and store them; then output them it back to us.

String mTitle = input.nextLine(); // accept & store string input

System.out.println("Enter the release date.");

int rDate = input.nextInt(); // accept & store int input

System.out.println(mTitle + " was released in " + rDate +"."); }

Creating Methods Thus far we have seen what methods are; how to call methods; how methods have parameters,

arguments and return types. Now we are ready to create our own methods.

Page 13: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 13 of 23

There are 5 Main Components of Methods

1. Access Specifier

2. Return Type

3. Identifier

4. Parameters

5. Instructions

Here are some sample methods for a public interface of the CreditCard Class:

public class CreditCard{

// Instance variables list

private int limit;

private int balance;

private String cardName;

private int purchases;

}

//Construct a credit card with a preset limit with supplied name

public CreditCard(String name)

// Fill instance variables with content

limit = 500; // preset initial credit limit

balance = 0; // initial opening balance

cardName = name; // name passed when instantiated

purchases = 0 // no purchases initially

//Construct a credit card with a preset limit and a supplied name

public CreditCard(String name)

// Fill instance variables with content

limit = 500; // preset initial credit limit

balance = 0; // initial opening balance

cardName = name; // name passed when instantiated

purchases = 0 // no purchases initially

//Constructs credit card with a supplied credit limit and a name

public CreditCard(String name, int amount){

limit = amount;

balance = 0;

cardName = name;

purchases = 0;

Page 14: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 14 of 23

// Accessors for retrieving data

// Gets the credit limit of the card.

public int getLimit() {

return limit;

}

// Accessor - Gets the value of the credit card balance

public int getBalance() {

return balance;

}

// Accessor - Gets the cardName

public String getCardName(){

return cardName;

}

// Mutators for manipulating data

// Makes a purchase – increase the balance of the card

public void makePurchase(int amount){

int creditAvailable = limit – balance

if (amount > creditAvailable) {

balance = balance + amount + 25;

} else {

// add the purchase amount passed to the balance

balance = balance + amount;

purchases++; // increment purchase count

}

}

// Makes a payment – decrease the balance

public void makePayment(int amount) {

// subtract the amount of the payment passed balance = balance - amount;

}

// Calculates the number of loyalty reward points;

// use the for loop method to loop over each card holder and

// for each purchase add 100 points

public int calcPoints () {

int points = 0;

for (int i = 0; i < purchases; i++) {

points = points + 100;

}

return points;

Page 15: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 15 of 23

Flow Control Statements • used to control the paths that programs take

1. if; elseif; else

2. nested ifs

3. switch

4. while loop

5. do while loop

6. for loop

"if " Statements

• check for a condition using relational and Boolean operators;

• if the condition is met, perform specified task

Relational Operators

== Equal to

!= Not Equal to

< Less than

<= Less than or Equal to

> Greater than

>= Greater than or Equal to

int balance = 999

if (balance < 1000) {

// do this

}

Boolean Operators – AND and OR

int balance = 999

if (balance > 0 && balance < 1000) { // AND – "&&"

// do this

}

int balance = 500

if (balance == 50 || balance == 500) { // OR – "||"

// do this

}

"else if" Statements

• if the preceding condition is not met then …

int balance = 99

if (balance > 0 && balance < 50) {

// do this

} else if (balance > 50 && < 100) {

// do that instead

}

Page 16: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 16 of 23

"else" Statement – specifies what to do if none of the conditions are met

int balance = 250

if (balance > 0 && balance < 50) { // FALSE

// do this

} else if (balance > 50 && < 100) { // FALSE

// do that instead

} else {

// do this if no other condition is met

}

public class IfStatements {

Public static void main(String[] args) {

// if, else if, and else statements

int number = 22

if (number == 0 || number ==20)

System.out.println("The number is equal to 0 or 20");

} else if (number > 15 && number < 40) {

System.out.println("Between 15 and 40");

} else {

System.out.println("Out of bounds!");

}

}

}

Performing Multiple Checks with The Nested "if" Statements

String gender = "male";

int age = 25;

if (gender.equalsIgnoreCase("female")) { // if "female"

if (age > 20) { // check age

System.out.println("You are a male over the age of 20");

} else {

System.out.println("You are a female under the age of 20");

}

} else { // if not "female"

if (age > 20) { // check age

System.out.println("You are a male over the age of 20");

} else {

System.out.println("You are a male under the age of 20");

}

Page 17: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 17 of 23

The Switch Statement

• An alternative to using several if and else ifs

int month = 3;

if (month == 1) {

System.out.println("January");

} else if (month == 2) {

System.out.println("February");

} else if (month == 3) {

System.out.println("March");

} ….. // can be repetitive and tedious

public class SwitchStatement {

Public static void main(String[] args) {

// the switch statement – Useful for checking single values

int month = 2

switch (month) { // month is the value to be compared

case 1: System.out.println("It is January!"); break; // break; preempts the flow

case 2: System.out.println("It is February!"); break;

case 3: System.out.println("It is March!"); break;

case 4: System.out.println("It is April!"); break;

case 5: System.out.println("It is May!"); break;

case 6: System.out.println("It is June!"); break;

case 7: System.out.println("It is July!"); break;

case 8: System.out.println("It is August!"); break;

case 9: System.out.println("It is September!"); break;

case 10: System.out.println("It is October!"); break;

case 11: System.out.println("It is November!"); break;

case 12: System.out.println("It is December!"); break;

default: System.out.println("Invalid Month");

}

}

Loops • a.k.a. iteration or running some code repeatedly

The While Loop

while (condition) {

// check condition first then do repeatedly // while condition = TRUE

// beware of infinite loop

}

Page 18: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 18 of 23

The Do While Loop

do {

// do at least once then repeatedly

// while condition = TRUE

// beware of infinite loop

} while (condition);

The for loop is similar to the more generic while loop

• Use when the number of iteration is known or calculable.

The for loop consists of 3 statements

1. initializer: the value to be used as the starting point of the loop

2. condition: to be evaluated TRUE or FALSE

3. increment: increments the initializer after each successful loop

for (initializer; condition; increment) {

//do repeatedly while condition = TRUE

}

Looping Examples:

//__while loop__Count from 1 to 10________

int number = 1 // initializer

while (number <= 10) {

System.out.println(number);

number++; // increment number by 1

// to ensure against infinite loop

}

//----do while loop----Count from 11 to 20------------

int number2 = 11 // initializer

do {

System.out.println(number);

number2++; // increment number2 by 1

// to ensure against infinite loop

} while (number2 <= 20);

//------for loop-------Count from 21 to 30--------------

for (int i = 21; i <= 30; i++) {

System.out.println(i);

}

Page 19: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 19 of 23

Arrays • Arrays allow us to store, organize and manipulate groups of data

• An array :

– consists of a group of data values of the same type - called elements

– Fixed size – the number of elements cannot change once declared

– accessed by an index number – the element's position in the array counting from [0]

Creating Arrays

Example 1. An array of odd numbers

int[] oddNums = new int[5] // [] to indicate an array object

oddNums[0] = 1;

oddNums[1] = 3;

oddNums[2] = 5;

oddNums[3] = 7;

oddNums[4] = 9;

Example 2. An array of odd numbers

int[] oddNums = {1,3,5,7,9};

Accessing Array Values

int[] oddNums = {1,3,5,7,9};

// print out the integer value 7 of index #3

System.out.println(oddNums[3]);

ArrayLists

• ArrayLists are similar to normal arrays that group values of the same type

• But unlike the normal array, the size can be changed by adding or deleting elements.

// Creating an ArrayList

ArrayList<String> teamList = new ArrayList<String>();

// Using the add method to insert values

teamList.add("Maple Leafs");

teamList.add(“Oilers");

teamList.add(“Jets");

teamList.add(“Canadians");

Page 20: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 20 of 23

// Using the remove method to delete values

teamList.remove(3)

// Using the get method to output the String value

System.out.println(teamList.get(1));

Nested Loops

• A nested loop is one loop inside of another loop

• Nested loops are helpful when working with two dimensional (2D) arrays

• 2D array allows you to store data in tabular fashion – with rows and columns – an array of

arrays

2D Arrays • We can build a table of data type examples by first storing 3 separate arrays.

String[] strings = { "Hello", "Ciao", "Aloha" };

String[] integers = { "1", "25", "999" };

String[] doubles = { "98.6", "1.34", "451.0" };

• Now we can store the separate arrays into a single array.

• The two sets of [] represent rows and columns through which their indexes can be accessed.

String[][] dataTypes = { strings, integers, doubles};

• Now we have 3 different arrays of strings, integers and doubles; and inside of those rows, we

have 3 columns of data, i.e., 9-element, 2-dimensional array.

strings "Hello" "Ciao" "Aloha"

integers 1 25 999

doubles 98.6 1.34 451.0

• A 2D array just contains a set of indexes, one for the row and one for the column.

• To access the data in our 2D array, we use the row and the column.

System.out.println(dataTypes[0] [1]); // index r0,c1 == Ciao

System.out.println(dataTypes[2] [2]); // index r2,c2 == 451.0

Now we can use a nested loop to make it simple to loop over the 2D array and output all of the values.

Page 21: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 21 of 23

We can use a common iteration variable name, i for our counter to loop over the rows while i is

less-than the length of the array and then increment the i variable.

for (int i = 0; i < dataType.length(); i++) { // normal loop over rows

But since our array is a 2D array, we need another loop to use for the columns.

For this loop we use another counter name j because duplicate variable names are not allowed.

And for the conditional we'll check while j is less-than the length of the dataType array's columns.

• To do this we use the outer loop's i variable for the row index so that we can get the length of

the columns of our array.

for (int j = 0; j < dataType[i].length(); j++) {

So:

• In the first iteration, row is i which is index 0, the strings row;

• then get its length which is the number of its columns;

• then continue to the next row, the integers row;

• then finally to the doubles row – looping over all of the row and all of the columns.

To finish our loop, we can output the contents inside the second loop.

• Using the dataType array, pass in the i variable as the row, and pass in the j variable as the

column.

• So the nested loop will go through all the elements of the table and output them.

for (int i = 0; i < dataType.length; i++) {

for (int j = 0; j < dataType[ i ].length(); j++) {

System.out.println(dataType[ i ][ j ]);

}

}

Cohesion and Coupling

Classes should be as cohesive as possible:

• Classes should model a single entity

• Goal-specific and focus on a well-defined role – single responsibility

• Avoid modeling multiple objects in one class

• Aim for related methods and instance variables that result in highly cohesive classes

Cohesive Classes are Benefial

• Modularization creates proper boundaries between the parts that compose a system and thus

minimizes complexity

• High-cohesion classes are easier to read, understand, and reuse, because it deals with one

specific entity.

• Cohesive classes are also easier to maintain because changes are localized and do not create

conflicts with other classes.

Page 22: Core Concepts of Programming - York U

Object-Based Programming: JAVA Fundamentals Summary

Page 22 of 23

Coupling

• Coupling is a measure of how much one class depends on another class to do its job.

• Low or Loose coupling has less dependencies and is desirable – easier to change

• High or Tight coupling may make programs complex and brittle and problems, if any exists,

could cascade throughout the program

A class with low cohesion will likely have

• an ambiguous or unclear name

• methods that are unrelated to the class

• methods to perform too many different tasks

Source: http://sce2.umkc.edu/BIT//burrise/pl/design/

Remember: Maximize cohesion and minimize coupling!