We learn Java. Third cup: primitive types, and objects. Basic designs

    Type real types

    I think, after a brief digression into the possibilities of Java and reading a couple of dozen lines of sample code, you wanted to know what each Java programmer should be able to handle. Well, let's talk about primitive types, classes (including a few basic ones), comparison, passing parameters, and simple structures in Java.

    Base types

    Them in Java 8:
    • boolean;
    • tsiferki: byte, char, short, int, long;
    • non-integer tags: float, double.

    In addition, there is the void keyword - in java it is not a type and can only be used before the function name, indicating that it does not return anything.

    boolean, which is logical to assume, can be true / false, byte - -128..127 (1 byte), char - 0..65536 (2 bytes), short - -32768..32767 (2 bytes).
    In 4 bytes of int, you can cram numbers up to 2 with a small billion, in 8 bytes of long - up to 9 * 10 18 .
    Non-integer floats and doubles consist of 4 and 8 bytes, respectively (more details here ).
    As you can see, the only unsigned type is char. Symbols are stored in it, and immediately in Unicode.
    All these types are passed exclusively by value, and you don’t have and will not have any "references to int" if you do not crawl into the Reflection mechanism.
    Each of the types is clearly limited in size, which allows us to use them equally on any Java platform. The only exception is that the first J2ME specifications did not contain non-integer numbers, but now everything is fine with this.
    In general, you can be sure that by writing
    byte x = 100;
    byte y = 100;
    int i = x + y;

    * This source code was highlighted with Source Code Highlighter.

    you get exactly 200, and not something else - the variables will automatically be converted to the desired type.
    There are several ways to set the value of integer variables, for example:

    byte a;
    a = 1;
    a = 07;//восьмеричненько
    a = 0x7;//hex
    a = 'a';//будет взят код символа
    a = 1.0;//упадёт с ошибкой - так можно делать только с float/double

    * This source code was highlighted with Source Code Highlighter.

    These types are called basic or primitive, they cannot be inherited, and indeed they are not objects in Java. We cannot receive any information about the essence of this type except its meaning. Yes and no, in general.

    Base Type Operations

    What can we do with them?
    • assign a value via =;
    • compare through == and! = (not equal).

    For everyone except boolean (but even for char):
    • increment / decrement through ++ / -;
    • increase / decrease / multiply / share in obvious ways (division - /);
    • find the remainder of the division in%;
    • (except float / double) shift using >> and <<;
    • (except float / double) apply binary logic via &, |, ^ (xor), ~ (not).

    For boolean - &&, ||, ^ ,! (not).


    The class hierarchy in Java begins with Object. What can each object do according to Java developers?
    1. An object can return its class using the getClass command.
    2. For the sake of comparison, there are equals and hashCode methods.
    3. An object may be able to clone itself through the clone method.
    4. An object can override the toString method and return smart information about itself for debugging.

    In addition, there is also the finalize method, which should be redefined if before death your object should “write a will” and a set of methods for working with threads that can lull / wake the current thread.

    How to handle this?

    So, we have a set of base types and a class from which everything except these types is inherited. What else do we need for happiness?
    We need something that unites them. Meet the wrapper classes.
    In order to be able to handle primes (and boolean) as objects, wrapper classes were invented.
    From the name: Byte, Short, Integer, Long, Float, Double, Boolean, Character (the only type that was "renamed").
    In new versions of Java you can use them in parallel with primitive types, absolutely transparent:
    Integer x = 1;
    Boolean a = false;

    * This source code was highlighted with Source Code Highlighter.

    In older versions, you had to “wrap” primitive types in wrappers, and then “unwrap” them from there. For example, like this:
    Integer x = new Integer(1);
    int r = x.intValue();

    * This source code was highlighted with Source Code Highlighter.


    Comparison of more or less is only for numbers, and the mechanism of its operation is obvious. Equality is more interesting.
    In Java, there are two ways to compare objects for equality, == and the equals method.
    == is used for primitive types. For its use with objects, smart people either beat on the ears or thank them in every way - for objects == this is only a comparison by reference, i.e. objects should be one object, not different (even if they have the same fields and so on - they are still not the same object).
    For the rest, you need to use the .equals method.
    In addition, the hashCode method serves (theoretically) for the same purpose. It’s good practice to redefine it if you redefined equals.
    The fact is that overriding equals you come up with your own rules for comparison. You can, for example, take into account only part of the fields of a class, and use only them for comparison.
    Golden rule of comparison:
    If after initializing some objects a and b the expression a.equals (b) returns true, then a.hashCode () must be equal to b.hashCode ().

    Why it is impossible to write == for objects

    The only thing == rolls with is numbers and strings, because they are "cached". And that’s not all. Each Integer rrr = 1; this is the same variable for Java, but it works on a limited range of values. If I remember correctly, values ​​greater than 127 and less than -128 are not cached.
    Do you want to show a joke in the style of "and in PHP 0 is '0'"?
    Integer a = new Integer(1);
    Integer b = new Integer(1);
    System.out.println(a System.out.println(a==b);

    * This source code was highlighted with Source Code Highlighter.

    This miracle will return you 3 times false. Because we explicitly indicated the creation of new objects with a single value, and comparison by reference returned false.
    And in the first two cases, the deployment occurred, since the comparison operation is defined only for primitive types.
    Moral: == only for primitive types.

    “By the way, the lines”

    What I did not mention yet, but you already guessed: in Java there is a class String.
    Simple use:
    String a = "hi!";
    String b = new String("hi!");

    * This source code was highlighted with Source Code Highlighter.

    Here, as you can see, there are 2 ways to initialize, the second one, although redundant, guarantees that your line will be "new".
    Strictly speaking, any double quotation construct in Java is already a new line created and cached (see below).

    In addition, there is a connection (concatenation) operation for strings:
    String r = “Hello” + “peace”;

    Constructors, references, and values: where what goes and where it goes.

    When you create a new object, you begin its life cycle.
    It starts with the constructor you called. Yes? Not.

    At the first mention of a class, all its static blocks of the form static {...} lying in the class are called in order.
    Static blocks of parents are called as they are mentioned.
    Then, in order, all blocks of the form {...} of the upper parent are called.
    Next, the constructor of the same parent is called.
    Then the last 2 steps are repeated for each class of the hierarchy.
    Lastly, the {} blocks and the constructor of your class are called.

    Next - your object lives as long as there are links to it.
    As soon as references to the object are lost, it is picked up by the garbage collector and destroyed. You don’t need to write a = null to “erase the link” - java already knows when you stopped using the object.
    Before destruction, the finalize method of your sweet object is called.

    By the way, such an error sometimes occurs: a person is passed an object to a method, and he assigns it null, thinking that in this way he will erase the object from all the links. No, this will not be, only this link will be destroyed. However, if there was only one link - of course, in this case the object will end.

    How designers are chosen.

    In the previous paragraph, constructors were mentioned. A class can have many of them, each with its own parameters.
    By default, if you did not write any with pens, an empty constructor without parameters will be created.
    Each of them must call the constructor of the parent class.
    To do this, you must append the super call to the constructor as the first line:

    public HelloWorld () {
    super ();
    } The

    super constructor is the constructor of the parent. You can use any of those that he has.
    In fact, if you do not write it, the compiler will do it for you. But what happens if the parent class does not have a constructor without parameters?
    In this case, you must explicitly call the super constructor always, and pass parameters to it as for the constructor of the parent class.

    What do you have about caching?

    I mentioned object caching. I will explain a little. The fact is that the mention of numbers / lines is a routine that constantly falls on us. In order not to store a thousand integers with 1, a caching mechanism was made as a value. It guarantees you that for each of your units or lines exactly one object will be created in memory, and with automatic expansion it will be used. The joke is that the developers of the platform have limited the number of cached numbers to the limits mentioned above.

    “By the way, lines”, part 2 - be careful.

    Remember, each line is an immutable object.
    By doing this: String x = "ads" + "dsada"; you are eating not 8 * 2 but 16 * 2 bytes. First, the first two lines are created, then the third.
    To avoid this, StringBuffer and StringBuilder were invented. If you need to build long lines, use these things. They are faster and less memory intensive (since they do not copy strings), and StringBuffer is also thread-safe (but it slows down a bit more).
    StringBuilder hi = new StringBuilder;
    hi.append("Привет, мир");
    hi.append(". ");
    hi.append("Как твои дела?");

    * This source code was highlighted with Source Code Highlighter.

    I hope I was able to make it clear how to work with simple objects. On this I could finish about them, but I remembered about arrays.


    Arrays in Java are much like arrays in C, but they do not operate with pointer arithmetic.
    Array examples:
    char[] asd = new char[5];//пустой массив на 5 символов
    char[] ghj = new char[]{'a','n'};//массив на 2 символа

    * This source code was highlighted with Source Code Highlighter.

    Of the nice bonuses, arrays have a length field, that is, the length of the array you always know and it is fixed.

    Basic Java Constructs

    if (any boolean expression or variable) {} else {}
    for (actions before the start of the loop; condition to continue the loop; action after each step) {}
    while (condition to continue the loop) {}
    do {} while (condition to continue the loop)
    switch (numeric or enum variable) {case value: ... break; case value: ... break; default:}
    for (Type nameVariable: array) {}

    I would like to dwell on the latter. In Java, the for-each loop looks like this. It iterates over each element of the array, like this:
    char[] chars = new char[]{'a','n'};
    for(char a : chars){

    * This source code was highlighted with Source Code Highlighter.

    In addition, for-each is applicable to any collection, and not only to them. I’ll talk about this later.

    PS How can I properly highlight Java code? Source Code Highlighter for Java, unfortunately, is not intended.

    Also popular now: