⬆️ ⬇️

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

Type real types



I think, after a brief insight into the possibility of Java and reading a couple dozen lines of code examples, you wanted to know what every Java programmer should be able to operate with. Well, let's talk about primitive types, classes (including several basic ones), comparison, passing parameters, and simple structures in Java.



Base types



Their in java 8:



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



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 int you can cram numbers up to 2 with a small billion, in 8 bytes long - up to 9 * 10 18 .

The non-committed float and double consist of 4 and 8 bytes, respectively (for more details, see here ).

As you can see, the only unsigned type is char. It stores the characters, and immediately in Unicode.

All these types are passed solely by value, and you will not have any “references to int”, unless you use the Reflection mechanism.

Each type is clearly limited in size, which allows us to use them equally on any Java platform. The only exception is that in the first specifications of J2ME there were no non-integer numbers, but now this is all right.

In general, you can be sure to write

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 be automatically 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 are not objects in Java. No information about the essence of this type except its value, we can not get. Yes, and do not, in general.



Operations with basic types



What can we do with them?



For all but boolean (but even for char):



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



Classes



The class hierarchy in Java begins with Object. What does each object do according to Java developers?

  1. An object can return its class with the command getClass.
  2. For the sake of comparison, there are methods equals and hashCode.
  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 debug.




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



How to handle this?



So, we have a set of basic types and a class from which everything is inherited, except for these types. What else do we need for happiness?

We need what unites them. Meet - wrapper classes.

In order to be able to operate with prime numbers (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, completely transparent:

Integer x = 1;

Boolean a = false ;




* This source code was highlighted with Source Code Highlighter .


In older versions, it was necessary to “wrap” primitive types into wrappers, and then “unwrap” them from there. For example:

Integer x = new Integer(1);

int r = x.intValue();



* This source code was highlighted with Source Code Highlighter .


Comparison



Comparing on more-less is only for numbers, and the mechanism of its work is obvious. With equality 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 hit the ears or thank in every way - for objects == this is only a comparison by reference, i.e. Objects must be one object, not different (even if they have the same fields, etc. - they are still not one object).

For the rest, use the .equals method.

In addition, the hashCode method serves (theoretically) for the same purpose. It is considered good practice to override it if you have redefined equals.

The fact is that by redefining equals you come up with your own comparison rules. You can, for example, take into account only a part of the class fields, and use only them for comparison.

Golden rule of comparison:

If, after initialization of some objects a and b, the expression a.equals (b) returns true, then a.hashCode () should be equal to b.hashCode ().



Why not write == for objects



The only thing with which == rolls are 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>b);

System. out .println(a<b);

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 specified the creation of new objects with one value, and the comparison by reference returned false.

And in the first two cases the deployment took place, since the comparison operation is defined only for primitive types.

Moral: == only for primitive types.



"By the way, the line"



What I haven’t mentioned yet, but you guessed it: Java has 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 of initialization, the second one, while redundant, but guarantees that your line will be “new”.

Strictly speaking, any construct in Java in double quotes is already a new string, created and cached (see below).



In addition, for strings there is a join (concatenation) operation:

String r = "Hello" + "world";



Constructors, links and values: where it goes, and where it goes.



When you create a new object, you begin its life cycle.

It begins with the constructor you called. Yes? Not.



At the first mention of a class, all its static-blocks of the type static {...} lying in a class are called in order.

Static-blocks of parents are called as they are mentioned.

Then all blocks of the form {...} of the upper parent are called in order.

Further, the constructor of the same parent is called.

Then the last 2 steps are repeated for each hierarchy class.

Last {} -blocks and constructor of your class are called.



Next - your object lives as long as it has links.

As soon as object references 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 destroying, the cute object's finalize method is called.



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



How designers are chosen.



In the previous paragraph, constructors were mentioned. The class can have a lot of them, each has its own parameters.

By default, if you haven't written any pens, then an empty constructor without parameters will be created.

Each of them must call the parent class constructor.

To do this, you need to write the first line in the constructor super-call:



public HelloWorld () {

super ();

}



The super constructor is the parent constructor. You can use any of those that he has.

In fact, if you do not write it, the compiler will do it for you. And what will happen if the parent class has no constructor without parameters?

In this case, you must always explicitly call the super constructor, and pass parameters to it as for the constructor of the parent class.



What do you have there about caching?



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



"By the way, the line", part 2 - be careful.



Remember, each line is an immutable object.

Doing this: String x = "ads" + "dsada"; you are not eating 8 * 2 but 16 * 2 bytes. First, the creation of the first two lines, 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 demanding of memory (since they do not copy strings), and StringBuffer is also thread-safe (but it slows down a bit more).

Example:

StringBuilder hi = new StringBuilder ;

hi.append( ", " );

hi.append( ". " );

hi.append( " ?" );

System. out .println(hi.toString());



* This source code was highlighted with Source Code Highlighter .


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



Arrays



Arrays in Java are a lot like arrays in C, but they do not operate with pointer arithmetic.

Examples of arrays:

char [] asd = new char [5]; // 5

char [] ghj = new char []{ 'a' , 'n' };// 2




* This source code was highlighted with Source Code Highlighter .




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



Basic java constructs



if (any boolean expression or variable) {} else {}

for (actions before the start of the cycle; condition for continuing the cycle; action after each step) {}

while (loop continuation condition) {}

do {} while (loop continuation condition)

switch (numeric variable or enum) {case value: ... break; case meaning: ... break; default:}

for (type name variable: array) {}



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

for ( char a : chars){

System. out .println(a);

}




* This source code was highlighted with Source Code Highlighter .




In addition, for-each is applicable for any collection, and not only for them. I will tell about it later.



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

Source: https://habr.com/ru/post/49582/



All Articles