hey guys , It's also the interview season ,cxuan I'm going to write it again Java Relevant interview questions , Let's start with the basics , These interview questions belong to the basic series , Does not include multithreading related interview questions and JVM Relevant interview questions , Multithreading and JVM I put it in the back , I won't say much about it next , start doing sth. !

Java The basic chapter

Java What are the characteristics of

  • Concurrent : You can execute many statements in it , You don't have to do it all at once
  • Object oriented : Class based and object-oriented programming languages .
  • Independent : Support Write once , Run anywhere Independent programming language of , The compiled code can support Java On all platforms .

Java Characteristics of

Java The following are the features of

  • Simple ,Java It will make your work easier , Enables you to focus on the main business logic , You don't have to care about the pointer 、 Operator overloading 、 Memory recycling and other functions unrelated to the main business .
  • Portability ,Java It's platform independent , This means that any application written on one platform can be easily ported to another platform .
  • Security , After compiling, all the code will be converted to bytecode , Humans can't read . It makes development virus-free , Tamper free system / Applications become possible .
  • dynamic , It has the ability to adapt to changing environments , It can support dynamic memory allocation , This reduces memory waste , Improved application performance .
  • Distributed ,Java The functionality provided helps to create distributed applications . Use Remote method call (RMI), A program can call another program's method and get the output through the network . You can access files by calling methods from any computer on the Internet . It's a revolutionary feature , It's so important for today's Internet .
  • Robustness, ,Java It has powerful memory management function , Checking code at compile and run time , It helps to eliminate mistakes .
  • High performance ,Java The darkest technology is bytecode programming ,Java The bytecode that the code is compiled into can be easily converted to local machine code . adopt JIT Real time compiler to achieve high performance .
  • Explanatory ,Java Be compiled into bytecode , from Java Runtime environment interpretation .
  • Multithreading ,Java Support multiple execution threads ( Also known as lightweight processes ), Includes a set of synchronization primitives . This makes it easier to program with threads ,Java Thread safety is realized through the management model .

What are the characteristics of object-oriented

There are three main characteristics of object-oriented

  • encapsulation : Encapsulation is one of the characteristics of object-oriented , Is the main feature of object and class concepts . encapsulation , That is to encapsulate objective things into abstract classes , And classes can keep their data and methods to trusted classes or objects , Hiding information from untrusted sources .

  • Inherit : Inheritance refers to using all the functions of an existing class , And extend these functions without having to rewrite the original class .

  • polymorphic : Polymorphism is a technique that allows you to set a parent object equal to one or more of its children , After the assignment , The parent object can then behave differently depending on the properties of the child object currently assigned to it . To put it simply , In a word : Allows assigning a pointer of a subclass type to a pointer of a parent type .

JDK and JRE What's the difference?

  • JRE Its English name is Java Runtime Environment,Java Runtime environment . It mainly consists of two parts ,jvm Standard implementation and Java Some basic class libraries of . It is relative to the jvm Come on , What's more is part of Java Class library .
  • JDK Its English name is Java Development Kit,Java Development kit .jdk As a whole Java The core of development , It integrates jre And some handy gadgets . for example :javac.exe,java.exe,jar.exe etc. .

Here's another explanation JVM What is it?

  • JVM Its English name is Java Virtual Machine, Refers to Java virtual machine .Java Virtual machine is the core of cross platform implementation

For the most part ,JRE、JDK and JVM The relationship is as follows

Describe the difference between value passing and reference passing

If you want to really understand , You can refer to this article : https://www.zhihu.com/question/31203609

In a nutshell, it is

Value passed Copy a copy of the actual parameter to the function when it is called , In this case, if the function modifies the formal parameter passed by it , Will not affect the actual parameters

reference It refers to passing the address of the object directly to the function when calling the function , If you are modifying formal parameters , Will affect the value of the actual parameter .

== and equals What's the difference

== yes Java One of the operators in , It has two ways of comparison

  • about Basic data type Come on , == It's on both sides value Whether it is equal or not
public class DoubleCompareAndEquals {
Person person1 = new Person(24,"boy");
Person person2 = new Person(24,"girl");
int c = 10; private void doubleCompare(){ int a = 10;
int b = 10; System.out.println(a == b);
System.out.println(a == c);
System.out.println(person1.getId() == person2.getId()); }
}
  • about Reference type Come on , == It's on both sides quote Whether it is equal or not , That is to determine whether two objects point to the same memory area .
private void equals(){
System.out.println(person1.getName().equals(person2.getName()));
}

equals yes Java The parent class of all objects in , namely Object A method defined by a class . It can only compare objects , It indicates whether the values of both sides of the reference are equal . So remember , Is not to say that == The comparison is whether the references are equal ,equals The comparison is the value , This needs to be distinguished between the two .

equals As a comparison between objects, it has the following characteristics

  • reflexivity : For any non empty reference x Come on ,x.equals(x) Should return to true.
  • symmetry : For any non empty reference x and y Come on , if x.equals(y) by true, be y.equals(x) Also for the true.
  • Transitivity : For the value of any non null reference , There are three values ,x、y and z, If x.equals(y) return true,y.equals(z) return true, that x.equals(z) Should also return to true.
  • Uniformity : For any non empty reference x and y Come on , If x.equals(y) Equal words , Then they must always be equal .
  • Non emptiness : For the value of any non null reference x Come on ,x.equals(null) Must return false.

Java What are the basic data types in , How many bytes does each take up

stay Java in , The data type is only There are four categories and eight kinds

  • Integer type :byte、short、int、long

byte That's byte ,1 byte = 8 bits,byte The default value of is 0 ;

short Takes two bytes , That is to say 16 position ,1 short = 16 bits, Its default value is also 0 ;

int Take up four bytes , That is to say 32 position ,1 int = 32 bits, The default value is 0 ;

long Take up eight bytes , That is to say 64 position ,1 long = 64 bits, The default value is 0L;

So the byte size of integer type is long > int > short > byte

  • floating-point

Floating point has two data types :float and double

float It's a single precision floating point , Occupy 4 position ,1 float = 32 bits, The default value is 0.0f;

double It's a double precision floating point , Occupy 8 position ,1 double = 64 bits, The default value is 0.0d;

  • Character

The character type is char,char The type is a single 16 position Unicode character , The minimum is \u0000 ( That is to say 0 ), The maximum is \uffff ( That is to say 65535),char The data type can store any character , for example char a = 'A'.

  • Boolean type

Boolean means boolean,boolean There are only two values ,true Or is it false, It just means 1 position , The default value is false.

above x position They all refer to the occupation of memory .

String Medium equals How to rewrite

String It stands for Java Medium character string ,String Class is special , Its whole class is final Embellished , in other words ,String Cannot be inherited by any class , whatever modify String String method is to create a new string .

equals The method is Object Method of class definition ,Object Is the parent of all classes , And of course String,String Rewrote equals Method , Let's see how it was rewritten

  • First, we will judge the two strings to be compared, their quote Whether it is equal or not . If the references are equal , Go straight back to true , If not, continue with the following judgment
  • Then judge whether the object being compared is String Example , If not, go straight back false, If so , Compare the length of the two strings , If the length does not want to wait, then there is no need to compare ; If the length is the same , Will compare each of the strings character Whether it is equal or not , Once a character is not equal , It'll go straight back false.

Here's the flow chart

Here's another hint , You may be wondering when

if (this == anObject) {
return true;
}

How can this judgment statement return true? Because it's all strings , String comparison is not all heap space , Suddenly, I found that I would never leave , But you forget String.intern() Method , It represents concepts in different JDK There are different versions

stay JDK1.7 And subsequent calls intern The method is to determine whether there is a specified string in the runtime constant pool , If not , Just add the string to the constant pool , And returns the object in the constant pool .

The verification process is as follows

private void StringOverrideEquals(){
String s1 = "aaa";
String s2 = "aa" + new String("a");
String s3 = new String("aaa"); System.out.println(s1.intern().equals(s1));
System.out.println(s1.intern().equals(s2));
System.out.println(s3.intern().equals(s1)); }
  • First s1.intern.equals(s1) This will come back anyway true, because s1 When a string is created, it already exists in the constant pool .

  • Then the second statement returns false, because s1 Returns an object from a constant pool , and s2 The object returned is the object in the heap

  • The third sentence s3.intern.equals(s1), return true , because s3 Object although an object is created in the heap , however s3 Medium "aaa" Returns an object from a constant pool .

Why rewrite equals Method must override hashcode Method

equals Methods and hashCode All are Object The method defined in , They are often rewritten together .

equals Method is used to compare whether the object size is equal ,hashcode Method is used to judge each object hash A way to value . If only rewrite equals Method without overriding hashcode Method , It's likely to create two different objects , Their hashcode Also equal , Cause conflict . such as

String str1 = " conversation ";
String str2 = " important ";

Two of them hashcode equal , however equals It's not equal .

Let's take a look hashCode The official definition

In summary

  • If in Java Call the same object at run time hashCode After the method , No matter how many times you call , Should return the same hashCode, But in different Java In the program , perform hashCode Methods may return inconsistent values .
  • If I have two objects equals equal , that hashCode It has to be the same
  • If two objects equals It's not equal , that hashCode It could be the same , So we need to rewrite hashCode Method , Because you don't know hashCode The underlying structure of ( Anyway, I don't know , There is a big cow to teach ), So you need to rewrite hashCode Method , To generate different... For different objects hashCode value , This can improve the access speed of different objects .
  • hashCode This is usually achieved by converting the address to an integer .

two-object hashcode identical , that equals Whether it must be for true

This is not necessarily certain , Take a very simple example , You rewrote it hashcode Method , To calculate the remainder , So two objects hashcode It's likely to repeat , But there are two objects equals But not necessarily the same .

Even if you don't rewrite it hashcode Method , I'll give you a code example

String str1 = " conversation ";
String str2 = " important ";
System. out. println(String. format("str1:%d | str2:%d", str1. hashCode(),str2. hashCode()));
System. out. println(str1. equals(str2));

The output of the above two pieces of code is

str1:1179395 | str2:1179395

false

These two strings are equals Is not the same . in other words , Even if it is hashcode The same string ,equals It could be different .

String s1 = new String("abc") Several objects are created in memory

One or two ,String s1 It's a statement String Type of s1 Variable , It's not the object . Use new Keyword creates an object in the heap , Another object is abc , It creates... In the constant pool , So two objects are created ; If abc If it already exists in the constant pool , Then an object is created .

Please refer to another article of the author for details A different piece of String、StringBuffer、StringBuilder Detailed explanation

String Why is it immutable 、jdk In the source String How is it defined 、 Why is it designed this way? .

First of all, let's understand what is Immutable object , Immutable objects are created once , The internal state of its object cannot be modified , What do you mean ? In other words, immutable objects need to follow the following principles

  • The internal properties of immutable objects are final Of
  • The internal properties of immutable objects are private Of
  • Immutable objects cannot provide any way to modify the internal state 、setter No way
  • Immutable objects cannot be inherited and extended

Rather than ask String Why is it immutable , It's better to say how to put String Designed to be immutable .

String A class is an object , It is independent of Java Basic data types exist ,String You can think of it as a collection of strings ,String Is designed to final Of , Express String Once the object is created , Its value can no longer be modified , Any right String A method of creating a string value is to modify it .String After the object is created, it will exist in the runtime constant pool , The runtime constant pool is part of the method area ,JDK1.7 And moved it into the pile .

Immutable objects are not really immutable , Can pass Reflection To modify its internal properties and values , But generally we don't do this .

static What is the key word used for ? Talk about your understanding

static yes Java The most important keyword in ,static The concept of representation is Static , stay Java in ,static Mainly for

  • Modifying variables ,static The modified variable is called Static variables 、 Also known as Class variables , Class variables belong to class , For different classes ,static There's only one variable ,static The modified variable is in the method area ;static Modified variables can be passed directly through Class name . Variable name To visit , You don't have to instantiate classes to use again .
  • Modification methods ,static The method of modification is called Static methods , Static methods can go directly through Class name . Method name To use , Non static properties and methods cannot be used inside static methods
  • static Code blocks can be decorated , There are two main types , One is defined directly in a class , Use static{}, This is called Static code block , One is to define... In a class Static inner class , Use static class xxx To define .
  • static Can be used for static guided packets , By using import static xxx To achieve , This method is generally not recommended
  • static Can be used with singleton mode , The singleton pattern of thread safety is realized by double checking lock .

Please refer to this article for further understanding A little static It's hard to live in me ?

final What is the key word used for ? Talk about your understanding

final yes Java Keywords in , It means Immutable , stay Java in ,final Mainly for

  • decorator ,final Modified classes cannot be inherited , Not to be inherited means not to be used extends To inherit final Modified class .
  • Modifying variables ,final Modified variables cannot be rewritten , There are two meanings of not being rewritten , For basic data types ,final Decorated variable , Its value cannot be changed ,final Decorated object , Object references cannot be changed , But the properties inside the object can be modified .final The modified variable plays a role in a way immutable The effect of , therefore , Can be used to protect read-only data , Especially in concurrent programming , Because it's clear that we can't do it again final Variable assignment , It helps to reduce the extra synchronization overhead .
  • Modification methods ,final Methods that modify cannot be overridden .
  • final The modifier and Java Program performance optimization is not necessarily related to

What's the difference between an abstract class and an interface

Abstract classes and interfaces are Java Keywords in , Methods are allowed to be defined in both abstract classes and interfaces , It doesn't have to be implemented in a specific way . Both abstract classes and interfaces are allowed to be inherited , They are widely used in JDK And the source code of the framework , To implement polymorphism and different design patterns .

The difference is

  • Different levels of abstraction : class 、 abstract class 、 Interfaces are actually three different levels of abstraction , The order of abstraction is Interface > abstract class > class . In the interface , Only method definitions are allowed , No implementation of methods is allowed , Methods can be defined and implemented in abstract classes ; Only methods are allowed to be implemented in a class , The definition of a method is that it is not allowed to appear after a method {}
  • The keywords used are different : Class uses class To express ; Abstract class use abstract class To express ; Interface to use interface To express
  • Variable : Variables defined in an interface can only be public static constants , Variables in an abstract class are ordinary variables .

The difference between rewriting and overloading

stay Java in , Rewriting and overloading are different representations of the same method , Let's make a simple distinction between rewriting and overloading

  • The relationship between children and parents is different , Rewriting is different representations of children and parents , Overloading is a different representation in the same class ;
  • Different concepts , The method of subclass overriding parent class usually uses @override To express ; The method declaration and parameter type of the overridden method 、 The order must be exactly the same as the parent class ; Overloading is for concepts in the same class , It requires that the overloaded method must satisfy any of the following requirements : The order of method parameters , Number of parameters , The type of any parameter remains different .

Can constructors be overloaded , Can it be rewritten ?

This question tests your understanding of constructors .

We Java To create an object in is to call the construction method of the object , For example, the following code

InstanceObject IO = new InstanceObject() ; // A parameterless constructor was called 
InstanceObject IO = new InstanceObject(xxx) ; // Called a construction method with parameters

And what is the concept of overloading ?

It means that we can define some methods with the same name , These methods are distinguished by defining different input parameters , And then when I call ,JVM It will be based on different parameter styles , To choose the right way to execute .

in other words , The concept of overloading is more about identical Different descriptions of naming methods . So the above code is obviously overloaded , Because the name is the same , I can judge whether there are parameters to call different construction methods for initialization .

So can constructors be rewritten ? Let's look at rewriting first

Rewriting is a subclass's rewriting of the implementation process of the parent's accessible methods , Neither the return value nor the parameter can be changed . From the conceptual definition of rewriting, we know that constructors cannot be rewritten .

First , Constructor has no return value , Second point , The name of the constructor must match the name of the class .

You can't be in class A Written in public A(); In the class B It's also written in Chinese public A() Well , This obviously can't be compiled .

byte What is the range of phi , How to work it out

byte The range of phi is zero -128 -> 127 Between , Is the total 256 individual . One byte Type occupies a byte in the computer , So that is 8 bit, So the biggest thing is 2^7 = 1111 1111.

Java of use Complement code To represent binary numbers , The highest bit of the complement is the sign bit , For the highest position 0 It means a positive number , highest 1 A negative number , The complement of a positive number is its In itself , Because the highest bit is the sign bit , So a positive number means 0111 1111 , That is to say 127. The biggest negative number is 1111 1111, There are two things involved 0 , One +0 , One -0 ,+0 Return to a positive number , That is to say 0 ,-0 Categorize as negative , That is to say -128, therefore byte The range of -128 - 127.

HashMap and HashTable The difference between

The same thing

HashMap and HashTable It's all based on hash table , Every element inside is key-value Key value pair ,HashMap and HashTable It's all done Map、Cloneable、Serializable Interface .

Difference

  • The father is different :HashMap Inherited AbstractMap class , and HashTable Inherited Dictionary class

  • Different null values :HashMap Allow empty key and value value ,HashTable Empty is not allowed key and value value .HashMap Will be able to Null key As ordinary key treat . Don't allow null key repeat .

  • Thread safety :HashMap Not thread safe , If multiple external operations are modified at the same time HashMap For example add Or is it delete, You have to synchronize , Just right key perhaps value Is not an operation to change the data structure . You can choose to construct thread safe Map such as Collections.synchronizedMap Or is it ConcurrentHashMap. and HashTable Is itself a thread safe container .
  • Performance aspect : although HashMap and HashTable It's all based on Single chain list Of , however HashMap Conduct put perhaps get

    3w The long words burst the liver Java Basic interview questions ! That's too much !!! More articles about

    1. The one closest to the real interview Java Basic interview questions

      This is a Java Basic interview questions . Online about Java There are so many interview questions , But I think most of them are not practical , There are a lot of questions that the interviewer won't ask , Those technical problems that have been divorced from the actual development . And this information comes from a personal opinion that ...

    2. classical Java A collection of basic interview questions

      classical Java A collection of basic interview questions , Welcome to collect and share . problem : If main Method is declared as private What will happen ? answer : It compiles normally , But when it runs, it will prompt ”main The method is not public Of ”. problem :Java The biography in ...

    3. Very comprehensive java Basic written test questions

      Here is java Basic written test questions , At that time, I went to the written test , Did 1 Hours (80 Multiple choice questions , There's no time for the short answer questions ), It turns out to be scary , It's frustrating , Finally, I was fooled by the interviewer to go to training , ha-ha . I secretly got the interview questions down , Use it to learn , And I hope I can help you ...

    4. Java Basic computer test questions

      package day8;import java.util.Scanner;/** * Java Basic computer test questions  * @author:lyrand * */public class convert {   ...

    5. 100 Avenue Java Basic interview questions ( Answer attached )

      Every step is worth a thousand miles , It's constantly collected and updated here Java Basic interview questions , So far... Has been collected 100 topic . 1. What is? B/S framework ? What is? C/S framework B/S(Browser/Server), browser / Server program C/S(Cl ...

    6. Big data learning --day04( Selection structure 、 Loop structure 、 big data java Basic interview questions )

      Selection structure . Loop structure . big data java Basic interview questions switch: Be careful : byte short int char String(jdk1.7 Support ) It can't be long float double boolea ...

    7. newest 28 Avenue java Basic interview questions - On

      28 Avenue java Basic interview questions 1. What are the features of object-oriented ? answer : The characteristics of object-oriented are as follows : abstract : Abstract is the process of summing up the common characteristics of a class of objects to construct a class , Including data abstraction and behavior abstraction . Abstractions focus only on where objects are ...

    8. 28 Avenue java Basic interview questions - Next

      28 Avenue java Basic interview questions 15.Java How to deal with language exceptions , keyword :throws.throw.try.catch.finally How to use them respectively ? answer :Java Object oriented method of exception handling , Put all kinds of No ...

    9. Java Basic interview questions ( One )

      Java Basic interview questions One . object-oriented programming (OOP) 7 Two . common Java problem 7 2.1. What is? Java virtual machine ? Why? Java Be called “ Platform independent programming language ”? 7 2.2.JDK and JRE What's the difference ? ...

    10. 2w Long writing ! A set of hands Java Basic interview questions

      Java The basic chapter Java What are the characteristics of Concurrent : You can execute many statements in it , You don't have to do it all at once Object oriented : Class based and object-oriented programming languages . Independent : Support one-time writing , Independent programming languages that run everywhere , That is, the compiled generation ...

    Random recommendation

    1. Java Concurrent programming :volatile keyword

      from :http://www.cnblogs.com/aigongsi/archive/2012/04/01/2429166.html Actually Java Language supports multithreading , To solve the problem of thread concurrency , Inside the language ...

    2. win7 spot IE The browser can't open

      The phenomenon :win7 System Open unresponsive , Install other browsers to use , But very slowly , And there is a password box that can't be entered Handle : WIN7 Delete add program , Choose on or off windows function , Among them IE11 I've checked , Then clear the check , There will be a mention of ...

    3. [C#] C# Knowledge review - Lambda

      C# Knowledge review - Lambda order It's the eleventh Greek letter , One with frustration . but . lonely . Low key and other popular symbols , It also indicates a section called “ half-life ” The game of . however , This time I'm talking about C# Medium Lambda. Catalog L ...

    4. JHipster Generate the application stack of microservice architecture ( Two )- Authentication microservice example

      This series demonstrates how to use JHipster Generate a microservice architecture style application stack . Environmental requirements : Install well JHipster Development environment CentOS 7.4( Reference here ) Application stack name :appstack Certified microservices : uaa trade ...

    5. C++:STL vector:sizeof(vector)

      Original address :http://blog.csdn.net/zcsylj/article/details/7857009 int Its size is 4, Definition vector<int> vec,vec There's an element in , ...

    6. hdu4870 Gauss elimination

      The question One man plays the game ,rating Yes p Probability To add 50 branch Yes 1-p The probability of is x-100 branch The maximum value is 1000 The minimum value is 0 There are two numbers Each time you submit it with a smaller number , The calculation finally arrives at 1000 What's the expected number of fields ...

    7. Codeforces Round #546 (Div. 2) E - Nastya Hasn&#39;t Written a Legend

      This is a line segment tree of a thief The line segment tree maintains Interval and a[i - j] First of all, for update You can find the location of secondly update When the lazy Compare skills For example, the update is l-r paragraph , What's added is c So the value of this paragraph is : ...

    8. LoadRunner FAQ2

      LR The definition and assignment of parameters in 1. Parameter assignment and value lr_save_string("hello world","param"); lr_eval_string(&qu ...

    9. python The old boy of learning python The ninth issue of the whole stack _day022 Summary of knowledge points —— First acquaintance with object orientation

      One . The introduction of object-oriented # Man dog war def person(name,HP,aggr,sex): person = { 'name':name, # nickname 'HP':HP, # Health value 'aggr':ag ...

    10. easyui datagrid How to get the text box of each line

      stay return '<input type="text" name="txtCount" class="inputvalue"/> ...