Presentation is loading. Please wait.

Presentation is loading. Please wait.

CIS265 & 506 Introduction to Computer Sciences Basic concepts

Similar presentations


Presentation on theme: "CIS265 & 506 Introduction to Computer Sciences Basic concepts"— Presentation transcript:

1 CIS265 & 506 Introduction to Computer Sciences Basic concepts
Part 1

2 CIS265 - Expected Outcomes
At the end of this (CS2) course, a student will be able to: (1) apply computational reasoning skills in solving problems, (2) understand code written by others, (3)design recursive solutions, (4) analyze algorithm complexities, (5) describe and analyze sorting algorithms, (6) use Java Collections Framework to develop applications, (7) implement classic data structures: array lists, linked lists, stacks, queues, heaps, binary trees, hash tables, (8) represent and solve problems using graph algorithms, (9) effectively test a program to assess its correctness, (10) use recommended style and conventions when writing a program.

3 A Minimalist’s Guide to Java Syntax:
1 Data Types String, int, double 2 Decision Making if (condition) { stm1; } else { stm2; } condition includes: true, false, &&,||,not, ==, <>, !=, >=, <= else {…} is optional 3 Iteration while (condition) { stm } for( init; control; step) { stm } 4 Assignment var = value-or-expression; Sender and receiver must be of compatible types 5 Everything is a class !!!

4 Some Problem Solving Strategies
Divide & Conquer (break into simpler sub-problems) Exhaustive Enumeration (brute force) Bisection Search (problem domain halving) Recursion (self-invoked domain reduction) Root-Cause Analysis (Fever:symptom- Infection:cause) Pattern-Recognition (eg. developing formulas for seq.) Examples pattern recognition:

5 A sample of what is ahead …
Problem: Integer Arithmetic Find a way of computing Assume x ≥ 0, and x is integer. Observations The solution must be an integer y such that y2 ⩳ x, and y ≥ 0 (disregard negative/real solutions). We could begin by guessing the answer is (y = 0). if y is not the right answer (y2 ≠ x), then we could try setting y to 1, then 2, 3, 4, … and so on until an exact match is found or (y2 > x), in such a case we state the answer is (y-1). 5

6 A sample of what is ahead …
Problem: Finding an algorithm to compute // VERSION1. Strategy: Brute Force - Exhaustive Enumeration // (works fine as a first draft, very limited) int x = 5; // number to calculate its square root int y = 0; // tentative first INTEGER solution while( y*y < x ){ y++; } if ( y*y > x ){ y--; System.out.println (" SQRT of " + x + " is " + y );

7 A sample of what is ahead …
Problem: Finding an algorithm to compute // VERSION2. Strategy: Bisection Techn. (real domain solutions) double x = 5; double first = 0; double last = (x<1)?1:x; double epsilon = 0.001; double middle = (first + last) / 2.0; while ( (middle * middle > x ) || ( middle*middle + epsilon < x ) ) { if ( middle*middle > x ) { last = middle - epsilon; } else { first = middle + epsilon; } middle = (first + last) / 2.0; System.out.println (" SQRT of " + x + " is " + middle ); 7

8 Review of Topics Basic Programming Logic String Concepts & Methods
Case/switch Using modifiers effectively Should the default constructor be over-ridden? How does passing arguments to/from methods work? String Concepts & Methods Including: compareTo(), string tokenizer, reversing strings, split() String Buffer Concepts & Methods Exceptions Dates and Times File I/O Console I/O Abstract Classes Why use, another example Example of instanceOf() Software engineering Concepts Designing classes Packages Naming conventions

9 Condition Testing Case/Switch Statements
Allows you to select from multiple, fixed values for a given expression The switch value must be: char, byte, int, short (CANNOT be long)

10 The Switch Statement break break break default Action(s) T
courseGrade an 'A' break 'A' actions T courseGrade a 'B' 'B' actions break T courseGrade a 'C' break 'C' actions default Action(s)

11 The Switch Statement switch(courseGrade) { case 'A':
System.out.println("You got an A!"); break; case 'B': System.out.println("You got a B!"); default: System.out.println("You didn’t get an A or B!"); }

12 The Switch Statement switch(courseGrade) { case 'A': case 'B':
case 'C': System.out.println("You passed!"); break; case 'D': System.out.println("You should retake this…"); default: System.out.println("hhhmmmmmm!"); }

13 Using modifiers effectively: Access Specifiers
Private Anything declared private is completely hidden from outside classes and subclasses Protected Accessible from within the same package and all subclasses Public Anyone can see the item

14 Access Specifiers - Rules of Thumb
Private For all methods not designed to be public, and fields Protected Used if (and only if) a subclass will need it Public Methods that are necessary to use an object. Attributes (fields) should never be public

15 Default Constructors The default constructor will be automatically provided by the compiler, UNLESS you have a constructor of another type. Then you must write your own default constructor, even if it does nothing As most of the classes we write will have a constructor of some sort, you will find yourself always writing a default constructor.

16 Passing Arguments to a Method
For each argument, we need to know The data type of the argument A local name for the argument The local name does not have to be the same name as we gave it in the calling program (and it usually is not the same name!) Example: int value1 = 15; int result = mySubtraction( value1, 22); public int mySubtraction( int arg1, int arg2 ){ . . . } Local type / name

17 How does passing arguments to/from methods work?
Primitives types are passed by value, objects are passed by reference. This is only partially true. Primitives are passed by value. A copy of the information is sent to the method. The method does it’s thing. When we return, the primitive is not changed If an object is immutable (like a String, Integer, or Double), then the address of that object is passed to the method. We can modify the object all we like, but the modifications are occurring on a copy of the object! The calling program will not see the changes.

18 String Concepts & Methods - Introduction
A string is a series of characters treated as a single unit It may include letters, digits, and various special characters, such as +, -, #, _ etc. A string is an object of class String There is no primitive data type for strings in Java We use the class String instead String literals or string constants (often called anonymous String objects) are written as a sequence of characters in double quotation marks

19 String Class A String may be assigned in a declaration to a String reference: String color = "blue"; This declaration will initialize a String reference to the anonymous String object "blue". Alternatively, you may also say String color = new String("blue");

20 String Class The class String is defined in java.lang.String
which is automatically imported into every program you write

21 String Class Strings are said to be immutable: That is, we can not change them If you would like to change the value of a string, Java will actually create a new object & throw away the old one. Thus, a String reference can not be used to modify a String object or to delete a String object from memory

22 Processing String Parts
We can treat a String somewhat like an array of characters Use the charAt(…) and length() methods str.charAt(…) – similar to array index str.length() – returns length of string

23 Example String s1; char charArray[]; s1 = new String(“Hola amigos”); charArray = new char[5]; // here is the length method: System.out.print("The string s1 (" + s1 + ") has a length of "); System.out.println(s1.length()); System.out.println(" "); // Here is the charAt method: System.out.println("Print the String in reverse!"); for (int i = s1.length()-1; i >= 0; i--) { System.out.print(s1.charAt(i) + " "); } Note that length() is a method for Strings (compare to it being a data member for arrays!)

24 // Using getChars, copy some characters from the
// String in to the array // We'll copy the characters starting at position 11 to 15 // and place them in the array called charArray starting // at position zero. Observe the call says 11 to 16 // (one more! - what were they thinking!) s1.getChars(11, 16, charArray, 0); System.out.println("The character array is now:"); for (int i = 0; i < charArray.length; i++) { System.out.print(charArray[i]); } System.out.println(" "); OUTPUT The string s1 (Hola amigos) has a length of 11 Print the String in reverse! s o g i m a a l o H

25 Comparing strings In Java a String is an object We create a String by creating an instance of the class String The String variable name refers to a location in memory, rather than a particular value This means how we compare Strings is somewhat different than you would expect We can not compare values using "==" This would compare memory locations, not values!

26 Comparing strings Compares one character at a time, until the values are no longer equal or until the end of the shortest string is reached. We use ASCII values to make the comparisons M a d D o g M a d C a t

27 So what happens? M a d D o g string one is “bigger” than string 2 M a
C a t String2 M a d C a t String two is “bigger” than string 1 String1 M a d D o g String2 M a d C a t String1 String one is “equal to” string 2 M a d C a t String2

28 compareTo() method We use the compareTo() method to determine if a string is greater than, less than, or equal to another string string1.compareTo(string2) string1 > string2 returns a positive value string1 < string2 returns a negative value string1 == string2 returns a zero (Please note that the actual number the method returns rarely matters. We are looking for positive, negative, or zero)

29 So what happens? String one is “bigger” than string 2 – method returns a positive value M a d D o g String1 M a d C a t String2 M a d C a t String two is “bigger” than string 1 – method returns a negative value String1 M a d D o g String2 M a d C a t String1 String one is “equal to” string 2 – method returns a zero M a d C a t String2

30 Comparing Strings To check if strings are equal to each other (that is, they are the same value), we use the “equals()” method. equals() is a CASE SENSITIVE comparison (a not eq. A) equals() returns a boolean value Syntax: string1.equals(string2)

31 Comparing Strings – Case Sensitive Example
String myPhrase1 = “This is string one.”; String myPhrase2 = “This is string two.”; if (myPhrase1.equals(myPhrase2)) System.out.println(“They are equal!”); else System.out.println(“They are not equal!”);

32 Comparing Strings – Case INsensitive Example
String myPhrase1 = “This is string one.”; String myPhrase2 = “This IS string ONE.”; if (myPhrase1.equalsIgnoreCase(myPhrase2)) System.out.println(“They are equal!”); else System.out.println(“They are not equal!”);

33 Changing Case We can change the case of a String by using toUpperCase() and toLowerCase() Example: “Hola”.toUpperCase() returns “HOLA”

34 public class usingStrings {
public static void main(String[] args) { String theWord1 = "little letters"; String theWord2 = "BIG LETTERS"; System.out.println("The string starts out like so: " + theWord1); System.out.println("It is now UPPER CASE: " + theWord1.toUpperCase()); System.out.println(" "); + theWord2); System.out.println("It is now lower case: " + theWord2.toLowerCase()); } The string starts out like so: little letters It is now UPPER CASE: LITTLE LETTERS The string starts out like so: BIG LETTERS It is now lower case: big letters

35 toString() The toString() method allows us to convert any primitive type to a String Whenever we use print or println, we are using the toString() method

36 public class Book { private String title; private int pages; public Book(String title, int pages) { this.title = title; this.pages = pages; } public String toString() { String temp = ""; temp += this.getClass().getName(); temp += " is "; temp += getTitle(); temp += " with "; temp += getPages(); temp += " pages."; return temp; Define our own toString() method which will over-ride the toString() method that is defined by the language

37 Print out the object using println
public class DemoBook { public static void main(String[] args) { /*******Create Objects *******/ Book book3 = new Book("100 Years of Solitude", 225); /*****/ Book book4 = new Book(); book4.setTitle("The McGuffey Reader"); book4.setPages(51); /*******Show results *******/ System.out.println(book3); System.out.println(book4); return; } Print out the object using println Book is 100 Years of Solitude with 225 pages.

38 Some string methods Checking the starting characters in a string
string1.startsWith(string2) Checking the ending characters in a string string1.endsWith(string2) Both are case sensitive

39 Extracting strings There are two substring methods used by class String stringName.substring(integer); The integer specifies that starting index from which characters are copied, and all characters are copied from that point until the end of the String stringName.substring(int1, int2); The first argument specifies the starting point, and the second argument should be one beyond the last character you wish to copy.

40 Substring starting at position 10 and going to position 15: very
Example: String sub1 = new String("This is a very long string!"); System.out.print("Substring starting at position 10 "); System.out.println("and going to the end of the String: "); System.out.println("\t" + sub1.substring(10)); System.out.println("and going to position 15: "); System.out.println("\t" + sub1.substring(10, 15)); Output: Substring starting at position 10 and going to the end of the String: very long string! Substring starting at position 10 and going to position 15: very

41 String Concatenation Because Strings are references to objects, we can not use the “+” concatenation operator. We can use the + in System.out.print as this operator has been modified to handle Strings in this context We need a new operator for actually modifying the Strings We need to use a String method s1.concat(s2); This appends s2 to the end of s1

42 In Java, you can use + to concatenate Strings together:
In Java, you can use + to concatenate Strings together: String cat = "cat"; System.out.println("con" + cat + "enation"); This is a little deceptive because, as you know, Strings can't be changed. However, behind the scenes the compiler uses StringBuffers to implement concatenation. The above example compiles to: String cat = "cat"; System.out.println( new StringBuffer().append("con") .append(cat) .append("enation") .toString());

43 Example String scat1 = new String("Happy "); String scat2 = new String("Birthday"); System.out.println(scat1.concat(scat2)); Output: Happy Birthday

44 Searching Strings We use the indexOf() and lastIndexOf() methods to search a string for the location of a specific character Both methods return an integer. If the character is not found, the method will return a –1.

45 public class UsingIndexOf { public static void main(String[] args) {
Example public class UsingIndexOf { public static void main(String[] args) { String myWordList = new String( "This is my word list and it is very long"); System.out.println("The indexOf the first space is: " + myWordList.indexOf(' ')); System.out.println("The indexOf the last space is: " + myWordList.lastIndexOf(' ')); // now we go thru the String, showing the // indexOf every space, and // extracting substrings

46 System.out.println("Word\tindexOf Space");
int currentIndex = 0; int oldIndex = 0; String tempString = ""; System.out.println("Word\tindexOf Space"); while (currentIndex != -1) { // makes sure we exit before going // past the end of the string oldIndex = currentIndex; // uses the format indexOf(ch, starting_location) currentIndex = myWordList.indexOf(' ', oldIndex+1);

47 //prints the last word if (currentIndex == -1) // uses the format substring(starting_location) tempString = myWordList.substring(oldIndex); else // uses the format // substring(starting_location, ending_location+1) tempString = myWordList.substring( oldIndex, currentIndex); System.out.println(tempString + "\t" + currentIndex); }

48 Using split() Split allows us to divide a string on a sequence of tokens and place the results in a String array. Splitting on a space or character is the simplest way We can also split using the concept of regular expressions We will not do so in this class. If you are interested, there is lots of information online!

49 public class MySplitExample {
public static void main(String[] args) { String t1 = "Play it, Sam. Play 'As Time Goes By'"; String[] sArray = t1.split(" "); for (int i = 0; i < sArray.length; i++) { System.out.print("\t " + sArray[i]); } System.out.println(" "); Play it, Sam. Play 'As Time Goes By'

50 String conversion Converting Strings to Numbers Two ways –
String to Integer String to double - note there is a difference between double & Double!!!! int anInt = Integer.parseInt(myStringVariable); String stringValue = new String("174.82"); Double tempValue = Double.valueOf(stringValue); double doubleValue = tempValue.doubleValue();

51 Arrays of Strings Since strings are objects, we can create arrays of Strings String[] names = new String[5]; 1 2 3 4 String type

52 Useful Character Methods There are many others…
Character.isLetter( c ) Checks to see if a character is a letter (A-Z, a-z) Character.isWhitespace( c ) or whitespace (‘ ‘, ‘\n’, ‘\t’, etc) Character.isDigit( c ) Or a digit Character.isLowerCase( c ) Character.isUpperCase( c ) Character.toUpperCase( c ) Character.toLowerCase( c )

53 Class StringTokenizer
We saw an example using IndexOf() to break an sentence in to words We can do this much easier by using a Tokenizer, of a method that breaks a String in to individual components, or tokens

54 import java.util.*; /* Using the StringTokenizer class */ String stringToTokenize = new String( "This is my word list and it is very long"); StringTokenizer tokens = new StringTokenizer(stringToTokenize); System.out.print("The number of tokens in this line is: "); System.out.println(tokens.countTokens()); /* Print out each piece */ while (tokens.hasMoreTokens() ) System.out.println(tokens.nextToken());

55 Output The number of tokens in this line is: 10 This is my word list and it very long

56 Learning About the StringBuffer Class
Value of any String type variable is fixed After String is created it is immutable StringBuffer class Alternative to String class when String will be modified Can be used anywhere you would use String Part of java.lang package Automatically imported into every program

57 Learning About the StringBuffer Class
Create StringBuffer object StringBuffer strbuffer = new StringBuffer("Hello there"); Must use Keyword new Constructor name Initializing value between constructor’s parentheses

58 Learning About the StringBuffer Class
setLength() method Change length of String in StringBuffer object length property Attribute of StringBuffer class Identifies number of characters in String currently contained in StringBuffer capacity() method Find total capacity of StringBuffer object

59 The StringBufferDemo Application

60 Learning About the StringBuffer Class
Using StringBuffer objects Provides improved computer performance over String objects Can insert or append new contents into StringBuffer StringBuffer constructors public StringBuffer() public StringBuffer(int capacity) public StringBuffer(String s)

61 Learning About the StringBuffer Class
append() method Add characters to end of StringBuffer object insert() method Add characters at specific location within StringBuffer object setCharAt() method Change character at specified position within StringBuffer object

62 Learning About the StringBuffer Class
charAt() method Accepts argument that is offset of character position from beginning of String Returns character at that position

63 Handling Exceptions Three new Java keywords you need to learn try
Encloses code that may give rise to one or more exceptions catch Encloses code that is intended to handle exceptions from the try block finally Always executed before the method ends

64 try must be followed immediately by at least one catch
try & catch try { // code that can throw an exception } catch (Exception exceptionVariableName) { // code to handle exception try must be followed immediately by at least one catch

65 Multiple Catch Blocks try { // code that can throw an exception }
catch (exceptionName1 variable1Name) { // code to handle exception1 catch (exceptionName2 variable2Name) { // code to handle exception2 catch (exceptionName3 variable3Name) { // code to handle exception3

66 Multiple Catch Blocks When an exception is thrown, it will be caught by the first catch block that has a parameter type that is the same as the exception, or a superclass of the type of the exception The catch blocks must be in sequence from the most derived type first, to the most general type last

67 finally The finally block provides the means to clean up at the end of a try block Used most when processing files or other complex data structures finally { // clean-up code to be executed last }

68 public class UseExcept {
public static void generateException(int var1) { int temp; System.out.println("The number coming in is: " + into); try { int nums[] = new int[var1]; // negative array size error if var1 = -1 switch(into) { case -1: temp=1; break; case 0: temp = 10/into; // divide by zero error case 1: nums[4] = 4; // array index error default: return; }

69 catch (ArithmeticException e) {
System.out.println("Can't divide by zero!!"); return; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Can't access that array element!!"); catch (NegativeArraySizeException e) { System.out.println( "Can't have an array with a negative index!!"); finally { System.out.println("In the finally block, leaving now ...");

70 public class exceptDemo {
public static void main(String[] args) { UseExcept useExcept = new UseExcept(); for (int i = -1; i < 3; i++) { useExcept.generateException(i); System.out.println(" "); } Pass a value to the routine that will intentionally create some exceptions!

71 The finally block is always called!
The number coming in is: -1 Can't have an array with a negative index!! In the finally block, leaving now ... The number coming in is: 0 Can't divide by zero!! The number coming in is: 1 Can't access that array element!! The number coming in is: 2 The finally block is always called!

72 Specifying the Exceptions a Method Can Throw
If an exception isn’t caught, you must declare that the exception can be thrown

73 Example public class simpleKeyboardInput { public static void main(String[] args) throws Exception { char userInput; System.out.println("Please enter a character"); userInput = (char)System.in.read(); System.out.println("You entered " + userInput); return; } An Exception is an error condition – we need to say this to handle any potential errors that may occur. System.in.read() accepts a byte & returns an int. We really want a char. We have to "cast" the input to tell the compiler to turn the incoming int in to a char

74 Stack Trace We can use the stack trace to find the exact location of the code where the exception was thrown: catch (ArithmeticException e) { System.out.println("Can't divide by zero!!"); System.out.println("Stack Trace:"); e.printStackTrace(); return; } The number coming in is: 0 Can't divide by zero!! Stack Trace: java.lang.ArithmeticException: / by zero at useExcept.generateException(useExcept.java:15) at exceptDemo.main(exceptDemo.java, Compiled Code) In the finally block, leaving now ...

75 toString() We can use toString() to find the exact name of the exception that was thrown: catch (NegativeArraySizeException e) { System.out.println( "Can't have an array with a negative index!!"); System.out.println("Using toString():"); System.out.println(e); return; } The number coming in is: -1 Can't have an array with a negative index!! Using toString(): java.lang.NegativeArraySizeException: In the finally block, leaving now ...

76 Dates and Times import java.util.*; public class PlayingWithDates {
public static void main(String[] args) { /* public static long currentTimeMillis() * * Returns the current time in milliseconds. Note that while the * unit of time of the return value is a millisecond, the * granularity of the value depends on the underlying operating * system and may be larger. For example, many operating systems * measure time in units of tens of milliseconds. */ System.out.println("The current date/time in milliseconds is: " + System.currentTimeMillis() + "\n"); Date today = new Date(); // print the newly created date: System.out.println("Today is: " + today + "\n"); System.out.println("The Time is: " + today.getTime() + "\n");

77 // all the interesting Date methods are deprecated:
Calendar rightNow = Calendar.getInstance(); // Get each part of the date System.out.println("The day of the month is " + rightNow.get(Calendar.DAY_OF_MONTH)); System.out.println("The day of the week is " + rightNow.get(Calendar.DAY_OF_WEEK)); System.out.println("The hour is " + rightNow.get(Calendar.HOUR_OF_DAY)); System.out.println("The minute is " + rightNow.get(Calendar.MINUTE)); System.out.println("The month is " + rightNow.get(Calendar.MONTH)); System.out.println("The second is " + rightNow.get(Calendar.SECOND)); int year = rightNow.get(Calendar.YEAR); System.out.println("The year is " + year); }

78 The current date/time in milliseconds is: 1215711763725
Today is: Thu Jul 10 13:42:43 EDT 2008 The Time is: The day of the month is 10 The day of the week is 5 The hour is 13 The minute is 42 The month is 6 The second is 43 The year is 2008

79 File I/O import java.io.*; import java.util.Scanner;
public class PlayWithFiles { public static void main(String[] args) throws IOException { // read from a file, and then write that information to a new file. Scanner infile = new Scanner(new FileReader("myGettysburgAddressText.txt")); // write a text file PrintWriter outfile = new PrintWriter(new FileWriter("outfile.txt")); String inString; while (infile.hasNextLine()) { inString = infile.nextLine(); outfile.println(inString); } infile.close(); outfile.close();

80 Console I/O - Simple Keyboard Input
We would really like our programs to be more interactive, that is, they can accept some input from elsewhere We would like to look at simple keyboard input

81 Simple Keyboard Input public class simpleKeyboardInput { public static void main(String[] args) throws Exception { char userInput; System.out.println("Please enter a character"); userInput = (char)System.in.read(); System.out.println("You entered " + userInput); return; } An Exception is an error condition – we need to say this to handle any potential errors that may occur. System.in.read() accepts a byte & returns an int. We really want a char. We have to "cast" the input to tell the compiler to turn the incoming int in to a char

82

83 import java.io.*; public class readFromKeyboard { public static void main(String argv[]) throws NumberFormatException, IOException { BufferedReader stdin = new BufferedReader( new InputStreamReader (System.in)); int theInt; double theDouble; String theString; char theChar; System.out.println("Enter a String"); theString = stdin.readLine().trim(); System.out.println("Enter an integer"); theInt = Integer.parseInt(stdin.readLine().trim()); System.out.println("Enter a double"); theDouble = Double.parseDouble(stdin.readLine().trim()); System.out.println("Finally, a character: "); theChar = (char) System.in.read(); }

84 Abstract Classes An abstract class is one that you create only to extend from. An abstract class may include methods that are declared but not implemented The methods are called abstract methods You can not instantiate (new…) an abstract class, but you can declare a variable of abstract type

85 Abstract Classes public abstract class Animal { private String type;
public abstract void sound(); // abstract method public Animal(String aType) { type = new String(aType); } public String toString() { return "This is a " + type;

86 public class Dog extends Animal {
private String name; public Dog (String name) { super ("Dog"); this.name = name; } public void sound() { System.out.println("Woof!"); public String getName() { return name; public class Snake extends Animal { public Snake (String name) { super ("Snake"); System.out.println("Ssssss!");

87 public class Cow extends Animal {
private String name; public Dog (String name) { super ("Cow"); this.name = name; } public void sound() { System.out.println("Woof!"); public String getName() { return name;

88 Example: package csu.matos; public class AnimalRef {
public static void main(String[] args) { Animal ref; Cow aCow = new Cow("AnnaBell"); Dog aDog = new Dog("Fluffy"); Snake aSnake = new Snake("Nagini"); ref = aCow; ref.sound(); ref = aDog; ref = aSnake; }

89 Creating Arrays of Subclass Objects
Recall that when we create arrays of objects, we are actually creating references to potential objects This allows us to make arrays of references to objects

90 public class AnimalArray { public static void main(String[] args) {
Example: public class AnimalArray { public static void main(String[] args) { Animal[] ref = new Animal[3]; Cow aCow = new Cow("AnnaBell"); Dog aDog = new Dog("Fluffy"); Snake aSnake = new Snake("Nagini"); ref[0] = aCow; ref[1] = aDog; ref[2] = aSnake; for (int x = 0; x < 3; x++) { ref[x].sound(); } Output Moooo! Woof! Ssssss!

91 Example package csu.matos; public class AminalRef {
public static void main(String[] args) { Animal[] ref2 = new Animal[3]; Cow aCow2 = new Cow("AnnaBell"); Dog aDog2 = new Dog("Fluffy"); Snake aSnake2 = new Snake("Nagini"); ref2[0] = aCow2; ref2[1] = aDog2; ref2[2] = aSnake2; for (int x = 0; x < 3; x++) { if (ref2[x] instanceof Cow) { System.out.println("An animal of type: " + ref2[x].getClass().getName() + " better known as: " + ((Cow)ref2[x]).getName() + " says "); ref2[x].sound(); System.out.println(" "); } else if (ref2[x] instanceof Dog) { + " better known as: " + ((Dog)ref2[x]).getName()

92 Example Output } else { if (ref2[x] instanceof Snake) {
System.out.println("An animal of type: " + ref2[x].getClass().getName() + " better known as: " + ((Snake)ref2[x]).getName() + " says "); ref2[x].sound(); System.out.println(" "); } Output An animal of type: csu.matos.Cow better known as: AnnaBell says Moooo! An animal of type: csu.matos.Dog better known as: Fluffy says Woof! An animal of type: csu.matos.Snake better known as: Nagini says Ssssss!

93 UML Diagrams UML diagrams
A collection of symbols used to represent classes and their interactions Class diagram for class Phone Class name Attributes & types Method headings

94 UML Diagrams Collaborates with Contains

95 UML Diagrams Can you see all the relation- ships ?

96 Naming conventions Java Code Conventions are available here:

97 Identifier Rules for Naming Examples Packages The name is always written in all-lowercase ASCII letters and typically: com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981. Subsequent components of the package name vary according to an organization's own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names. com.sun.eng com.apple.quicktime.v2 edu.cmu.cs.bovik.cheese Classes Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML). class Raster; class ImageSprite; Interfaces Interface names should be capitalized like class names. interface RasterDelegate; interface Storing;

98 Methods Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. run(); runFast(); getBackground(); Variables Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed. Variable names should be short yet meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters. int i; char c; float myWidth; Constants The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.) static final int MIN_WIDTH = 4; static final int MAX_WIDTH = 999; static final int GET_THE_CPU = 1;

99 Even if you're on the right track, you'll get run over if you just sit there.
Will Rogers


Download ppt "CIS265 & 506 Introduction to Computer Sciences Basic concepts"

Similar presentations


Ads by Google