IT232 Study Guide — Modules 6-13

Unit 6-13 Finals Study Guide

Module 6 — Methods (Part 1)

1. Modules Approach

Suppose you want to build a program as follows:

int sum = 0;
for (int i = 1; i <= 10; i++)
    sum += i;
System.out.println("Sum from 1 to 10 is " + sum);

sum = 0;
for (int i = 20; i <= 30; i++)
    sum += i;
System.out.println("Sum from 20 to 30 is " + sum);

sum = 0;
for (int i = 35; i <= 45; i++)
    sum += i;
System.out.println("Sum from 35 to 45 is " + sum);

Defining a method will make you code more simpler:

public class SumExample {
    public static int sum(int i1, int i2) {
        int sum = 0;
        for (int i = i1; i <= i2; i++)
            sum += i;
        return sum;
    }

    public static void main(String[] args) {
        System.out.println("Sum from 1 to 10 is " + sum(1, 10));
        System.out.println("Sum from 20 to 30 is " + sum(20, 30));
        System.out.println("Sum from 35 to 45 is " + sum(35, 45));
    }
}

You build Java programs by combining new methods and classes with predefined ones available in the Java Application Programming Interface (API).

Methods help you modularize a program by separating its tasks into self-contained units.

Divide and Conquer

  • It makes program development more manageable by constructing programs from small, simple pieces.
  • Software reusability — using existing methods as building blocks to create new programs.

Hierarchical Relationship Between Method Calls

A method is invoked by a method call

  • when the called method completes its task
  • it returns control — and possibly a result — to the caller.

A boss method calls worker methods (e.g. worker1, worker2, worker3) in a hierarchical boss-method/worker-method relationship.

Review Questions

Practice — Section 1: Modules Approach

Source:quiz-1-2026-hot

What is the main purpose of using methods in Java?

Answer

D. To modularize programs into smaller parts

Methods break a big program into smaller named pieces you can read, test, and reuse. That's modularization — the whole point of writing methods.

Source:CS140 MidTerm Fall-2014-15

What does it mean to invoke a method in Java? Give an example.

Answer

Invoking a method means calling it by writing its name followed by parentheses.

greet("Sara");

static void greet(String name) {
    System.out.println("Hello, " + name);
}

2. Declaring Methods

public static int methodName(int a, int b) {
    // body
}
  • public static — modifier
  • int — return type
  • methodName — name of the method
  • a, b — formal parameters
  • int a, int b — list of parameters

  • The method name should be a verb and start with a lowercase letter.

  • If the method name has more than two words, the first name must be a verb followed by adjective or noun.
  • In the multi-word method name, the first letter of each word must be in uppercase except the first word.

For example:

  • Single-word method name: sum(), area()
  • Multi-word method name: areaOfCircle(), stringComparision()

Types of Method

  • Predefined Method
  • User-defined Method

Predefined Method are the method that is already defined in the Java class libraries.

  • known as the standard library method or built-in method.
public class Demo {
    public static void main(String[] args) {
        // using the max() method of Math class
        System.out.print("The maximum number is: " + Math.max(9, 7));
    }
}

User-defined Method

  • The method written by the user or programmer
import java.util.Scanner;

public class EvenOdd {
    // user defined method
    public static void findEvenOdd(int num) {
        // method body
        if (num % 2 == 0)
            System.out.println(num + " is even");
        else
            System.out.println(num + " is odd");
    }

    public static void main(String[] args) {
        // creating Scanner class object
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the number: ");
        // reading value from the user
        int num = scan.nextInt();
        // method calling
        findEvenOdd(num);
    }
}

Example

public class Addition {
    public static void main(String[] args) {
        int a = 19;
        int b = 5;
        // method calling
        int c = add(a, b); // a and b are actual parameters
        System.out.println("The sum of a and b is=" + c);
    }

    // user defined method
    public static int add(int n1, int n2) { // n1 and n2 are formal parameters
        int s;
        s = n1 + n2;
        return s; // returning the sum
    }
}

Return Values

  • The void keyword, used in the examples above, indicates that the method should not return a value.
  • If you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead of void, and use the return keyword inside the method:
public class Main {
    static int myMethod(int x) {
        return 5 + x;
    }

    public static void main(String[] args) {
        System.out.println(myMethod(3));
    }
}
// Outputs 8 (5+3)
Review Questions

Practice — Section 2: Declaring Methods

Source:232

The method name should be a ___________ and start with a ___________ letter.

Answer

D. Verb / Lowercase

Java method names usually describe an action, so they should be verbs and start with a lowercase letter, like calculateTotal.

Source:232

The following method declaration return a/an ________________ value/s.

public String print(int x, String y) {
    return y;
}
Answer

B. String

The method header says public String, so the method must return a String. The line return y; also returns the String parameter.

Source:232

sqrt() is a ____________ method of Math class. It returns the square root of a number.

Answer

A. Predefined

sqrt() is already provided by Java in the Math class, so it is a predefined method, not one you write yourself.

Source:232

What is the return type of a method that does not return any value?

Answer

B. void

Use void when a method performs an action but does not send any value back with return.

Source:232 · IT232 Final T2 2021-2022

To calculate the maximum number of two variables x and y, we can use the following java statement:

Answer

B. Math.max(x,y);

Math.max(x, y) is the Java library method that returns the larger of two numbers.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

In Java, the method name should be a verb and start with a ________.

Answer

C. lowercase letter

Java method names normally start with a lowercase letter and use a verb-style name, such as printReport.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

To get a value from a method that you just created in Java, you would use the ________ keyword.

Answer

C. return

return sends a value back from a method to the place where the method was called.

Source:Final Exam IT-232

Which option follows Java's recommended naming conventions for methods?

Answer

D. calculateTotal()

Java method names should start lowercase and use camelCase for multiple words, like calculateTotal().

Source:Final Exam IT-232

What should be the return type of the following method in Java?

public static ______ getSum(double a, double b)
{
return a + b;
}
Answer

D. double

a and b are double, so a + b is also a double. The method return type should match that result.

Source:IT232 Final T2 2021-2022

The following method declaration return a/anpublic String methl (int x, String y)

Answer

D. String

The method header starts with public String, so the method's return type is String.

Source:IT232 Final T2 2021-2022

The method name should be a ______ and start with a ______ letter.

Answer

B. verb/lowercase

Method names usually describe actions, so they should be verbs and start with a lowercase letter.

Source:232 · IT232 Final T2 2021-2022

To calculate the maximum number of two variables x and y, we can use the following java statement:

Answer

B. Math.max(x,y);

Math.max(x, y) is the Java library method that returns the larger of two numbers.

Source:IT232 Final T2 2021-2022

Which of the following can't be used as a returned type in a method declaration?

Answer

D. null

null is a value, not a return type. A method return type must be something like int, char, String, void, or a class type.

Source:Java Final v3

In java, the method name should be a verb and start with ____________

Answer

C. Lowercase letter

Java method names usually start with a lowercase letter, like calculateTotal.

Source:Java Final v3

To get a value from method that you just created in java, you should use the ______________ keyword inside the method.

Answer

C. return

return sends a value from the method back to the code that called it.

Source:Java Final v3

What is the output of the following code snippet?

double x = 2;
double y = 3;
double z = Math.pow(x, 3) + Math.pow(y, 2) + x * (2 + y);
System.out.println(z);
Answer

B. 27.0

Math.pow(2, 3) is 8.0, Math.pow(3, 2) is 9.0, and 2 * (2 + 3) is 10.0. The total is 27.0.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

What is the output of the following code snippet?

double x = 2;
double y = 3;
double z = Math.pow(x, 3) + Math.pow(y, 2);
System.out.println(z);
Answer

Output: 17.0

(Math.pow(2,3) + Math.pow(3,2) = 8.0 + 9.0 = 17.0.)

Source:IT232 Final T2 2021-2022

Write the method isMultipleOf (not a complete java program) that receives two integer parameters a and b then returns true if b is a multiple of a and false otherwise.

Examples:

  • isMultipleOf(3, 27); returns true.
  • isMultipleOf(4, 25); returns false.
Answer
public static boolean isMultipleOf(int a, int b) {
    return b % a == 0;
}

Source:Java Final v3

Write the method named calculateArea (not a complete java program) to calculate and print the area of the Rectangle and Triangle based on the following formulas:

Rectangle_area = height * width

Triangle_area = height * width / 2

The method receives two float parameters height and width and has no return type.

Examples of the method call:

calculateArea(1,3)

// method prints

// Area of the rectangle is: 3.0

// Area of the triangle is: 1.5

Answer
public static void calculateArea(float height, float width) {
    System.out.println("Area of the rectangle is :" + (height * width));
    System.out.println("Area of the triangle is: "  + (height * width / 2));
}

3. Arguments and Casting

Information can be passed to methods as parameter. Parameters are specified after the method name, inside the parentheses.

You can add as many parameters as you want, just separate them with a comma.

public class Main {
    static void myMethod(String fname) {
        System.out.println(fname + " Refsnes");
    }

    public static void main(String[] args) {
        myMethod("Liam");
        myMethod("Jenny");
        myMethod("Anja");
    }
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes

Multiple Parameters

public class Main {
    static void myMethod(String fname, int age) {
        System.out.println(fname + " is " + age);
    }

    public static void main(String[] args) {
        myMethod("Liam", 5);
        myMethod("Jenny", 8);
        myMethod("Anja", 31);
    }
}
// Liam is 5
// Jenny is 8
// Anja is 31

pass-by-value

When Java passes a variable to a method via a parameter, the method itself receives a copy of the variable's value, not the variable itself.

public class ChangeParameters {
    public static void main(String[] args) {
        int number = 1;
        tryToChangeNumber(number);
        System.out.println(number);
    }

    public static void tryToChangeNumber(int i) {
        i = 2;
    }
}

Argument Promotion

  • Coercion of arguments
  • Forcing arguments to appropriate type to pass to method e.g., System.out.println( Math.sqrt( 4 ) );
  • Evaluates Math.sqrt(4) Then evaluates System.out.println()
  • Promotion rules
  • Specify how to convert types without data loss

The following table:

Type Valid promotions
double None
float double
long float or double
int long, float or double
char int, long, float or double
short int, long, float or double (but not char)
byte short, int, long, float or double (but not char)
boolean None (boolean values are not considered to be numbers in Java)

Promotions allowed for primitive types.

  • Suppose method square calculates the square of an integer
  • Thus requires an int argument.
  • To call square with a double argument named doubleValue, we would be required to write the method call as square((int) doubleValue)
  • This method call explicitly casts (converts) doubleValue's value to a temporary integer for use in method square.
  • Thus, if doubleValue's value is 4.5, the method receives the value 4 and returns 16, not 20.25.
Review Questions

Practice — Section 3: Arguments and Casting

Source:232

The input to a method is called a(n) ____________.

Answer

A. Parameter

A parameter is the input name written in the method header. The method uses it to receive a value from the caller.

Source:Final Exam IT-232

What is the output when running the following method with the parameters 9 and 19?

public static int myMethod(int x, int y)
{
x++;
y++;
return x * y;
}
Answer

C. 200

x becomes 10 and y becomes 20 after the increments. The method returns 10 * 20, which is 200.

Source:Final Exam IT-232

Which example shows explicit casting when calling a method expecting an int parameter?

Answer

D. square((int) value)

(int) value explicitly casts value to an integer before passing it to square.

Source:IT232 Final T2 2021-2022

What is the output of the execution of the following code?

public class Test {
    public static void mult2 (int b, int a, int c)
    {
        a = a + 1;
        b = b + 2;
    }
    public static void main(String[] args)
    {
        int x = 9, y = 8;
        mult2(x, y, 2);
        System.out.print(x + "-" + y);
    }
}
Answer

D. 9-8

Java passes copies of x and y into the method. Changing a and b inside mult2 does not change the original x and y.

Source:IT232 Final T2 2021-2022

The input to a method is called a(n) ______

Answer

D. parameter

A parameter is the input variable written in a method header.

Source:Java Final (New)

What are the formal parameters in the method header of the following code snippet?

public static int sumTwoNumbers(int numberOne, int numberTwo) {
    int sumNumbers = 0;
    for (int number = numberOne; number <= numberTwo; number ++)
        sumNumbers += number;
    return sumNumbers;
}
Answer

C. numberOne and numberTwo

Formal parameters are the variables listed in the method header parentheses: numberOne and numberTwo.

Module 7 — Methods (Part 2)

1. Java API Packages

A package is a group of related classes grouped together to promote software reuse. Use import statements to bring classes from a package into your program (e.g. import javax.swing.JApplet;).

The Java API ships with many packages. Some of the most commonly used ones:

Package Description
java.awt.event The Java Abstract Window Toolkit Event Package contains classes and interfaces that enable event handling for GUI components in both the java.awt and javax.swing packages. (See Chapter 12, GUI Components: Part 1, and Chapter 22, GUI Components: Part 2.)
java.awt.geom The Java 2D Shapes Package contains classes and interfaces for working with Java's advanced two-dimensional graphics capabilities. (See Chapter 13, Graphics and Java 2D.)
java.io The Java Input/Output Package contains classes and interfaces that enable programs to input and output data. (See Chapter 15, Files, Streams and Object Serialization.)
java.lang The Java Language Package contains classes and interfaces (discussed throughout the book) that are required by many Java programs. This package is imported by the compiler into all programs.
java.net The Java Networking Package contains classes and interfaces that enable programs to communicate via computer networks like the Internet. (See online Chapter 28, Networking.)
java.security The Java Security Package contains classes and interfaces for enhancing application security.
java.sql The JDBC Package contains classes and interfaces for working with databases. (See Chapter 24, Accessing Databases with JDBC.)
java.util The Java Utilities Package contains utility classes and interfaces that enable storing and processing of large amounts of data. Many of these classes and interfaces have been updated to support Java SE 8's new lambda capabilities. (See Chapter 16, Generic Collections.)
java.util.concurrent The Java Concurrency Package contains utility classes and interfaces for implementing programs that can perform multiple tasks in parallel. (See Chapter 23, Concurrency.)
javax.swing The Java Swing GUI Components Package contains classes and interfaces for Java's Swing GUI components that provide support for portable GUIs. This package still uses some elements of the older java.awt package. (See Chapter 12, GUI Components: Part 1, and Chapter 22, GUI Components: Part 2.)
javax.swing.event The Java Swing Event Package contains classes and interfaces that enable event handling (e.g., responding to button clicks) for GUI components in package javax.swing. (See Chapter 12, GUI Components: Part 1, and Chapter 22, GUI Components: Part 2.)
javax.xml.ws The JAX-WS Package contains classes and interfaces for working with web services in Java. (See online Chapter 32, REST-Based Web Services.)
javafx packages JavaFX is the preferred GUI technology for the future. We discuss these packages in Chapter 25, JavaFX GUI: Part 1 and in the online JavaFX GUI and multimedia chapters.
java.time The new Java SE 8 Date/Time API. Classes and interfaces for working with dates and times. These features are designed to replace the older date and time capabilities of package java.util. (See Chapter 23, Concurrency.)
java.util.function Classes and interfaces for Java SE 8's functional programming. (See Chapter 17, Java SE 8 Lambdas and Streams.)
java.util.stream Classes and interfaces for stream pipelines built on top of java.util.function. (See Chapter 17.)
Review Questions

Practice — Section 1: Java API Packages

Source:232

Which package in Java provides classes and Interfaces for data structures like lists, sets, and maps?

Answer

C. java.util

java.util contains the common utility classes, including collections such as lists, sets, and maps.

Source:232

Which of the following statements is true about Java API packages?

Answer

A. Java API packages provide a collection of classes and interfaces for various programming tasks.

Java API packages are ready-made groups of classes and interfaces. You import and use them instead of writing everything from scratch.

Source:232

Which package in Java provides classes and Interfaces for basic input/output operations?

Answer

D. java.io

java.io is the package used for input and output classes, such as reading from or writing to files and streams.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

In Java, which of the following is correct to import the entire package namedmy_pack?

Answer

D. import my_pack.*;

To import all classes from a package, use lowercase import, the package name, a dot, then *.

Source:IT232 Final T1 2021-2022

Which of the following is the correct way of importing an entire package 'pack'?

Answer

C. import pack.*;

To import every class from a package, use lowercase import, the package name, a dot, then *.

Source:IT232 Final T2 2021-2022

The statement ______ is used to define the package pac.

Answer

C. package pac;

A package declaration uses the keyword package, then the package name, then a semicolon.

Source:IT232 MidTerm A · IT232 MidTerm A 251015 024809 251015 025458 · IT232 MidTerm B

Consider the following program:

import myLibrary.*;
public class ShowSomeClass
{
    // code for the class...
}

What is the name of the java file containing this program?

Answer

B. ShowSomeClass.java

A public class must be saved in a file with the same name as the class, plus .java.

Source:Java Final (New)

A(n) ________ is a group of related classes and interfaces.

Answer

A. Package.

A package groups related Java classes and interfaces together.

Source:Java Final (New)

Which keyword is used to import a package in Java?

Answer

A. import

The keyword import lets a Java file use classes from another package.

Source:Java Final v3

In Java, which of the following is correct to import the entire package "my_pack"

Answer

D. import my_pack.*;

Java is case-sensitive, so the keyword is lowercase import, and * brings in every public class from the package — import my_pack.*;.

Source:quiz-1-2026-hot

What is the purpose of Java API packages?

Answer

B. To group related classes

Packages bundle related classes together so they're easy to find and import — java.util for collections, java.io for I/O, and so on.

Source:CS140 MidTerm Fall-2014-15

Is the java.util package automatically imported in every Java program? Justify your answer.

Answer

No. Only java.lang is automatically imported. To use java.util, import it explicitly.

import java.util.ArrayList;   // a single class
import java.util.*;           // every public class in java.util

2. Scope of Declaration

The scope of a declaration is the portion of the program that can refer to the declared entity by its name. Outside that portion, the name does not exist.

Basic scope rules cover:

  • Scope of a parameter declaration
  • Scope of a local-variable declaration
  • Scope of a label in a labeled break or continue statement
  • Scope of a local-variable declaration that appears in the initialization section of a for statement's header
  • Scope of a method or field of a class

Example

// Fig. 5.9: Scope.java
// Scope class demonstrates field and local variable scopes.

public class Scope
{
    // field that is accessible to all methods of this class
    private static int x = 1;

    // method main creates and initializes local variable x
    // and calls methods useLocalVariable and useField
    public static void main(String[] args)
    {
        int x = 5; // method's local variable x shadows field x
        System.out.printf("local x in main is %d%n", x);

        useLocalVariable(); // useLocalVariable has local x
        useField(); // useField uses class Scope's field x
        useLocalVariable(); // useLocalVariable reinitializes local x
        useField(); // class Scope's field x retains its value

        System.out.printf("%nlocal x in main is %d%n", x);
    }

    // create and initialize local variable x during each call
    public static void useLocalVariable()
    {
        int x = 25; // initialized each time useLocalVariable is called
        System.out.printf(
            "%nlocal x on entering method useLocalVariable is %d%n", x);
        ++x; // modifies this method's local variable x
        System.out.printf(
            "local x before exiting method useLocalVariable is %d%n", x);
    }

    // modify class Scope's field x during each call
    public static void useField()
    {
        System.out.printf(
            "%nfield x on entering method useField is %d%n", x);
        x *= 10; // modifies class Scope's field x
        System.out.printf(
            "field x before exiting method useField is %d%n", x);
    }
} // end class Scope

Output

local x in main is 5
local x on entering method useLocalVariable is 25
local x before exiting method useLocalVariable is 26
field x on entering method useField is 1
field x before exiting method useField is 10
local x on entering method useLocalVariable is 25
local x before exiting method useLocalVariable is 26
field x on entering method useField is 10
field x before exiting method useField is 100
local x in main is 5
Review Questions

Practice — Section 2: Scope of Declaration

Source:232 · IT232 MidTerm A 251015 024809 251015 025458

What is the scope of a local variable in Java?

Answer

B. The scope of a local variable is limited to the block or method in which it is declared.

A local variable only exists inside the method or block where you declare it. Code outside that area cannot use its name.

Source:Final Exam IT-232

What does the scope of a declaration define?

Answer

A. The part of the program that can refer to a declared entity

Scope means where a declared name can be used. Outside its scope, Java does not recognize that name.

Source:IT232 Final T2 2021-2022

Which of the following statements generally describes the scope of a variable?

Answer

C. The region of a program in which the variable can be accessed.

Scope is the part of the program where a variable name can be used.

Source:quiz-1-2026-hot

What does "scope of declaration" refer to?

Answer

C. The portion of a program that can refer to the declared entity by its name

Scope is the region of code where a name is visible. Outside that region, the name doesn't exist as far as the compiler is concerned.

3. Method Overloading

Method overloading lets you give several methods the same name as long as each takes a different parameter list. Java picks which version to run by matching the call's argument count and types to a signature.

What counts as "different parameters":

  • Different number of parameters
  • Different parameter types
  • Different order of types

Example: square(int) vs square(double):

// Fig. 5.10: MethodOverload.java
// Overloaded method declarations.

public class MethodOverload
{
    // test overloaded square methods
    public static void main(String[] args)
    {
        System.out.printf("Square of integer 7 is %d%n",
            square(7));

        System.out.printf("Square of double 7.5 is %f%n", square(7.5));
    }

    // square method with int argument
    public static int square(int intValue)
    {
        System.out.printf("%nCalled square with int argument: %d%n",
            intValue);
        return intValue * intValue;
    }

    // square method with double argument
    public static double square(double doubleValue)
    {
        System.out.printf("%nCalled square with double argument: %f%n",
            doubleValue);
        return doubleValue * doubleValue;
    }
} // end class MethodOverload

Output

Called square with int argument: 7
Square of integer 7 is 49
Called square with double argument: 7.500000
Square of double 7.5 is 56.250000

Example: same name, different parameter types (int vs double):

class Adder {
    static int add(int a, int b) {
        return a + b;
    }
    static double add(double a, double b) {
        return a + b;
    }
    public static void main(String[] args) {
        System.out.println(add(11, 11));
        System.out.println(add(12.3, 12.6));
    }
}

Example: same name, different number of parameters:

class Adder {
    static int add(int a, int b) {
        return a + b;
    }
    static int add(int a, int b, int c) {
        return a + b + c;
    }
    public static void main(String[] args) {
        System.out.println(add(11, 11));
        System.out.println(add(11, 11, 11));
    }
}

Example: overloading with type promotion (int argument promotes to long):

class OverloadingCalculation1 {
    static void sum(int a, long b) {
        System.out.println(a + b);
    }
    static void sum(int a, int b, int c) {
        System.out.println(a + b + c);
    }
    public static void main(String[] args) {
        sum(20, 20); // now second int literal will be promoted to long
        sum(20, 20, 20);
    }
}
Review Questions

Practice — Section 3: Method Overloading

Source:232

Which of the following is an example of method overloading for: public int add(int a, int b)

Answer

A. public void add(int[] numbers)

Overloading keeps the same method name but changes the parameter list. This version still uses add, but it takes an int[] instead of two int values.

Source:232

Which of the following statements is true about method overloading in Java?

Answer

B. Method overloading allows multiple methods with the same name but different parameters.

Overloading means several methods can share one name as long as their parameter lists are different.

Source:232

Which of the following is not a valid example of method overloading for display method?

Answer

A. public int display(int num)

This has the same name and same parameter list as public void display(int num). Changing only the return type is not enough for overloading.

Source:Final Exam IT-232 · quiz-1-2026-hot

What is Method Overloading?

Answer

A. Using the same method name with different parameters

Method overloading means reusing one method name, but changing the number or types of parameters.

Source:Final Exam IT-232

What is the benefit of method overloading?

Answer

A. Makes the program more readable and reusable

Overloading lets related actions share one name, so code is easier to read while still supporting different inputs.

Source:IT232 Final T1 2021-2022

What is the output of the following Java code?

public class Test{
    public static int sum(int a){
        return a +5;}
    public static int sum(int a, int b){
        return a+10;
    }

    public static void main(String []args){
        System.out.print(" " +sum(1));
        System.out.print(" " +sum(5));
    } }
Answer

A. 6 10

Both calls have one argument, so both use sum(int a), not the two-parameter method. sum(1) gives 6, and sum(5) gives 10.

Source:Java Final v3

Method overloading is implemented in Java by having several methods ____________

Answer

C. With the same name

Overloaded methods share the same name, but their parameter lists must be different.

Source:Final Exam IT-232 · quiz-1-2026-hot

What is Method Overloading?

Answer

A. Using the same method name with different parameters

Method overloading means reusing one method name, but changing the number or types of parameters.

Module 8 — Arrays

1. Primitive vs. Reference type

  • A primitive-type variable can hold exactly one value of its declared type at a time. For example, an int variable can store one integer at a time.
  • When another value is assigned to that variable, the new value replaces the previous one.
  • Programs use variables of reference types to store the addresses of objects in the computer's memory.

Scanner input = new Scanner(System.in); creates a Scanner object, then assigns to the variable input a reference to that Scanner object.

2. Creating, Initializing, and modifying arrays

Arrays

  • Data structures
  • Related data items of same type
  • Remain same size once created
  • Fixed-length entries
Name of array (c) Value Index (or subscript) of the element in array c
c[0] -45 0
c[1] 6 1
c[2] 0 2
c[3] 72 3
c[4] 1543 4
c[5] -89 5
c[6] 0 6
c[7] 62 7
c[8] -3 8
c[9] 1 9
c[10] 6453 10
c[11] 78 11
  • Index
    • Also called subscript
    • Position number in square brackets
    • Must be positive integer or integer expression
a = 5;
b = 6;
c[a + b] += 2;
  • Adds 2 to c[11]

  • The name of the array is c

  • c.length returns array c's length
  • This array's 12 elements are referred to as c[0], c[1], c[2],...,c[11]
  • The value of c[0] is -45
  • The value of c[1] is 6
  • The value of c[2] is 0
  • sum = c[0] + c[1] + c[2];

Declaring and Creating Arrays

  • Array objects occupy space in memory.
  • Arrays are created with keyword new.
int[] c = new int[12];

Equivalent to:

int[] c;            // declare the array variable
c = new int[12];    // create the array; assign to array variable

Create several arrays in a single declaration:

String[] b = new String[100], x = new String[27];

Creating and Initializing an Array Example

// Fig. 6.2: InitArray.java
// Initializing the elements of an array to default values of zero.

public class InitArray {
    public static void main(String[] args) {
        // declare variable array and initialize it with an array object
        int[] array = new int[10]; // create the array object

        System.out.printf("%s%s%n", "Index", "Value"); // column headings

        // output each array element's value
        for (int counter = 0; counter < array.length; counter++)
            System.out.printf("%5d%8d%n", counter, array[counter]);
    }
} // end class InitArray

Output

Index Value
    0     0
    1     0
    2     0
    3     0
    4     0
    5     0
    6     0
    7     0
    8     0
    9     0

Using an Array Initializer

// Fig. 6.3: InitArray.java
// Initializing the elements of an array with an array initializer.

public class InitArray {
    public static void main(String[] args) {
        // initializer list specifies the initial value for each element
        int[] array = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };

        System.out.printf("%s%s%n", "Index", "Value"); // column headings

        // output each array element's value
        for (int counter = 0; counter < array.length; counter++)
            System.out.printf("%5d%8d%n", counter, array[counter]);
    }
} // end class InitArray

Output

Index Value
    0    32
    1    27
    2    64
    3    18
    4    95
    5    14
    6    90
    7    70
    8    60
    9    37

Calculating the Values to Store in an Array

// Fig. 6.4: InitArray.java
// Calculating the values to be placed into the elements of an array.

public class InitArray {
    public static void main(String[] args) {
        final int ARRAY_LENGTH = 10; // declare constant
        int[] array = new int[ARRAY_LENGTH]; // create array

        // calculate value for each array element
        for (int counter = 0; counter < array.length; counter++)
            array[counter] = 2 + 2 * counter;

        System.out.printf("%s%s%n", "Index", "Value"); // column headings

        // output each array element's value
        for (int counter = 0; counter < array.length; counter++)
            System.out.printf("%5d%8d%n", counter, array[counter]);
    }
} // end class InitArray

Output

Index Value
    0     2
    1     4
    2     6
    3     8
    4    10
    5    12
    6    14
    7    16
    8    18
    9    20

Summing the Elements of an Array

// Fig. 6.5: SumArray.java
// Computing the sum of the elements of an array.

public class SumArray {
    public static void main(String[] args) {
        int[] array = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
        int total = 0;

        // add each element's value to total
        for (int counter = 0; counter < array.length; counter++)
            total += array[counter];

        System.out.printf("Total of array elements: %d%n", total);
    }
} // end class SumArray

Output

Total of array elements: 849

Using Bar Charts to Display Array Data Graphically

// Fig. 6.6: BarChart.java
// Bar chart printing program.

public class BarChart {
    public static void main(String[] args) {
        int[] array = {0, 0, 0, 0, 0, 0, 1, 2, 4, 2, 1};

        System.out.println("Grade distribution:");

        // for each array element, output a bar of the chart
        for (int counter = 0; counter < array.length; counter++) {
            // output bar label ("00-09: ", "90-99: ", "100: ")
            if (counter == 10)
                System.out.printf("%5d: ", 100);
            else
                System.out.printf("%02d-%02d: ", counter * 10, counter * 10 + 9);

            // print bar of asterisks
            for (int stars = 0; stars < array[counter]; stars++)
                System.out.print("*");

            System.out.println();
        }
    }
} // end class BarChart

Output

Grade distribution:
00-09:
10-19:
20-29:
30-39:
40-49:
50-59:
60-69: *
70-79: **
80-89: ****
90-99: **
  100: *

Using the Elements of an Array as Counters

// Fig. 6.7: RollDie.java
// Die-rolling program using arrays instead of switch.
import java.security.SecureRandom;

public class RollDie {
    public static void main(String[] args) {
        SecureRandom randomNumbers = new SecureRandom();
        int[] frequency = new int[7]; // array of frequency counters

        // roll die 6,000,000 times; use die value as frequency index
        for (int roll = 1; roll <= 6000000; roll++)
            ++frequency[1 + randomNumbers.nextInt(6)];

        System.out.printf("%s%10s%n", "Face", "Frequency");

        // output each array element's value
        for (int face = 1; face < frequency.length; face++)
            System.out.printf("%4d%10d%n", face, frequency[face]);
    }
} // end class RollDie

Output

Face Frequency
   1    999690
   2    999512
   3   1000575
   4    999815
   5    999781
   6   1000627
Review Questions

Practice — Section 2: Creating, Initializing, and modifying arrays

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232 · IT232 Final T2 2021-2022 · Java Final v3

What is the valid range of index values for an array of size 10?

Answer

C. 0 to 9

Java array indexes start at 0. An array with 10 elements therefore has indexes 0 through 9.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

To get the number of elements that an array can have, we use:

Answer

D. myArray.length

Arrays use the length field to tell how many elements they can store. It is not a method, so there are no parentheses.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

What is the output of the following Java code?

int array_variable[] = new int[10];
for (int i = 0; i < 10; ++i) {
    array_variable[i] = i;
    System.out.print(array_variable[i] + " ");
    i++;
}
Answer

A. 0 2 4 6 8

The loop prints i, then the extra i++ inside the loop skips the next index. That is why only 0, 2, 4, 6, 8 are printed.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232 · Java Final v3

Which of these is an incorrect array declaration?

Answer

C. int arr[] = int[4] new;

int arr[] = int[4] new; is incorrect because new int[4] must stay together in that order.

Source:Final Exam IT-232

Which of the following correctly declares and creates an array of 5 integers?

Answer

A. int[] a = new int[5];

int[] a declares an integer array variable, and new int[5] creates space for 5 integers.

Source:IT232 Final T1 2021-2022

Which one of the following statements is a valid initialization of a String array named shapes?

Answer

A. String[] shapes = {"Circle", "Rectangle", "Square"};

A Java array declaration uses String[], and array literals use curly braces {}.

Source:IT232 Final T1 2021-2022

What is the output of the following Java code?

int []myArray = new int [5];
for(int i=0; i< myArray.length; i++)
{
    if(i%2 ==0)
        myArray[i] = i+1;
    System.out.print(" "+myArray[i]);
}
Answer

A. 1 0 3 0 5

Only even indexes get assigned: index 0 becomes 1, index 2 becomes 3, and index 4 becomes 5. Odd indexes stay at the default 0.

Source:IT232 Final T1 2021-2022

Which statement about Java arrays is correct?

Answer

A. An array stores elements of the same type.

A Java array has one element type, and all elements must match that type.

Source:IT232 Final T1 2021-2022

How do you get the number of elements in a Java array named MyArray?

Answer

A. MyArray.length

Arrays use the length field, not a length() method.

Source:IT232 Final T2 2021-2022

Given this array declaration, which line stores 20.5 in the last element of arr?

double[] arr = new double[15];
Answer

D. arr[14] = 20.5;

The array has 15 elements, so its last valid index is 14.

Source:IT232 Final T2 2021-2022

The code below keeps m as the smallest value seen so far. It prints an array value only when that value is not smaller than m. What is the output?

int[] x = {0, -2, 1};
int m = x[0];
for(int i=0; i<=2; i++)
    if(x[i] < m)
    {
        m = x[i];
    }
    else
        System.out.print("+ " + x[i]);
System.out.print(" " + m);
Answer

C. + 0+ 1 -2

At i = 0, 0 is not less than m, so it prints + 0. At i = 1, -2 becomes the new minimum and nothing is printed. At i = 2, 1 is not less than -2, so it prints + 1. Finally, it prints the minimum value -2.

Source:IT232 Final T2 2021-2022

Which one of the following is a valid java statement?

Answer

A. char[] c = new char[5];

A valid array creation must include the element type and size, so new char[5] creates a char array with 5 elements.

Source:Java Final (New)

Which of the following is used to declare, create, and initialize an array?

Answer

B. int arr [ ] = {1, 2, 3};

The braces {1, 2, 3} create and initialize the array values in one statement.

Source:Java Final (New)

What is the output of the following code snippet?

int[] odd = {1, 3, 5, 7, 9, 11};
odd[3] = 13; odd[4] = 77;
System.out.println( odd[0] + " " + odd[3] );
Answer

D. 1, 13

odd[0] is still 1. odd[3] is changed from 7 to 13, so those two printed values are 1 and 13.

Source:Java Final (New)

What is the type of the array in following code snippet?

public class Main{
    public static void main(String[] args){
        String[] numbers = {"One", "Two", "Three"};
        System.out.println("First Number is: " + numbers[0]);
    }
}
Answer

A. String

The array is declared as String[], so its elements are strings.

Source:Java Final (New)

What is the output of the following program?

public class Test {
    public static void main(String[] args) {
        int i;
        char[] course_chars = {'C', 'S', '3', '1', '1'};
        for (i = 5; i > 0; i--) {
            System.out.print(course_chars[--i] + " ");
        }
    }
}
Answer

A. 1 3 C

--i decreases the index before reading the array. The loop reads indexes 4, 2, and 0, which are 1, 3, and C.

Source:Java Final (New)

Which of the following correctly declares an array of integers in Java?

Answer

C. int[] numbers = new int[5];

int[] numbers declares an integer array variable, and new int[5] creates an array with 5 integer slots.

Source:Java Final (New)

What is the output of the following code snippet?

public class Main{
    public static void main(String[] args){
        int[] age = {12, 4, 5, 2, 5};
        System.out.println("First Element: " + age[0]);
        System.out.println("Third Element: " + age[2]);
        System.out.println("Fifth Element: " + age[4]);
    }
}
Answer

C. First Element: 12 Third Element: 5 Fifth Element: 5

Array indexes start at 0. So age[0] is 12, age[2] is 5, and age[4] is 5.

Source:Java Final v3

To get the number of elements that an array can have, we use _____________

Answer

D. myArray.length;

Arrays use the length field to store how many elements they have.

Source:Java Final v3

What is the output of the following java code?

public static void main(String[] args) {
    int arr_variable[] = new int[10];
    for (int i = 0; i < 10; ++i) {
        arr_variable[i] = i;
        System.out.print(arr_variable[i] + " ");
        i++;
    }
}
Answer

A. 0 2 4 6 8

The loop prints the current i, then the extra i++ inside the loop skips the next value. That leaves 0, 2, 4, 6, and 8.

Source:Java Final v3

What is the output of the following java code?

int arr[] = {0,1, 2, 3, 4, 5, 6, 7, 8,9};
int n = 6;
n = arr[arr[n] / 2];
System.out.println(arr[n] / 2);
Answer

A. 1

arr[n] is arr[6], which is 6; 6 / 2 is 3, so n becomes arr[3], which is 3. Then arr[3] / 2 is 1 with integer division.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232 · Java Final v3

Which of these is an incorrect array declaration?

Answer

C. int arr[] = int[4] new;

int arr[] = int[4] new; is incorrect because new int[4] must stay together in that order.

Source:Java Final v3

What is the output of the following java

// index of a is 0
// index of b is 1
// index of c is 2
char chars[] = {'a','b','c'};
System.out.println(chars[1]);
Answer

A. b

Java arrays are zero-indexed, so chars[1] is the second element — 'b'.

Source:Java Final v3

What is the output of the following code snippet?

int[] myArray = {11,12,13,14,15};
System.out.print(myArray[2]+",");
System.out.print(myArray[3]);
Answer

D. 13,14

myArray[2] is 13 and myArray[3] is 14. The first print adds the comma between them, so the output is 13,14.

Source:quiz-1-2026-hot

Which of the following correctly declares and creates an array of 12 integers named c in Java?

Answer

A. int[] c = new int[12];

The standard form is Type[] name = new Type[size] — so int[] c = new int[12];. The brackets go on the type, and the size goes inside new int[...].

Source:quiz-1-2026-hot

Which statement best describes a Java array?

Answer

D. A group of related data items of the same type whose length is fixed once the array is created

A Java array holds values of one fixed type, and its length is locked in when you create it — int[] a = new int[5] always has 5 slots.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

What is the output of the following Java code?

int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int n = 6;
n = arr[arr[n] / 2];
System.out.println(arr[n] / 2);
Answer

Output: 1

(arr[6]=6, 6/2=3, n=arr[3]=3. arr[3]/2 = 3/2 = 1.)

Source:IT232 Final T1 2021-2022

Write a complete java program that perform the following tasks:

  • Declare and initialize an array of int numbers with the following elements 10,11,12,13,14,15
  • Calculate and print the sum of odd and even numbers of the array.
Answer
public class SumOddEven {
    public static void main(String[] args) {
        int[] nums = {10, 11, 12, 13, 14, 15};
        int oddSum = 0, evenSum = 0;
        for (int n : nums) {
            if (n % 2 == 0) evenSum += n;
            else            oddSum  += n;
        }
        System.out.println("Even sum: " + evenSum);
        System.out.println("Odd sum: " + oddSum);
    }
}

Output: even sum = 36, odd sum = 39.

Source:Java Final v3

Write a Java Program to calculate the sum and the average of an array

1 - Your program must do the following:

2 - Calculate the sum of all the items of the array using for loop

3 - Print the sum

4 - Divide the sum with the length of the array to get the average of numbers

5 - Print the average.

Example of the output:

Enter all the elements:

1 2 3 4 5

sum: 15

Average of Array Element is: 3.0

Answer
import java.util.Scanner;
public class ArrayAvg {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] arr = new int[5];
        System.out.print("Enter all the elements: ");
        for (int i = 0; i < 5; i++) arr[i] = sc.nextInt();
        int sum = 0;
        for (int i = 0; i < 5; i++) sum += arr[i];
        System.out.println("sum : " + sum);
        double avg = (double) sum / arr.length;
        System.out.println("Average of Array Element is : " + avg);
    }
}

3. Exception Handling (Try-Catch Statement)

An exception indicates a problem that occurs while a program is executing. To handle an exception, place any code that might throw it inside a try-catch statement.

The try Statement

The try block contains the code that might throw an exception.

The catch Statement

The catch block contains the code that handles the exception if one occurs.

Try-Catch Syntax

try {
    // Block of code to try
}
catch (Exception e) {
    // Block of code to handle errors
}

Exception Example

public class Main {
    public static void main(String[] args) {
        int[] myNumbers = {1, 2, 3};
        System.out.println(myNumbers[10]); // error!
    }
}

Output

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

finally statement lets you execute code, after try...catch, regardless of the result:

public class Main {
    public static void main(String[] args) {
        try {
            int[] myNumbers = {1, 2, 3};
            System.out.println(myNumbers[10]);
        }
        catch (Exception e) {
            System.out.println("Something went wrong.");
        }
        finally {
            System.out.println("The try catch is finished.");
        }
    }
}

Output

Something went wrong.
The try catch is finished.

Exception Example

public class Main {
    public static void main(String[] args) {
        try {
            int[] myNumbers = {1, 2, 3};
            System.out.println(myNumbers[10]);
        }
        catch (Exception e) {
            System.out.println("Something went wrong.");
        }
    }
}

Output

Something went wrong.
Review Questions

Practice — Section 3: Exception Handling (Try-Catch Statement)

Source:Final Exam IT-232

What is the purpose of the finally block?

Answer

C. It always runs regardless of exceptions

A finally block is used for cleanup code. It runs whether an exception happens or not.

Source:Final Exam IT-232

What happens when an exception occurs inside a try block?

Answer

A. The catch block executes (if it matches)

When code inside try throws an exception, Java looks for a matching catch block to handle it.

Source:Final Exam IT-232

Which debugging tool stops the program when a specific exception occurs?

Answer

C. Exception breakpoint

An exception breakpoint is used to pause the program when a selected exception is thrown.

Source:quiz-1-2026-hot

Which of the following statements best distinguishes between fatal and nonfatal runtime errors?

Answer

D. Fatal runtime errors terminate program execution immediately, whereas nonfatal errors allow execution to continue, possibly with incorrect results.

Fatal runtime errors stop the program right when they occur. Nonfatal ones let it keep running, but the output may be wrong.

Source:Final Exam IT-232

What is the difference between the "try statement" and the "catch statement"?

Answer
  • try statement: encloses a block of code that may throw an exception.
  • catch statement: handles the exception thrown inside the matching try block.

4. Enhanced for Statement

Iterates through the elements of an array without using a counter.

  • thus avoiding the possibility of "stepping outside" the array
for (parameter : arrayName)
    statement
  • parameter has a type and an identifier
  • arrayName is the array through which to iterate.
// Fig. 6.9: EnhancedForTest.java
// Using the enhanced for statement to total integers in an array.

public class EnhancedForTest {
    public static void main(String[] args) {
        int[] array = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
        int total = 0;

        // add each element's value to total
        for (int number : array)
            total += number;

        System.out.printf("Total of array elements: %d%n", total);
    }
} // end class EnhancedForTest

Output

Total of array elements: 849
Review Questions

Practice — Section 4: Enhanced for Statement

Source:Final Exam IT-232

What is the output of the following code?

int[] a = {10, 20, 30};
for(int x: a) {
System.out.print(x + " ");
}
Answer

D. 10 20 30

The enhanced for loop visits each array value in order. It prints 10, then 20, then 30.

Source:Final Exam IT-232

Which statement about the enhanced for loop is TRUE?

Answer

D. It prevents accessing invalid indices

An enhanced for loop visits existing elements directly, so you do not write an index that might go out of range.

Source:IT232 Final T1 2021-2022

Complete the following code snippet with the correct enhanced for loop so it iterates over the array without using an index variable.

int[] evenNo = {2, 4, 6, 8, 10};
________________
    System.out.print(e + " ");
}
Answer

C. for (int e: evenNo) {

An enhanced for loop needs the element type, a variable name, then the array after the colon.

Source:IT232 Final T2 2021-2022

Complete the following code snippet with the correct enhanced for loop so it iterates over the array without using an index variable.String[] arr = { "red", "green", "blue", "black" };

Answer

D. for (String str: arr)

The enhanced for loop needs the element type String, a loop variable str, then the array name after the colon.

Source:Java Final v3

Complete the following code snippet with the correct enhanced for loop so it iterates over the array.

String[] fruit = {"apple", "orange", "banana"};
________________
    System.out.println(e);
}
Answer

D. for (String e: fruit) {

Enhanced for syntax is for (Type element : collection) — for (String e : fruit) declares e as a String for each item in the array.

Source:quiz-1-2026-hot

What is the output of the following code? int[] array = { 2, 4, 6, 8 }; int total = 0; for (int number: array) total += number; System.out.println(total);

Answer

A. 20

The loop adds 2 + 4 + 6 + 8 = 20 into total, then prints 20.

Source:IT232 Final T2 2021-2022

Write a complete Java program that does the following:

  • Asks the user to give a number and save it in a variable nb.
  • Declares an array tab that contains nb integers.
  • Asks the user to enter nb values and saves them in the array.
  • Computes and prints the sum and the average of the elements in the array.
  • Prints the content of the array using an enhanced for loop.
Answer
import java.util.Scanner;
public class ArrayStats {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int nb = sc.nextInt();
        int[] tab = new int[nb];
        for (int i = 0; i < nb; i++) tab[i] = sc.nextInt();
        int sum = 0;
        for (int v : tab) sum += v;
        double avg = (double) sum / nb;
        System.out.println("Sum: " + sum);
        System.out.println("Average: " + avg);
        System.out.print("Array: ");
        for (int v : tab) System.out.print(v + " ");
    }
}

5. Passing Arrays to Methods

  • To pass an array argument to a method, specify the name of the array without any brackets.
  • For example to pass the array hourlyTemperatures:
double[] hourlyTemperatures = new double[24];

The method call will be:

modifyArray(hourlyTemperatures);

The method header will be:

void modifyArray(double[] b)

Example

// Fig. 6.10: PassArray.java
// Passing arrays and individual array elements to methods.

public class PassArray {
    // main creates array and calls modifyArray and modifyElement
    public static void main(String[] args) {
        int[] array = { 1, 2, 3, 4, 5 };

        System.out.printf(
            "Effects of passing reference to entire array:%n" +
            "The values of the original array are:%n");

        // output original array elements
        for (int value : array)
            System.out.printf(" %d", value);

        modifyArray(array); // pass array reference

        System.out.printf("%n%nThe values of the modified array are:%n");

        // output modified array elements
        for (int value : array)
            System.out.printf(" %d", value);

        System.out.printf(
            "%n%nEffects of passing array element value:%n" +
            "array[3] before modifyElement: %d%n", array[3]);

        modifyElement(array[3]); // attempt to modify array[3]

        System.out.printf(
            "array[3] after modifyElement: %d%n", array[3]);
    }

    // multiply each element of an array by 2
    public static void modifyArray(int[] array2) {
        for (int counter = 0; counter < array2.length; counter++)
            array2[counter] *= 2;
    }

    // multiply argument by 2
    public static void modifyElement(int element) {
        element *= 2;
        System.out.printf(
            "Value of element in modifyElement: %d%n", element);
    }
} // end class PassArray

Output

Effects of passing reference to entire array:
The values of the original array are:
 1 2 3 4 5

The values of the modified array are:
 2 4 6 8 10

Effects of passing array element value:
array[3] before modifyElement: 8
Value of element in modifyElement: 16
array[3] after modifyElement: 8
Review Questions

Practice — Section 5: Passing Arrays to Methods

Source:Final Exam IT-232

Given the following Java code, what is printed?

public class Test {
    public static void modify(int[] x) {
        x[0] = 99;
    }

    public static void main(String[] args) {
        int[] a = {1, 2, 3};
        modify(a);
        System.out.println(a[0]);
    }
}
Answer

B. 99

Arrays are objects, so the method changes the same array element to 99.

6. Pass-By-Value vs. Pass-By-Reference

  • Two ways to pass arguments in method calls in many programming languages are
    • pass-by-value (call-by-value).
    • pass-by-reference (call-by-reference).

pass-by-value

When an argument is passed by value:

  • a copy of the argument's value is passed to the called method.
  • The called method works exclusively with the copy.
  • Changes to the called method's copy do not affect the original variable's value in the caller.

pass-by-reference

When an argument is passed by reference:

  • The called method can access the argument's value in the caller directly and modify that data, if necessary.
  • It improves performance by eliminating the need to copy possibly large amounts of data.

Java does not allow you to choose pass-by-value or pass-by-reference — all arguments are passed by value.

7. Multidimensional Arrays

  • Tables with rows and columns
  • Two-dimensional array
  • Declaring two-dimensional array b[2][2]
int b[][] = {{1, 2}, {3, 4}};
  • 1 and 2 initialize b[0][0] and b[0][1]
  • 3 and 4 initialize b[1][0] and b[1][1]
int b[][] = {{1, 2}, {3, 4, 5}};
  • row 0 contains elements 1 and 2
  • row 1 contains elements 3, 4 and 5
Column 0 Column 1 Column 2 Column 3
Row 0 a[0][0] a[0][1] a[0][2] a[0][3]
Row 1 a[1][0] a[1][1] a[1][2] a[1][3]
Row 2 a[2][0] a[2][1] a[2][2] a[2][3]
// Fig. 6.12: InitArray.java
// Initializing two-dimensional arrays.

public class InitArray {
    // create and output two-dimensional arrays
    public static void main(String[] args) {
        int[][] array1 = { { 1, 2, 3 },
                           { 4, 5, 6 } };
        int[][] array2 = { { 1, 2 }, { 3 }, { 4, 5, 6 } };

        System.out.println("Values in array1 by row are");
        outputArray(array1); // displays array1 by row

        System.out.printf("%nValues in array2 by row are%n");
        outputArray(array2); // displays array2 by row
    }

    // output rows and columns of a two-dimensional array
    public static void outputArray(int[][] array) {
        // loop through array's rows
        for (int row = 0; row < array.length; row++) {
            // loop through columns of current row
            for (int column = 0; column < array[row].length; column++)
                System.out.printf("%d ", array[row][column]);

            System.out.println();
        }
    }
} // end class InitArray

Output

Values in array1 by row are
1 2 3
4 5 6

Values in array2 by row are
1 2
3
4 5 6
Review Questions

Practice — Section 7: Multidimensional Arrays

Source:Final Exam IT-232

Which is TRUE about multidimensional arrays in java?

Answer

A. They can be "jagged" (rows of different lengths)

In Java, a 2D array is really an array of arrays, so each row can have a different length.

Source:Final Exam IT-232

What is the number of rows in this 2D array?

int[][] b = { {1, 2, 3}, {3, 4}};
Answer

C. 2

The outer braces contain two inner arrays: {1, 2, 3} and {3, 4}. That means the 2D array has 2 rows.

Source:IT232 Final T2 2021-2022

What is the output of the following code snippet?

int[][] arr = {
    {1, 2, 3},
    {4, 5, 6}
};
int val = arr[0][2] + arr[1][2];
System.out.println(val);
Answer

D. 9

arr[0][2] is 3 and arr[1][2] is 6. Adding them gives 9.

Source:Java Final (New)

Which of the following is a correct statement to create and initialize a two-dimensional array of the type int?

Answer

C. int b[][] = {{1, 2}, {3, 4}};

A 2D int array can be declared with int b[][] and initialized with nested braces.

Source:Java Final v3

What is the output of the following java code?

int array_variable [][] = {{1,2,3},
                           {4,5,6},
                           {7,8,9}};

System.out.println(array_variable[0][0]);
Answer

C. 1

array_variable[0][0] is the first element of the first row — 1.

Module 9 — Classes and Objects I

1. Declaring classes, instance variables, methods

Object Oriented Programming (OOP)

  • Encapsulates data (attributes) and methods (behaviors)
  • Objects
  • Allows objects to communicate
  • Well-defined interfaces

What are Classes and Objects?

class objects
Fruit Apple, Banana, Mango

Another example:

class objects
Car Volvo, Audi, Toyota

A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

  • Fields
  • Methods
  • Constructors
  • Blocks
  • Nested class and interface

An object is an instance of a class. A class is a template or blueprint from which objects are created. So, an object is the instance (result) of a class.

Object Definitions:

  • An object is a real-world entity.
  • An object is a runtime entity.
  • The object is an entity which has state and behavior.
  • The object is an instance of a class.

Instance variable in Java

  • A variable which is created inside the class but outside the method is known as an instance variable.
  • Instance variable doesn't get memory at compile time.
  • It gets memory at runtime when an object or instance is created.
  • That is why it is known as an instance variable.

Method in Java

In Java, a method is like a function which is used to expose the behavior of an object. Methods in classes represent a behavior of an object from the class.

Example

// Fig. 7.1: Account.java
// Account class that contains a name instance variable
// and methods to set and get its value.

public class Account {
    private String name; // instance variable

    // method to set the name in the object
    public void setName(String name) {
        this.name = name; // store the name
    }

    // method to retrieve the name from the object
    public String getName() {
        return name; // return value of name to caller
    }
} // end class Account

Instance Variable name

private String name; // instance variable
  • Instance variables are declared inside a class declaration but outside the bodies of the class's methods.
  • Access Modifiers public and private:
    • Variables or methods declared with access modifier public are accessible from outside the class in which they're declared.
    • Variables or methods declared with access modifier private are accessible only to methods of the class in which they're declared.

Instance Method setName of Class Account

public void setName(String name) {
    this.name = name; // store the name
}
  • Indicates that setName receives parameter name of type String — which represents the name that will be passed to the method as an argument.
  • If a method contains a local variable with the same name as an instance variable, the method's body can use the keyword this to refer to the shadowed instance variable explicitly.

AccountTest Class That Creates and Uses an Object of Class Account

// Fig. 7.2: AccountTest.java
// Creating and manipulating an Account object.
import java.util.Scanner;

public class AccountTest {
    public static void main(String[] args) {
        // create a Scanner object to obtain input from the command window
        Scanner input = new Scanner(System.in);

        // create an Account object and assign it to myAccount
        Account myAccount = new Account();

        // display initial value of name (null)
        System.out.printf("Initial name is: %s%n%n", myAccount.getName());

        // prompt for and read name
        System.out.println("Please enter the name:");
        String theName = input.nextLine(); // read a line of text
        myAccount.setName(theName); // put theName in myAccount
        System.out.println(); // outputs a blank line

        // display the name stored in object myAccount
        System.out.printf("Name in object myAccount is:%n%s%n",
            myAccount.getName());
    }
} // end class AccountTest

Output

Initial name is: null

Please enter the name:
Jane Green

Name in object myAccount is:
Jane Green

Instantiating an Object — Keyword new

// create an Account object and assign it to myAccount
Account myAccount = new Account();
  • Keyword new creates a new object of the specified class — in this case, Account.
  • The parentheses to the right of Account are required.

static Methods

Recall that static methods relate to a class as a whole, whereas instance methods are associated with a specific instance (object) of the class and may manipulate the instance variables of that object.

Review Questions

Practice — Section 1: Declaring classes, instance variables, methods

Source:Final Exam IT-232

What is a class in Java?

Answer

D. A template or blueprint for creating objects

A class describes what its objects will have and do. The actual object is created from that blueprint.

Source:Final Exam IT-232

Which of the following is NOT a component of a java class?

Answer

B. Libraries

A class can contain fields, constructors, methods, and nested classes. Libraries are collections of reusable code, not parts inside one class.

Source:Final Exam IT-232

What defines an object's state and behavior?

Answer

D. Instance variables and methods

Instance variables store an object's state, and methods define its behavior.

Source:Final Exam IT-232

Where are instance variables declared in a class?

Answer

D. Inside the class declaration but outside its methods

Instance variables belong to the object, so they are declared in the class body, not inside a method.

Source:Final Exam IT-232

Which statement is true about an object?

Answer

D. It is an instance of a class

An object is a real instance created from a class blueprint.

Source:IT232 Final T1 2021-2022

Each class you create becomes a new ________ that can be used to declare variables and create objects.

Answer

D. type

A class defines a new type. After creating the class, you can declare variables using that class name.

Source:IT232 Final T1 2021-2022

Which statement best describes an object in Java?

Answer

A. An object is an entity you can use by accessing fields and calling methods.

An object is an instance of a class and can have data and behavior.

Source:IT232 Final T1 2021-2022

Which statement best describes a class in Java?

Answer

A. A class is a blueprint for creating objects.

A class defines the fields and methods that its objects can have.

Source:Java Final (New)

To reveal the behavior of an object in a class we use ________.

Answer

C. Method

Methods define what an object can do, so they describe the object's behavior.

Source:Java Final (New)

If a variable is declared inside a class but outside the bodies of the class's methods it's called ________.

Answer

B. Instance variable

A variable declared in the class body, outside methods, belongs to each object, so it is an instance variable.

Source:Java Final (New)

Objects encapsulate ________ and ________.

Answer

C. Data, methods

Objects combine data, stored in fields, with methods that define behavior.

Source:Java Final v3

A variable which is created inside the class but outside the method is known as __________ variable.

Answer

D. instance

A variable declared inside the class but outside any method is an instance variable — every object of the class gets its own copy.

Source:quiz-1-2026-hot

Which statement correctly describes the relationship between a class and an object in Java?

Answer

B. A class is a blueprint or template, and an object is an instance of that class

The class is the blueprint — it lists the fields and methods. An object is a specific instance built from that blueprint at runtime.

Source:An Example of Open Question

How many instance variables in the program above? kindly list them.

Answer

3 instance variables:

  1. String Student_Name
  2. int Student_ID
  3. String College

Source:CS140 MidTerm Fall-2014-15

Write True/False: Encapsulation is the process of hiding object data and providing methods for data access.

Answer

True

Source:FINAL IT 232 FIRST Semester-2025

Giving the following code:

public class Animal {
    public void makeSound() {
        System.out.println("The animal makes a sound");
    }

    public static void main(String[] args) {
        Animal myAnimal = new Animal();
        myAnimal.makeSound();
    }
}

What is the name of the class?

Answer

Animal

Source:FINAL IT 232 FIRST Semester-2025

Giving the following code:

public class Animal {
    public void makeSound() {
        System.out.println("The animal makes a sound");
    }

    public static void main(String[] args) {
        Animal myAnimal = new Animal();
        myAnimal.makeSound();
    }
}

What is the name of the method in the class Animal?

Answer

makeSound

Source:FINAL IT 232 FIRST Semester-2025

Explain the difference between a class and an object in Java.

Answer

A class is a blueprint. An object is a real instance created from that class using new.

2. Default and Explicit Initialization for Instance Variables

  • Recall that local variables are not initialized by default. Primitive-type instance variables are initialized by default.
  • Instance variables of types byte, char, short, int, long, float and double are initialized to 0, and variables of type boolean are initialized to false.

You can initialize an instance variable as:

private int numberOfStudents = 10;
Review Questions

Practice — Section 2: Default and Explicit Initialization for Instance Variables

Source:IT232 Final T1 2021-2022

If a class does not define constructors, the compiler provides a default constructor with no parameters, and the class's instance variables are initialized to ________.

Answer

C. their default values

Instance variables receive their default values when no constructor sets them.

Source:quiz-1-2026-hot

In Java, a class has the instance variables int count; and boolean active; with no explicit initialization. What are their default values after an object of the class is created?

Answer

C. count = 0, active = false

Java initializes instance fields automatically — numeric types get 0, boolean gets false, references get null.

3. Constructors, private, public, static.

  • Each class you declare can optionally provide a constructor with parameters that can be used to initialize an object of a class when the object is created.
  • It has the same name as its class and is syntactically similar to a method.
  • However, constructors have no explicit return type.

Example

public class MyClass {
    int num;

    MyClass() {
        num = 100;
    }
}

public class ConsDemo {
    public static void main(String args[]) {
        MyClass t1 = new MyClass();
        MyClass t2 = new MyClass();
        System.out.println(t1.num + " " + t2.num);
    }
}

Output

100 100

Parameterized Constructors

// A simple constructor.
class MyClass {
    int x;

    MyClass(int i) {
        x = i;
    }
}

public class ConsDemo {
    public static void main(String args[]) {
        MyClass t1 = new MyClass(10);
        MyClass t2 = new MyClass(20);
        System.out.println(t1.x + " " + t2.x);
    }
}

Output

10 20
  • If you declare any variable as static, it is known as a static variable.
  • The static variable can be used to refer to the common property of all objects.
  • The static variable gets memory only once in the class area at the time of class loading.
class Student {
    int rollno;
    String name;
    String college = "ITS";
}
class Student {
    int rollno;            // instance variable
    String name;
    static String college = "ITS"; // static variable

    Student(int r, String n) {
        rollno = r;
        name = n;
    }

    void display() {
        System.out.println(rollno + " " + name + " " + college);
    }
}

public class TestStaticVariable1 {
    public static void main(String args[]) {
        Student s1 = new Student(111, "Karan");
        Student s2 = new Student(222, "Aryan");
        s1.display();
        s2.display();
    }
}

Output

111 Karan ITS
222 Aryan ITS

Program of the counter without static variable:

class Counter {
    int count = 0; // will get memory each time when the instance is created

    Counter() {
        count++; // incrementing value
        System.out.println(count);
    }

    public static void main(String args[]) {
        // Creating objects
        Counter c1 = new Counter();
        Counter c2 = new Counter();
        Counter c3 = new Counter();
    }
}

Output

1
1
1

Program of the counter with static variable:

class Counter {
    static int count = 0;

    Counter() {
        count++; // incrementing value
        System.out.println(count);
    }

    public static void main(String args[]) {
        // Creating objects
        Counter c1 = new Counter();
        Counter c2 = new Counter();
        Counter c3 = new Counter();
    }
}

Output

1
2
3

Static Method Example:

class Calculate {
    static int cube(int x) {
        return x * x * x;
    }

    public static void main(String args[]) {
        int result = Calculate.cube(5);
        System.out.println(result);
    }
}

Output

125

Public & Private Modifiers

Access location default private protected public
Same class Yes Yes Yes Yes
Same package subclass Yes No Yes Yes
Same package non-subclass Yes No Yes Yes
Different package subclass No No Yes Yes
Different package non-subclass No No No Yes

Public Modifier

package abcpackage;

public class Addition {
    public int addTwoNumbers(int a, int b) {
        return a + b;
    }
}
package xyzpackage;
import abcpackage.*;

public class Test {
    public static void main(String args[]) {
        Addition obj = new Addition();
        System.out.println(obj.addTwoNumbers(10, 21));
    }
}

Output

31

Private Modifier

class ABC {
    private double num = 100;

    private int square(int a) {
        return a * a;
    }
}

public class Example {
    public static void main(String args[]) {
        ABC obj = new ABC();
        System.out.println(obj.num);
        System.out.println(obj.square(10));
    }
}

Output

Compile - time error
Review Questions

Practice — Section 3: Constructors, private, public, static.

Source:CS140 MidTerm Fall-2014-15

private instance variables ________________.

Answer

B. can only be accessed by methods of the same class.

private hides the instance variable from other classes. Methods inside the same class can still use it.

Source:CS140 MidTerm Fall-2014-15

Constructors contain instructions to _______________.

Answer

C. Initialize the instance variables of an object.

A constructor runs when an object is created. Its main job is to give the new object's instance variables starting values.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

Given a class named Author, which of the following is a valid constructor?

Answer

A. Author(String a) { }

A constructor has the same name as the class and no return type. Author(String a) { } follows that rule.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

________ variables are visible and accessible only within the class they are declared in.

Answer

B. private

private restricts access to the same class. Code outside the class cannot directly use that variable.

Source:Final Exam IT-232

Which access modifier allows methods or variables to be accessible from outside their class?

Answer

B. public

public means code outside the class is allowed to access that member.

Source:Final Exam IT-232

If we don't usethiskeyword in a constructor with parameters having the same name as instance variables, what will happen?

Answer

A. Instance variables will remain uninitialized

Without this, an assignment like name = name assigns the parameter to itself. The instance variable is not updated.

Source:IT232 Final T1 2021-2022

Java requires a ________ call for every object that's created.

Answer

A. Constructor

Every new object is created through a constructor call, even when Java supplies the default constructor.

Source:IT232 Final T1 2021-2022

Where can a private variable or method be accessed?

Answer

A. Only inside the class where it is declared.

The private modifier limits access to the declaring class.

Source:IT232 Final T1 2021-2022

Which statement about constructors in Java is correct?

Answer

A. Constructors do not have an explicit return type.

A constructor has the same name as the class and no return type.

Source:IT232 Final T2 2021-2022

Which access specifier is usually used for data members of a class?

Answer

B. private

Data members are usually private so other classes cannot change them directly. Access is normally controlled through methods.

Source:IT232 Final T2 2021-2022

What is Not true about of the constructor methods?

Answer

A. It has a return value

Constructors do not have a return type or return value. They have the same name as the class and initialize new objects.

Source:Java Final (New)

In java, which of the following is not an access modifier?

Answer

B. prevented

public, protected, and default access are access levels in Java. prevented is not an access modifier.

Source:Java Final (New)

________ access modifier offers an intermediate level of access between public and private.

Answer

D. Protected

protected gives more access than private, but less than public, especially for subclasses.

Source:Java Final (New)

In java, which of the following must have the same name as its class's name?

Answer

C. Constructor

A constructor must have the same name as its class and has no return type.

Source:Java Final v3

Given a class named Author, which of the following is valid constructor declaration for the class?

Answer

A. Author (String a) { ....... }

A constructor has the same name as the class and no return type, so Author(String a) is valid.

Source:Java Final v3

______________ variables that can be visible and accessible within the class they belong to and not outside the class or any other class

Answer

B. private

private members are accessible only inside the class that declares them — that's the standard encapsulation rule.

Source:An Example of Open Question

From the following java code answer the questions below:

class FinalExam {
    private String Student_Name;
    private int Student_ID;
    private String College;

// first constructor
    public FinalExam() {
        System.out.println("Student 1 Informations:");
        this.Student_Name = Student_Name;
        this.Student_ID = Student_ID;
        this.College = College;
    }

// second constructor
    public FinalExam(String Student_Name, int Student_ID) {
        System.out.println("Student 2 Informations:");
        this.Student_Name = Student_Name;
        this.Student_ID = Student_ID;
    }

// third constructor
    public FinalExam(String Student_Name, int Student_ID, String College) {
        System.out.println("Student 3 Informations:");
        this.Student_Name = Student_Name;
        this.Student_ID = Student_ID;
        this.College = College;
    }

    public void setStudent_Name(String Student_Name) {
        this.Student_Name = Student_Name;
    }

    public String getStudent_Name() {
        return Student_Name;
    }

    public void setStudent_ID(int Student_ID) {
        this.Student_ID = Student_ID;
    }

    public int getStudent_ID() {
        return Student_ID;
    }

    public void setCollege(String College) {
        this.College = College;
    }

    public String getCollege() {
        return College;
    }
}

public class FinalExamTest {
    public static void main(String[] args) {
        FinalExam S1 = new FinalExam();
        System.out.println("Student 1: Name: " + S1.getStudent_Name() + ", ID: " + S1.getStudent_ID() + ", College: " + S1.getCollege());

        FinalExam S2 = new FinalExam("Sarah Ahmed", 102);
        System.out.println("Student 2: Name: " + S2.getStudent_Name() + ", ID: " + S2.getStudent_ID() + ", College: " + S2.getCollege());

        FinalExam student3 = new FinalExam("Ali Hassan", 103, "Computer Science");
        System.out.println("Student 3: Name: " + student3.getStudent_Name() + ", ID: " + student3.getStudent_ID() + ", College: " + student3.getCollege());
    }
}

How many Constructors Created in the program? what they are?

Answer

3 constructors:

  1. FinalExam()
  2. FinalExam(String, int)
  3. FinalExam(String, int, String)

Source:CS140 MidTerm Fall-2014-15

Find output of the following java code.

public class Circle{
    double radius = 1;
    public static final double PI = 3.14;
    public static void main(String[] args){
        double volume = PI * radius * radius;
        System.out.println(volume);
    }
}
Answer

Compile-time error: radius is non-static, so main cannot use it without creating an object.

Source:Final Exam IT-232

Describe the difference between the public and private access modifiers in Java. Give an example for each.

Answer
  • public: the member is accessible from any class in any package.
  • private: the member is accessible only from within the same class.

Example

public class Account {
    public  String owner;    // accessible anywhere
    private double balance;  // accessible only inside Account
}

4. Instantiating and using objects

Each of the following statements creates an object and assigns it to a variable:

Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);

Each of these statements has three parts:

  • Declaration: The code set in bold are all variable declarations that associate a variable name with an object type.
  • Instantiation: The new keyword is a Java operator that creates the object.
  • Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
Review Questions

Practice — Section 4: Instantiating and using objects

Source:CS140 MidTerm Fall-2014-15

Which is the correct version of Java code construction an object of class Rectangle, and for declaring an object variable of class Rectangle.

Answer

D. All of the above.

All three statements use the correct object-creation pattern: class type, variable name, new, and a matching constructor call.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232 · Java Final v3

What is the correct syntax to create an object from the class Book?

Answer

A. Book obj = new Book();

To create a Book object, declare a Book variable and call the Book constructor with new Book().

Source:Final Exam IT-232

Which operator is used to instantiate an object in Java?

Answer

B. new

new creates an object by calling a constructor, such as new Book().

Source:IT232 Final T2 2021-2022

Which of these operators is used to allocate memory for an object?

Answer

C. new

new allocates memory for an object and calls its constructor.

Source:IT232 Final T2 2021-2022

Creating an object from a class is also called ______

Answer

C. Instantiating

Instantiating means creating an actual object from a class.

Source:IT232 Final T2 2021-2022

What is the correct syntax to create an object from the class Account?

Answer

D. Account obj = new Account();

Object creation uses the class type, a variable name, new, and the class constructor: Account obj = new Account();.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232 · Java Final v3

What is the correct syntax to create an object from the class Book?

Answer

A. Book obj = new Book();

To create a Book object, declare a Book variable and call the Book constructor with new Book().

Source:An Example of Open Question

How many objects created from class FinalExam? list them.

Answer

3 objects: S1, S2, student3

Source:FINAL IT 232 FIRST Semester-2025

Giving the following code:

public class Animal {
    public void makeSound() {
        System.out.println("The animal makes a sound");
    }

    public static void main(String[] args) {
        Animal myAnimal = new Animal();
        myAnimal.makeSound();
    }
}

What is the name of the object created?

Answer

myAnimal

Source:IT232 Final T2 2021-2022

What is the output of the following code? Cat c = new Cat (); c.speak();

Answer

Depends on the implementation of class Cat. Assuming Cat has a method:

class Cat { void speak() { System.out.println("Meow"); } }

Output: Meow

5. Implementing a test class

Example 1:

class Lamp {
    // stores the value for light
    // true if light is on
    // false if light is off
    boolean isOn;

    // method to turn on the light
    void turnOn() {
        isOn = true;
        System.out.println("Light on? " + isOn);
    }

    // method to turn off the light
    void turnOff() {
        isOn = false;
        System.out.println("Light on? " + isOn);
    }
}

class Main {
    public static void main(String[] args) {
        // create objects led and halogen
        Lamp led = new Lamp();
        Lamp halogen = new Lamp();

        // turn on the light by calling method turnOn()
        led.turnOn();

        // turn off the light by calling method turnOff()
        halogen.turnOff();
    }
}

Output

Light on? true
Light on? false

Example 2:

class Account {
    int acc_no;
    String name;
    float amount;

    void insert(int a, String n, float amt) {
        acc_no = a;
        name = n;
        amount = amt;
    }

    void deposit(float amt) {
        amount = amount + amt;
        System.out.println(amt + " deposited");
    }

    void withdraw(float amt) {
        if (amount < amt) {
            System.out.println("Insufficient Balance");
        } else {
            amount = amount - amt;
            System.out.println(amt + " withdrawn");
        }
    }

    // method to check the balance of the account
    void checkBalance() {
        System.out.println("Balance is: " + amount);
    }

    // method to display the values of an object
    void display() {
        System.out.println(acc_no + " " + name + " " + amount);
    }
}
class TestAccount {
    public static void main(String[] args) {
        Account a1 = new Account();
        a1.insert(832345, "Ankit", 1000);
        a1.display();
        a1.checkBalance();
        a1.deposit(40000);
        a1.checkBalance();
        a1.withdraw(15000);
        a1.checkBalance();
    }
}

Output

832345 Ankit 1000.0
Balance is: 1000.0
40000.0 deposited
Balance is: 41000.0
15000.0 withdrawn
Balance is: 26000.0
Review Questions

Practice — Section 5: Implementing a test class

Source:FINAL IT 232 FIRST Semester-2025

Giving the following code:

public class Animal {
    public void makeSound() {
        System.out.println("The animal makes a sound");
    }

    public static void main(String[] args) {
        Animal myAnimal = new Animal();
        myAnimal.makeSound();
    }
}

What is the output of this program when it runs?

Answer

The animal makes a sound

Source:FINAL IT 232 FIRST Semester-2025

Write a Java program that does the following:

  • defines a class named Car with the following instance variables: 1. String brand (to store the car's brand) 2. int year (to store the car's manufacturing year)

  • Create a constructor that accepts two parameters to initialize these instance variables.

  • Add a method displayDetails() that prints the car's details in a readable format.

  • In the main method, create an object of the Car class using the following data: ("Toyota", 2024) and display its details by calling the displayDetails() method.

Answer
public class Car {
    String brand;
    int year;
    public Car(String brand, int year) {
        this.brand = brand;
        this.year = year;
    }
    public void displayDetails() {
        System.out.println("Brand: " + brand + ", Year: " + year);
    }
    public static void main(String[] args) {
        Car c = new Car("Toyota", 2024);
        c.displayDetails();
    }
}

Source:IT232 Final T2 2021-2022

What will be the output of the following program?

class demo {
    int a, b, c;
    demo () {
        a = 10; b = 20; c = 30;
    }
    public void print() {
        System.out.println ("a= " + a + " b = " + b + "c = " + c);
    }
}
public class Test {
    public static void main(String[] args) {
        demo obj1 = new demo();
        obj1.a += 1;
        obj1.b += 1;
        System.out.println ("values of obj1: ");
        obj1.print();
    }
}
Answer

Output: values of obj1: a= 11 b = 21c = 30

(obj1.a goes from 10 -> 11; obj1.b goes from 20 -> 21; obj1.c remains 30.)

6. Additional Practice

Review Questions

Practice — Section 6: Additional Practice

Source:CS140 MidTerm Fall-2014-15

A method which changes state of its implicit parameter is known as _______________.

Answer

B. Mutator.

A mutator method changes an object's state, usually by updating one of its instance variables.

Module 10 — Classes and Objects II

1. `this` Reference

The problem if we don't use this keyword by the example given below:

class Student {
    int rollno;
    String name;
    float fee;

    Student(int rollno, String name, float fee) {
        rollno = rollno;
        name = name;
        fee = fee;
    }

    void display() {
        System.out.println(rollno + " " + name + " " + fee);
    }
}

class TestThis1 {
    public static void main(String args[]) {
        Student s1 = new Student(111, "ankit", 5000f);
        Student s2 = new Student(112, "sumit", 6000f);
        s1.display();
        s2.display();
    }
}

Output

0 null 0.0
0 null 0.0

The solution using this keyword:

class Student {
    int rollno;
    String name;
    float fee;

    Student(int rollno, String name, float fee) {
        this.rollno = rollno;
        this.name = name;
        this.fee = fee;
    }

    void display() {
        System.out.println(rollno + " " + name + " " + fee);
    }
}

class TestThis1 {
    public static void main(String args[]) {
        Student s1 = new Student(111, "ankit", 5000f);
        Student s2 = new Student(112, "sumit", 6000f);
        s1.display();
        s2.display();
    }
}

Output

111 ankit 5000.0
112 sumit 6000.0

this(): to invoke current class constructor

class A {
    A() {
        System.out.println("hello a");
    }

    A(int x) {
        this();
        System.out.println(x);
    }
}

class TestThis5 {
    public static void main(String args[]) {
        A a = new A(10);
    }
}

Output

hello a
10

Example

// Fig. 8.4: ThisTest.java
// this used implicitly and explicitly to refer to members of an object.

public class ThisTest {
    public static void main(String[] args) {
        SimpleTime time = new SimpleTime(15, 30, 19);
        System.out.println(time.buildString());
    }
} // end class ThisTest

// class SimpleTime demonstrates the "this" reference
class SimpleTime {
    private int hour;   // 0-23
    private int minute; // 0-59
    private int second; // 0-59

    // if the constructor uses parameter names identical to
    // instance variable names the "this" reference is
    // required to distinguish between the names
    public SimpleTime(int hour, int minute, int second) {
        this.hour = hour;     // set "this" object's hour
        this.minute = minute; // set "this" object's minute
        this.second = second; // set "this" object's second
    }

    // use explicit and implicit "this" to call toUniversalString
    public String buildString() {
        return String.format("%24s: %s%n%24s: %s",
            "this.toUniversalString()", this.toUniversalString(),
            "toUniversalString()", toUniversalString());
    }

    // convert to String in universal-time format (HH:MM:SS)
    public String toUniversalString() {
        // "this" is not required here to access instance variables,
        // because method does not have local variables with same
        // names as instance variables
        return String.format("%02d:%02d:%02d",
            this.hour, this.minute, this.second);
    }
} // end class SimpleTime

Output

this.toUniversalString(): 15:30:19
     toUniversalString(): 15:30:19
Review Questions

Practice — Section 1: `this` Reference

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

Which of the following keywords is used to differentiate between local variables and instance variables in Java where formal arguments and instance variables are the same?

Answer

D. this

this refers to the current object. It helps distinguish an instance variable from a local variable or parameter with the same name.

Source:Final Exam IT-232

What is the purpose of the (this) keyword in Java?

Answer

C. To refer to the current object

this means the current object. It is often used to access the object's fields or call another constructor.

Source:Java Final v3

Which of the following keyword is used to differentiate between local variables and instance variables in java program, where formal arguments and instance variable are the same?

Answer

D. this.

this refers to the current object, so this.fieldName separates an instance variable from a parameter with the same name.

Source:CS140 MidTerm Fall-2014-15

What is this reference? What is the difference between instance variable and instance of class?

Answer

this means the current object.

  • Instance variable: a field inside a class.
  • Instance of a class: an object created using new.

2. Overloaded Constructors

  • Java Constructor overloading is a technique in which a class can have any number of constructors that differ in parameter list.
  • The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.

Example of valid constructors for class Account:

Account(int a);
Account(int a, int b);
Account(String a, int b);
class Demo {
    int value1;
    int value2;

    Demo() {
        value1 = 10;
        value2 = 20;
        System.out.println("Inside 1st Constructor");
    }

    Demo(int a) {
        value1 = a;
        System.out.println("Inside 2nd Constructor");
    }

    Demo(int a, int b) {
        value1 = a;
        value2 = b;
        System.out.println("Inside 3rd Constructor");
    }

    public void display() {
        System.out.println("Value1 === " + value1);
        System.out.println("Value2 === " + value2);
    }

    public static void main(String args[]) {
        Demo d1 = new Demo();
        Demo d2 = new Demo(30);
        Demo d3 = new Demo(30, 40);
        d1.display();
        d2.display();
        d3.display();
    }
}

Output

Inside 1st Constructor
Inside 2nd Constructor
Inside 3rd Constructor
Value1 === 10
Value2 === 20
Value1 === 30
Value2 === 0
Value1 === 30
Value2 === 40

Time Class Case Study — check the full case study in Chapter 8, pages from 316 to 322.

Review Questions

Practice — Section 2: Overloaded Constructors

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

Java allows a class to have any number of constructors with different parameter lists via ________.

Answer

A. Constructor Overloading

Constructor overloading means a class has more than one constructor, but each constructor has a different parameter list.

Source:Final Exam IT-232

What is constructor overloading?

Answer

B. Having multiple constructors with different parameter lists

Constructor overloading lets a class create objects in different ways by providing constructors with different parameters.

Source:IT232 Final T2 2021-2022

What will be the output of the following Java code?

class ClassConst{
    ClassConst () {
        System.out.print("hello b ");
    }
    ClassConst (String x) {
        this();
        System.out.print("hello a ");
    }
}
public class Test {
    public static void main(String args[]) {
        ClassConst a = new ClassConst ("hello c");
    }
}
Answer

B. hello b hello a

The String constructor calls this(), so the no-argument constructor runs first and prints hello b. Then the String constructor continues and prints hello a.

Source:IT232 Final T2 2021-2022

Java constructor overloading is a technique in which a class can have ______ constructor(s).

Answer

D. any number of

A class can overload constructors by giving them different parameter lists, so it can have any number of constructors.

Source:Java Final (New)

When a programmer needs to initialize an object in different ways, he can do this using ________.

Answer

A. Constructor overloading

Constructor overloading lets a class provide different constructors for different ways of creating an object.

Source:Java Final v3

Java ___________ allows a class to have any number of constructors with different parameters.

Answer

A. Constructor Overloading

Constructor overloading means a class has multiple constructors with different parameter lists.

Source:IT232 Final T1 2021-2022

Find the output of the following code:

class Demo {
    int value1;
    int value2;

    Demo() {
        value1 = 1;
        value2 = 2;
        System.out.println("Inside 1st Constructor");
    }

    Demo(int a) {
        value1 = a;
        System.out.println("Inside 2nd Constructor");
    }

    Demo(int a, int b) {
        value1 = a;
        value2 = b;
        System.out.println("Inside 3rd Constructor");
    }

    public void display() {
        System.out.println("Value1 === " + value1);
        System.out.println("Value2 === " + value2);
    }

    public static void main(String args[]) {
        Demo d1 = new Demo();
        Demo d2 = new Demo(3);
        Demo d3 = new Demo(3, 4);
        d1.display();
        d2.display();
        d3.display();
    }
}
Answer

Output

Inside 1st Constructor
Inside 2nd Constructor
Inside 3rd Constructor
Value1 === 1
Value2 === 2
Value1 === 3
Value2 === 0
Value1 === 3
Value2 === 4

d2 prints Value2 === 0 because value2 keeps its default value.

3. Default and No-Argument Constructors

  • Every class must have at least one constructor.
  • If you do not provide any in a class's declaration, the compiler creates a default constructor that takes no arguments when it's invoked.
  • The default constructor initializes the instance variables to the initial values specified in their declarations or to their default values.
  • If we do not create any constructor, the Java compiler automatically create a no-arg constructor during the execution of the program.
  • This constructor is called default constructor.
Review Questions

Practice — Section 3: Default and No-Argument Constructors

Source:Final Exam IT-232

When no constructor is explicitly defined in a class, what happens?

Answer

C. JVM creates a default constructor

If you do not write any constructor, Java provides a no-argument default constructor so objects can still be created.

4. Composition

  • A class can have references to objects of other classes as members.
  • This is called composition and is sometimes referred to as a has-a relationship.
  • Example:
  • An AlarmClock object needs to know the current time and the time when it's supposed to sound its alarm.
  • It's reasonable to include two references to Time objects in an AlarmClock object.
  • A car has-a steering wheel, a break pedal and an accelerator pedal.

Example — Class Date:

// Fig. 8.7: Date.java
// Date class declaration.

public class Date {
    private int month; // 1-12
    private int day;   // 1-31 based on month
    private int year;  // any year

    private static final int[] daysPerMonth =
        { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    // constructor: confirm proper value for month and day given the year
    public Date(int month, int day, int year) {
        // check if month in range
        if (month <= 0 || month > 12)
            throw new IllegalArgumentException(
                "month (" + month + ") must be 1-12");

        // check if day in range for month
        if (day <= 0 ||
            (day > daysPerMonth[month] && !(month == 2 && day == 29)))
            throw new IllegalArgumentException("day (" + day +
                ") out-of-range for the specified month and year");

        // check for leap year if month is 2 and day is 29
        if (month == 2 && day == 29 && !(year % 400 == 0 ||
            (year % 4 == 0 && year % 100 != 0)))
            throw new IllegalArgumentException("day (" + day +
                ") out-of-range for the specified month and year");

        this.month = month;
        this.day = day;
        this.year = year;

        System.out.printf(
            "Date object constructor for date %s%n", this);
    }

    // return a String of the form month/day/year
    public String toString() {
        return String.format("%d/%d/%d", month, day, year);
    }
} // end class Date

Class Employee

// Fig. 8.8: Employee.java
// Employee class with references to other objects.

public class Employee {
    private String firstName;
    private String lastName;
    private Date birthDate;
    private Date hireDate;

    // constructor to initialize name, birth date and hire date
    public Employee(String firstName, String lastName, Date birthDate, Date hireDate) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.birthDate = birthDate;
        this.hireDate = hireDate;
    }

    // convert Employee to String format
    public String toString() {
        return String.format("%s, %s Hired: %s Birthday: %s",
            lastName, firstName, hireDate, birthDate);
    }
} // end class Employee

Class EmployeeTest

// Fig. 8.9: EmployeeTest.java
// Composition demonstration.

public class EmployeeTest {
    public static void main(String[] args) {
        Date birth = new Date(7, 24, 1949);
        Date hire = new Date(3, 12, 1988);

        Employee employee = new Employee("Bob", "Blue", birth, hire);
        System.out.println(employee);
    }
} // end class EmployeeTest

Output

Date object constructor for date 7/24/1949
Date object constructor for date 3/12/1988
Blue, Bob Hired: 3/12/1988 Birthday: 7/24/1949
Review Questions

Practice — Section 4: Composition

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

In Java, which of the following design methods should be used to implement the "has-a" relationship?

Answer

C. Composition

Composition means one class has another object inside it. That is the usual way to model a has-a relationship.

Source:IT232 Final T2 2021-2022

A class can have references to objects of other classes as members. This is called ______

Answer

C. composition

Composition means a class has fields that refer to objects of other classes.

Source:Java Final v3

In Java, which of the following design method should be used to implement the has-a connection in classes

Answer

C. Composition

Composition models a has-a relationship, where one class contains an object of another class.

5. `enum` Types

It is a special class which defines a set of constants represented as unique identifiers.

enum Level {
    LOW,
    MEDIUM,
    HIGH
}

Level myVar = Level.MEDIUM;

Example

class EnumExample1 {
    // defining the enum inside the class
    public enum Season { WINTER, SPRING, SUMMER, FALL }

    // main method
    public static void main(String[] args) {
        // traversing the enum
        for (Season s : Season.values())
            System.out.println(s);
    }
}

Output

WINTER
SPRING
SUMMER
FALL

Example

class EnumExample1 {
    // defining enum within class
    public enum Season { WINTER, SPRING, SUMMER, FALL }

    // creating the main method
    public static void main(String[] args) {
        // printing all enum
        for (Season s : Season.values()) {
            System.out.println(s);
        }
        System.out.println("Value of WINTER is: " + Season.valueOf("WINTER"));
        System.out.println("Index of WINTER is: " + Season.valueOf("WINTER").ordinal());
        System.out.println("Index of SUMMER is: " + Season.valueOf("SUMMER").ordinal());
    }
}

Output

WINTER
SPRING
SUMMER
FALL
Value of WINTER is: WINTER
Index of WINTER is: 0
Index of SUMMER is: 2
Review Questions

Practice — Section 5: `enum` Types

Source:Final Exam IT-232

In Java, what does an enum define?

Answer

B. A set of constants

An enum defines a fixed set of named constants, such as days of the week or order statuses.

Source:IT232 Final T1 2021-2022

Which declaration correctly defines a Java enum?

Answer

A. enum Level { LOW, MEDIUM, HIGH }

An enum uses the enum keyword followed by its constants inside braces.

6. Garbage Collection

  • Object uses system resources, such as memory.
  • We need a disciplined way to give resources back to the system when they're no longer needed.

Garbage collection is the process that:

  • Returns memory to system.
  • Java performs this automatically.
  • Object marked for garbage collection if no references to object.

Finalizer method:

  • Returns resources to system.
  • Java provides method finalize.
  • Defined in java.lang.Object.
  • Receives no parameters.
  • Returns void.
Review Questions

Practice — Section 6: Garbage Collection

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

Which of the following Java processes automates the removal of objects that are no longer needed, returning memory to the system?

Answer

C. Garbage collection

Garbage collection automatically frees memory from objects that the program no longer uses.

Source:Java Final (New)

An unreferenced object in java programming is called ________.

Answer

D. Garbage

An object with no references pointing to it can no longer be used, so it is considered garbage.

Source:Java Final v3

Which of the following Java process automates the removal of objects that are no longer required or active and returns memory to System?

Answer

C. Garbage Collection

Garbage collection removes unused objects from memory automatically.

Source:CS140 MidTerm Fall-2014-15

Explain how Java's garbage collector reclaims objects. When does an object become eligible for garbage collection?

Answer

Garbage collection removes unreachable objects.

An object is eligible when no live reference points to it.

  • The reference goes out of scope.
  • The reference is reassigned or set to null.

7. `static` Class Members & `static` import

  • static keyword
  • static class variable
  • Class-wide information
  • All class objects share same data
  • Access to a class's public static members
  • Qualify the member name with the class name and a dot.

Example

// Fig. 8.12: Employee.java
// static variable used to maintain a count of the number of
// Employee objects in memory.

public class Employee {
    private static int count = 0; // number of Employees created
    private String firstName;
    private String lastName;

    // initialize Employee, add 1 to static count and
    // output String indicating that constructor was called
    public Employee(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
        ++count; // increment static count of employees
        System.out.printf("Employee constructor: %s %s; count = %d%n",
            firstName, lastName, count);
    }

    // get first name
    public String getFirstName() {
        return firstName;
    }

    // get last name
    public String getLastName() {
        return lastName;
    }

    // static method to get static count value
    public static int getCount() {
        return count;
    }
} // end class Employee

Example

// Fig. 8.13: EmployeeTest.java
// static member demonstration.

public class EmployeeTest {
    public static void main(String[] args) {
        // show that count is 0 before creating Employees
        System.out.printf("Employees before instantiation: %d%n", Employee.getCount());

        // create two Employees; count should be 2
        Employee e1 = new Employee("Susan", "Baker");
        Employee e2 = new Employee("Bob", "Blue");

        // show that count is 2 after creating two Employees
        System.out.printf("%nEmployees after instantiation:%n");
        System.out.printf("via e1.getCount(): %d%n", e1.getCount());
        System.out.printf("via e2.getCount(): %d%n", e2.getCount());
        System.out.printf("via Employee.getCount(): %d%n", Employee.getCount());

        // get names of Employees
        System.out.printf("%nEmployee 1: %s %s%nEmployee 2: %s %s%n",
            e1.getFirstName(), e1.getLastName(),
            e2.getFirstName(), e2.getLastName());
    }
} // end class EmployeeTest

Output

Employees before instantiation: 0
Employee constructor: Susan Baker; count = 1
Employee constructor: Bob Blue; count = 2

Employees after instantiation:
via e1.getCount(): 2
via e2.getCount(): 2
via Employee.getCount(): 2

Employee 1: Susan Baker
Employee 2: Bob Blue
  • A static import declaration enables you to import the static members of a class or interface so you can access them via their unqualified names in your class.
  • That is, the class name and a dot (.) are not required when using an imported static member.
  • A static import declaration has two forms:
  • One that imports a particular static member: import static packageName.ClassName.staticMemberName;
  • One that imports all static members of a class: import static packageName.ClassName.*;

Example

// Fig. 8.14: StaticImportTest.java
// Static import of Math class methods.
import static java.lang.Math.*;

public class StaticImportTest {
    public static void main(String[] args) {
        System.out.printf("sqrt(900.0) = %.1f%n", sqrt(900.0));
        System.out.printf("ceil(-9.8) = %.1f%n", ceil(-9.8));
        System.out.printf("E = %f%n", E);
        System.out.printf("PI = %f%n", PI);
    }
} // end class StaticImportTest

Output

sqrt(900.0) = 30.0
ceil(-9.8) = -9.0
E = 2.718282
PI = 3.141593
Review Questions

Practice — Section 7: `static` Class Members & `static` import

Source:CS140 MidTerm Fall-2014-15

What do static variables belong to?

Answer

B. a class.

A static variable belongs to the class itself, so it is shared instead of copied separately for each object.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

A ________ variable gets memory only once in the class area at the time of class loading.

Answer

B. static

A static variable belongs to the class and is created once when the class is loaded.

Source:IT232 Final T1 2021-2022

Which statement about a static variable is correct?

Answer

A. It is shared by all objects of the class.

A static variable belongs to the class, so all objects share the same value.

Source:IT232 Final T2 2021-2022

A/An ______ variable can be used to refer to the common property of all objects.

Answer

B. static

static belongs to the class, so it can represent a value shared by all objects of that class.

Source:Java Final v3

_____________ variable gets memory only once in the class area at the time of class loading

Answer

B. static

A static variable belongs to the class itself, so it gets memory once when the class loads — not per object.

Source:Final Exam IT-232

State and explain two differences for each of the following in Java: instance variables, static variables, and local variables.

Answer
  • Instance variable: belongs to one object.
  • Static variable: belongs to the class and is shared.
  • Local variable: declared inside a method.

8. `final` Instance Variables

  • final keyword
  • Indicates that variable is not modifiable.
  • Any attempt to modify final variable results in error. private final int INCREMENT = 5;
  • Declares variable INCREMENT as a constant.
  • Enforces principle of least privilege.

Example

class Bike9 {
    final int speedlimit = 90; // final variable

    void run() {
        speedlimit = 400;
    }

    public static void main(String args[]) {
        Bike9 obj = new Bike9();
        obj.run();
    }
} // end of class

Output

Compile Time Error
Review Questions

Practice — Section 8: `final` Instance Variables

Source:IT232 Final T2 2021-2022

What will be the result of the execution of the following code?

class Test {
    private static final int x = 10;
    public static void main (String [] args) {
        System.out.print(x + "*");
        {
            x++;
        }
    }
}
Answer

B. There will be compile-time error

x is declared static final, so it cannot be changed. The statement x++ causes a compile-time error.

9. Creating packages

Package is a:

  • Group of related classes and interfaces.
  • Helps manage complexity of application components.
  • Facilitates software reuse.
  • Provides convention for unique class names.

Popular package-naming convention:

  • Reverse Internet domain name.
  • e.g., com.deitel

Create Package pack

package pack;

public class A {
    public void msg() {
        System.out.println("Hello");
    }
}

Create Package mypack

package mypack;
import pack.*;

class B {
    public static void main(String args[]) {
        A obj = new A();
        obj.msg();
    }
}

Output

Hello

10. Additional Practice — `FinalExam` Class

Read this program carefully and answer the questions below. It is a worked example of constructor overloading combined with this and getter/setter encapsulation.

class FinalExam {
    private String Student_Name;
    private int Student_ID;
    private String College;

    // first constructor (no-arg)
    public FinalExam() {
        System.out.println("Student 1 Informations:");
        this.Student_Name = Student_Name;
        this.Student_ID = Student_ID;
        this.College = College;
    }

    // second constructor (2 args)
    public FinalExam(String Student_Name, int Student_ID) {
        System.out.println("Student 2 Informations:");
        this.Student_Name = Student_Name;
        this.Student_ID = Student_ID;
    }

    // third constructor (3 args)
    public FinalExam(String Student_Name, int Student_ID, String College) {
        System.out.println("Student 3 Informations:");
        this.Student_Name = Student_Name;
        this.Student_ID = Student_ID;
        this.College = College;
    }

    public void setStudent_Name(String Student_Name) { this.Student_Name = Student_Name; }
    public String getStudent_Name() { return Student_Name; }
    public void setStudent_ID(int Student_ID) { this.Student_ID = Student_ID; }
    public int getStudent_ID() { return Student_ID; }
    public void setCollege(String College) { this.College = College; }
    public String getCollege() { return College; }
}

public class FinalExamTest {
    public static void main(String[] args) {
        FinalExam S1 = new FinalExam();
        System.out.println("Student 1: Name: " + S1.getStudent_Name() + ", ID: " + S1.getStudent_ID() + ", College: " + S1.getCollege());

        FinalExam S2 = new FinalExam("Sarah Ahmed", 102);
        System.out.println("Student 2: Name: " + S2.getStudent_Name() + ", ID: " + S2.getStudent_ID() + ", College: " + S2.getCollege());

        FinalExam student3 = new FinalExam("Ali Hassan", 103, "Computer Science");
        System.out.println("Student 3: Name: " + student3.getStudent_Name() + ", ID: " + student3.getStudent_ID() + ", College: " + student3.getCollege());
    }
}
Review Questions

Practice — Section 10: Additional Practice

Source:An Example of Open Question

How many constructors are defined in class FinalExam? List them with their parameter signatures.

Answer

Three constructors:

  1. FinalExam()
  2. FinalExam(String Student_Name, int Student_ID)
  3. FinalExam(String Student_Name, int Student_ID, String College)

Source:An Example of Open Question

How many instance variables are declared in class FinalExam? List them.

Answer

Three instance variables (all private):

  1. String Student_Name
  2. int Student_ID
  3. String College

Source:An Example of Open Question

How many objects are created from class FinalExam in main? List them.

Answer

Three objects:

  1. S1
  2. S2
  3. student3

Source:An Example of Open Question

What is the output produced when this program runs?

Answer
Student 1 Informations:
Student 1: Name: null, ID: 0, College: null
Student 2 Informations:
Student 2: Name: Sarah Ahmed, ID: 102, College: null
Student 3 Informations:
Student 3: Name: Ali Hassan, ID: 103, College: Computer Science

S1 uses default values. S2 has no college value, so it is null.

Module 11 — Inheritance and Polymorphism

1. Super classes and Subclasses

Inheritance

  • It is a mechanism in which one object acquires all the properties and behaviors of a parent object.
  • Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Features:

  • Software reusability
  • Create new class from existing class
  • Absorb existing class's data and behaviors
  • Enhance with new capabilities

Terms used in Inheritance

  • Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.
  • Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.
  • Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.
  • Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.

  • Subclass extends superclass (referred as base class)

  • Subclass (referred as derived class)
  • More specialized group of objects
  • Behaviors inherited from superclass
  • Can customize
  • Add its own fields and methods
  • Additional behaviors
  • The subclass exhibits the behaviors of its superclass and can modify those behaviors

Class hierarchy

  • Direct superclass
  • Inherited explicitly (one level up hierarchy)
  • Indirect superclass
  • Inherited two or more levels up hierarchy

Single inheritance

  • Inherits from one superclass

Multiple inheritance

  • Inherits from multiple superclasses
  • Java does not support multiple inheritance

Types of inheritance in java

  1. Single (ClassB inherits from ClassA)
  2. Multilevel (ClassC inherits from ClassB, which inherits from ClassA)
  3. Hierarchical (ClassB and ClassC both inherit from ClassA)

is-a relationship and the has-a relationship

In an is-a relationship:

  • An object of a subclass can also be treated as an object of its superclass e.g., a car is a vehicle.
  • Vehicle properties/behaviors also car properties/behaviors

In has-a represents:

  • Composition
  • An object contains as members references to other objects e.g., a car has a steering wheel
  • An object of one class is an object of another class as well.

For example:

  • A CarLoan is a Loan as are HomeImprovementLoans and MortgageLoans. Thus, in Java, class CarLoan can be said to inherit from class Loan.

In this context:

  • Class Loan is a superclass
  • Class CarLoan is a subclass
  • A CarLoan is a specific type of Loan
  • But it's incorrect to claim that every Loan is a CarLoan — the Loan could be any type of loan.
  • Superclass typically represents larger set of objects than subclasses

Examples:

Superclass Subclasses
Student Graduate Student, Undergraduate Student
Shape Circle, Triangle, Rectangle, Sphere, Cube
Loan CarLoan, Home Improvement Loan, MortgageLoan
Employee Faculty, Staff
BankAccount CheckingAccount, SavingsAccount

Inheritance hierarchy

  • Inheritance relationships: tree-like hierarchy structure
  • Each class becomes either:
    • superclass
      • Supply data/behaviors to other classes
    • subclass
      • Inherit data/behaviors from other classes

University Community Member Hierarchy

  • CommunityMember
    • Employee
      • Faculty
        • Administrator
        • Teacher
      • Staff
    • Student
    • Alumnus

Shape Hierarchy

  • Shape
    • TwoDimensionalShape
      • Circle
      • Square
      • Triangle
    • ThreeDimensionalShape
      • Sphere
      • Cube
      • Tetrahedron
Review Questions

Practice — Section 1: Super classes and Subclasses

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

Which of the following is NOT an object-oriented programming concept in Java?

Answer

C. Compilation

Inheritance, polymorphism, and composition are OOP ideas. Compilation is just translating source code, not an OOP concept.

Source:Final Exam IT-232

Which of the following is true about single inheritance in Java?

Answer

C. A class inherits from only one superclass

Single inheritance means one child class extends one parent class. Java classes cannot extend multiple classes.

Source:IT232 Final T1 2021-2022

If class Student is subclassed from class Person, which syntax is correct?

Answer

B. class Student extends Person{}

extends is used when one class inherits from another class.

Source:IT232 Final T1 2021-2022

Find Superclass and Subclass in the below Java code snippet?

class B
{
    void show(){}
}
class A
{
    void hide(){}
}
Answer

C. There is no superclass or subclass present

Neither class uses extends, so A and B are just separate classes. No inheritance relationship is shown.

Source:IT232 Final T1 2021-2022

Which statement correctly describes a has-a relationship in Java?

Answer

A. It is implemented by composition, such as a class having an instance variable of another class.

A has-a relationship means one object contains or uses another object.

Source:IT232 Final T1 2021-2022

Which statement about multiple inheritance in Java is correct?

Answer

A. A class can extend only one class but can implement multiple interfaces.

Java prevents multiple class inheritance, but interfaces can provide multiple types.

Source:IT232 Final T2 2021-2022

In inheritance, Super class is also known as:

Answer

B. Base class

A superclass is also called a base class because other classes inherit from it.

Source:IT232 Final T2 2021-2022

You are creating a Circle class that is supposed to be a subclass of the Shape class. Which statement will accomplish this?

Answer

B. public class Circle extends Shape

The subclass name comes first, then extends, then the superclass name.

Source:Java Final (New)

In Java, the keyword ________ is used in subclass/child class to inherit another class.

Answer

C. extends

A child class uses extends to inherit from a parent class.

Source:Java Final (New)

If class Circle is subclassed from class Shape then which is the correct syntax?

Answer

C. class Circle extends Shape {}

The subclass name comes before extends, and the parent class name comes after it.

Source:Java Final (New)

________ is a mechanism in which one object acquires all the properties and behaviours of a parent object.

Answer

B. Inheritance

Inheritance lets a child object receive properties and behaviors from a parent class.

Source:Java Final (New)

________ is a class which inherits from another class

Answer

C. child class

A child class is the class that inherits from another class.

Source:Java Final v3

Which of the following is NOT an object oriented programming concept in Java

Answer

C. Compilation

Inheritance, polymorphism, and composition are object-oriented features. Compilation is just the build step that turns source into bytecode — it isn't an OOP concept.

Source:Java Final v3

If you want to define class as child you use_______________?

Answer

C. extends

A child class declares its parent with extends, e.g. class Dog extends Animal.

2. protected Members

protected access offers:

  • An intermediate level of access between public and private.
  • A superclass's protected members can be accessed:
  • by members of that superclass
  • by members of its subclasses
  • by members of other classes in the same package
  • Subclass access superclass member
  • Keyword super and a dot (.)
Scope default private protected public
Same Class Yes Yes Yes Yes
Same package subclass Yes No Yes Yes
Same package non-subclass Yes No Yes Yes
Different package subclass No No Yes Yes
Different package non-subclass No No No Yes
Review Questions

Practice — Section 2: protected Members

Source:IT232 Final T1 2021-2022

What is the output of the following Java code?.

class Vehicle{

    protected String brand ="Kia";
    protected String color = "White";
    protected int year = 2020;
void run()
{
    System.out.println(" Vehicle is moving");
}
}

class Car extends Vehicle{

void display(){
    System.out.println(" brand: "+brand +" color: "+color + " year: "+year);}

void stop(){
    System.out.println(" Car stopped moving");}
}

public class TestFinal{
public static void main(String args[]){

    Car c = new Car();
    c.display();
    c.run();
    c.stop();
}
}
Answer

Output: brand: Kia color: White year: 2020 Vehicle is moving Car stopped moving

3. Relationship Between Super classes and Subclasses

Superclass and subclass relationship

  • Example: Point/circle inheritance hierarchy
  • Point
  • x-y coordinate pair
  • Circle
  • x-y coordinate pair
  • Radius
  • Area()

Example

class Employee {
    float salary = 40000;
}

class Programmer extends Employee {
    int bonus = 10000;

    public static void main(String args[]) {
        Programmer p = new Programmer();
        System.out.println("Programmer salary is:" + p.salary);
        System.out.println("Bonus of Programmer is:" + p.bonus);
    }
}

Output

Programmer salary is:40000.0
Bonus of programmer is:10000

Single Inheritance Example

class Animal {
    void eat() {
        System.out.println("eating...");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("barking...");
    }
}

class TestInheritance {
    public static void main(String args[]) {
        Dog d = new Dog();
        d.bark();
        d.eat();
    }
}

Output

barking...
eating...

Multilevel Inheritance Example

class Animal {
    void eat() {
        System.out.println("eating...");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("barking...");
    }
}

class BabyDog extends Dog {
    void weep() {
        System.out.println("weeping...");
    }
}

class TestInheritance2 {
    public static void main(String args[]) {
        BabyDog d = new BabyDog();
        d.weep();
        d.bark();
        d.eat();
    }
}

Output

weeping...
barking...
eating...

Hierarchical Inheritance Example

class Animal {
    void eat() {
        System.out.println("eating...");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("barking...");
    }
}

class Cat extends Animal {
    void meow() {
        System.out.println("meowing...");
    }
}

class TestInheritance3 {
    public static void main(String args[]) {
        Cat c = new Cat();
        c.meow();
        // c.bark(); // C.T.Error
        c.eat();
    }
}

Output

meowing...
eating...

The final Keyword

  • If you don't want other classes to inherit from a class, use the final keyword:
final class Vehicle {
}

class Car extends Vehicle {
}

Compile error:

Main.java:9: error: cannot inherit from final Vehicle
class Main extends Vehicle {
1 error

Example for Super Keyword in Java:

class Superclass {
    int i = 20;

    void display() {
        System.out.println("Superclass display method");
    }
}

class Subclass extends Superclass {
    int i = 100;

    void display() {
        super.display();
        System.out.println("Subclass display method");
        System.out.println(" i value =" + i);
        System.out.println("superclass i value =" + super.i);
    }
}

class SuperUse {
    public static void main(String args[]) {
        Subclass obj = new Subclass();
        obj.display();
    }
}

Output

Superclass display method
Subclass display method
 i value = 100
superclass i value = 20

Example for protected members:

public class Shape {
    protected double height;
    protected double width;
    private double test;

    public void setValues(double height, double width) {
        this.height = height;
        this.width = width;
    }
}

public class Rectangle extends Shape {
    public double getArea() {
        // test = 10.2;
        // Error cannot access private variable
        return height * width; // accessing protected members
    }
}

Example for protected members (continued):

public class Triangle extends Shape {
    public double getArea() {
        return height * width / 2;
    }
}

public class TestProgram {
    public static void main(String[] args) {
        Rectangle rectangle = new Rectangle();
        Triangle triangle = new Triangle();
        rectangle.setValues(5, 4);
        triangle.setValues(5, 10);

        System.out.println("Area of rectangle : " + rectangle.getArea());
        System.out.println("Area of triangle: " + triangle.getArea());
    }
}

Output

Area of rectangle : 20.0
Area of triangle: 25.0
Review Questions

Practice — Section 3: Relationship Between Super classes and Subclasses

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

To stop or block inheriting a given class, the ________ keyword is used before the class.

Answer

A. final

A final class cannot be extended, so no subclass can inherit from it.

Source:Final Exam IT-232

super.i refers to:

Answer

D. Parent class variable i

super refers to the parent class part of the object. So super.i means the parent's variable named i.

Source:IT232 Final T1 2021-2022

Which statement about a final class in Java is correct?

Answer

A. A final class cannot be inherited.

The final keyword on a class stops other classes from extending it.

Source:IT232 Final T2 2021-2022

Consider the following code snippet:

public void deposit (double amount)
{
    transactionCount ++;
    super.deposit (amount);
}

Which of the following statements is true?

Answer

C. This method calls a public method in its superclass

super.deposit(amount) calls the deposit method from the superclass.

Source:Java Final (New)

In inheritance, ________ keyword is used by the child class to access parent's variables, methods and constructors.

Answer

D. super

super refers to the parent class part of the object, so it can access parent constructors, methods, or variables.

Source:Java Final v3

To Stop or block inheriting a given class, the ________ keyword is used before the class name.

Answer

A. final

A final class cannot be extended, so it blocks inheritance.

Source:Java Final (New)

Programming Task:

  1. Create a class Employee according to the following requirement:
  2. A teacher has three attributes: employeeID, name, salary.

  3. Create a class Teacher that inherits from the class Employee.

  4. Add one attribute: bonus.
  5. Add a constructor with four parameters to initialize all the attributes (employeeID, name, salary, and bonus) by specific values.

  6. Create the tester class (main Class), and:

  7. Create an instructor object (instructor1), provide all values (employeeID, name, salary, and bonus) for the class attributes.
  8. Create another instructor object (instructor2), provide all values (employeeID, name, salary, and bonus) for the class attributes.
  9. Print the salary of each Instructor object (i.e. instructor1 and instructor2).
Answer
class Employee {
    int    employeeID;
    String name;
    double salary;
}

class Teacher extends Employee {
    double bonus;
    public Teacher(int id, String name, double salary, double bonus) {
        this.employeeID = id;
        this.name       = name;
        this.salary     = salary;
        this.bonus      = bonus;
    }
}

public class Tester {
    public static void main(String[] args) {
        Teacher instructor1 = new Teacher(101, "Ahmed", 5000, 500);
        Teacher instructor2 = new Teacher(102, "Sara",  6000, 600);
        System.out.println("instructor1 salary: " + instructor1.salary);
        System.out.println("instructor2 salary: " + instructor2.salary);
    }
}

Source:Java Final v3

Essay — the question is below the code.

class Person {
    String first_name;
    String last_Name;
    void printInf() {
        System.out.println("First Name is " + first_name + "last Name is " +
last_Name);
    }
}
class Student extends Person {
    double GPA;
    String department;

    Student() {
        first_name = "Ahmed ";
        last_Name = " Alghamdi ";
        GPA = 4;
        department = "Computer Science";
    }
    void printInf(){
        super.printInf();
        System.out.println(" GPA is "+ GPA + " department is "+ department);
    }
}
// Second Class
public class FinalTester {
    public static void main(String[] args) {
        Person P = new Person();
        Student s = new Student();
        P.printInf();
        s.printInf();
    }
}

1 - What is the object-oriented programing concept presents in this code?

2 - Give the output of the program.

Answer

OOP concepts: inheritance and method overriding.

Output

First Name is nulllast Name is null
First Name is Ahmed last Name is  Alghamdi
GPA is 4.0 department is Computer Science

4. Polymorphism Examples

Polymorphism

  • means "many forms", and it occurs when we have many classes that are related to each other by inheritance.
  • Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.
  • Treat objects in same class hierarchy as if all superclass
  • Abstract class
  • Common functionality
  • Makes programs extensible
  • New classes added easily, can still be processed

In our examples

  • Use abstract superclass Shape
  • Defines common interface (functionality)
  • Point, Circle and Cylinder inherit from Shape
  • Class Employee for a natural example

Example

class Shapes {
    public void area() {
        System.out.println("The formula for area of ");
    }
}

class Triangle extends Shapes {
    public void area() {
        System.out.println("Triangle is 1/2 * base * height ");
    }
}

class Circle extends Shapes {
    public void area() {
        System.out.println("Circle is 3.14 * radius * radius ");
    }
}

class Main {
    public static void main(String[] args) {
        Shapes myShape = new Shapes();    // Create a Shapes object
        Shapes myTriangle = new Triangle(); // Create a Triangle object
        Shapes myCircle = new Circle();    // Create a Circle object

        myShape.area();
        myTriangle.area();
        myShape.area();
        myCircle.area();
    }
}

Output

The formula for area of Triangle is 1/2 * base * height
The formula for area of Circle is 3.14 * radius * radius

Polymorphism in Java can be performed by two different methods:

Method Overloading

  • Defined as a process that can create multiple methods of the same name in the same class, and all the methods work in different ways.
  • Method overloading occurs when there is more than one method of the same name in the class

Method Overriding

  • Defined as a process when the subclass or a child class has the same method as declared in the parent class.

Method Overriding Example:

class Vehicle {
    void run() {
        System.out.println("Vehicle is moving");
    }
}

class Car2 extends Vehicle {
    void run() {
        System.out.println("car is running safely");
    }

    public static void main(String args[]) {
        Car2 obj = new Car2();
        obj.run(); // calling method
    }
}
  • Overriding is done by using a reference variable of the superclass.
  • Which method to be called is determined based on the object which is being referred to by the reference variable.
  • This is also known as Upcasting.
class A {}
class B extends A {}

A a = new B(); // upcasting

Example

class Animal {
    void eat() {
        System.out.println("Animals Eat");
    }
}

class herbivores extends Animal {
    void eat() {
        System.out.println("Herbivores Eat Plants");
    }
}

class omnivores extends Animal {
    void eat() {
        System.out.println("Omnivores Eat Plants and meat");
    }
}

class carnivores extends Animal {
    void eat() {
        System.out.println("Carnivores Eat meat");
    }
}

class main {
    public static void main(String args[]) {
        Animal A = new Animal();
        Animal h = new herbivores(); // upcasting
        Animal o = new omnivores();  // upcasting
        Animal c = new carnivores(); // upcasting
        A.eat();
        h.eat();
        o.eat();
        c.eat();
    }
}

Output

Animals eat
Herbivores Eat Plants
Omnivores Eat Plants and meat
Carnivores Eat meat
Review Questions

Practice — Section 4: Polymorphism Examples

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

Polymorphism in Java can be achieved by ________.

Answer

D. Method Overloading

Method overloading is a form of polymorphism because the same method name can behave differently based on the parameters.

Source:Final Exam IT-232

Which method output runs?

class Animal {
void eat() { System.out.println("Animal eats"); }
}
class Cat extends Animal {
void eat() { System.out.println("Cat eats fish"); }
}
class Main {
public static void main(String[] args) {
Animal a = new Cat();
a.eat();
}
}
Answer

A. Cat eats fish

a is declared as Animal, but the actual object is new Cat(). Overridden methods run based on the real object, so Cat's eat() runs.

Source:IT232 Final T1 2021-2022

Which polymorphism behavior do you see in below class?

class Draw{
    public void Color(int x) { }
    public void Color(int x, int y) { }
    public void Color(int x, int y, int z) { }
}
Answer

A. Method overloading

All three methods have the same name Color, but their parameter lists are different. That is method overloading.

Source:IT232 Final T2 2021-2022

______ is a process when a subclass has the same method as declared in the parent class.

Answer

A. Method Overriding

Method overriding happens when a subclass provides its own version of a method already declared in the parent class.

Source:Java Final (New)

What kind of polymorphism behavior does the below class show?

class MathCalculation{
    public void Add(int x) { }
    public void Add(int x, double y) {}
    public void Add(int x, int y, int z) {}
}
Answer

B. Method overloading

The class has three Add methods with different parameter lists. Same name plus different parameters means method overloading.

Source:Java Final (New)

Which of the following lines in the main() method creates a compile time error?

class A {
    void print() {System.out.println(" class A");}
}
class B extends A {
    void print(int x) { System.out.println(" class B ");}
}
class C extends A {
    void print(double y) {System.out.println("class C ");}
}
class Main {
    public static void main(String[] args) {
        B obj = new B();
        obj.print();
        obj.print(10.4);
        obj.print(5);
    }
}
Answer

B. obj.print(10.4);

B has print() from A and print(int) in B, but it does not have print(double). The double version exists only in class C.

Source:Java Final v3

What is the output of the following code snippet?

class Father {
    int age = 55;
    void display_Name() {
        System.out.println("Ahmed, Age: "+age);
    }
}
class Son extends Father {
    int age = 18;
    void display_Name() {
        System.out.println("Omar,Age:"+age);
    }
    public static void main(String[] args) {
        Son A1 = new Son();
        A1.display_Name();
    }
}
Answer

D. Omar, Age: 18

A1 is a Son object, so Son's display_Name() runs and uses Son's age value, 18.

Source:Java Final v3

What is the output for the following code snippet?

class Mom {
    String name = "Layla";
    void my_Name(){
        System.out.println(name);
    }
}
class daughter extends Mom{
    String name = "Zainab";
    void my_Name(){
        System.out.println(name);
    }
    public static void main(String[] args) {
        daughter first = new daughter();
        System.out.println(first.name);
    }
}
Answer

C. Zainab

first is a daughter object, and direct field access first.name uses the name field in daughter, which is Zainab.

Source:Java Final v3

Polymorphism is Java can be achieved by ___________

Answer

D. Method Overloading

Method overloading lets the same name take different parameter lists, so the compiler picks the right version at the call — that's compile-time polymorphism.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

What is the output of the following Java program?

class A {
    int i;
    void display() {
        System.out.println(i);
    }
}

class B extends A {
    int j;
    void display() {
        System.out.println(j);
    }
}

public class InheritanceDemo {
    public static void main(String[] args) {
        B obj = new B();
        obj.i = 1;
        obj.j = 2;
        obj.display();
    }
}
Answer

Output

2

B overrides display(), so it prints j.

5. Abstract Classes and Methods

Abstract class:

  • is a restricted class that cannot be used to create objects
  • to access it, it must be inherited from another class.

Abstract method:

  • can only be used in an abstract class, and it does not have a body.
  • The body is provided by the subclass (inherited from).

Example

abstract class Animal {
    public abstract void animalSound();

    public void sleep() {
        System.out.println("Zzz");
    }
}
  • If you try to execute: Animal myObj = new Animal(); // will generate an error

Example

abstract class Animal {
    public abstract void animalSound();

    public void sleep() {
        System.out.println("Zzz");
    }
}

class Cat extends Animal {
    public void animalSound() {
        System.out.println("The cat says: meow meow");
    }
}

class Main {
    public static void main(String[] args) {
        Cat myCat = new Cat();
        myCat.animalSound();
        myCat.sleep();
    }
}

Output

The cat says: meow meow
Zzz

An interface:

  • is a completely "abstract class" that is used to group related methods with empty bodies.
  • To access the interface methods, the interface must be "implemented".
  • The body of the interface method is provided by the "implement" class

Interface Example:

interface Animal {
    public void animalSound();
    public void sleep();
}

class Cat implements Animal {
    public void animalSound() {
        System.out.println("The cat says: meow meow ");
    }

    public void sleep() {
        System.out.println("Zzz");
    }
}

class Main {
    public static void main(String[] args) {
        Cat myCat = new Cat();
        myCat.animalSound();
        myCat.sleep();
    }
}

Output

The cat says: meow meow
Zzz
Review Questions

Practice — Section 5: Abstract Classes and Methods

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232 · Java Final v3

Which of these keywords is used to define interfaces in Java?

Answer

D. interface

Java uses the lowercase keyword interface to declare an interface.

Source:IT232 Final T1 2021-2022

Which keyword is used to implement an interface in Java?

Answer

A. implements

implements is used when a class implements an interface.

Source:Java Final (New)

________ is a completely "abstract class" that is used to group related methods with empty bodies.

Answer

D. Interface

An interface groups method declarations that classes can implement.

Source:Java Final (New)

________ is a restricted class that cannot be used to create objects. To access it, it must be inherited from another class.

Answer

C. Abstract class

An abstract class cannot be instantiated directly; it is meant to be extended.

6. Additional Practice

Review Questions

Practice — Section 6: Additional Practice

Source:Java Final (New)

A method written by a programmer is called ________.

Answer

B. User-defined Method

A method written by the programmer is user-defined, unlike predefined methods that already come with Java.

Source:Java Final (New)

The "new" keyword in java creates an/a ________.

Answer

A. Object

new creates an object and calls a constructor.

Source:oop - 2025

Which key feature of Java allows programs to be written once and run on many different computer systems and devices?

Answer

D. Platform independence

Java's bytecode runs on any JVM, so the same .class file works on Windows, Linux, or macOS — that's platform independence.

Module 12 — Strings and Characters

1. Fundamentals of strings and characters

Characters:

  • The fundamental building blocks of Java source programs.
  • A character literal is an integer value represented as a character in single quotes.
  • The value of a character literal is the integer value of the character in the Unicode character set.

Class String:

  • Used to represent strings in Java.
Review Questions

Practice — Section 1: Fundamentals of strings and characters

Source:IT232 Final T1 2021-2022

How should two String values usually be compared for the same text?

Answer

A. Use the equals() method.

equals() compares String contents, while == compares object references.

Source:IT232 Final T1 2021-2022

Which statement about the Java String class is correct?

Answer

A. String objects are immutable.

A String cannot be changed in place; operations create new String objects.

Source:IT232 Final T1 2021-2022

What happens when you appear to modify a Java String?

Answer

A. A new String object is created.

Strings are immutable, so changing text produces another String.

Source:IT232 Final T2 2021-2022

What is the output of the following java statement?System.out.println (Character.toLowerCase ('B'));

Answer

A. b

Character.toLowerCase('B') converts the uppercase character B to lowercase b.

Source:Java Final (New)

What is the output of the following code snippet?

String name = "ali";
if (name == "ali")
    System.out.print("ALI ");
System.out.println("GOOD");
Answer

B. ALI GOOD

Here name and the literal "ali" refer to the same pooled string, so the if prints ALI. The final println always prints GOOD.

Source:Java Final v3

What is the output of the following Java code?

public static void main(String[] args) {
    String name1 = "FOX", name2 = "DOG";
    if (name1 == "FOX")
        System.out.println("FOX ");
        System.out.println("Good");
    if (name2 == "CAT") {
        System.out.println("DINO");
    }
}
Answer

A. FOX GOOD

name1 == "FOX" is true (string literals share the same object), so FOX prints. The next println("Good") is not inside the if — only the line directly under an unbraced if belongs to it — so Good runs unconditionally. name2 == "CAT" is false, so DINO is skipped.

2. Class String, Class Character

Class String provides constructors for initializing String objects in a variety of ways.

charArray Index Value
charArray[0] b
charArray[1] i
charArray[2] r
charArray[3] t
charArray[4] h
charArray[5] ' '
charArray[6] d
charArray[7] a
charArray[8] y
// Fig. 14.1: StringConstructors.java
// String class constructors.

public class StringConstructors
{
    public static void main(String[] args)
    {
        char[] charArray = { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y'};
        String s = new String("hello");

        // use String constructors
        String s1 = new String();
        String s2 = new String(s);
        String s3 = new String(charArray);
        String s4 = new String(charArray, 6, 3);

        System.out.printf(
            "s1 = %s%ns2 = %s%ns3 = %s%ns4 = %s%n", s1, s2, s3, s4);
    }
} // end class StringConstructors

Output

s1 = 
s2 = hello
s3 = birth day
s4 = day

String Methods length, charAt and getChars

// Fig. 14.2: StringMiscellaneous.java
// This application demonstrates the length, charAt and getChars
// methods of the String class.

public class StringMiscellaneous
{
    public static void main(String[] args)
    {
        String s1 = "hello there";
        char[] charArray = new char[5];

        System.out.printf("s1: %s", s1);

        // test length method
        System.out.printf("%nLength of s1: %d", s1.length());

        // loop through characters in s1 with charAt and display reversed
        System.out.printf("%nThe string reversed is: ");
        for (int count = s1.length() - 1; count >= 0; count--)
            System.out.printf("%c", s1.charAt(count));

        // copy characters from string into charArray
        s1.getChars(0, 5, charArray, 0);

        System.out.printf("%nThe character array is: ");
        for (char character : charArray)
            System.out.print(character);
        System.out.println();
    }
} // end class StringMiscellaneous

Output

s1: hello there
Length of s1: 11
The string reversed is: ereht olleh
The character array is: hello
charArray Index Value
charArray[0] h
charArray[1] e
charArray[2] l
charArray[3] l
charArray[4] o

Comparing Strings

Java String class compareTo() method compares the given string with the current string lexicographically.

  1. If s1 > s2, it returns a positive number.
  2. If s1 < s2, it returns a negative number.
  3. If s1 == s2, it returns 0.
public class CompareToExample
{
    public static void main(String[] args)
    {
        String myStr1 = "Hello";
        String myStr2 = "Hello";

        System.out.println(myStr1.compareTo(myStr2));
        // Returns 0 because they are equal
    }
}
s1 = "hello"
s2 = "goodbye"

s1.compareTo(s2)  →  32
s2.compareTo(s1)  →  -2
public class Test {
    public static void main(String args[]) {
        System.out.println("cargo".compareTo("cathode"));
        System.out.println("car".compareTo("Car"));
        System.out.println("hello".compareTo("hello"));
    }
}

Figure 3 — Lexicographic Comparison:

The letter r comes before t.

Class Character

// Fig. 14.15: StaticCharMethods.java
// Character static methods for testing characters and converting case.
import java.util.Scanner;

public class StaticCharMethods
{
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in); // create scanner
        System.out.println("Enter a character and press Enter");
        String input = scanner.next();
        char c = input.charAt(0); // get input character

        // display character info
        System.out.printf("is defined: %b%n", Character.isDefined(c));
        System.out.printf("is digit: %b%n", Character.isDigit(c));
        System.out.printf("is first character in a Java identifier: %b%n",
            Character.isJavaIdentifierStart(c));
        System.out.printf("is part of a Java identifier: %b%n",
            Character.isJavaIdentifierPart(c));
        System.out.printf("is letter: %b%n", Character.isLetter(c));
        System.out.printf("is letter or digit: %b%n", Character.isLetterOrDigit(c));
        System.out.printf("is lower case: %b%n", Character.isLowerCase(c));
        System.out.printf("is upper case: %b%n", Character.isUpperCase(c));
        System.out.printf("to upper case: %s%n", Character.toUpperCase(c));
        System.out.printf("to lower case: %s%n", Character.toLowerCase(c));
    }
} // end class StaticCharMethods

Output

Enter a character and press Enter
A
is defined: true
is digit: false
is first character in a Java identifier: true
is part of a Java identifier: true
is letter: true
is letter or digit: true
is lower case: false
is upper case: true
to upper case: A
to lower case: a

Check the book for more examples on String and Character:

  • String Class Methods:
    • String Method equals
    • String Method equalsIgnoreCase
    • String Method regionMatches
    • String Methods startsWith and endsWith
    • String Method valueOf
  • Locating Characters and Substrings in Strings
  • Extracting Substrings from Strings
  • Concatenating Strings

String Method equals

public class StringEqualsExample
{
    public static void main(String[] args)
    {
        String s1 = new String("hello");
        String s2 = "hello";
        String s3 = "Hello";

        System.out.println(s1 == "hello"); // false
        System.out.println(s1.equals("hello")); // true
        System.out.println(s2 == "hello"); // true
        System.out.println(s1.equals(s3)); // false
        System.out.println(s1.equalsIgnoreCase(s3)); // true
    }
}

String Method regionMatches

public class StringMiscellaneous
{
    public static void main(String[] args)
    {
        String s1 = "Happy Birthday";
        String s2 = "happy birthday";

        // test regionMatches (ignore case)
        System.out.println(" s3.regionMatches(0, s4, 0, 5): "
            +s1.regionMatches (0, s2, 0, 5));

        // test regionMatches (ignore case)
        System.out.println(" s3.regionMatches (true, 0, s4, 0, 5): "
            +s1.regionMatches (true, 0, s2, 0, 5));
    }
}

Output

----jGRASP exec: java StringMiscellaneous
s3.regionMatches (0, s4, 0, 5): false
s3.regionMatches (true, 0, s4, 0, 5): true
----jGRASP: operation complete.

startsWith and endsWith

public class StringMiscellaneous
{
    public static void main(String[] args)
    {
        String array[] = {"started", "starting"};
        for(String s: array)
        {
            // test method startsWith
            System.out.println("string "+ s +" starts with st? "+ s.startsWith("st"));
            // test method startsWith starting from position 2 of string
            System.out.println("string "+s+" starts with art at position 2? "+ s.startsWith("art",2));
            // test method endsWith
            System.out.println("string "+s+ " end with ed? "+ s.endsWith("ed"));
        }
    }
}

Output

----jGRASP exec: java StringMiscellaneous
string started starts with st? true
string started starts with art at position 2? true
string started end with ed? true
string starting starts with st? true
string starting starts with art at position 2? true
string starting end with ed? false

String Method valueOf (static method)

public class StringMiscellaneous
{
    public static void main(String[] args)
    {
        char array[] = {'a', 'b', 'c'};
        int x = 50;
        System.out.println(" char array: "+String.valueOf(array));
        System.out.println(" x: " +String.valueOf(x));
    }
}

Output

----jGRASP exec: java StringMiscellaneous
char array: abc
x: 50

Locating Characters

public class StringMiscellaneous
{
    public static void main(String[] args)
    {
        String letters = "abcdabcd";
        System.out.println(" c is located at " +letters.indexOf('c'));
        System.out.println(" c is located at " +letters.lastIndexOf('c'));
        System.out.println(" abc is located at " +letters.indexOf("abc"));
    }
}

Output

----jGRASP exec: java StringMiscellaneous
c is located at 2
c is located at 6
abc is located at 0

Extracting Substrings from Strings and Concatenating Strings

public class StringMiscellaneous
{
    public static void main(String[] args)
    {
        String s = "Hello World!";
        String s2 = "Happy";
        String s3 = "Birthday";
        int x = 10;

        System.out.println(" substring from index 6 to the end is "+s.substring(6));
        System.out.println(" Substring from index 1 up to, but not including 7 is "+ s.substring(1,7));
        System.out.println(" Result of s2.concat(s3) = "+ s2.concat(s3));
        System.out.println(" the value of x is "+ x);
    }
}

Output

----jGRASP exec: java StringMiscellaneous
substring from index 6 to the end is World!
Substring from index 1 up to, but not including 7 is ello W
Result of s2.concat(s3) = HappyBirthday
the value of x is 10
Review Questions

Practice — Section 2: Class String, Class Character

Source:CS140 MidTerm Fall-2014-15

Which java statements change the string "SEU" to "seu".

Answer

C. All of the above.

Both listed statements can produce seu: replace swaps the exact text, and toLowerCase() converts the letters to lowercase.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232 · Java Final v3

What is the output of the following code snippet?

String value1 = "Work hard";
System.out.println(value1.length());
Answer

B. 9

length() counts every character in the string, including the space. Work hard has 9 characters.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

What is the output of the following code snippet?

char array[] = {' ', 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
String value = new String(array, 3, 5);
System.out.println(value);
Answer

C. lo wo

new String(array, 3, 5) starts at index 3 and takes 5 characters. Those characters are l, o, space, w, o, giving lo wo.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

The method "compareTo()" in Java is used to compare ________.

Answer

B. one string with another string

compareTo() is a String method used to compare one string with another in lexicographic order.

Source:Final Exam IT-232

What does the charAt() method provide when used on a String?

Answer

D. It returns the character located at a specified index

charAt(index) returns the single character stored at that position in the string.

Source:Final Exam IT-232

What is the expected output of the following Java expression? "apple".compareTo("banana")

Answer

B. A negative integer

compareTo() returns a negative number when the first string comes before the second. apple comes before banana.

Source:Final Exam IT-232

Lexicographical comparison is performed by:

Answer

C. compareTo()

compareTo() compares strings in dictionary-style order and returns a negative, zero, or positive number.

Source:Final Exam IT-232

What does the length() method of a String return in Java?

Answer

D. It returns the total number of characters in the string

length() returns how many characters are in the string, including spaces.

Source:IT232 Final T1 2021-2022

Indicate the result of comparing the first string: "Apples", with the second string: "Oranges".

Answer

A. less than

In lexicographic order, Apples comes before Oranges, so the first string is less than the second.

Source:IT232 Final T1 2021-2022 · IT232 Final T2 2021-2022

Which of these methods of String class is used to obtain character at specified index?

Answer

D. charAt()

charAt(index) returns the character stored at that exact position in the string.

Source:IT232 Final T1 2021-2022

Which of these methods of String class can be used to test two strings for equality?

Answer

D. equals()

Use equals() to compare the text inside two strings. Do not use == for string content comparison.

Source:IT232 Final T2 2021-2022

What will be the output of the following Java program?

class string_class
{
    public static void main(String args[]) {
        char[] arr = {'O','O', 'P',' ', 'E', 'x', 'a', 'm'};
        String s = new String(arr);
        System.out.println(s);
    }
}
Answer

D. OOP Exam

The String constructor builds a string from every character in the array, including the space, so the result is OOP Exam.

Source:IT232 Final T2 2021-2022

Which of these methods of String class can be used to compare two strings lexicographically?

Answer

D. compareTo()

compareTo() compares strings in lexicographic order and returns a negative, zero, or positive value.

Source:IT232 Final T2 2021-2022

What will be the output of the following Java program?

class string_demo {
    public static void main(String args[]) {
        String obj = "IlikeJava";
        System.out.println(obj.length());
    }
}
Answer

B. 9

length() counts all characters in IlikeJava. There are 9 characters.

Source:IT232 Final T1 2021-2022 · IT232 Final T2 2021-2022

Which of these methods of String class is used to obtain character at specified index?

Answer

D. charAt()

charAt(index) returns the character stored at that exact position in the string.

Source:Java Final (New)

In the String class, the ________ is used to compare the equality of two string values.

Answer

B. equals()

equals() compares the actual text inside two strings.

Source:Java Final (New)

The statementSystem.out.println("Hello".compareTo("Hello"));

Answer

C. Prints 0 because the two strings are equal.

compareTo() returns 0 when both strings have the same text.

Source:Java Final v3

The method compareTo() in Java is used to compare _____________

Answer

B. One String with another String

compareTo() is a String method used to compare one string with another.

Source:Java Final v3

What is the output of the following code snippet?

String value = "Today is an exam day!";
System.out.println(value.substring(12));
Answer

B. exam day!

substring(12) returns everything from index 12 onward. Counting from 0, position 12 lands at the e of exam day!.

Source:Java Final v3

What is the output of the following code snippet?

public static void main(String[] args) {
    char[] array = {'H', 'i', ' ',
                    'w', 'o', 'r', 'l', 'd',
                    'f', 'r', 'o', 'm', 'S', 'E', 'U'};
    String value = new String(array, 3, 5);
    System.out.println(value);
}
Answer

C. World

new String(array, 3, 5) starts at index 3 and takes 5 characters: w, o, r, l, d.

Source:Final Exam IT-232

Write a Java method (inside a runnable program) that takes a String from the user and prints the following information:

  • the first character, using charAt()
  • the length of the string, using length()
  • whether the string starts with "A", using startsWith()
  • whether the string ends with "Z", using endsWith()
Answer
import java.util.Scanner;
public class StringInfo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        System.out.println("First char: " + s.charAt(0));
        System.out.println("Length: " + s.length());
        System.out.println("Starts with A: " + s.startsWith("A"));
        System.out.println("Ends with Z: " + s.endsWith("Z"));
    }
}

Source:IT232 Final T1 2021-2022

Write a complete java program that perform the following tasks:

  • Asks the user to input two strings.
  • Uses the method compareTo of the class String to compare the two strings input by the user. Output whether the first string is less than, equal to or greater than the second.
Answer
import java.util.Scanner;
public class CompareStrings {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s1 = sc.nextLine();
        String s2 = sc.nextLine();
        int r = s1.compareTo(s2);
        if (r < 0)      System.out.println(s1 + " is less than "   + s2);
        else if (r > 0) System.out.println(s1 + " is greater than " + s2);
        else            System.out.println(s1 + " is equal to "    + s2);
    }
}

Source:IT232 MidTerm B

Determine the output of the following code.

int x=3;
int y=4;
String s="S";
System.out.print("output is "+s+x+y);
System.out.print(" output is "+s+(y+y));
Answer
output is S34 output is S8

x and y join as text after s; (y+y) is calculated first.

3. Tokenizing Strings

  • Tokenizer
    • Partition String into individual substrings
    • His Name is Ali -> His, Name, is, Ali
  • Use delimiter
    • Student's name is Ali
    • His grad is 80
  • Java offers java.util.StringTokenizer

Example:

Token Value
tokens[0] This
tokens[1] is
tokens[2] a
tokens[3] sentence
tokens[4] with
tokens[5] seven
tokens[6] tokens
// Fig. 14.18: TokenTest.java
// StringTokenizer object used to tokenize strings.
import java.util.Scanner;

public class TokenTest
{
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a sentence and press Enter");
        String sentence = scanner.nextLine();

        // process user sentence
        String[] tokens = sentence.split(" ");
        System.out.printf("Number of elements: %d%nThe tokens are:%n",
            tokens.length);

        for (String token : tokens)
            System.out.println(token);
    }
} // end class TokenTest

Output

Enter a sentence and press Enter
This is a sentence with seven tokens
Number of elements: 7
The tokens are:
This
is
a
sentence
with
seven
tokens
Review Questions

Practice — Section 3: Tokenizing Strings

Source:Final Exam IT-232

A Tokenizer partition String into individual substrings using the method:

Answer

B. split

split() breaks a string into smaller strings using a delimiter, such as a space or comma.

Source:Java Final (New)

The following Java program is correct. Replace each // ..... comment line with a one-sentence description of what the next line of code does.

public class TokenizingExample {
    public static void main(String[] args) {
        // .................................................... (1 mark)
        String breakfastMenu = "I plan to have scrambled eggs, peanut butter, toast, honey, and coffee for breakfast.";
        // .................................................... (1 mark)
        String[] items = breakfastMenu.split(", ");
    }
}
Answer

Suggested comment fill-in:

  1. // Declare the breakfast menu String.
  2. // Split the String using ", ".

Source:Java Final (New)

Programming Task:

Consider the following code snippet from Question 2:

public static void main(String[] args) {
    // .................................................... (1 mark)
    String breakfastMenu = "I plan to have scrambled eggs, peanut butter, toast, honey, and coffee for breakfast.";
    // .................................................... (1 mark)
    String[] items = breakfastMenu.split(", ");
    // .................................................... (1 mark)
    for (String item : items) {
        System.out.println(item);
    }
}
Answer

Comment fill-in:

  1. // Declare the breakfast menu String.
  2. // Split the String using ", ".
  3. // Print each item.

4. Regular Expressions

  • Regular expression
    • A string that describes a search pattern for matching characters in another string.
    • Sequence of characters and symbols
    • Defines a set of strings
    • Expressions are useful for validating input and ensuring that data is in a particular format.
  • Class Pattern
    • An immutable regular expression
    • Example methods: matches(".s", "as"), compile(".s"), p.matcher("as")
  • Class Matcher
    • A regular expression matching operation. matches();

Predefined Character Classes

Character Matches Character Matches Example Code
\d any digit \D any nondigit System.out.println(Pattern.matches("\\d", "abc"));//false (non-digit)
\w any word character \W any nonword character System.out.println(Pattern.matches("\\d", "1"));//true (digit and comes once)
\s any white-space character \S any non-whitespace character System.out.println(Pattern.matches("\\D", "m"));//true(nondigit and comes once)
System.out.println(Pattern.matches("\\D", "1"));//false (digit)

Example 1 — Three Ways to Match

import java.util.regex.*;

public class RegexExample1 {
    public static void main(String args[]) {
        // 1st way
        Pattern p = Pattern.compile(".s"); // . represents single character
        Matcher m = p.matcher("as");
        boolean b = m.matches();

        // 2nd way
        boolean b2 = Pattern.compile(".s").matcher("as").matches();

        // 3rd way
        boolean b3 = Pattern.matches(".s", "as");

        System.out.println(b + " " + b2 + " " + b3);
    }
}

Output

true true true

Example 2

import java.util.regex.*;

class RegexExample2 {
    public static void main(String args[]) {
        System.out.println(Pattern.matches(".s", "as"));   // true (2nd char is s)
        System.out.println(Pattern.matches(".s", "mk"));   // false (2nd char is not s)
        System.out.println(Pattern.matches(".s", "mst"));  // false (has more than 2 char)
        System.out.println(Pattern.matches(".s", "amms")); // false (has more than 2 char)
        System.out.println(Pattern.matches("..s", "mas")); // true (3rd char is s)
    }
}

Regex Character Classes

No. Character Class Description
1 [abc] a, b, or c (simple class)
2 [^abc] Any character except a, b, or c (negation)
3 [a-zA-Z] a through z or A through Z, inclusive (range)
4 [a-d[m-p]] a through d, or m through p: [a-dm-p] (union)
5 [a-z&&[def]] d, e, or f (intersection)
6 [a-z&&[^bc]] a through z, except for b and c: [ad-z] (subtraction)
7 [a-z&&[^m-p]] a through z, and not m through p: [a-lq-z] (subtraction)

Regex Character Classes Example

import java.util.regex.*;

class RegexExample3 {
    public static void main(String args[]) {
        System.out.println(Pattern.matches("[amn]", "abcd"));   // false (not a or m or n)
        System.out.println(Pattern.matches("[amn]", "a"));      // true (among a or m or n)
        System.out.println(Pattern.matches("[amn]", "ammmna")); // false (m and a comes more than once)
    }
}

Validating Input

import java.util.Scanner;

class ValidateInput {
    // validate first name
    public static boolean validateFirstName(String firstName) {
        return firstName.matches("[A-Z][a-zA-Z]*");
    }

    // validate last name
    public static boolean validateLastName(String lastName) {
        return lastName.matches("[a-zA-Z]+(-[a-zA-Z]+)*");
    }

    // validate address
    public static boolean validateAddress(String address) {
        return address.matches("\\d+\\s+([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");
    }

    // validate city
    public static boolean validateCity(String city) {
        return city.matches("([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");
    }

    // validate state
    public static boolean validateState(String state) {
        return state.matches("([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");
    }

    // validate zip
    public static boolean validateZip(String zip) {
        return zip.matches("\\d{5}");
    }

    // validate phone
    public static boolean validatePhone(String phone) {
        return phone.matches("[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}");
    }
} // end class ValidateInput

public class Validate {
    public static void main(String[] args) {
        // get user input
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter first name:");
        String firstName = scanner.nextLine();
        System.out.println("Please enter last name:");
        String lastName = scanner.nextLine();
        System.out.println("Please enter address:");
        String address = scanner.nextLine();
        System.out.println("Please enter city:");
        String city = scanner.nextLine();
        System.out.println("Please enter state:");
        String state = scanner.nextLine();
        System.out.println("Please enter zip:");
        String zip = scanner.nextLine();
        System.out.println("Please enter phone:");
        String phone = scanner.nextLine();

        // validate user input and display error message
        System.out.println("\nValidate Result:");

        if (!ValidateInput.validateFirstName(firstName))
            System.out.println("Invalid first name");
        else if (!ValidateInput.validateLastName(lastName))
            System.out.println("Invalid last name");
        else if (!ValidateInput.validateAddress(address))
            System.out.println("Invalid address");
        else if (!ValidateInput.validateCity(city))
            System.out.println("Invalid city");
        else if (!ValidateInput.validateState(state))
            System.out.println("Invalid state");
        else if (!ValidateInput.validateZip(zip))
            System.out.println("Invalid zip code");
        else if (!ValidateInput.validatePhone(phone))
            System.out.println("Invalid phone number");
        else
            System.out.println("Valid input. Thank you.");
    }
} // end class Validate

Validate — Sample Outputs

Output 1 Output 2
Please enter first name:
Jane
Please enter first name:
Jane
Please enter last name:
Doe
Please enter last name:
Doe
Please enter address:
123 Some Street
Please enter address:
123 Some Street
Please enter city:
Some City
Please enter city:
Some City
Please enter state:
SS
Please enter state:
SS
Please enter zip:
123
Please enter zip:
12345
Please enter phone:
123-456-7890
Please enter phone:
123-456-7890
Validate Result:
Invalid zip code
Validate Result:
Valid input. Thank you.

Regex Quantifiers

Quantifiers specify the number of occurrence of a character.

Regex Description
X? X occurs once or not at all
X+ X occurs once or more times
X* X occurs zero or more times
X{n} X occurs n times only
X{n,} X occurs n or more times
X{y,z} X occurs at least y times but less than z times
import java.util.regex.Pattern;

public class RegexQuantifierExample {
    public static void main(String[] args) {
        System.out.println(Pattern.matches("[a-c]?", "d")); // false
        System.out.println(Pattern.matches("[a-c]?", "a")); // true
        System.out.println(Pattern.matches("A+", "AAA"));    // true
        System.out.println(Pattern.matches("A*", ""));        // true
    }
}

Quantifier Example — {6}

import java.util.regex.*;

class RegexExample6 {
    public static void main(String args[]) {
        System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "arun32"));    // true
        System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "kkvarun32")); // false (more than 6 char)
        System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "JA2Uk2"));    // true
        System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "arun$2"));    // false ($ is not matched)
    }
}
Review Questions

Practice — Section 4: Regular Expressions

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

What is the output of the following code snippet?

System.out.println(java.util.regex.Pattern.matches(".s", "as"));
Answer

A. true

The pattern .s means any one character followed by s, so as matches it.

Source:Final Exam IT-232

What is the output of the following java statement?

System.out.println(java.util.regex.Pattern.matches("..x*","max"));
Answer

B. true

In the regex, .. matches the first two characters m and a, and x* matches the final x. So max matches.

Source:IT232 Final T1 2021-2022

What is the output of this statement?

System.out.println(java.util.regex.Pattern.matches(".s", "books"));
Answer

A. false

The pattern .s matches exactly two characters, but books has five characters.

Source:IT232 Final T1 2021-2022

What is the output of this statement?

System.out.println(java.util.regex.Pattern.matches("[a-zA-Z0-9]{6}", "EX#123"));
Answer

A. false

The # character is not allowed by [a-zA-Z0-9], so the match is false.

Source:IT232 Final T2 2021-2022

What is the output of the following java statement?System.out.println(Pattern.matches(".v","av"));

Answer

D. true

In the pattern .v, the dot matches any one character and v matches v. So av matches.

Source:Java Final (New)

What is the output of the following statement?

System.out.println(java.util.regex.Pattern.matches(".d", "ad"));
Answer

B. true

The pattern .d means any one character followed by d. The string ad matches that pattern.

Source:Java Final (New)

What is the output of the following statement?

System.out.println(java.util.regex.Pattern.matches("..l", "CCI"));
Answer

B. false

..l requires two characters followed by lowercase l. CCI ends with uppercase I, so it does not match.

Source:Java Final (New)

What is the output of the following java statement?

System.out.println(java.util.regex.Pattern.matches(".*x", "max"));
Answer

C. true

.*x means any characters followed by x. The string max ends with x, so it matches.

Source:Java Final v3

What is the output of the following code snippet?

System.out.println(java.util.regex.Pattern.matches(".s",".as"));
Answer

D. false

The pattern .s matches exactly two characters ending with s. The string .as has three characters, so it does not match.

Module 13 — Recursion

1. Recursion Concepts

  • Recursive method: calls itself (directly or indirectly) through another method
  • Method knows how to solve only a base case
  • Method divides problem
  • Base case → Simpler problem
  • Method now divides simpler problem until solvable

A recursive method has two parts:

  1. Base case
  2. Recursive call (recursive step)

Direct Recursion — a method calls itself:

public double A() {
    A();
}

Indirect Recursion — method A calls B, and B calls A:

public double A() {
    B();
}

public double B() {
    A();
}
Review Questions

Practice — Section 1: Recursion Concepts

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

In Java, a method that calls itself (directly or indirectly) through another method is known as ________.

Answer

A. A recursive method

A recursive method is a method that calls itself, either directly or through another method.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

When a recursive method is called to solve a problem, it actually knows how to solve only the ________.

Answer

C. base case(s)

The base case is the simple case the recursive method can answer directly. The other cases keep calling the method with a smaller problem.

Source:IT232 Final T1 2021-2022

A ____________ is needed to terminate recursion.

Answer

D. base case

A base case gives recursion a stopping point. Without it, the method would keep calling itself.

Source:IT232 Final T1 2021-2022

What is the base case in recursion?

Answer

A. The simplest case that the method solves directly.

A base case stops recursion because it can be answered without another recursive call.

Source:IT232 Final T1 2021-2022

Which statement about recursion and memory is correct?

Answer

A. Recursion can use extra memory because each call adds a new stack frame.

Each recursive call stays on the call stack until it returns, so memory use can grow.

Source:IT232 Final T2 2021-2022

Which of the following problems can't be solved using recursion?

Answer

D. Problems without base case

Recursion needs a base case to stop. Without a base case, the calls keep going until the program runs out of stack space.

Source:IT232 Final T2 2021-2022

What is the output of the execution of the following code?

public class Test {
    public static int my_recursive_method(int n)
    {
        if (n <= 0)
            return 1;
        else
            return n + my_recursive_method (n - 1);
    }
    public static void main(String[] args)
    {
        System.out.print(my_recursive_method (3));
    }
}
Answer

D. 7

my_recursive_method(3) returns 3 + my_recursive_method(2), then 2 + my_recursive_method(1), then 1 + my_recursive_method(0). The base case returns 1, so the total is 3 + 2 + 1 + 1 = 7.

Source:IT232 Final T2 2021-2022

In case of a recursion solution of a problem, a ______ is needed to terminate the recursion.

Answer

A. base case

A base case stops recursion by giving the method a case it can answer without calling itself again.

Source:IT232 Final T2 2021-2022

A recursive method is defined as a method that ______

Answer

C. call itself

A recursive method calls itself to solve a smaller version of the same problem.

Source:Java Final (New)

What is the base case in a recursive method?

Answer

C. The condition that stops the recursion

The base case is the condition that returns an answer without making another recursive call.

Source:Java Final (New)

A recursive method is terminated only if it has a ________.

Answer

D. base case

A base case stops recursive calls. Without one, recursion keeps going.

Source:Java Final (New)

A method that calls itself either directly or indirectly is called ________.

Answer

D. Recursive method

A recursive method is a method that calls itself.

Source:Java Final (New)

What is the output of the execution of the following code?

public class Test{
    public static int recursive_method(int n)
    {
        if(n <=0)
            return 1;
        else
            return n + recursive_method(n-1);
    }

    public static void main(String [] args)
    {
        System.out.print(recursive_method (2));
    }
}
Answer

D. 4

recursive_method(2) returns 2 + recursive_method(1). Then recursive_method(1) returns 1 + recursive_method(0), and the base case returns 1, so the total is 4.

Source:Java Final v3

In java, a method that call itself (directly or indirectly) through another method is known as ____________

Answer

A. Recursive method

A recursive method is a method that calls itself, either directly or through another method.

Source:Java Final v3

What is the output of the following code snippet?

public class Final {
    Final f = new Final();
    public static int my_recursive_method(int n) {
        if (n <= 0)
            return 1;
        else
            return n + my_recursive_method(n-1);
    }
    public static void main(String[] args) {
        System.out.println(my_recursive_method(1));
    }
}
Answer

B. 2

my_recursive_method(1) returns 1 + my_recursive_method(0). The base case returns 1, so the result is 2.

Source:Java Final v3

When a recursive method is called to solve a problem, it's actually capable of solving only ____________

Answer

C. Base case

A recursive method directly solves the base case. Other cases are reduced until they reach that base case.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

What is the output of the following Java program?

public class Final {
    public static int my_recursive_method(int n) {
        if (n <= 0)
            return 1;
        else
            return n + my_recursive_method(n - 1);
    }
    public static void main(String[] args) {
        System.out.print(my_recursive_method(1));
    }
}
Answer

Output: 2

(my_recursive_method(1) = 1 + my_recursive_method(0) = 1 + 1 = 2.)

2. Using Recursion: Factorials

  • The factorial of a positive integer n, written n!, is n·(n-1)·(n-2)·...·1

Sequence of recursive calls

  • 5! = 5 * 4!
  • 4! = 4 * 3!
  • 3! = 3 * 2!
  • 2! = 2 * 1!
  • 1! returns 1 (base case)

Values returned from each recursive call

  • 1! = 1 (base case)
  • 2! = 2 * 1 = 2 is returned
  • 3! = 3 * 2 = 6 is returned
  • 4! = 4 * 6 = 24 is returned
  • 5! = 5 * 24 = 120 is returned (Final value = 120)

Factorial 3 Example

  • factorial(3)
  • return 3 * factorial(2)
  • 2 * factorial(1)
  • 1 (base case)
// Fig. 18.3: FactorialCalculator.java
// Recursive factorial method.

public class FactorialCalculator {
    // recursive method factorial (assumes its parameter is >=0)
    public static long factorial(long number) {
        if (number <= 1) // test for base case
            return 1; // base cases: 0!=1 and 1!=1
        else // recursion step
            return number * factorial(number - 1);
    }

    public static void main(String[] args) {
        // calculate the factorials of 3
        System.out.printf("%d! = %d%n", 3, factorial(3));
    }
} // end class FactorialCalculator
Output: 3! = 6

Factorials from 0 to 21

// Fig. 18.3: FactorialCalculator.java
// Recursive factorial method.

public class FactorialCalculator {
    // recursive method factorial (assumes its parameter is >=0)
    public static long factorial(long number) {
        if (number <= 1) // test for base case
            return 1; // base cases: 0!=1 and 1!=1
        else // recursion step
            return number * factorial(number - 1);
    }

    // output factorials for values 0-21
    public static void main(String[] args) {
        // calculate the factorials of 0 through 21
        for (int counter = 0; counter <= 21; counter++)
            System.out.printf("%d! = %d%n", counter, factorial(counter));
    }
} // end class FactorialCalculator
Output:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
Review Questions

Practice — Section 2: Using Recursion: Factorials

Source:Final Exam IT-232

What does calling factorial(3) recursively produce when the base case<=1?

Answer

D. 321=6

factorial(3) multiplies 3 * 2 * 1. The base case stops before multiplying by 0.

Source:IT232 Final T1 2021-2022

Write a complete java program that perform the following tasks:- Asks the user to input a positive number. If the user enters a negative number, then the program keeps asking for a positive one. - Find out and print the factorial of the given number. Note: factorial of 5 is equal to: 5*4*3*2*1 = 120

Answer
import java.util.Scanner;
public class Factorial {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n;
        do {
            System.out.print("Enter positive number: ");
            n = sc.nextInt();
        } while (n < 0);
        long fact = 1;
        for (int i = 1; i <= n; i++) fact *= i;
        System.out.println(n + "! = " + fact);
    }
}

3. Using Recursion: Fibonacci Series

  • The Fibonacci series, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...
  • It has the property that each subsequent Fibonacci number is the sum of the previous two.
  • The Fibonacci series may be defined recursively as follows:
  • fibonacci(0) = 0
  • fibonacci(1) = 1
  • fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)

Example

// Fig. 18.5: FibonacciCalculator.java
// Recursive fibonacci method.
import java.math.BigInteger;

public class FibonacciCalculator {
    private static BigInteger TWO = BigInteger.valueOf(2);

    // recursive declaration of method fibonacci
    public static BigInteger fibonacci(BigInteger number) {
        if (number.equals(BigInteger.ZERO) || number.equals(BigInteger.ONE)) // base cases
            return number;
        else // recursion step
            return fibonacci(number.subtract(BigInteger.ONE)).add(fibonacci(number.subtract(TWO)));
    }

    // displays the fibonacci values from 0-40
    public static void main(String[] args) {
        for (int counter = 0; counter <= 40; counter++)
            System.out.printf("Fibonacci of %d is: %d%n", counter, fibonacci(BigInteger.valueOf(counter)));
    }
} // end class FibonacciCalculator
Output:
Fibonacci of 0 is: 0
Fibonacci of 1 is: 1
Fibonacci of 2 is: 1
Fibonacci of 3 is: 2
...
Fibonacci of 39 is: 63245986
Fibonacci of 40 is: 102334155

Recursive calls for fibonacci(3):

  • fibonacci(3) calls return fibonacci(2) + fibonacci(1)
  • fibonacci(2) calls return fibonacci(1) + fibonacci(0)
Review Questions

Practice — Section 3: Using Recursion: Fibonacci Series

Source:Java Final (New)

The function fib in the following code represents:

public static long fib(long n) {
    if ((n == 0) || (n == 1))
        return n;
    else
        return fib(n - 1) + fib(n - 2);
}
Answer

C. Recursive method

fib calls itself with fib(n - 1) and fib(n - 2), so it is recursive.

Source:Java Final v3

The ______________ series has the characteristic that every succeeding number is the sum of the two before it.

Answer

D. Fibonacci

In the Fibonacci series, each number is made by adding the two previous numbers.

Source:⁨21⁩ فبراير ⁨2023⁩ ⁩ فاينل جافاIT232

The Fibonacci series has the property that every term (after the first two) is the sum of the two preceding terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

Write a recursive Java method fib(int n) that returns the n-th Fibonacci number (taking fib(0) = 0 and fib(1) = 1).

Answer
public static int fib(int n) {
    if (n <= 1) return n;           // base cases: fib(0)=0, fib(1)=1
    return fib(n - 1) + fib(n - 2); // recursive case
}

4. Recursion vs. Iteration

Iteration

  • Uses repetition structures (for, while or do...while)
  • Repetition through explicitly use of repetition structure
  • Terminates when loop-continuation condition fails
  • Controls repetition by using a counter
long result = 1;
for (long i = number; i >= 1; i--)
    result *= i;

Recursion

  • Uses selection structures (if, if...else or switch)
  • Repetition through repeated method calls
  • Terminates when base case is satisfied
  • Controls repetition by dividing problem into simpler one
  • More overhead than iteration
  • More memory intensive than iteration
  • Can also be solved iteratively
  • Often can be implemented with only a few lines of code
public static long factorial(long number) {
    if (number <= 1) return 1; // test for base case
    else return number * factorial(number - 1); // recursion step
}

Example: calculating Factorial using iteration

// Fig. 18.9: FactorialCalculator.java
// Iterative factorial method.

public class FactorialCalculator {
    // iterative declaration of method factorial
    public static long factorial(long number) {
        long result = 1;
        for (long i = number; i >= 1; i--)
            result *= i;
        return result;
    }

    // output factorials for values 0-10
    public static void main(String[] args) {
        // calculate the factorials of 0 through 10
        for (int counter = 0; counter <= 10; counter++)
            System.out.printf("%d! = %d%n", counter, factorial(counter));
    }
} // end class FactorialCalculator
Review Questions

Practice — Section 4: Recursion vs. Iteration

Source:Final Exam IT-232

What is a key difference between recursion and iteration?

Answer

C. Recursion uses repeated method calls while iteration uses loops

Recursion repeats by calling the same method again. Iteration repeats by using loop statements like for or while.

Source:Java Final v3

Recursion Controls repetition by ___________

Answer

C. dividing problem into simpler one

Recursion works by reducing the problem to a smaller version of itself, then solving that. The base case stops the breakdown.

5. Towers of Hanoi

  • Object: move all the disks over to Tower 3.
  • You cannot place a larger disk onto a smaller disk.
  • Minimum Moves for 5 disks: 31

Useful Links: