Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the problems that should be understood in Java

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the problems that should be understood in Java". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Question 1: what did I declare!

String s = "Hello world!"

A lot of people have done this, but what exactly did we declare?

[@ more@]

The answer is usually: a String with the content "Hello world!". Such a vague answer is usually the source of confusion. If you want an accurate answer, half of the people will probably give the wrong answer.

This statement declares a reference to an object named "s", which can point to any object of type String, currently pointing to "Hello world!" This object of type String. That's what really happened. We don't declare a String object, we just declare a reference variable that can only point to the String object. So, if you run another sentence after that sentence:

String string = s

We declare another reference that can only point to the String object, named string, and no second object is generated, and the string still points to the original object, that is, to the same object as s.

Question 2: what is the difference between the "=" method and the equals method?

The = = operator is used specifically to compare whether the values of variables are equal. What is easier to understand is:

Int axi10

Int baggage 10

Then it will be true.

But what's hard to understand is:

String a=new String ("foo")

String b=new String ("foo")

Then the false will be returned by aroomroomb.

As mentioned in the previous post, an object variable is actually a reference whose value points to the memory address where the object is located, not to the object itself. Both an and b use the new operator, which means that two strings with the content "foo" will be generated in memory, and since they are "two", they are naturally located at different memory addresses. The values of an and b are actually values of two different memory addresses, so using the "= =" operator, the result is false. Admittedly, the contents of the objects an and b refer to are "foo" and should be "equal", but the = = operator does not involve the comparison of object contents.

Comparing the contents of an object is exactly what the equals method does.

Take a look at how the equals method of the Object object is implemented:

Boolean equals (Object o) {

Return this==o

}

The Object object uses the = = operator by default. So if your self-created class does not override the equals method, then your class will get the same result using equals and using =. You can also see that Object's equals method does not achieve what the equals method should achieve: compare whether the contents of the two objects are equal. Because the answer should be decided by the creator of the class, Object leaves this task to the creator of the class.

Take a look at an extreme class:

Class Monster {

Private String content

...

Boolean equals (Object another) {return true;}

}

I override the equals method. This implementation causes comparisons between Monster instances to always return true regardless of their contents.

So when you use the equals method to determine whether the content of an object is equal, please don't take it for granted. Because you may think equal, but the author of this class does not think so, and the implementation of the equals method of the class is controlled by him. If you need to use the equals method, or any hash code-based collection (HashSet,HashMap,HashTable), take a look at java doc to confirm how the equals logic of this class is implemented.

Question 3: has String changed or not?

No. Because String is designed to be an immutable class, all of its objects are immutable. Look at the following code:

String s = "Hello"

S = s + "world!"

Has the object pointed to by s changed? This conclusion can be easily derived from the conclusion of the first article in this series. Let's see what happened. In this code, s originally points to a String object with the content "Hello", and then we do a + operation on s, so does the object that s points to change? The answer is no. At this point, s no longer points to the original object, but points to another String object with the content "Hello world!". The original object still exists in memory, but the reference variable s no longer points to it.

From the above, it is easy to draw another conclusion that using String to represent a string will incur a lot of memory overhead if you often make various changes to the string, that is to say, unforeseen changes. Because the String object cannot be changed after it is created, a String object is needed to represent each different string. At this point, you should consider using the StringBuffer class, which allows modification instead of generating a new object for each different string. Moreover, the conversion between these two kinds of objects is very easy.

At the same time, we also know that if you want to use a string with the same content, you don't have to new one String at a time. For example, to initialize a String reference variable called s in the constructor and set it to the initial value, you should do this:

Public class Demo {

Private String s

...

Public Demo {

S = "Initial Value"

}

...

}

Instead of

S = new String ("Initial Value")

The latter calls the constructor every time to generate a new object, which is slow in performance, high in memory overhead, and meaningless, because the String object is immutable, so for a string with the same content, it only needs a String object to represent it. That is, the above constructor is called multiple times to create multiple objects, and their String type properties s all point to the same object.

The above conclusion is also based on the fact that for string constants, Java believes that they represent the same String object if the contents are the same. Calling the constructor with the keyword new always creates a new object, regardless of whether the content is the same or not.

Why the String class is designed to be immutable is determined by its purpose. In fact, not only String, the classes in many Java standard class libraries are immutable. When developing a system, we sometimes need to design immutable classes to pass a set of related values, which is also the embodiment of object-oriented thinking. Immutable classes have some advantages, for example, because its objects are read-only, there is no problem with multithreaded concurrent access. Of course, there are some disadvantages, such as each different state is represented by an object, which may cause performance problems. So the Java standard class library also provides a variable version, StringBuffer.

Question 4: what exactly does the final keyword modify?

Final makes the modified variable "unchanged", but because the essence of the object-type variable is "reference", "immutable" has two meanings: the immutability of the reference itself, and the object that the reference points to.

The invariance of the reference itself:

Final StringBuffer a=new StringBuffer ("immutable")

Final StringBuffer b=new StringBuffer ("not immutable")

An error at compile time

The object that the reference points to remains the same:

Final StringBuffer a=new StringBuffer ("immutable")

A.append ("broken!"); / / compiled through

As you can see, final is only valid for the "value" of the reference (that is, the memory address of the object it points to). It forces the reference to point only to the object that was originally pointed to, and changing its direction will result in a compile-time error. Final is not responsible for changes in the objects it points to. This is very similar to the = operator: the = operator is only responsible for the equality of the referenced "value". As to whether the content of the object pointed to by this address is equal, the = operator does not care.

It is important to understand the final problem. Many program vulnerabilities are based on this-final can only guarantee that the reference will always point to a fixed object, not that the state of that object will remain unchanged. In multithreaded operations, an object is shared or modified by multiple threads, and unconscious modifications by one thread to the object may cause another thread using the object to crash. One wrong solution is to declare this object as final when it is created, with the intention of making it "forever". In fact, it was in vain.

Question 5: exactly how to initialize!

This question discusses the initialization of variables, so let's take a look at what kinds of variables are available in Java.

1. The property of the class, or range

two。 Local variables in the method

3. Parameters of the method

For the first variable, the Java virtual machine initializes automatically. If an initial value is given, it is initialized to that initial value. If it is not given, initialize it to the default initial value of this type of variable.

The default initial value of the int type variable is 0

The default initial value of float type variable is 0.0f

The default initial value of the double type variable is 0.0

The default initial value of the boolean type variable is false

The default initial value of the char type variable is 0 (ASCII code)

The default initial value of the long type variable is 0

The default initial value of all object reference type variables is null, which does not point to any object. Note that the array itself is also an object, so the value of an uninitialized array reference is also null after automatic initialization.

For two different class attributes, the static property and the instance property, the timing of initialization is different. The instance property is initialized when the instance is created, the static property is initialized when the class is loaded, that is, the class is used for the first time, and subsequent instance creation is not initialized again. This issue will be discussed in detail in a future series.

For the second variable, it must be explicitly initialized. If you try to use it before initialization, the compiler will protest. If the initialized statement is in a try block or an if block, you must also make sure that it is assigned before it is used for the first time. That is, putting initialization statements in conditional judgment statements with only if blocks will also protest, because execution may not meet the judgment conditions behind if, so that initialization statements will not be executed, which violates the rule that local variables must be initialized before they are used. But if there is also an initialization statement in the else block, it can be compiled, because in any case, at least one initialization statement will be executed and nothing that is not initialized before use will occur. The same is true for try-catch, if there is an initialization statement only in the try block, the compiler passes. If you have it in catch or finally, you can compile it. In short, make sure that local variables are initialized before they are used. So, it's a good idea to initialize them when you declare them, and if you don't know what the value will be, use the default values above.

In fact, the third variable is essentially the same as the second, both local variables in the method. It's just that as a parameter, it must have been initialized, and the value passed in is the initial value, so there is no need for initialization.

Question 6: what is instanceof?

Instanceof is a binary operator of Java, and =, >

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

  • How to use html to implement annotations

    This article is about how to use html to implement annotations. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look. The HTML comment begins with

    © 2024 shulou.com SLNews company. All rights reserved.

    12
    Report