Welcome to CIS 36B!


Learning Objectives for Today's Lesson

By the end of today's lesson, you should know...

  • Why study Java
  • How this class is structured
  • How to write a method (review)
  • How to read from and write to a file (review)
  • How to declare an array and assign it values (review)

1. Introduction to the Course

  • This course is an intermediate level Java class, which is a continuation of CIS 36A
  • It picks up where we left off last quarter - arrays!
  • The focus of the class will be to learn more about arrays and other ways of making lists inside of programs
  • The other primary focus will be to teach you how to write your own data types (classes and objects!)
    • Review: Give me an example of a data type in Java
  • After this class, you should have most of the knowledge to pass the Oracle Java Certification Exam level 1 (Associate Level)

Q: What is Java?

  • You have studied Java for one quarter already? How would you describe this language to someone unfamiliar with it?
  • What is Java? Video

Q: Why Study Java? A: Java is a Useful and Prevalent Language

1. THE most popular programming language in industry


2. Large Number of Useful Libraries - Java API (Application Programming Interface)

  • Libraries provide prewritten code that is relatively mature and stable
  • The libraries include code such as:
  • Input/Output: for many devices besides the console
  • Math: usual functions plus support for arbitrary precision numbers
  • 2D Graphics (3D is an add on library)
  • Graphical User Interfaces: buttons and widgets galore
  • Database connectivity
  • Security management
  • Multi-threading
  • Sound: sampled and MIDI based
  • XML processing
  • Industrial strength cryptography
  • With these core libraries, you do not need to spend time looking for third-party libraries
  • With Java, you can just start "doing stuff"

3. Safety and Stability

  • Java is a great choice for projects that value safety and stability
  • Automatic memory management ("garbage" collection)
    • Unlike C++, where a special function must be called when memory is no longer needed
    • Improves dynamic memory usage and reliability
  • Intelligent use of pointers (references)
    • No direct manipulation of memory (like in C++), but Java code is less error prone and more reliable
    • Automatic dereferencing when needed
  • Built-in bounds checking of arrays
    • Helps prevent buffer overflow
    • Buffer overflows are one of the leading causes of computer vulnerabilities
  • Strongly-typed language, unlike Python
    • Fewer errors at runtime
  • Runs without recompiling on many operating systems and hardware platforms

4. Performance

  • In the beginning, Java earned a reputation as a slow language
  • However that situation has changed as Java tools have progressed
  • Today, Java runs about the same speed as C++and faster than Python
  • Java Virtual Machine compiles code to the native machine code while the program is running
  • Compiling while the code is running is called Just in Time (JIT) compiling
  • JIT compiling contrasts with Ahead Of Time (AOT) compiling
  • Thus a Java program may start slower but quickly reaches the same speed, or better, than AOT compiled code
  • Several studies argue that Java can be faster than C++ because:
    • JIT compilers tailor the program optimization to the particular processor, memory and program "hot-spots", rather than a more general optimization
    • C++ pointers make optimization difficult since they may point to arbitrary data or code
    • In Java, newly allocated data is often closer together because the garbage collector knows what parts of memory are available
    • Data that is closer together are more likely to be in the computer's cache memory
    • Note that compilers exist to translate directly to native machine code ahead of time (GCJ)
  • Thus, your computer would run the code like it runs C++
  • However, you lose portability when you compile to native code ahead of time
More information


2. Course Logistics

Structure of this course

  • 2 Lessons per week
  • Lesson Videos and assignments released on Sunday
  • Practice Exam Questions and Activities for first lesson due Tuesday at 11:59pm
  • Practice Exam Questions and Activities for the second lesson due Thursday at 11:59pm
  • 1 Lab assignment per week - due Mondays
    • Must be completed with a pair programming partner using Zoom
  • 1 Quiz per week due Fridays
  • Peer reviews of Practice Exam Question assignments due Saturdays
    • 2 reviews per assignment
    • total of 4 reviews due on Saturday
    • doing peer reviews gives you more practice
Advice for Success
  • Expect this course to be a step up in difficulty from 36A
  • Get started on assignments early!
  • Get help as soon as you get stuck
    • Piazza.... Office Hours... Email.... Tutoring
  • Cultivate a Growth Mindset
    • Studies show you will be more successful in this class - and in life!
    • See this week's lab

3. Complete the Following Activities - due Tuesday at 11:59pm


Activity 1.1: Syllabus and Website Treasure Hunt Quiz (10 pts)

  • Read the syllabus and look through the course website.
  • Then, complete the Syllabus and Website Treasure Hunt Quiz posted on Canvas
  • You can take the quiz as many times as you would like until the deadline
  • The score of the final quiz attempt will be the one entered into the gradebook

Activity 1.2: Pair Programming Fundamentals (10 pts)

  • Watch Introduction to Pair Programming Video (10 minutes)
  • Then, complete the Pair Programming Video Quiz posted on Canvas
  • You can take the quiz as many times as you would like until the deadline
  • The score of the final quiz attempt will be the one entered into the gradebook

Activity 1.3: 36A Review (10 pts)

  • Open up a new Java project on Eclipse named Review and create a new class called Review.java.
  • Note that you may need to install Eclipse on your home computer first. See the tutorial here.
  • This activity should be complete individually.
    • If you get stuck, refer to the lesson video and the review notes below covering methods, File I/O and arrays
  • Copy and paste the below starter code into your file:
/**
* @author FILL IN YOUR NAME HERE
* CIS 36B, Activity 1.3
*/

//write your two import statements here

public class Review {
  
    public static void main(String[] args) { //don't forget IOException
        File infile = new File("scores.txt");
        //declare scores array
        //Use a for or while loop to read in data from scores.txt to the array
        //call method
        //Use a for loop to write data from array into extraCredit.txt
      
    }
    
        
    /**
     * Write complete Javadoc comment here
     */
    //write your addExtraCredit method here   
  
}

  • Next, create a new text file named scores.txt
    • Rick-click the project. Go to New->File.
    • Name your file scores.txt
    • Make sure the text file gets saved inside the overall project folder (Review), not in the src folder
  • Now, copy and paste the following data (exam scores) into your scores.txt file:
90
95
86
41
79
56
90
83
74
98
56
81
64
99
12

  • Your program must declare an array of integers, and populate the array with the contents of the file.
    • You may assume that the length of the array is known to be 15 elements.
  • Next, write a method called addExtraCredit:
    • The addExtraCredit method takes in one parameter - an array of integers
    • It adds 2 to each element in the array (hint: think for loop)
    • It returns nothing
  • Inside of main, call the addExtraCredit method, passing it the array of exam scores.
  • Next, write the contents of the array to a file named extraCredit.txt.
    • Use PrintWriter to write out to the file (see lesson notes above).
  • When you are finished, extraCredit.txt should contain the following:
    • Don't forget the title!
Scores with Extra Credit:
92
97
88
43
81
58
92
85
76
100
58
83
66
101
14

  • Hint: Your program should include either 3 for loops or 2 for loops and a while loop.
  • If you get stuck, review today's lesson notes.
  • When extraCredit.txt contains the above data, submit your program to Canvas.


4. Method Review

Defining a Method

  • In this section we look at method definition syntax and examine a simple example method
  • After we understand the syntax we can write more complicated methods

Method Syntax

  • The general syntax for defining a method is:
    public static returnType methodName(parameter1, ..., parametern) {
        statements
    }
    
  • Where:
    • returnType: the data type of the value returned
    • methodName: the name you make up for the method
    • parameterx: the input values, if any
    • statements: the list of statements to execute when the method is called

Example Program with a Method

  • As an example, the following program has a simple method to add two numbers
  • Notice that the code has three methods: add(), sub() and main()
  • The methods add()and sub() can be placed either above or below main().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

24
25
26
27

28
29
30
31
32
33
34
35
36
37
38
39
40

/**
* @author Jennifer Parrish
* CIS 36b
*/

public class Methods {

    /**
    * Sums two whole numbers
    * @param num1 the first number to sum
    * @param num2 the second number to sum
    * @return the sum of num1 and num2
    */    


    public static int add(int num1, int num2) {

        return num1 + num2;
    }

    public static void main(String[] args) {

    int result;
    System.out.print("The sum of 2 and 5 is: ");
    int sum = add(2,5); //"call" to the add method
    System.out.println(sum);
    
    System.out.print("The difference between 7.2 and 9.3 is: ");
    double difference = sub(7.2,9.3); //"call" to the sub method
    System.out.println(difference);
    }

    /**    
    * Subtracts two floating point numbers
    * @param a the first number in the expression (minuend)
    * @param b the second number in the expression (subtrahend)
    * @return the difference between the two numbers
    */
    public static double sub(double a, double b) {
        return a - b;
    }
}



  • In addition, you put Javadoc comments like the following before every method:

    /**
    * description of method
    * @param nameParam1 description param1
    * @param nameParam2 description of param2
    * @return description of what method returns (do not include if void)
    */

  • Then you use a tool, known as Javadoc, to automatically create program documentation
  • Also, a tool known as CheckStyle will check your comments (among other things) for correct usage
  • For your homework, every method must have a Javadoc comment.
  • Comments are for human readers, not compilers
  • Your comments should be structured as follows
    1. Method comments start with /** and ends with */
    2. The first line explains the idea of the method, not the implementation
    3. An @param entry explains each parameter - one for each parameter in the method
    4. An @return entry describes the return value (not required for void methods)
  • The following example has two fully commented methods:

    /**
     * multiplies a number by itself
     * @param number the number to square
     * @return the squared number
     */

    public static double square(double number) {
        double result = number * number;
        return result;
    }

    /**
    * Writes the contents of a names array and scores array to the console,
    * where each name and score is displayed on its own line
    * @param names a String array of student names
    * @param scores an integer array of student exam scores
    */

    public static void printArray(String[] names, int[] scores[]) {
        for (int i = 0; i < array.length; i++ ) {
            System.out.println(names[i] + "\t" + scores[i]);
        }
    }

  • Note that if you type /** above a method, Eclipse will help you fill in the rest.

More Information

5. File I/O Review

Procedure For Reading a Text File

1. Place import java.io.*; at the top of your program
  • Note that .* is the wildcard. Using a * will import all classes from that package.
2. Add throws IOException as part of the signature for main to avoid compiler errors.
3. Create a File object with a pathname to your file:
File data = new File("data.txt");
4. Add a Scanner object to parse the data in the file:
Scanner input = new Scanner(data);
5. Read data using methods calls for the correct type:

int x = input.nextInt();
double y = input.nextDouble();
string word = input.next();
string line = input.nextLine();

6. Close the streams when finished reading:
in.close();

Example Program Reading a Text File

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

import java.io.*;
import java.util.Scanner;

class TextReaderApp {
    public static void main(String[] args)
            throws IOException {
        File data = new File("data.txt");
        Scanner input = new Scanner(data);
        String str = input.nextLine();
        System.out.println(str);

        char ch = input.nextLine().charAt(0);
        System.out.println(ch);

        int x = input.nextInt();
        System.out.println(x);

        double d = input.nextDouble();
        System.out.println(d);

        for (int i = 0; i <= 10; i++) {
            x = input.nextInt();
            System.out.print(x + " ");
        }
        System.out.println();

        input.close();
    }
}

Procedure for Writing a Text File

  • Place import java.io.*; at the top of your program
  • Note that .* is the wildcard. Using a * will import all classes from that package.
  • We need 3 classes here so we will save time by using the * instead of importing all 3 separately (java.io.File, java.io.PrintWriter, and java.io.IOException)
  • Add throws IOException as part of the signature for main to avoid compiler errors
  • Create a File object with a pathname to your file:

    File data = new File("data.txt");
  • Connect the file to a stream: 
PrintWriter out = new PrintWriter(data); 
  • If you want to append data then use: PrintWriter out = new PrintWriter(data, true); 
  • Write to the file using the print() and println() methods:
out.println("This is a string");
out.println('c'); out.println(1234);
out.println(1.234);

for (int i = 0; i <= 10; i++) {
    out.print(i + ",");
}

out.println();

  • Close the streams when finished writing: 
out.close();

Example Program Writing a Text File

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

import java.io.*;

class TextWriterApp {
    public static void main(String[] args)
            throws IOException {
        File data = new File("data.txt");
        PrintWriter out = new PrintWriter(data);
        out.println("This is a string");
        out.println('c');
        out.println(1234);
        out.println(1.234);
        for (int i = 0; i <= 10; i++) {
            out.print(i + " ");
        }
        out.println();
        out.close();
        System.out.println("Finished writing file");
    }
}


Using Loops to Read Files

  • Sometimes you do not know how many lines are in a file
  • To solve this, the typical approach is to use a loop to process the file
  • The Scanner object has methods like hasNext() to see if there is any more input in the stream
  • You can use these methods to signal when your program reaches the end of a file

Example Program Testing for End-of-File

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

import java.io.*;
import java.util.Scanner;

public class Files {
public static void main(String[] args)
throws IOException {
File data = new File("sonnet.txt");
Scanner input = new Scanner(data);

while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
}

}

Some Test Methods of a Scanner Object

Method Description
hasNext() Returns true if this scanner has another token in its input.
hasNextLine() Returns true if there is another line in the input of this scanner.
hasNextDouble() Returns true if the next token can be interpreted as a double value.
hasNextInt() Returns true if the next token can be interpreted as an int value.

6. Array Review

Defining Arrays in Java

  • An array is a collection of data items all of the same type
  • You declare an array like this:
    dataType[] variableName = new dataType[length];
    
  • You can also declare an array like this:
    dataType variableName[] = new dataType[length];
    
  • Where:
    • dataType: the data type of all the array items
    • variableName: the name you make up for the array
    • length: the number of data items the array can hold
  • For example, the following is the declaration of an array named scores that holds 10 values of type int:
    int[] scores = new int[10];
  • When a program executes this statement, it creates 10 contiguous slots in memory like this:
    scores = 
     
     
     
     
     
     
     
     
     
     
  • Each of the memory slots can hold one data value
  • We can have arrays of any type:
double[] anArrayOfDoubles;
boolean anArrayOfBooleans[];
char[] anArrayOfChars;
String anArrayOfStrings[];
  • Once you define the length of an array, it cannot change length later in the program.
  • When defining an array, you must guess the maximum number of elements you need to store:
    int[] scores = new int[100];
    
  • If you need to know the length of an array, you can always use the length property (more on this below):
          System.out.println(scores.length) //Will print out 100

Initializing Array Items

  • We specify which slot of an array to access with the [] operator:
    scores[4] = 98;
  • The indexes of arrays are numbered starting at 0
  • We can assign a value to an array element any time after it is declared:
    scores[0] = 90;
    scores[1] = 95;
    scores[2] = 87;
    scores[3] = 89;
    scores[4] = 98;
    
  • We can also initialize array elements in the declaration statement:
    • Called static initialization
    • We use a comma-separated list inside curly-braces
  • For example:
    int[] scores = { 90, 95, 87, 89, 98 };
    
  • This produces the same array as in the previous example
  • The compiler computes the size automatically by counting the items in the list
Default Array Values
  • When an array is declared, Java automatically assigns each element a default value: false for booleans, 0 for numerical types

Accessing Array Items

  • To access the slots in an array, we must specify which slot to use with the [] operator
  • For instance:
    scores[4] = 98;
  • The number inside the brackets is called an index or subscript
  • In Java, the slots of an array are numbered starting at 0, as shown below:
    scores = 
     
     
     
     
    98
     
     
     
     
     
    [0]
    [1]
    [2]
    [3]
    [4]
    [5]
    [6]
    [7]
    [8]
    [9]
  • Thus, assignment to the slot with an index of 4 is put into the fifth slot

Using Slots

  • We declared our example array with a data type of int:
    int[] scores = new int[10];
  • Because scores is an array containing int values, we can use a slot, such as scores[4], just like any variable of type int:
    scores[4]++;
    System.out.println(scores[4]);
    
  • This includes using a slot as an argument to a method with a parameter of the same type:
    public static void myMethod(int singleScore){//method body}
    ...
    myMethod(scores[4]); 

Array Length

  • We can always access the length of an array using .length

System.out.println(scores.length);

  • Note that the length of the array is always one less than its last index

Illustration of an array as 10 boxes numbered 0 through 9; an index of 0 indicates the first element in the array

Image source.

Using Arrays to Collect Data Items

  • Note that the index of an array can be any integer value
  • Thus, we can use an integer variable for the index
  • We can use an integer variable with a loop to read data into the array
  • Also, we can display the contents of an array using a loop
  • The following program shows an example of collecting and displaying data items


Example Program Using Arrays to Collect and Display Data Items



/**
*
* @author parrishj
*/
import java.util.Scanner;
public class Arrays {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

int[] scores = new int[5];
System.out.println("Array elements initialized to 0:");
for (int i =0; i <scores.length; i++){
System.out.println("Index " + i + ": " + scores[i]);
}
System.out.println("\nEnter " + scores.length + " scores:");
for (int i =0; i <scores.length; i++){
scores[i] = input.nextInt();
}
System.out.println("\nYou entered:");
for (int i =0; i <scores.length; i++){
System.out.println("Score " + i + ": " + scores[i]);
}
}

}

Arrays and Methods

  • When writing a method with an array parameter, we place an empty [] after the datatype or parameter name:
    public static void print(int values[]); //will work for an array of any size
    
  • When we call the method, we do NOT include the []:
    print(data); // name of the array is data
    
  • Instead, we pass in the name of the array.

Example program passing an array to a method

public static void print(int values[]){
        for (int i = 0; i < values.length; i++)
            System.out.println(values[i]);
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[] scores = {90, 89, 76, 55, 91};
        print(scores);
     
    }

  • Unlike other parameters, you can pass the array into the method and then alter the array inside of the method without needing to return a new array.
  • For example, what do you think will be the result of running the following program?
import java.util.Scanner;
public class Arrays {
   
    public static void assignValues(int values[]){
        for (int i = 0; i < values.length; i++){
            values[i] = i;
        }
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[]  arr = new int[10];
        assignValues(arr);
     
        for (int i = 0; i < arr.length; i++){
            System.out.println(arr[i]);
        }
    }
       

  • It is also possible to return an array from a method.
  • For example:



/**
 * @author Jennifer Parrish

 * CIS 36b 

 */
import java.util.Scanner;
public class Arrays {
   
    public static int[] assignValues(int values[]){
        for (int i = 0; i < values.length; i++){
            values[i] = i;
        }
        return values;
    }



    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[]  arr = new int[10];
        arr = assignValues(arr);

        System.out.println("After filling the array:");
        for (int i = 0; i < arr.length; i++){
            System.out.println(arr[i]);
        }

       
    }
 
}



Wrap Up

  • Answer the Practice Exam questions for this lesson on Canvas


Upcoming Assignments:


  • Activities 1.1-1.3 due Tuesday
  • Lesson 1 Practice Exam Questions due Tuesday
  • Quiz 1 due Friday
  • Lab 1 due this coming Monday

~Have a Great Day!~