num / char

edited October 2014 in Programming Questions

What's the difference between;

text(num, x, y)
text(1,10,70); 

And:

text(c, x, y)
text(1,10,70); 

In other words, between char and num?

Also I didn't understand how to use;

text(chars, start, stop, x, y)

Answers

  • edited April 2014

    As you can see from its reference:
    http://Processing.org/reference/text_.html

    There are 9 overloaded versions of text()! Varying in both data-types and # of parameters.

    What they call num parameter: int, or float: the numeric value to be displayed.
    You can see from the explanation that it refers to types int & float. Which is any number type.

    Even though it says it accepts only those 2, the other primitive types work too, except boolean & double.
    While long it thinks it's float somehow though! :(|)

    In this particular primitive type: char, even though it's a number type too,
    it's purpose is to display Unicode characters (UTF-16) rather than its numerical values.

    And for the text(chars, start, stop, x, y) overloaded version, we got the chars parameter:
    char[]: the alphanumeric symbols to be displayed.

    Which is an array of primitive data-type char.
    Notice that the class String got a char[] field in order to store its characters!
    Basically we can specify the initial & end indices from a char[] to be displayed.

    forum.processing.org/two/discussion/4802/num-char
    
    size(300, 150, JAVA2D);
    clear();
    fill(#FFFF00);
    textSize(030);
    
    final char[] myChars = {
      'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', 'n', ' ', 
      'a', 'r', 'r', 'a', 'y', ' ', 'o', 'f', ' '
    };
    text(myChars, 0, myChars.length, 20, 50);
    
    char[] fromStr = "CRAZY characters!".toCharArray();
    text(fromStr, 6, fromStr.length, 20, 90);
    
  • edited April 2014

    1 - You don't need to create the array, before initialising it? What I mean by that is the following code:

    char[] myChars = new char[size];

    So I take it,

    char[] myChars = {
      'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', 'n', ' ', 
      'a', 'r', 'r', 'a', 'y', ' ', 'o', 'f', ' '
    }; 
    

    That CREATES and INITIALISES the array? And the SIZE is according to how many characters you include?

    It basically saves us from writing:

    char[] myChars = new char[20];
    
         myChars[0] = 'T';
        char[] myChars[1] = 'h';
        --- etc
    

    ?

    Also I didn't understand this line:

    char[] fromStr = "CRAZY characters!".toCharArray();

    That declares a reference variable, to an array of type char, named fromStr?

    And puts in it, "Crazy characters!"?

    What is .toCharArray()?

    And finally, basically String, is an array of chars? So creating an array of chars, is akin to creating a String? So each element of a String, is stored inside a variable of type char?

  • edited May 2014 Answer ✓

    "That CREATES and INITIALISES the array? And the SIZE is according to how many characters you include?"
    Good understanding...

    "That declares a reference variable, to an array of type char, named fromStr?"
    Yes. And it is filled with the characters from the given string; that's the task of toCharArray(), splitting the string into an array of chars.

    Last paragraph: yes, more or less. A String is made of chars, that's the idea. How the chars are stored internally by Java isn't really important. But you have methods to transform a string to a bunch of chars and the reverse.

    Note that char in Java is actually a 16-bit unsigned numerical type, holding the Unicode code point of the character.

  • edited May 2014

    And puts in it, "Crazy characters!"? What is .toCharArray()?

    The "" is actually a special Java instantiation for the String class called string literal! @-)
    http://docs.oracle.com/javase/tutorial/java/data/strings.html

    The keyword new is implicitly hidden. However, even though it doesn't seem so, the "" returns its reference! :)]
    That's why I was able to invoke 1 of the String methods just after the "":
    "CRAZY characters!".toCharArray();
    http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#toCharArray--

    B/c the "" actually behaves as a memory address reference for a String object!!! o->

  • edited May 2014 Answer ✓

    A String is made of chars, that's the idea. How the chars are stored internally by Java isn't really important.

    If you're curious, the String class has a field called value which holds the array of type char (UTF-16).
    Which in turn is responsible for the immutable sequence of characters: ;)
    private final char[] value

    You can inspect it for yourself by using these IDEs: :-bd
    http://Greenfoot.org or http://BlueJ.org

    Or directly issuing the command below:
    println(String.class.getDeclaredFields()[0]);

  • edited October 2014

    The following, which you wrote above:

    "private final char[] value"

    I thought this would be a non-static field, so the String objects can have their own copies of it? I don't understand why value is a static field as you put above?

    Thanks.

  • edited October 2014

    I don't understand why value is a static field as you put above?

    I said "is responsible for the immutable sequence of characters". I didn't say static, but immutable.
    It is immutable b/c the String class doesn't provide us with any methods which'd allow us to change its content.
    BtW, here's some characteristics for static fields:

    • Keyword static can also be interpreted as "shared by all objects of the class".
    • If a field is static, when a class is instantiated it doesn't get a copy of it.
    • It stays in the class, not in the objects created from it.
    • Another OOP term for them is "class variables". While non-static fields are called "instance variables".
    • Its effect is that if we modify its value, it's also reflected in all the objects of that class.
    • And since it's not instantiated, it saves memory. ;)
    • Notice that methods also stay in the class. No point for each object having their own copy of a method.
      Merely invoke the 1s defined in the original class! <):)
    • In short, only non-static fields actually go to an instantiated object.
    • Which in turn is simply a contiguous chunk of memory allocated dynamically at runtime.
  • edited October 2014

    Okay, let me get this right. I thank you for your patience:

    private final char[] value

    A STRING class, has as one it's members, a NON-STATIC FIELD/ INSTANCE VARIABLE/ OBJECT VARIABLE called char [] value?

    EVERY instance of class String, in other words, every object created/instantiated from the class String, gets a copy of char [] value?

    So lets for example, say:

     String str //Reference variable
    
    String str = new String ("Hello");
    

    So the reference variable, str, will hold the reference (1st physical memory address of the dynamically allocated object). It will point to the contiguous block of memory in other words. Now that object it's pointing to (of type String), will contain:

    NON-STATIC/Instance variables of the Class, so:

    char [] value

    So the object would contain a reference variable, called "value", of type char[], which holds the reference to an array object. An array of chars? The array object, array of chars, will hold the characters "Hello". So the array will have 5 slots?

    So it's a case of, the reference variable, str, pointing to the object of type String (holding it's reference, the 1st physical memory address), which in turns contains within it, a reference variable, value, that points to an object, of type array (array of chars)?

    Finally, because of FINAL (private final char[] value), the characters in the array of chars can not be changed? They are immutable, due to final.

    Is that all correct?

  • edited October 2014 Answer ✓

    I had thought, the reference variable, str, would point to an object, of type array.

    In order to point to an array, variable str would need to be declared this way: <type_chosen>[] str.
    However arrays aren't String, but can have slots which store references for String objects: String[].

    Even though it has special treatment within Java, String is a class like all the others!
    It got fields, methods & constructors!

    1 of those fields are called values, which is of type char[].
    That is, an array object w/ slots for primitive type char.

    As you have guessed already, that char[] object isn't stored inside a String object.
    Rather its reference is stored in the non-static field (or instance variable) values.
    That is so b/c each object in Java has its own contiguous chunk of memory within the heap region.

    When a String is instantiated, be it by new String() or by quotes "", all those non-static fields are cloned.
    Then, a char[] array is also instantiated and its reference assigned to values.

    Why can't str, point directly to the array of chars?

    B/c arrays don't have methods to deal w/ string-like operations like charAt(), indexOf(), substring(), toLowerCase() and many others:

    It's the responsibility of a String object to provide all of those features for us!
    Arrays only got its final non-static field length, and slots of the same datatype!

  • edited October 2014 Answer ✓

    They are "immutable", due to final.

    Nope! Only thing final does is disallow field values to be re-assigned to another char[] array object:
    http://processing.org/reference/final.html

    Arrays slots by themselves can be freely reassigned! Keyword final can't do anything about that to any object! :P

    What makes a String immutable is the fact it locks us out from its fields via the private access-level keyword:
    http://processing.org/reference/private.html

    Although that can be hacked by an advanced technique called "reflection". Unless Java is configured to disallow that!

  • edited October 2014

    So an array can be of 2 types?

    1) Array of primitive data type - i.e int [] a = new int[3] (array of ints). Each slot holding an int value.

    2) Array of object data type - i.e String[] a = new String[3] (array of Strings, each of the three slots in the array of type String, being a reference variable, holding the 1st physical memory address for a single String object)

    ?

    And do arrays have any methods?

    When a String is instantiated, be it by new String() or by quotes "", all those non-static fields are cloned.

    Isn't the only thing copied from the String class to their instances/objects, are non-static fields? And the only thing objects contain is the non-static fields/instance variables of their classes.

    So each object/instance of String class, they all contain the char [] value non-static field only? What other non-static fields does it have, in other words, that the object contains apart from the reference variable values?

    final stops the value in the reference variable, values, from being changed to anything once it's been initialized?

    Well if we didn't have privatelocking us out, and could access the String fields, so accessing the values reference variable... isn't because values field is set to final, that would make a String immutable even if private wasn't in place?

    I apologize for asking too many questions!

  • edited October 2014 Answer ✓

    So an array can be of 2 types?

    I'd say that arrays, like variables, can be of any 1 type, no matter whether it's primitive or reference.
    Their "slots" are their internal "variables" of the chosen datatype.

    And do arrays have any methods?

    Like all Java objects, they inherit from class Object: http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html

    Aren't the only things copied from the String class to their instances/objects, their non-static fields?

    Basically yes! Apart from some 12 bytes of internal data, objects contain non-static fields only.
    When some object needs to access methods & static fields, it requests it from its original class!
    If we use the inspect feature from BlueJ or GreenFoot IDEs, we'll only find non-static fields to look at!

    Well, if we didn't have private locking us out, ...

    If String's values wasn't private, we'd be able to read & change the values of its char[] array!
    Like aforementioned, final only protects against a variable from being reassigned.

    That is, we couldn't do: values = new char[] {'H', 'a', 'c', 'k'};.
    However, we're free to read & change the array object itself: println(value[3] = '*');.

    In short, immutability depends more on private and careful restrict access via methods! :-B

  • I thank you for your patience, and thorough explanation.

    A class is also a contiguous block of memory, that is in memory at run-time of the program, so the object is able to access it's static-fields and methods? When we use the import statement in a Java program, does it basically lead to the class being loaded in memory, so the Java program can access it's static fields and static methods?

  • edited October 2014 Answer ✓

    A class is also a contiguous block of memory, ...

    Yes! But it's got everything defined in it: both static fields & methods & constructors.
    While objects keep the non-static fields and access the original class for the rest.

    ... , does it basically lead to the class being loaded in memory, ...

    No expert in class loading, but I believe it is as you said!

  • edited October 2014

    Is System.out and System.err reference variables, with println() a method that belongs to the objects referenced by them?

    I'm not totally sure what System.out.println() means. I tried to understand it based on your explanation of what objects/classes/reference variables are, but didn't manage.

  • edited October 2014

    Those in, out & err are all System's fields

    err & out are static fields of class System, as well as reference variables, of type Printstream? They point to objects of type Printstream?

    in is a static field of System, and reference variable, pointing to an object instantiated from the class InputStream?

    print &printlnare methods of the PrintStream & InputStream class?

    Is it correct to say System.out is a standard output stream, an object (instance of PrintStream), connected to the output display (i.e a Monitor), and println is the method that sends characters into System.out stream, and hence it (System.out.println("these characters") appears displayed on the monitor?

    That System.err is the same as above. Only difference being a standard error output stream.

    And that System.in is a standard input stream, an object (instance of InputStream) that is connected to the keyboard. So whatever is typed into the keyboard, the characters go into this System.in stream, and you can use a Scanner to scan those characters in the System.in?

  • edited October 2014 Answer ✓

    Are print() & println() methods of the PrintStream & InputStream classes?

    You can see that for yourself in the links I've pasted in my previous post!

    But PrintStream & InputStream have not been instantiated so how are there objects of their type?

    They're statically instantiated either when System class is loaded or then used for the 1st time in the app.
    Take a look at MyVector example below. Static field vec is assigned the reference of some newly created PVector object.
    Pay attention that even though MyVector wasn't itself instantiated, its field vec is nonetheless ready-to-use: o->

    // forum.processing.org/two/discussion/4802/num-char
    
    static final class MyVector {
      static final PVector vec = new PVector();
    }
    
    void setup() {
      MyVector.vec.set(PI, EPSILON, random(1000)); // vec is ready-to-use
      println(MyVector.vec);
      println();
    
      MyVector vecInstance = new MyVector();
      vecInstance.vec.set(1, 2, 3); // static vec still points to
      println(vecInstance.vec); // the same PVector object
      println(MyVector.vec); // even though it's from a MyVector instantiated object
    
      exit(); // that's b/c static fields are shared for all copies of the class!
    }
    

    That's the same case w/ System class. We can access its out static field w/o instantiating the class 1st!
    Actually, class System prohibits its instantiation. Static access only! (~~)

    P.S.: Since class MyVector doesn't have any non-static fields, its objects got nothing inside but those basic 12 bytes that every object got. :-@

  • edited October 2014

    Sorry, I didn't see your comment, as I have already edited my previous comment a number of hours ago, as I realized println() & print() are indeed methods of PrintStream &InputStream, as well as the fact when System class is loaded, PrintStream & InputStream are instantiated.

    But wait, I'm still not entirely sure, that just because System is loaded, how is that related to PrintStream & InputStream being instantiated without a newoperator?

    i.e System.out is a reference variable, holding an address of a PrintStream object. But I never created this PrintStream object to begin with. I didn't do PrintStream out = new PrintStream () or InputStream in = new InputStream(). So unsure why System.out, System.err, & System.in, all point to an object (that I didn't create).. ?

    "Actually, class System prohibits its instantiation. Static access only! "

    Because of final class System?

    What is "those basic 12 bytes that every object got".

    A few questions:

    • err & out are static fields of class System, as well as reference variables, of type Printstream? They point to objects of type Printstream?

    • in is a static field of System, and reference variable, pointing to an object instantiated from the class InputStream?

    • Is it correct to say System.out is a standard output stream, an object (instance of PrintStream), connected to the output display (i.e a Monitor), and println() is the method that sends characters into System.out stream, and hence it (System.out.println("these characters") ) appears displayed on the monitor?

    • ThatSystem.err is the same as above. Only difference being a standard error output stream.

    • And that System.in is a standard input stream, an object (instance of InputStream) that is connected to the keyboard. So whatever is typed into the keyboard, the characters go into this System.in stream, and you can use a Scanner to scan those characters in the System.in?

  • Answer ✓

    ""class System prohibits its instantiation." Because of final class System?"
    No. final prevents sub-typing, but not instantiation. To prevent instantiation of a class, you make all its constructors private.

    "just because System is loaded, how is that related to PrintStream & InputStream being instantiated without a newoperator?"
    It is the principle of static variables: they exists only once per class, and can be initialized in various ways by the class itself, on first instance creation (if instances can be created), or at declaration time (like static int i = 5;) or in static blocks in the class, etc. It is transparent for the consumer of the class..

    Your questions:

    1. Yes. All object declarations are references to instances of these instances.
    2. Yes.
    3. I am not too sure, but I believe out points to stdout, standard out of your system, and Processing intercepts this stdout to redirect this output to the console.
    4. Idem, with stderr.
    5. Idem, with stdin, although I don't think Processing redirects it. There is no terminal where you can type something and get it inside Processing.
  • edited October 2014 Answer ✓

    What is "those basic 12 bytes that every object got".

    It's the Java object header. Suffice it to say it occupies 12 bytes of memory inside an object.
    4 of those 12 bytes refer the original class memory address!

    According to site Java-Performance's article, each Processing's PVector object would use 32 bytes.
    https://github.com/processing/processing/blob/master/core/src/processing/core/PVector.java

    PVector class got 4 non-static fields (instance variables):

    1. float x; // 4 bytes (32-bit)
    2. float y; // 4 bytes (32-bit)
    3. float z; // 4 bytes (32-bit)
    4. float[] array; // 4 bytes (32-bit)

    Well, 12 bytes + 4*4 bytes = 28 bytes. But b/c it's gotta be aligned to a multiple of 8, it rises up to 32 bytes! 8-X
    But if Processing's devs got rid of that dumb useless array field, each PVector would drop to 24 bytes! *-:)

  • edited October 2014

    Regarding earlier discussion on Strings:

    String eg = "An immutable string";
    
      char a =  eg.charAt(0);
      char b = eg.charAt(1);
      char c = eg.charAt(5);
    
      System.out.println(eg.value[0]);
    

    Why won't the last statement print? value has private access, but I thought that I'm only prevented from changing the cells, but also from printing? Slightly confused, or maybe I haven't understood the private access modifier as it should be understood. My understanding of it, is you can't access and change anything marked private. But you can see what's inside and print. Or ?

  • edited October 2014

    Access level is both for reading & modifying members:
    http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

    B/c field value is private, only its class String can access it!
    As I've already tipped before, that can be "hacked" via "reflection" if Java security allows it so!

    • So only methods belonging to the class, can read or modify private fields?

      • String doesn't have a method that allows you to modify the values field (a "setter"), hence why they are immutable? So chartAt() method is considered a "getter"? Gets/reads data from, in this case, a private field, and as it's a method that belongs to the class String, and thus able to access the field, but only to read?
  • edited October 2014

    String doesn't have a method that allows you to modify the values field (a "setter"), hence why they are immutable?

    That's what I've been telling you all along. Just forgot to use its jargon term "setter": 8-X

    "It is immutable b/c the String class doesn't provide us with any methods which'd allow us to change its content."

    Anyways, here's charAt()'s source code: =:)
    http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/java/lang/String.java?av=f#656

    public char charAt(int index) {
      if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
      }
      return value[index];
    }
    
  • edited October 2014

    So charAt() is a getter. And String class has no setter to access & modify the chars. If it wasn't for the private access modifier, we wouldn't need a setter, but access it directly (a.value[1] = 'h').

    Ok, thanks, that makes sense!

  • edited October 2014

    I'm not sure, why in order to override a parents method, you must have the same method signature AND return type? Why the return type too?

  • Why the return type too?

    I wonder why as well! I guess b/c the caller gotta know the returning type in order to use it, it becomes part of signature somewhat. :-/

  • An overridden method can return a sub-type of the original return type.

  • Still haven't fully understood?

  • edited October 2014

    Here is a less abstract example:

    class Parent
    {
      int var;
      public String toString()
      {
        return "Parent{var=" + var + "}";
      }
    }
    class Child extends Parent
    {
      String name;
      public String toString()
      {
        return "Child{var=" + var + ", name=" + name + "}";
      }
    }
    
    class Main
    {
      Parent p; 
      Main()
      {
        p = new Parent();
        p.var = 42;
      }
      Parent getObject()
      {
        return p;
      }
      public String toString()
      {
        return "Main{" + p + "}";
      }
    }
    class SubMain extends Main
    {
      SubMain()
      {
        p = new Child();
        p.var = 12;
        ((Child) p).name = "Baby";
      }
      @ Override
      Child getObject()
      {
        return (Child) p;
      }
    }
    
    void setup()
    {
      SubMain sm = new SubMain();
      println(sm);
      println(sm.getObject());
      exit();
    }
    

    SubMain overrides Main's getObject() method, but changes the return type, to specialize it.

    It is allowed because it doesn't change the contract of the method: a class calling getObject() receives an object behaving exactly like a Parent. That's the Liskov substitution principle

Sign In or Register to comment.