国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java JavaInterview questions Basic Java interview questions (2)

Basic Java interview questions (2)

Nov 30, 2019 pm 03:28 PM
java

Basic Java interview questions (2)

#11. Is it possible to issue a call to a non-static method from within a static method?

Can't. Because non-static methods are associated with objects, an object must be created before method calls can be made on the object. However, static methods do not need to create an object when calling, and can be called directly. (Recommended study: java interview questions)

That is to say, when a static method is called, no instance object may have been created. If a non-static method is issued from a static method, When calling a method, which object is the non-static method associated to? This logic cannot be established, so a static method internally issues a call to a non-static method.

12. The difference between Integer and int

int is one of the 8 primitive data types provided by java. Java provides wrapper classes for each primitive type. Integer is the wrapper class provided by java for int. The default value of int is 0, while the default value of Integer is null, that is, Integer can distinguish the difference between unassigned value and value 0, while int cannot express the situation of unassigned value.

For example: If you want to express the difference between not taking the exam and having an exam score of 0, you can only use Integer. In JSP development, the default value of Integer is null, so when the el expression is used to display it in the text box, the value is a blank string, and the default value of int is 0, so when the el expression is used to display it in the text box, The result is 0, so int is not suitable as the form data type of the web layer.

In Hibernate, if OID is defined as Integer type, then Hibernate can determine whether an object is temporary based on whether its value is null. If OID is defined as int type, it also needs to be mapped in hbm Set its unsaved-value attribute in the file to 0.

In addition, Integer provides multiple integer-related operation methods, such as converting a string into an integer. Integer also defines constants that represent the maximum and minimum values ??of integers.

13. How much is Math.round(11.5) equal to? What is Math.round(-11.5) equal to?

The Math class provides three functions related to rounding Methods: ceil, floor, round, the functions of these methods correspond to the meanings of their English names.

For example, the English meaning of ceil is ceiling, and this method means rounding up. The result of Math.ceil(11.3) is 12, and the result of Math.ceil(-11.3) is -11;

The English meaning of floor is floor. This method means rounding down. The result of Math.ceil(11.6) is 11, and the result of Math.ceil(-11.6) is -12;

most What is difficult to master is the round method, which means "rounding". The algorithm is Math.floor(x 0.5), which means adding 0.5 to the original number and then rounding down. Therefore, the result of Math.round(11.5) is 12, The result of Math.round(-11.5) is -11.

14. What is the difference between Overload and Override? Can the Overloaded method change the type of return value?

Overload means overloading, and Override means overwriting, that is, rewriting.

Overload means that there can be multiple methods with the same name in the same class, but the parameter lists of these methods are different (that is, the number or type of parameters are different).

Overriding Override means that the method in the subclass can have the same name and parameters as a method in the parent class. When this method is called through the instance object created by the subclass, the definition in the subclass will be called. method, which is equivalent to overwriting the exact same method defined in the parent class. This is also a manifestation of polymorphism in object-oriented programming.

When a subclass overrides the method of the parent class, it can only throw fewer exceptions than the parent class, or throw sub-exceptions of the exceptions thrown by the parent class, because the subclass can solve some of the parent class's problems. Problems cannot have more problems than the parent class.

The access rights of subclass methods can only be greater than those of the parent class, not less. If the method of the parent class is of private type, then there is no overriding restriction in the subclass, which is equivalent to adding a brand new method to the subclass.

As for the question of whether the Overloaded method can change the type of return value, it depends on what you want to ask?

This question is very vague. If the parameter lists of several Overloaded methods are different, of course their return types can also be different.

But I guess the question you want to ask is: If the parameter lists of two methods are exactly the same, can their return values ??be different to implement overloading.

This is not possible. We can use proof by contradiction to illustrate this problem, because sometimes we do not need to define the return result variable when calling a method, that is, we do not care about its return result.

For example, when we call the map.remove(key) method, although the remove method has a return value, we usually do not define a variable to receive the return result. At this time, assume that there are two names in the class and The parameter list of the method is exactly the same, but the return type is different. Java cannot determine which method the programmer wants to call, because it cannot judge by the return result type.

Override can be translated as coverage. From the literal meaning, it covers a method and rewrites it to achieve different functions.

The most familiar coverage for us is the implementation of interface methods. Generally, only methods are declared in the interface, and when we implement it, we need to implement all the methods declared by the interface. In addition to this typical usage, we may also override methods in the parent class in the subclass during inheritance. When covering, you should pay attention to the following points:

1. The flag of the overridden method must completely match the flag of the overridden method to achieve the overwriting effect;

2. The return value of the method must be consistent with the return value of the overridden method;

3. The exception thrown by the overridden method must be consistent with the exception thrown by the overridden method, or its subclass;

4. The overridden method cannot be private, otherwise only a new method will be defined in its subclass without overriding it.

Overload may be familiar to us and can be translated as overloading. It means that we can define some methods with the same name, distinguish these methods by defining different input parameters, and then call the VM The appropriate method will be selected for execution based on different parameter styles. When using overloading, you should pay attention to the following points:

1. When using overloading, you can only use different parameter styles. For example, different parameter types, different number of parameters, different parameter order (of course, several parameter types in the same method must be different, for example, it can be fun(int, float), but it cannot be fun(int, int) ));

2. It cannot be overloaded by access permissions, return types, and thrown exceptions;

3. The exception type and number of methods will not affect overloading;

4. For inheritance, if a method has privileged access in the parent class, it cannot be overloaded in the subclass. If it is defined, it will only define a new method. It will not achieve the effect of overloading.

15. Can interfaces inherit interfaces? Can abstract classes implement interfaces? Can abstract classes inherit concrete classes? Can there be a static main method in an abstract class?

Interfaces can inherit interfaces. Abstract classes can implement interfaces, and abstract classes can inherit concrete classes. Abstract classes can have static main methods.

Note: As long as you understand the nature and role of interfaces and abstract classes, these questions are easy to answer. Think about it, if you were a designer of the Java language, would you provide such support? If not If so, is there any reason? If you have no reason not to provide it, then the answer is yes.

Just remember that the only difference between abstract classes and ordinary classes is that instance objects cannot be created and abstract methods are allowed.

16. What is the mechanism to implement polymorphism in Java?

relies on the fact that the reference variables defined by the parent class or interface can point to the instance object of the subclass or specific implementation class, and the method called by the program is dynamically bound at runtime, which is what the reference variable points to. The method of the specific instance object is the method of the object running in the memory, rather than the method defined in the type of the reference variable.

17. What is the difference in syntax between abstractclass and interface?

1. Abstract classes can have constructors, but interfaces cannot have constructors.

2. There can be ordinary member variables in the abstract class, but there are no ordinary member variables in the interface.

3. The abstract class can contain non-abstract ordinary methods, and all methods in the interface must be It is abstract and cannot have non-abstract ordinary methods.

4. The access types of abstract methods in abstract classes can be public, protected and (default type, although no error is reported under eclipse, but it should not work), but abstract methods in interfaces can only be public types. , and the default is public abstract type.

5. Abstract classes can contain static methods, but interfaces cannot contain static methods.

6. Both abstract classes and interfaces can contain static member variables. The static member variables in abstract classes are The access type can be arbitrary, but the variables defined in the interface can only be of publicstatic final type, and the default is publicstatic final type.

7. A class can implement multiple interfaces, but can only inherit one abstract class.

18. Can the abstract method be static, native, and synchronized at the same time?

The abstract method cannot be static. Because abstract methods must be implemented by subclasses, and static has nothing to do with subclasses!

The native method means that the method is to be implemented in another platform-dependent programming language. There is no problem of being implemented by a subclass. Therefore, it cannot be abstract and cannot be mixed with abstract.

For example, the FileOutputSteam class needs to deal with hardware, and the underlying implementation uses operating system-related api implementation; for example, it is implemented in C language in Windows, so if you look at the source code of jdk, you can find the open of FileOutputStream The method is defined as follows:

private native void open(Stringname) throwsFileNotFoundException;

If we want to use Java to call a C language function written by others, we cannot call it directly. We need to write a C language function according to the requirements of Java, and then our C language function calls someone else's C language function. function.

Since our C language function is written according to the requirements of Java, our C language function can be connected to Java. The docking method on the Java side is to define the corresponding function of our C language. Method, the corresponding method in Java does not need to write specific code, but it needs to be declared native in front.

Regarding the problem of using synchronized and abstract together, I don’t think it is possible, because in my several years of study and development, I have never seen this situation, and I think synchronized should be used in a specific It only makes sense in terms of method.

Moreover, the synchronization lock object used by synchronized synchronization on the method is this, and it is impossible to determine what this is on the abstract method.

19. Can an inner class reference members of its containing class? Are there any restrictions?

absolutely okay. If it's not a static inner class, there's no limit!

If you treat a static nested class as a special case of an inner class, then in this case you cannot access the ordinary member variables of the outer class, but you can only access the static members in the outer class, for example , the following code:

class Outer
{
    static int x;
    static class Inner
    {
        voidtest(){
          syso(x);
        }
    }
}

20. String s = "Hello"; s = s "world!"; After these two lines of code are executed, has the content in the original String object changed? ?

No. Because String is designed to be an immutable class, all its objects are immutable objects.

In this code, s originally pointed to a String object with the content "Hello", and then we operated on s. Has the object pointed to by s changed? The answer is no.

At this time, s no longer points to the original object, but to another String object with the content "Hello world!". The original object still exists in the memory, but the reference variable s no longer exists. Point to it.

Through the above explanation, we can easily derive another conclusion. If strings are often modified in various ways, or in other words, unforeseen modifications, then using String to represent strings will cause A lot of memory overhead.

Because the String object cannot be changed after it is created, a String object is needed to represent each different string. At this time, you should consider using the StringBuffer class, which allows modification, rather than generating a new object for each different string. Moreover, it is very easy to convert these two types of objects.

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

public class Demo {
    private String s;
    ...
public Demo {
    s = "Initial Value";
    }
    ...
}

instead of

s = new String("Initial Value");

The latter will call the constructor every time to generate a new object, which has low performance and high memory overhead, and is meaningless because the String object cannot be changed, so for strings with the same content, only one String object is needed to represent them.

In other words, if you call the above constructor multiple times to create multiple objects, their String type attributes s all point to the same object.

The above conclusion is also based on the fact that for string constants, if the contents are the same, Java considers them to represent the same String object. Calling the constructor with the new keyword will always create a new object, regardless of whether the contents are the same.

As for why the String class should be designed as an immutable class, it is determined by its purpose. In fact, not only String, but also many classes in the Java standard class library are immutable.

When developing a system, we sometimes need to design immutable classes to pass a set of related values, which is also a manifestation of object-oriented thinking.

Immutable classes have some advantages. For example, because its objects are read-only, there will be no problems with concurrent access by multiple threads. Of course, there are also some disadvantages. For example, each different state needs an object to represent it, which may cause performance problems. Therefore, the Java standard class library also provides a variable version, StringBuffer.

The above is the detailed content of Basic Java interview questions (2). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to iterate over a Map in Java? How to iterate over a Map in Java? Jul 13, 2025 am 02:54 AM

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)-&gt

Java Optional example Java Optional example Jul 12, 2025 am 02:55 AM

Optional can clearly express intentions and reduce code noise for null judgments. 1. Optional.ofNullable is a common way to deal with null objects. For example, when taking values ??from maps, orElse can be used to provide default values, so that the logic is clearer and concise; 2. Use chain calls maps to achieve nested values ??to safely avoid NPE, and automatically terminate if any link is null and return the default value; 3. Filter can be used for conditional filtering, and subsequent operations will continue to be performed only if the conditions are met, otherwise it will jump directly to orElse, which is suitable for lightweight business judgment; 4. It is not recommended to overuse Optional, such as basic types or simple logic, which will increase complexity, and some scenarios will directly return to nu.

Comparable vs Comparator in Java Comparable vs Comparator in Java Jul 13, 2025 am 02:31 AM

In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar

How to fix java.io.NotSerializableException? How to fix java.io.NotSerializableException? Jul 12, 2025 am 03:07 AM

The core workaround for encountering java.io.NotSerializableException is to ensure that all classes that need to be serialized implement the Serializable interface and check the serialization support of nested objects. 1. Add implementsSerializable to the main class; 2. Ensure that the corresponding classes of custom fields in the class also implement Serializable; 3. Use transient to mark fields that do not need to be serialized; 4. Check the non-serialized types in collections or nested objects; 5. Check which class does not implement the interface; 6. Consider replacement design for classes that cannot be modified, such as saving key data or using serializable intermediate structures; 7. Consider modifying

How to handle character encoding issues in Java? How to handle character encoding issues in Java? Jul 13, 2025 am 02:46 AM

To deal with character encoding problems in Java, the key is to clearly specify the encoding used at each step. 1. Always specify encoding when reading and writing text, use InputStreamReader and OutputStreamWriter and pass in an explicit character set to avoid relying on system default encoding. 2. Make sure both ends are consistent when processing strings on the network boundary, set the correct Content-Type header and explicitly specify the encoding with the library. 3. Use String.getBytes() and newString(byte[]) with caution, and always manually specify StandardCharsets.UTF_8 to avoid data corruption caused by platform differences. In short, by

Java method references explained Java method references explained Jul 12, 2025 am 02:59 AM

Method reference is a way to simplify the writing of Lambda expressions in Java, making the code more concise. It is not a new syntax, but a shortcut to Lambda expressions introduced by Java 8, suitable for the context of functional interfaces. The core is to use existing methods directly as implementations of functional interfaces. For example, System.out::println is equivalent to s->System.out.println(s). There are four main forms of method reference: 1. Static method reference (ClassName::staticMethodName); 2. Instance method reference (binding to a specific object, instance::methodName); 3.

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

How to parse JSON in Java? How to parse JSON in Java? Jul 11, 2025 am 02:18 AM

There are three common ways to parse JSON in Java: use Jackson, Gson, or org.json. 1. Jackson is suitable for most projects, with good performance and comprehensive functions, and supports conversion and annotation mapping between objects and JSON strings; 2. Gson is more suitable for Android projects or lightweight needs, and is simple to use but slightly inferior in handling complex structures and high-performance scenarios; 3.org.json is suitable for simple tasks or small scripts, and is not recommended for large projects because of its lack of flexibility and type safety. The choice should be decided based on actual needs.

See all articles