Programing Exam1 Notes

Java Exam 1 Review Topics
Variable Types
  • int: Represents integer data types without fractional components. Commonly used for counting or indexing.

  • double: Represents double-precision floating-point numbers. Useful for precise calculations requiring decimals.

  • long: Represents larger integers. Ideal when values exceed the range of int.

  • String: Represents a sequence of characters. Used for text manipulation.

  • char: Represents a single character. Used to store individual characters.

Declaring and Instantiating Variables
  • Declaration is the process of defining a variable type and name, e.g., int count;

  • Instantiation is allocating memory for the variable, e.g., count = 10;

  • Combined declaration and instantiation: int count = 10;

Casting Between Types
  • Casting: Converting data from one type to another.

  • Implicit casting (widening): Automatically done by Java, e.g., int to double.

  • Explicit casting (narrowing): Must be defined by the programmer, e.g., double to int, using (int) value;.

Scanner Class
  • Import Statement: import java.util.Scanner;

  • Creating Scanner Object:

    • Scanner input = new Scanner(System.in);

  • Common Methods:

    • input.next(): Reads the next token.

    • input.nextLine(): Reads the entire line of input.

    • input.nextDouble(): Reads a double value.

    • input.nextInt(): Reads an integer value.

  • Clearing the Buffer: To prevent input issues after reading numeric data, use input.nextLine(); after nextInt() or nextDouble().

Print Statements
  • print(): Outputs data without a newline.

  • println(): Outputs data followed by a newline.

  • printf(): Formats output based on format specifiers, such as %d for integers, %f for floats, etc.

Math & Math Class
  • Mathematical operations include:

    • Addition: +

    • Subtraction: -

    • Multiplication: *

    • Division: /

    • Integer Division: Returns the quotient without fractions, e.g., 5 / 2 = 2.

    • Modulus: %, gives the remainder of the division, e.g., 5 % 2 = 1.

    • Use parentheses to control operation precedence.

    • Math Methods:

    • Math.pow(base, exponent): Returns base raised to the power of exponent.

    • Math.sqrt(value): Returns the square root of the value.

    • Math.PI: Constant representing the value of π (approximately 3.14159).

  • Fractions: Can be dealt with using floating-point representation and controlled via double data type.

  • Compound assignment operators: +=, -=, *= allow for more concise math operation syntax.

Methods
  • Creating Methods:

    • Method Header: Format is [public/private] [static] [return_type] method_name(parameters);

  • Utilizing Java Methods: Integrate methods in class definitions to modularize code.

Objects & Classes
  • Driver Class: Contains the main method from which the program execution starts.

  • Main Method: Signature: public static void main(String[] args) { }.

Domain Class
  • Default Constructor: Provides a way to initialize objects without parameters.

  • Parameterized Constructor: Allows passing parameters to set properties upon creation of the object.

  • Getters: Methods to retrieve property values from objects.

  • Setters: Methods to update property values in objects.

  • toString(): Overrides the default toString() method to provide a string representation of the object.

  • String Methods:

    • substring(beginIndex, endIndex): Retrieves a portion of the string.

    • charAt(index): Returns the character at the specified index.

    • indexOf(char): Finds the first occurrence of a specified character.

    • toUpperCase(): Converts all characters to uppercase.

    • toLowerCase(): Converts all characters to lowercase.

Example Questions
  1. Difference Between scnr.nextLine() and scnr.next():

    • scnr.next(): Reads input until whitespace is reached. For example, input "Hello Bye-bye" will give "Hello".

    • scnr.nextLine(): Reads the entire line of input. The same input will return "Hello Bye-bye".

  2. Using Math Methods:

    • Example for Math.sqrt(), Math.pow(), and Math.PI:

    double squareRoot = Math.sqrt(16); // 4.0
    double power = Math.pow(2, 3); // 8.0
    double pi = Math.PI; // Approximately 3.14159
    
  3. Calculation of Answer with Given Variables:

    • Given:

    int num1 = 3;
    int num2 = 2;
    int num3 = 8;
    int num4 = 5;
    int answer = num1 + num3 / num2 * num4;
    
    • Calculate following the order of operations:

      • num3 / num2 = 8 / 2 = 4

      • 4 * num4 = 4 * 5 = 20

      • answer = num1 + 20 = 3 + 20 = 23.

  4. Cylinder Volume and Area:

    • Formulas are:

      • Volume: V=πr2hV = \text{π}r^2h

      • Area: A=2πrh+2πr2A = 2\text{π}rh + 2\text{π}r^2

    • Java Class Declaration:

    public class VolumeAndArea {
       // Methods for volume and area calculations go here
    }
    
  5. Substring Extraction:

    • Code to return substring from after the first occurrence of 'a':

    String str = "example string";
    int index = str.indexOf('a');
    String substring = str.substring(index + 1);
    
  6. String Variable Operations:

    • Declaration: String miamiFlorida = "South Beaches";

    • Print the second to last character:

    System.out.println(miamiFlorida.charAt(miamiFlorida.length() - 2));
    
    • Print the position of the second occurrence of 'e':

    int firstIndex = miamiFlorida.indexOf('e');
    int secondIndex = miamiFlorida.indexOf('e', firstIndex + 1);
    System.out.println(secondIndex);
    
    • Print initials:

    String[] words = miamiFlorida.split(" ");
    String initials = "";
    for (String word : words) {
      initials += word.charAt(0);
    }
    System.out.println(initials);
    
  7. Exponential Value Method:

    • Method Creation:

    public static double exponentialValue(double base, double exponent) {
       return Math.pow(base, exponent);
    }
    
  8. Shoes Domain Class:

    • Class Properties: Brand, Year Released, Color.

    • In Driver Class, gather user input to create an instance:

      java Shoes myShoe = new Shoes(brand, yearReleased, color); System.out.println(myShoe.toString());

    • Manipulate the domain class to display all details.

      • Example of toString() in the Shoes class returns formatted details of the shoe.

  9. User Input, Data Types, and Casting Example:

    • Practical scenario to get user input, perform a calculation, and demonstrate casting:

    import java.util.Scanner;
    
    public class PriceCalculator {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
        System.out.print("Enter item price (e.g., 25.99): ");
        double price = scanner.nextDouble(); // Reads a double
    
        System.out.print("Enter quantity: ");
        int quantity = scanner.nextInt(); // Reads an integer
        scanner.nextLine(); // Clear the buffer after reading int
    
        double totalCost = price * quantity;
        System.out.printf("Total cost: $%.2f%n", totalCost);
    
        // Explicit casting example: Calculate approximate integer cost
        int approximateCost = (int) totalCost; // Casts double to int, truncating decimals
        System.out.println("Approximate cost (integer part): $" + approximateCost);
    
        scanner.close();
    }
    

    }

  10. String & Character Manipulation with Method:

    • Method to reverse a string and its usage:

    import java.util.Scanner;
    
    public class StringUtility {
    // Method to reverse a given string
    public static String reverseString(String original) {
        String reversed = "";
        for (int i = original.length() - 1; i >= 0; i--) {
            reversed += original.charAt(i);
        }
        return reversed;
    }
    
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a word or phrase to reverse: ");
        String userString = input.nextLine();
    
        String reversedResult = reverseString(userString);
        System.out.println("Original: " + userString);
        System.out.println("Reversed: " + reversedResult);
    
        input.close();
    }
    

    }