Illuminatiiiiii
12/31/2018 - 5:04 AM

Creating String Objects

Java Library 1:

class Cow{
    int milk;
    int utters;

    Cow(int milk, int utters){
        this.milk = milk;
        this.utters = utters;
    }

    //custom toString because the default one for strings is poop
    public String toString(){
        return "(MOO) Milk: " + milk + " Utters: " + utters;
    }
}
public class Main {

    public static void main(String[] args) {

        String bob = "bob";
        bob = "jerry"; //bob is not actually changed. Strings are immutable, meaning they can not be changed. The object is just re-created.

        String string1 = "abcd";
        String string2 = "abcd"; //Points to the same object, because they are both initialized with the same object stored in memory
        // https://www.programcreek.com/wp-content/uploads/2013/07/java-string-pool.jpeg

        //Making Strings
        String empty = new String(); //Empty string
        //Creating a string with a char array. Strings in their literal sense contain an array of characters
        char[] letters = {'d', 'i', 'e'};
        String charsString = new String(letters);
        System.out.println(charsString);

        //You can initialize a string with some extra parameters[called a subrange]
        String anotherString = new String(letters, 1, 2); //Starts at the 1 index and goes for 2 characters.
        System.out.println(anotherString);

        //You can also use byte arrays to make a String
        byte ascii[] = {65, 67, 68, 69, 70, 71};
        String s1 = new String(ascii);
        String s2 = new String(ascii, 1, 4); //You can use the subrange here too
        System.out.println(s1);
        System.out.println(s2);

        //Finally, to create a String object, you can use another String object,
        //a StringBuffer object, or a StringBuilder object.

        //Finally, you can also make a String literal, which is something you have been doing
        String rapper = "Juice WRLD"; //Automatically makes a String object. Effectively, it IS one.
        System.out.println(rapper.length());

        //Strings are also automatically made in other cases
        String age = "10";
        String sentence = "Bob is " + age + " years old"; //This is called concatenation. It automatically combines these strings to make a new String object.

        String weird = "twenty-two: " + 2 + 2;
        System.out.println(weird); //Other datatypes, when used in addition with Strings, will be converted to strings and concatenated
        String weird2 = "4: " + (2 + 2); //Since "operator precedence" forces the 2's to be added to each other force, they make4
        System.out.println(weird2);

        Cow cow = new Cow(2, 4141);
        System.out.println(cow); //All objects when printed will convert to its string form by calling upon toString();
    }
}