Data Types w/ Primitives Code

double a = 10/4;
double b = 10/4.0;
System.out.println(a+b);
4.5
String word ="pizza";  
int p = word.indexOf("zz");
word.substring(p+2);
p = word.indexOf("zz");

System.out.println(p);
2
Sample s = new Sample();
String x = new String('h');
s.writeMe(x);
|   Sample s = new Sample();
cannot find symbol
  symbol:   class Sample

|   Sample s = new Sample();
cannot find symbol
  symbol:   class Sample
//create a java program to find the first
//non-repeating character in a string
//example: "alligator"
//output: i

import java.util.*;

// Define the Main class, main method
public class Main {
  public static void main(String[] args) {
    
    // Declare and initialize the string variable "str" with the value "alligator"
    String str = "alligator";
    
    System.out.println("The string is: " + str);
    
    // Iterate through each character in the string using a for loop
    for (int i = 0; i < str.length(); i++) {
      
      // Declare and initialize a boolean variable "unique" with the value true
      boolean unique = true;
      
      // Iterate through each character in the string again using another for loop
      for (int j = 0; j < str.length(); j++) {
        
        // Check if the current character in the outer loop is the same as the current character in the inner loop
        // and if the indices of the characters are different
        if (i != j && str.charAt(i) == str.charAt(j)) {
          
          // If the characters are the same and their indices are different, set "unique" to false and break out of the loop
          unique = false;
          break;
        }
      }
      
      // If "unique" is still true after iterating through the inner loop, print the first non-repeating character and break out of the outer loop
      if (unique) {
        System.out.println("The 1st non-repeating is: " + str.charAt(i));
        break;
      }
    }
  }
}

Main.main(null);
The string is: alligator
The 1st non-repeating is: i

The first code segment is a standalone Java program that uses nested for loops to iterate through each character in the input string and compare it to all other characters to check if it is unique. If a unique character is found, it is printed as the first non-repeating character and the program exits. This code segment does not use any classes or objects and is a simple implementation of the algorithm.

Wrapper Classes + Arrays Conversion

public class NonRepeatingCharacterFinder {
    private String str; // instance variable to store the input string
    
    public NonRepeatingCharacterFinder(String str) {
        this.str = str; // constructor -- initializes instance variable with the input string
    }
    
    public char findFirstNonRepeating() {
        int[] charCount = new int[256]; // integer array of size 256 to store the frequency of each character in the string
        for (int i = 0; i < str.length(); i++) {
            charCount[str.charAt(i)]++; // increment the count of the character at the i-th position in the string
        }
        for (int i = 0; i < str.length(); i++) {
            if (charCount[str.charAt(i)] == 1) { // check if the count of the character at the i-th position in the string is equal to 1
                return str.charAt(i); // return the first non-repeating character found
            }
        }
        return '\0'; // return null character if no non-repeating character is found
    }
    
    public static void main(String[] args) {
        String str = "alligator"; // example input string
        NonRepeatingCharacterFinder finder = new NonRepeatingCharacterFinder(str); // create an instance of the NonRepeatingCharacterFinder class with the input string
        char result = finder.findFirstNonRepeating(); // call the findFirstNonRepeating method to get the first non-repeating character
        System.out.println("The string is: " + str);
        if (result == '\0') { // check if no non-repeating character is found
            System.out.println("There is no non-repeating character in the string.");
        } else {
            System.out.println("The 1st non-repeating character is: " + result); // print the first non-repeating character found
        }
    }
}
NonRepeatingCharacterFinder.main(null);
The string is: alligator
The 1st non-repeating character is: i

The second code segment is a Java class contains a constructor and a method to find the first non-repeating character in a given string. The constructor takes an input string and initializes an instance variable with it. The findFirstNonRepeating method uses an integer array to keep track of the frequency of each character in the input string, and then iterates through the input string again to find the first character with a frequency of 1. The method returns this character as the first non-repeating character, or a null character if no non-repeating character is found. The main method creates an instance of the NonRepeatingCharacterFinder class with an example input string, calls the findFirstNonRepeating method, and prints the result. This code segment is more object-oriented and reusable than the first code segment.

Summary from ChatGPT

  • Here is a brief overview of the relationship between primitives, wrapper classes, and arrays in Java:

Primitives:

byte: 8-bit integer short: 16-bit integer int: 32-bit integer long: 64-bit integer float: 32-bit floating point double: 64-bit floating point char: 16-bit Unicode character boolean: true or false value

Wrapper classes:

Byte: wraps byte Short: wraps short Integer: wraps int Long: wraps long Float: wraps float Double: wraps double Character: wraps char Boolean: wraps boolean Wrapper classes provide useful methods for working with primitives. For example, you can convert a string to an int using the Integer.parseInt() method.

Arrays:

Arrays can be declared for primitives or objects. For example: int[] numbers = new int[10]; creates an array of 10 int values. Integer[] numbers = new Integer[10]; creates an array of 10 Integer objects. Arrays can be used to store multiple values of the same type, and provide useful methods for working with collections of values.

Key Differences: Primitives w/ Wrapper Classes and Primitives w/o Wrapper Classes:

  • Primitives without wrapper classes are basic data types and are not objects. Wrapper classes, on the other hand, are objects and allow you to perform object-oriented operations on primitives.

  • Primitives without wrapper classes are typically more efficient in terms of memory and performance than their wrapper class counterparts. This is because wrapper classes introduce additional overhead due to their object-oriented nature.

  • Wrapper classes provide additional functionality that primitives without wrapper classes do not. For example, wrapper classes have methods that allow you to convert between primitive types, perform arithmetic operations, and more.

  • Wrapper classes are required in situations where an object is expected, such as when working with collections or generics. Primitives without wrapper classes cannot be used in these situations.

FRQ 2014 Question

A & B

public class ScrambleWord {

    public static String scramble(String word) {
        int curChar = 0;
        String result = "";

        // iterates through the word as long as the current character index is less than the final index in the word (keeps last letter open for potential pairs, so doesn't check the last letter until it breaks out of the loop)
        while (curChar < word.length() - 1) {
            // if both letters are A, add one as is and don't scramble
            if (word.substring(curChar, curChar + 1).equals("a") && word.substring(curChar + 1, curChar + 2).equals("a")) {
                result += word.substring(curChar, curChar + 1);
                curChar++; // increment the character index by 1 because no scrambling is necessary
            } else {
                // if the condition in the if statement is false, scramble and add
                result += "a"; // add the letter A to the result
                result += word.substring(curChar + 1, curChar + 2); // add the second letter to the result
                curChar += 2; // increment the character index by 2 to allow for swap of A and following letter
            }
        }

        // check whether curChar is less than the total length of the string, regardless of whether there are more characters in the string that can form a pair with the current character
        if (curChar < word.length()) {
            result += word.substring(curChar);
        }

        return result; // return the scrambled word
    }

}
public class Main {
    public static void main(String[] args) {
        String word1 = "apple";
        System.out.println(ScrambleWord.scramble(word1)); 
    }
}
Main.main(null);
apale
public class ScrambleWord {
    public static String scramble(String word) {
        int curChar = 0;
        String result = "";
        // iterates through the word as long as the current character index is less than the final index in the word (keeps last letter open for potential pairs, so doesn't check the last letter until it breaks out of the loop)
        while (curChar < word.length() - 1) {
            // if both letters are A, add one as is and don't scramble
            if (word.substring(curChar, curChar + 1).equals("a") && word.substring(curChar + 1, curChar + 2).equals("a")) {
                result += word.substring(curChar, curChar + 1);
                curChar++; // increment the character index by 1 because no scrambling is necessary
            } else {
                // if the condition in the if statement is false, scramble and add
                result += "a"; // add the letter A to the result
                result += word.substring(curChar + 1, curChar + 2); // add the second letter to the result
                curChar += 2; // increment the character index by 2 to allow for swap of A and following letter
            }
        }
        // check whether curChar is less than the total length of the string, regardless of whether there are more characters in the string that can form a pair with the current character
        if (curChar < word.length()) {
            result += word.substring(curChar);
        }
        return result; // return the scrambled word
    }
    public static void scrambleOrRemove(List<String> wordList, int minWordLength){
    // Loop through each word in the wordList
    for (int i = 0; i < wordList.size(); i++){
        // Get the current word
        String word = wordList.get(i);
        // If the word is shorter than the minimum word length, skip it
        if (word.length() < minWordLength){
            continue;            
            // else {
            // wordList.remove(i);
        }
        // Scramble the word
        String scrambled = ScrambleWord.scramble(word);
        //String scrambled = scramble(word);
        // If the scrambled word is the same as the original word, remove the word from the list
        if (word.equals(scrambled)){
            wordList.remove(i);
            // Decrement the index to account for the removed element
            i--;
        } else {
            // Replace the original word with the scrambled word
            wordList.set(i, scrambled);
        }
    }
}
}
import java.util.ArrayList;
import java.util.List;
public class Main {
    public static void main(String[] args) {
        List<String> wordList = new ArrayList<String>();
        wordList.add("apple");
        wordList.add("hello");
        wordList.add("whoa");
        ScrambleWord.scrambleOrRemove(wordList, 5);
        System.out.println(wordList);
    }
}
Main.main(null);
[apale, aealo, whoa]