TIC2002 (2019)
  • Full Timeline
  • Week 1 [Aug 12]
  • Week 2 [Aug 19]
  • Week 3 [Aug 26]
  • Week 4 [Sep 2]
  • Week 5 [Sep 9]
  • Week 6 [Sep 16]
  • Week 7 [Sep 30]
  • Week 8 [Oct 7]
  • Week 9 [Oct 14]
  • Week 10 [Oct 21]
  • Week 11 [Oct 28]
  • Week 12 [Nov 4]
  • Week 13 [Nov 11]
  • Textbook
  • Admin Info
  • Report Bugs
  • Forum
  • Announcements
  • File Submissions
  • repl.it link
  • Java Coding Standard
  • Duke repo
  • Week 1 [Aug 12] - Topics

    Topics allocated to the week will appear in this tab.

    • [W1.1] Software Engineering: Intro
    • [W1.1a] Software Engineering → Introduction → Pros and Cons

    • [W1.2] Java: Intro
    • [W1.2a] C++ to Java → About this Chapter

    • [W1.2b] C++ to Java → The Java World → What is Java?

    • [W1.2c] C++ to Java → The Java World → How Java Works

    • [W1.2d] C++ to Java → The Java World → Java Editions

    • [W1.3] Java: HelloWorld
    • [W1.3a] C++ to Java → Getting Started → Installation

    • [W1.3b] C++ to Java → Getting Started → HelloWorld

    • [W1.3c] C++ to Java → Getting Started → Compliling a Program

    • [W1.3d] C++ to Java → Getting Started → Running a Program

    • [W1.4] Java: Data Types
    • [W1.4a] C++ to Java → Data Types → Primitive Data Types

    • [W1.4b] C++ to Java → Data Types → Variables

    • [W1.4c] C++ to Java → Data Types → Operators

    • [W1.4d] C++ to Java → Data Types → Arrays

    • [W1.5] Java: Control Flow
    • [W1.5a] C++ to Java → Control Flow → Branching

    • [W1.5b] C++ to Java → Control Flow → Methods

    • [W1.5c] C++ to Java → Control Flow → Loops


    [W1.1] Software Engineering: Intro

    W1.1a

    Software Engineering → Introduction → Pros and Cons

    Can explain pros and cons of software engineering

    Software Engineering: Software Engineering is the application of a systematic, disciplined, quantifiable approach to the development, operation, and maintenance of software" -- IEEE Standard Glossary of Software Engineering Terminology

    The following description of the Joys of the Programming Craft was taken from Chapter 1 of the famous book The Mythical Man-Month, by Frederick P. Brooks.

    Why is programming fun? What delights may its practitioner expect as his reward?

    First is the sheer joy of making things. As the child delights in his mud pie, so the adult enjoys building things, especially things of his own design. I think this delight must be an image of God's delight in making things, a delight shown in the distinctness and newness of each leaf and each snowflake.

    Second is the pleasure of making things that are useful to other people. Deep within, we want others to use our work and to find it helpful. In this respect the programming system is not essentially different from the child's first clay pencil holder "for Daddy's office."

    Third is the fascination of fashioning complex puzzle-like objects of interlocking moving parts and watching them work in subtle cycles, playing out the consequences of principles built in from the beginning. The programmed computer has all the fascination of the pinball machine or the jukebox mechanism, carried to the ultimate.

    Fourth is the joy of always learning, which springs from the nonrepeating nature of the task. In one way or another the problem is ever new, and its solver learns something: sometimes practical, sometimes theoretical, and sometimes both.

    Finally, there is the delight of working in such a tractable medium. The programmer, like the poet, works only slightly removed from pure thought-stuff. He builds his castles in the air, from air, creating by the exertion of the imagination. Few media of creation are so flexible, so easy to polish and rework, so readily capable of realizing grand conceptual structures....

    Yet the program construct, unlike the poet's words, is real in the sense that it moves and works, producing visible outputs separate from the construct itself. It prints results, draws pictures, produces sounds, moves arms. The magic of myth and legend has come true in our time. One types the correct incantation on a keyboard, and a display screen comes to life, showing things that never were nor could be.

    Programming then is fun because it gratifies creative longings built deep within us and delights sensibilities we have in common with all men.

    Not all is delight, however, and knowing the inherent woes makes it easier to bear them when they appear.

    First, one must perform perfectly. The computer resembles the magic of legend in this respect, too. If one character, one pause, of the incantation is not strictly in proper form, the magic doesn't work. Human beings are not accustomed to being perfect, and few areas of human activity demand it. Adjusting to the requirement for perfection is, I think, the most difficult part of learning to program.

    Next, other people set one's objectives, provide one's resources, and furnish one's information. One rarely controls the circumstances of his work, or even its goal. In management terms, one's authority is not sufficient for his responsibility. It seems that in all fields, however, the jobs where things get done never have formal authority commensurate with responsibility. In practice, actual (as opposed to formal) authority is acquired from the very momentum of accomplishment.

    The dependence upon others has a particular case that is especially painful for the system programmer. He depends upon other people's programs. These are often maldesigned, poorly implemented, incompletely delivered (no source code or test cases), and poorly documented. So he must spend hours studying and fixing things that in an ideal world would be complete, available, and usable.

    The next woe is that designing grand concepts is fun; finding nitty little bugs is just work. With any creative activity come dreary hours of tedious, painstaking labor, and programming is no exception.

    Next, one finds that debugging has a linear convergence, or worse, where one somehow expects a quadratic sort of approach to the end. So testing drags on and on, the last difficult bugs taking more time to find than the first.

    The last woe, and sometimes the last straw, is that the product over which one has labored so long appears to be obsolete upon (or before) completion. Already colleagues and competitors are in hot pursuit of new and better ideas. Already the displacement of one's thought-child is not only conceived, but scheduled.

    This always seems worse than it really is. The new and better product is generally not available when one completes his own; it is only talked about. It, too, will require months of development. The real tiger is never a match for the paper one, unless actual use is wanted. Then the virtues of reality have a satisfaction all their own.

    Of course the technological base on which one builds is always advancing. As soon as one freezes a design, it becomes obsolete in terms of its concepts. But implementation of real products demands phasing and quantizing. The obsolescence of an implementation must be measured against other existing implementations, not against unrealized concepts. The challenge and the mission are to find real solutions to real problems on actual schedules with available resources.

    This then is programming, both a tar pit in which many efforts have floundered and a creative activity with joys and woes all its own. For many, the joys far outweigh the woes....

    [Text and book cover source: Wikipedia]

    [Fred Brooks photo source]

    The Mythical Man-Month: Essays on Software Engineering is a book on software engineering and project management by Fred Brooks, whose central theme is that "adding manpower to a late software project makes it later". This idea is known as Brooks's law, and is presented along with the second-system effect and advocacy of prototyping.

    Compare Software Engineering with Civil Engineering in terms of how work products in CE (i.e. buildings) differ from those of SE (i.e. software).

    Buildings Software
    Visible, tangible Invisible, intangible
    Wears out over time Does not wear out
    Change is limited by physical restrictions (e.g. difficult to remove a floor from a high rise building) Change is not limited by such restrictions. Just change the code and recompile.
    Creating an exact copy of a building is impossible. Creating a near copy is almost as costly as creating the original. Any number of exact copies can be made with near zero cost.
    Difficult to move. Easily delivered from one place to another.
    Many low-skilled workers following tried-and-tested procedures. No low-skilled workers involved. Workers have more freedom to follow their own procedures.
    Easier to assure quality (just follow accepted procedure). Not easy to assure quality.
    Majority of the work force has to be on location. Can be built by people who are not even in the same country.
    Raw materials are costly, costly equipment required. Almost free raw materials and relatively cheap equipment.
    Once construction is started, it is hard to do drastic changes to the design. Building process is very flexible. Drastic design changes can be done, although costly
    A lot of manual and menial labor involved. Most work involves highly-skilled labor.
    Generally robust. E.g. removing a single brick is unlikely to destroy a building. More fragile than buildings. A single misplaced semicolon can render the whole system useless.

    Comment on this statement: Building software is cheaper and easier than building bridges (all we need is a PC!).

    Depends on the size of the software. Manpower required for software is very costly. On the other hand, we can create a very valuable software (e.g. an iPhone application that can make million dollars in a month) with a just a PC and a few days of work!

    Justify this statement: Coding is still a ‘design’ activity, not a ‘manufacturing’ activity. You may use a comparison (or an analogy) of Software engineering versus Civil Engineering to argue this point.

    Arguments to support this statement:

    • If coding is a manufacturing activity, we should be able to do it using robotic machines (just like in the car industry) or low-skilled laborers (like in the construction industry).
    • If coding is a manufacturing activity, we wouldn’t be changing it so much after we code software. But if the code is in fact a ‘design’, yes, we would fiddle with it until we get it right.
    • Manufacturing is the process of building a finished product based on the design. Code is the design. Manufacturing is what is done by the compiler (fully automated).

    However, the type of ‘design’ that occurs during coding is at a much lower level than the ‘design’ that occurs before coding.

    List some (at least three each) pros and cons of Software Engineering compared to other traditional Engineering careers.

    • a. Need for perfection when developing software
    • b. Requiring some amount of tedious, painstaking labor
    • c. Ease of copying and transporting software makes it difficult to keep track of versions
    • d. High dependence on others
    • e. Seemingly never ending effort required for testing and debugging software
    • f. Fast moving industry making our work obsolete quickly

    (c)

    [W1.2] Java: Intro

    W1.2a

    C++ to Java → About this Chapter

    This book chapter assumes you are familiar with basic C++ programming. It provides a crash course to help you migrate from C++ to Java.

    This chapter borrows heavily from the excellent book ThinkJava by Allen Downey and Chris Mayfield. As required by the terms of reuse of that book, this chapter is released under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License and not under the MIT license as the rest of this book.

    Some conventions used in this chapter:

    icon marks the description of an aspect of Java that works mostly similar to C++

    icon marks the description of an aspect of Java that is distinctly different from C++

    Other resources used:

    W1.2b

    C++ to Java → The Java World → What is Java?

    Can explain what Java is

    Java was conceived by James Gosling and his team at Sun Microsystems in 1991.

    Java is directly related to both C and C++. Java inherits its syntax from C. Its object model is adapted from C++. --Java: A Beginner’s Guide, by Oracle

    Fun fact: The language was initially called Oak after an oak tree that stood outside Gosling's office. Later the project went by the name Green and was finally renamed Java, from Java coffee. --Wikipedia

    Oracle became the owner of Java in 2010, when it acquired Sun Microsystems.

    Java has remained the most popular language in the world for several years now (as at July 2018), according to the TIOBE index.

    W1.2c

    C++ to Java → The Java World → How Java Works

    Can explain how Java works at a higher-level

    Java is both compiled and interpreted. Instead of translating programs directly into machine language, the Java compiler generates byte code. Byte code is portable, so it is possible to compile a Java program on one machine, transfer the byte code to another machine, and run the byte code on the other machine. That’s why Java is considered a platform independent technology, aka WORA (Write Once Run Anywhere). The interpreter that runs byte code is called a “Java Virtual Machine” (JVM).

    Java technology is both a programming language and a platform. The Java programming language is a high-level object-oriented language that has a particular syntax and style. A Java platform is a particular environment in which Java programming language applications run. --Oracle

    W1.2d

    C++ to Java → The Java World → Java Editions

    Can explain Java editions

    According to the Official Java documentation, there are four platforms of the Java programming language:

    • Java Platform, Standard Edition (Java SE): Contains the core functionality of the Java programming language.

    • Java Platform, Enterprise Edition (Java EE): For developing and running large-scale enterprise applications. Built on top of Java SE.

    • Java Platform, Micro Edition (Java ME): For Java programming language applications meant for small devices, like mobile phones. A subset of Java SE.

    • JavaFX: For creating applications with graphical user interfaces. Can work with the other three above.

    This book chapter uses the Java SE edition unless stated otherwise.

    [W1.3] Java: HelloWorld

    W1.3a

    C++ to Java → Getting Started → Installation

    Can install Java

    To run Java programs, you only need to have a recent version of the Java Runtime Environment (JRE) installed in your device.

    If you want to develop applications for Java, download and install a recent version of the Java Development Kit (JDK), which includes the JRE as well as additional resources needed to develop Java applications.

    W1.3b

    C++ to Java → Getting Started → HelloWorld

    Can explain the Java HelloWorld program

    In Java, the HelloWorld program looks like this:

    public class HelloWorld {
    
        public static void main(String[] args) {
            // generate some simple output
            System.out.println("Hello, World!");
        }
    }
    

    For reference, the equivalent C++ code is given below:

    #include <iostream>
    using namespace std;
    
    int main() {
        // generate some simple output
        cout << "Hello, World!";
        return 0;
    }
    

    This HelloWorld Java program defines one method named main: public static void main(String[] args)

    System.out.println displays results on the screen.

    Some similarities:

    • Java programs are made up of class and method definitions, and methods are made up of statements.
    • Java is “case-sensitive”, which means SYSTEM is different from System.
    • public is an access modifier that indicates the method is accessible from outside this class. Similarly, private access modifier indicates that a method/attribute is not accessible outside the class.
    • static indicates this method is defined as a class-level member. Do not worry if you don’t know what that means. It will be explained later.
    • void indicates that the method does not return anything.
    • The name and format of the main method is special as it is the method that Java executes when you run a Java program.
    • A class is a collection of methods. This program defines a class named HelloWorld.
    • Java uses squiggly braces ({ and }) to group things together.
    • The line starting with // is a comment. You can use // for single line comments and /* ... */ for multi-line comments in Java code.

    A statement is a line of code that performs a basic operation. In the HelloWorld program, this line is a print statement that displays a message on the screen:

    System.out.println("Hello, World!");

    Some differences:

    • Java use the term method instead of function. In particular, Java doesn’t have stand-alone functions. Every method should belong to a class. The main method will not work unless it is inside the HelloWorld class.
    • A Java class definition does not end with a semicolon, but most Java statements do.
    • In most cases (i.e., there are exceptions), the name of the class has to match the name of the file it is in, so this class has to be in a file named HelloWorld.java.
    • There is no need for the HelloWorld code to have something like #include <iostream>. The library files needed by the HelloWorld code is available by default without having to "include" them explicitly.
    • There is no need to return 0 at the end of the main method to indicate the execution was successful. It is considered as a successful execution unless an error is signalled specifically.

    W1.3c

    C++ to Java → Getting Started → Compliling a Program

    Can compile a simple Java program

    To compile the HelloWorld program, open a command console, navigate to the folder containing the file, and run the following command.

    >_ javac HelloWorld.java

    If the compilation is successful, you should see a file HelloWorld.class. That file contains the byte code for your program. If the compilation is unsuccessful, you will be notified of the compile-time errors.

    Compile-time errors (aka compile errors) occur when you violate the syntax rules of the Java language. For example, parentheses and braces have to come in matching pairs.

    Error messages from the compiler usually indicate where in the program the error occurred, and sometimes they can tell you exactly what the error is.

    Notes:

    • javac is the java compiler that you get when you install the JDK.
    • For the above command to work, your console program should be able to find the javac executable (e.g., the location of the javac.exe should be in the PATH system variable).

    W1.3d

    C++ to Java → Getting Started → Running a Program

    Can run a simple Java program

    To run the HelloWorld program, in a command console, run the following command from the folder containing HelloWorld.class file.

    >_ java HelloWorld

    Notes:

    • java in the command above refers to the Java interpreter installed in your computer.
    • Similar to javac, your console should be able to find the java executable.

    When you run a Java program, you can encounter a run-time error. These errors are also called "exceptions" because they usually indicate that something exceptional (and bad) has happened. When a run-time error occurs, the interpreter displays an error message that explains what happened and where.

    For example, modify the HelloWorld code to include the following line, compile it again, and run it.

    System.out.println(5/0);
    

    You should get a message like this:

    Exception in thread "main" java.lang.ArithmeticException: / by zero
        at Hello.main(Hello.java:5)
    

    Integrated Development Environments (IDEs) can automate the intermediate step of compiling. They usually have a Run button which compiles the code first and then runs it.

    Example IDEs:

    • Intellij IDEA
    • Eclipse
    • NetBeans
    • Install Java in your computer, if you haven't done so already.
    • Write, compile and run a small Java program (e.g., a HelloWorld program) in your computer. You can use any code editor to write the program but use the command prompt to compile and run the program.
    • Modify the code and run the program again.

    [W1.4] Java: Data Types

    W1.4a

    C++ to Java → Data Types → Primitive Data Types

    Can use primitive data types

    Here are the primitive data types in Java:

    • byte: an integer in the range -128 to 127 (inclusive).
    • short: an integer in the range -32,768 to 32,767 (inclusive).
    • int: an integer in the range -231 to 231-1.
    • long: An integer in the range -263 to 263-1.
    • float: a single-precision 32-bit IEEE 754 floating point. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead.
    • double: a double-precision 64-bit IEEE 754 floating point. For decimal values, this data type is generally the default choice. This data type should never be used for precise values, such as currency.
    • boolean: has only two possible values: true and false.
    • char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

    String (a peek)

    Java has a built-in type called String to represent strings. While String is not a primitive type, they are used as often, if not more. String values are demarcated by enclosing in a pair of double quotes. You can use the plus operator to concatenate strings. E.g.,

    String name = "John Doe";
    System.out.println("Hello " + name + "!");
    

    String is not a primitive type. You’ll learn more about strings in a later section.

    W1.4b

    C++ to Java → Data Types → Variables

    Can use variables

    Java is a statically-typed language in that variables have a fixed type. Here are some examples of declaring variables and assigning values to them.

    int x;
    x = 5;
    int hour = 11;
    boolean isCorrect = true;
    char capitalC = 'C';
    byte b = 100;
    short s = 10000;
    int i = 100000;
    

    You can use any name starting with a letter, underscore, or $ as a variable name but you cannot use Java keywords as variables names. You can display the value of a variable using System.out.print or System.out.println (the latter goes to the next line after printing). To output multiple values on the same line, it’s common to use several print statements followed by println at the end.

    int hour = 11;
    int mintue = 59;
    System.out.print("The current time is ");
    System.out.print(hour);
    System.out.print(":");
    System.out.print(minute);
    System.out.println("."); //use println here to complete the line
    System.out.println("done");
    
    

    The current time is 11:59.
    done
    

    Use the keyword final to indicate that the variable value, once assigned, should not be allowed to change later i.e., act like a ‘constant’. By convention, names for constants are all uppercase, with the underscore character (_) between words.

    final double CM_PER_INCH = 2.54;
    

    W1.4c

    C++ to Java → Data Types → Operators

    Can use operators

    Java has the following arithmetic operators:

    Operator Description Examples
    + Additive operator 2 + 3 5
    - Subtraction operator 4 - 1 3
    * Multiplication operator 2 * 3 6
    / Division operator 5 / 2 2 but 5.0 / 2 2.5
    % Remainder operator 5 % 2 1

    The following program uses some operators as part of an expression hour * 60 + minute:

    int hour = 11;
    int minute = 59;
    System.out.print("Number of minutes since midnight: ");
    System.out.println(hour * 60 + minute);
    

    Number of minutes since midnight: 719
    

    When an expression has multiple operators, normal operator precedence rules apply. Furthermore, you can use parentheses to specify a precise precedence.

    Examples:

    • 4 * 5 - 1 19 (* has higher precedence than -)
    • 4 * (5 - 1) 16 (parentheses ( ) have higher precedence than *)

    Java does not allow operator overloading.

    The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.-- Java Tutorial

    Operator Description -- Java Tutorial example
    + Unary plus operator; indicates positive value
    (numbers are positive without this, however)
    x = 5; y = +x y is 5
    - Unary minus operator; negates an expression x = 5; y = -x y is -5
    ++ Increment operator; increments a value by 1 i = 5; i++ i is 6
    -- Decrement operator; decrements a value by 1 i = 5; i-- i is 4
    ! Logical complement operator; inverts the value of a boolean foo = true; bar = !foo bar is false

    Relational operators are used to check conditions like whether two values are equal, or whether one is greater than the other. The following expressions show how they are used:

    Operator Description example true example false
    x == y x is equal to y 5 == 5 5 == 6
    x != y x is not equal to y 5 != 6 5 != 5
    x > y x is greater than y 7 > 6 5 > 6
    x < y x is less than y 5 < 6 7 < 6
    x >= y x is greater than or equal to y 5 >= 5 4 >= 5
    x <= y x is less than or equal to y 4 <= 5 6 <= 5

    The result of a relational operator is a boolean value.

    Java has three conditional operators that are used to operate on boolean values.

    Operator Description example true example false
    && and true && true true true && false false
    || or true || false true false || false false
    ! not not false not true

    W1.4d

    C++ to Java → Data Types → Arrays

    Can use arrays

    Arrays are indicated using square brackets ([]). To create the array itself, you have to use the new operator. Here are some example array declarations:

    int[] counts;
    counts = new int[4]; // create an int array of size 4
    
    int size = 5;
    double[] values;
    values = new double[size]; //use a variable for the size
    
    double[] prices = new double[size]; // declare and create at the same time
    
    Alternatively, you can use the shortcut syntax to create and initialize an array:
    int[] values = {1, 2, 3, 4, 5, 6};
    
    int[] anArray = {
        100, 200, 300,
        400, 500, 600,
        700, 800, 900, 1000
    };
    

    -- Java Tutorial

    The [] operator selects elements from an array. Array elements indices start from 0.

    int[] counts = new int[4];
    
    System.out.println("The first element is " + counts[0]);
    
    counts[0] = 7; // set the element at index 0 to be 7
    counts[1] = counts[0] * 2;
    counts[2]++; // increment value at index 2
    

    A Java array is aware of its size. A Java array prevents a programmer from indexing the array out of bounds. If the index is negative or not present in the array, the result is an error named ArrayIndexOutOfBoundsException.

    int[] scores = new int[4];
    System.out.println(scores.length) // prints 4
    scores[5] = 0; // causes an exception
    

    4
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    	at Main.main(Main.java:6)
    

    It is also possible to create arrays of more than one dimension:

    String[][] names = {
        {"Mr. ", "Mrs. ", "Ms. "},
        {"Smith", "Jones"}
    };
    
    System.out.println(names[0][0] + names[1][0]); // Mr. Smith
    System.out.println(names[0][2] + names[1][1]); // Ms. Jones
    

    -- Java Tutorial

    Passing arguments to a program

    The args parameter of the main method is an array of Strings containing command line arguments supplied (if any) when running the program.

    public class Foo{
        public static void main(String[] args) {
            System.out.println(args[0]);
        }
    }
    

    You can run this program (after compiling it first) from the command line by typing:

    >_ java Foo abc

    abc

    Write a Java program that takes two command line arguments and prints true or false to indicate if the two arguments have the same value. Follow the sample output given below.

    class WordComparator {
      public static void main(String[] args) {
          // add your code here
      }
    }
    

    >_ java WordComparator adam eve

    Words given: adam, eve
    They are the same: false
    

    >_ java WordComparator eve eve

    Words given: eve, eve
    They are the same: true
    

    Use the following technique to compare two Strings(i.e., don't use ==). Reason: to be covered in a later topic.

    String x = "foo";
    boolean isSame = x.equals("bar") // false
    isSame = x.equals("foo") // true
    
    • The two command line arguments can be accessed inside the main method using args[0] and args[1].
    • When using multiple operators in the same expression, you might need to use parentheses to specify operator precedence. e.g., "foo" + x == y vs "foo" + (x == y)
    class WordComparator {
      public static void main(String[] args) {
          String first = args[0];
          String second = args[1];
          System.out.println("Words given: " + first + ", " + second);
          // ...
      }
    }
    
    

    [W1.5] Java: Control Flow

    W1.5a

    C++ to Java → Control Flow → Branching

    Can use branching

    if-else statements

    Java supports the usual forms of if statements:

    if (x > 0) {
        System.out.println("x is positive");
    }
    
    if (x % 2 == 0) {
        System.out.println("x is even");
    } else {
        System.out.println("x is odd");
    }
    
    if (x > 0) {
        System.out.println("x is positive");
    } else if (x < 0) {
        System.out.println("x is negative");
    } else {
        System.out.println("x is zero");
    }
    
    if (x == 0) {
        System.out.println("x is zero");
    } else {
        if (x > 0) {
            System.out.println("x is positive");
        } else {
            System.out.println("x is negative");
        }
    }
    

    The braces are optional (but recommended) for branches that have only one statement. So we could have written the previous example this way ( Bad):

    if (x % 2 == 0)
        System.out.println("x is even");
    else
        System.out.println("x is odd");
    
    switch statements

    The switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enums, String.

    Here is an example (adapted from -- Java Tutorial):

    public class SwitchDemo {
        public static void main(String[] args) {
    
            int month = 8;
            String monthString;
            switch (month) {
            case 1:  monthString = "January";
                break;
            case 2:  monthString = "February";
                break;
            case 3:  monthString = "March";
                break;
            case 4:  monthString = "April";
                break;
            case 5:  monthString = "May";
                break;
            case 6:  monthString = "June";
                break;
            case 7:  monthString = "July";
                break;
            case 8:  monthString = "August";
                break;
            case 9:  monthString = "September";
                break;
            case 10: monthString = "October";
                break;
            case 11: monthString = "November";
                break;
            case 12: monthString = "December";
                break;
            default: monthString = "Invalid month";
                break;
            }
            System.out.println(monthString);
        }
    }
    

    August

    Write a Java program that takes several command line arguments that describe a person or a family | and prints out a greeting. The parameters can be one of two formats.

    arguments format explanation expected output
    NAME GENDER Indicates a single person. GENDER can be M or F Smith M Dear Mr. Smith
    Lee F Dear Mdm. Lee
    NAME MULTIPLE_GENDERS Indicates a family. Tan M M F Dear Tan family

    Follow the sample output given below.

    >_ java Greeter Smith M Dear Mr. Smith

    >_ java Greeter Lee F Dear Mdm. Lee

    >_ java Greeter Tan M M F Dear Tan family

    You can assume that the input is always in the correct format i.e., no need to handle invalid input cases.

    Partial solution:

    public class Greeter {
        public static void main(String[] args) {
            String first = args[0];
            String second = args[1];
            if (args.length == 2) {
                if (second.equals("M")) {
                    // ...
                }
            } else {
                // ...
            }
        }
    }
    

    Write a Java program that takes a letter grade e.g., A+ as a command line argument and prints the CAP value for that grade.

    Use a switch statement in your code.

    A+ A A- B+ B B- C Else
    5.0 5.0 4.5 4.0 3.5 3.0 2.5 0

    Follow the sample output given below.

    >_ java GradeHelper B CAP for grade B is 3.5

    You can assume that the input is always in the correct format i.e., no need to handle invalid input cases.

    Partial solution:

    public class GradeHelper {
        public static void main(String[] args) {
            String grade = args[0];
            double cutoff = 0;
            switch (grade) {
            case "A+":
                // ...
            }
            System.out.println("CAP for grade " + grade + " is " + cutoff);
        }
    }
    

    W1.5b

    C++ to Java → Control Flow → Methods

    Can use methods

    Defining methods

    Here’s an example of adding more methods to a class:

    public class PrintTwice {
    
        public static void printTwice(String s) {
            System.out.println(s);
            System.out.println(s);
        }
    
        public static void main(String[] args) {
            String sentence = “Polly likes crackers”
            printTwice(sentence);
    
        }
    }
    
    

    Polly likes crackers
    Polly likes crackers
    

    By convention, method names should be named in the camelCase format.

    CamelCase is named after the "humps" of its capital letters, similar to the humps of a Bactrian camel. Camel case (stylized as camelCase) is the practice of writing compound words or phrases such that each word or abbreviation in the middle of the phrase begins with a capital letter, with no intervening spaces or punctuation.

    -- adapted from Wikipedia

    e.g., createEmptyList, listOfIntegers, htmlText, dvdPlayer. This book defines camelCase style as requiring the first letter to be lower case. If the first letter is upper case instead e.g., CreateEmptyList, it is called UpperCamelCase or PascalCase.

    Similar to the main method, the printTwice method is public (i.e., it can be invoked from other classes) static and void.

    Parameters

    A method can specify parameters. The printTwice method above specifies a parameter of String type. The main method passes the argument "Polly likes crackers" to that parameter.

    The value provided as an argument must have the same type as the parameter. Sometimes Java can convert an argument from one type to another automatically. For example, if the method requires a double, you can invoke it with an int argument 5 and Java will automatically convert the argument to the equivalent value of type double 5.0.

    Because variables only exist inside the methods where they are defined, they are often called local variables. Parameters and other variables declared inside a method only exist inside their own methods. Inside main, there is no such thing as s. If you try to use it there, you’ll get a compiler error. Similarly, inside printTwice there is no such thing as sentence. That variable belongs to main.

    return statements

    The return statement allows you to terminate a method before you reach the end of it:

    public static void printLogarithm(double x) {
        if (x <= 0.0) {
            System.out.println("Error: x must be positive.");
            return;
        }
        double result = Math.log(x);
        System.out.println("The log of x is " + result);
    }
    

    It can be used to return a value from a method too:

    public class AreaCalculator{
    
        public static double calculateArea(double radius) {
            double result = 3.14 * radius * radius;
            return result;
        }
    
        public static void main(String[] args) {
            double area = calculateArea(12.5);
            System.out.println(area);
        }
    }
    
    Overloading

    Java methods can be overloaded. If two methods do the same thing, it is natural to give them the same name. Having more than one method with the same name is called overloading, and it is legal in Java as long as each version takes different parameters.

    public static double calculateArea(double radius) {
        //...
    }
    
    public static double calculateArea(double height, double width) {
        //...
    }
    
    Recursion

    Methods can be recursive. Here is an example in which the nLines method calls itself recursively:

    public static void nLines(int n) {
        if (n > 0) {
            System.out.println();
            nLines(n - 1);
        }
    }
    

    Add the following method to the class given below.

    • public static double getGradeCap(String grade): Returns the CAP value of the given grade. The mapping from grades to CAP is given below.
    A+ A A- B+ B B- C Else
    5.0 5.0 4.5 4.0 3.5 3.0 2.5 0
    public class Main {
    
        // ADD YOUR CODE HERE
    
        public static void main(String[] args) {
            System.out.println("A+: " + getGradeCap("A+"));
            System.out.println("B : " + getGradeCap("B"));
        }
    }
    

    A+: 5.0
    B : 3.5
    

    Partial solution:

        public static double getGradeCap(String grade) {
            double cap = 0;
            switch (grade) {
            case "A+":
            case "A":
                cap = 5.0;
                break;
            case "A-":
                cap = 4.5;
                break;
            case "B+":
                cap = 4.0;
                break;
            case "B":
                cap = 3.5;
                break;
            case "B-":
                cap = 3.0;
                break;
            default:
            }
            return cap;
        }
    

    W1.5c

    C++ to Java → Control Flow → Loops

    Can use loops

    while loops

    Here is an example while loop:

    public static void countdown(int n) {
        while (n > 0) {
            System.out.println(n);
            n = n - 1;
        }
        System.out.println("Blastoff!");
    }
    
    for loops

    for loops have the form:

    for (initializer; condition; update) {
        statement(s);
    }
    

    Here is an example:

    public static void printTable(int rows) {
        for (int i = 1; i <= rows; i = i + 1) {
            printRow(i, rows);
        }
    }
    
    do-while loops

    The while and for statements are pretest loops; that is, they test the condition first and at the beginning of each pass through the loop. Java also provides a posttest loop: the do-while statement. This type of loop is useful when you need to run the body of the loop at least once.

    Here is an example (from -- Java Tutorial):

    class DoWhileDemo {
        public static void main(String[] args){
            int count = 1;
            do {
                System.out.println("Count is: " + count);
                count++;
            } while (count < 11);
        }
    }
    
    break and continue

    A break statement exits the current loop.

    Here is an example (from -- Java Tutorial):

    class Main {
        public static void main(String[] args) {
            int[] numbers = new int[] { 1, 2, 3, 0, 4, 5, 0 };
            for (int i = 0; i < numbers.length; i++) {
                if (numbers[i] == 0) {
                    break;
                }
                System.out.print(numbers[i]);
            }
        }
    }
    

    123
    

    [Try the above code on Repl.it]

    A continue statement skips the remainder of the current iteration and moves to the next iteration of the loop.

    Here is an example (from -- Java Tutorial):

    public static void main(String[] args) {
        int[] numbers = new int[] { 1, 2, 3, 0, 4, 5, 0 };
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == 0) {
                continue;
            }
            System.out.print(numbers[i]);
        }
    }
    

    12345
    

    [Try the above code on Repl.it]

    Enhanced for loops

    Since traversing arrays is so common, Java provides an alternative for-loop syntax that makes the code more compact. For example, consider a for loop that displays the elements of an array on separate lines:

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

    We could rewrite the loop like this:

    for (int value : values) {
        System.out.println(value);
    }
    

    This statement is called an enhanced for loop. You can read it as, “for each value in values”. Notice how the single line for (int value : values) replaces the first two lines of the standard for loop.

    Add the following method to the class given below.

    • public static double[] getMultipleGradeCaps(String[] grades): Returns the CAP values of the given grades. e.g., if the input was the array ["A+", "B"], the method returns [5.0, 3.5]. The mapping from grades to CAP is given below.
    A+ A A- B+ B B- C Else
    5.0 5.0 4.5 4.0 3.5 3.0 2.5 0
    public class Main {
    
        // ADD YOUR CODE HERE
    
        public static double getGradeCap(String grade) {
            double cap = 0;
            switch (grade) {
            case "A+":
            case "A":
                cap = 5.0;
                break;
            case "A-":
                cap = 4.5;
                break;
            case "B+":
                cap = 4.0;
                break;
            case "B":
                cap = 3.5;
                break;
            case "B-":
                cap = 3.0;
                break;
            case "C":
                cap = 2.5;
                break;
            default:
            }
            return cap;
        }
    
        public static void main(String[] args) {
            String[] grades = new String[]{"A+", "A", "A-"};
            double[] caps = getMultipleGradeCaps(grades);
            for (int i = 0; i < grades.length; i++) {
                System.out.println(grades[i] + ":" + caps[i]);
            }
        }
    }
    

    A+:5.0
    A:5.0
    A-:4.5
    

    Partial solution:

        public static double[] getMultipleGradeCaps(String[] grades) {
            double[] caps = new double[grades.length];
            for (int i = 0; i < grades.length; i++) {
               // ...
            }
            return caps;
        }