Here are some basic interview questions for Java interns:
(Recommendations for more related interview questions: java interview questions and answers)
1. What exactly is Java?
Java is an object-oriented programming language. It was launched by SUN (Stanford University Network) in 1995 and was acquired by ORACLE in 2010.
2. Java is so popular. What are its characteristics?
Java is a cross-platform language (compile once, execute everywhere).
For example: Java writes the hello.java file on the Windows platform -> compiles it into a hello.class file; installs the corresponding Java virtual machine in different operating systems (all system platforms must have a JVM to run Java compilation file), you can run it directly
3. Three technical architectures of Java
The three basic technical architectures of Java are: JavaSE, JavaEE, JavaME
JavaSE: It is the basis of JavaEE and JavaME and is very flat
JavaEE: A platform suitable for developers, mainly for the development of WEB application systems
JavaME: Development of small electronic consumer products; such as: APP on mobile phones; Language (elevator, sweeping robot)
4. Points to note when writing Java programs
(1) Java is case-sensitive, and the corresponding Hello and hello are different
(2) For all Java classes, the first letter of the class should be capitalized. If the class name consists of multiple words, the first letter of each word should be capitalized. For example: MyFirstJava
(3) The first letter of all Java method names should be lowercase. If it consists of multiple words, the first letter of the following words should be capitalized. For example: findByName
(4). The source file must be consistent with the class name
5. What basic data types does Java have?
Java has eight basic data types: byte, short, int, long, float, double, char, boolean (six number types: four integer types (byte, short, int, long), two floating point types (float, double))
byte: The data type is an 8-bit, signed integer represented by two's complement. Used to save space in large arrays. The space occupied by byte variables is only one-quarter of the int type. Corresponding packaging class: Byte, value (27- 27-1)
short: The data type is 16 bits, binary complement The integer represented by the code. The short data type can also save space like byte. A short variable is one-half the size of an int type variable. Corresponding packaging class: Short. Value (215- 215-1)
int: The data type is 32-bit, signed, expressed in two’s complement integer. General integer variables default to type int. Value (231- 231-1)
long: The data type is 64 bits, signed, expressed in two’s complement integer. This data type is mainly used on systems that need to compare large integers. Value (263-263-1)
float: The data type is a single-precision, 32-bit floating point number. float can save memory space when storing large floating point arrays. The default value is 0.0f. Floating point numbers cannot be used to represent precise values such as currency.
double: The data type is a double-precision, 64-bit floating point number. The default type of floating point numbers is double. The double type also cannot represent precise values, such as currency. The default value is 0.0d.
char: The type is a single 16-bit Unicode character. The char data type can store any character. But it can only store one character
boolean: The data type represents one-digit information and has only two values: true and false. This type is only used as a flag to record true\false situations, and the default value is false.
6. What are the access permission modifiers?
Access rights modifiers include: public, protected, default (not written by default), private
public: maximum access rights, used for external interfaces
protected: used to protect subclasses passed to A thing inherited by subclasses
default: designed for access to this package
private: access rights are limited to the inside of the class and cannot be accessed by outer classes
7. How to run a program?
All Java programs are executed by the public static viod main(String []args){} method.
8. What are the objects often mentioned in Java?
An object is an instance of a class, with state and behavior.
For example: a dog is an object, its status includes: color, name, breed; behaviors include: wagging tail, barking, eating, etc.
Software objects also have state and behavior. The objects of software are attributes, and behaviors are reflected through methods
9. What is a class?
A class is a template, which describes the behavior and status of a class of objects. A class can have multiple methods
10. How to construct the methods in a class?
When creating an object, at least one constructor must be called. The name of the constructor must be the same as the class. A class can have multiple constructors.
11. How to create an object?
Objects are created based on classes. In Java, use the keyword new to create a new object. Three steps are required to create an object:
Declaration: Declare an object, including the name of the object and the type of the object.
Instantiation: Use the keyword new to create an object
Initialization: When using new to create an object, the constructor method will be called to initialize the object
12. Source file Are there declaration rules for declarations?
(1) The source file can only have one public class
(2) There can be multiple non-public classes
(3) The name of the source file must have the same name as the class
(4) If the source file is defined in a package, the import package should be on the first line of the source file.
(5) If the source file contains an import statement, then it is defined between the package statement and the class. If there is no package statement, the import statement should be at the front of the source file
(6), Import statement and package statement Valid for all classes defined in the source file. In the same source file, different package declarations cannot be defined for different classes
13. What are variables?
Variables apply for memory to store values. In other words, when creating a variable, you need to apply for space in memory. The memory management system allocates space according to the type of the variable, and the allocated space can only be used to store data of that type.
14. What is the function of defining variables?
By defining different types, it can be used to store different types of numbers (such as integers, decimals, characters)
15. Can the various types be converted?
From low to high:
byte, short, char——>int——>long——>float——>double
can be converted automatically.
(1). Type conversion cannot be performed on the boolean type.
(2) Object types cannot be converted into objects of unrelated classes.
(3) Types with large capacity can be converted into types with small capacity. Must cast (type) value type. The conversion process may cause overflow or loss of precision
(4) Automatic type conversion must satisfy that the number of digits of the data before conversion is smaller than the number of digits of the data type after conversion.
(5). The conversion from floating point to integer is obtained directly by discarding the decimal part instead of rounding.
For example: (int)23.7 == 23, (int)-23.7 == -23
16. What are the java operators?
(·1) Arithmetic operators: similar to those in mathematics, mainly - * \ % -- (a first adds 1 to the original basis and then performs the operation, a– operates first and then subtracts 1 )
(2) Logical operators: mainly && ||!
(3) Assignment operator: It mainly plays the role of an assignment. Commonly used ones are = = -=
(4) Conditional operator: It is also called the ternary operator. This operator has three operands and needs to evaluate the value of a Boolean expression. The main purpose of this operator is to determine which value should be assigned to the variable
For example: int a = (20==40)? 30 : 50;
17. The three main loop structures of java yes?
There are three main loop structures in Java: while loop, do...while loop, for loop
(1). while is the most basic loop, and its structure is:
while(Boolean Expression){
//Loop content
}
As long as the Boolean expression is true, the loop will continue.
(2) The do...while loop is familiar to the while loop. The difference is that the do...while loop will be executed at least once.
do{
//Loop content
}while (Boolean expression)
(3). The number of times the for loop is executed is determined before execution
for (initialization ;Boolean expression; update){
//Code statement
}
18. Are there any keywords for loop structures?
Mainly include: break and continue;
break: mainly used in loop statements or switch statements to jump out of the entire statement block; break jumps out of the current loop and continues to execute the statements below the loop.
continue: Applicable to any loop control structure, its function is to allow the program to immediately jump to the next iteration of the loop. In the for loop, the continue statement causes the program to jump immediately to the update statement.
In while and do...while loops, the program immediately jumps to the judgment statement of the Boolean expression.
19. What is the Number class?
When a built-in data type is used as an object, the compiler will box the built-in type into a wrapper class. Number class belongs to java.lang package. All wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number.
20. What does the Math class in Java look like?
Contains properties and methods for performing basic mathematical operations, such as elementary exponents, objects, square roots, and trigonometric functions. Math methods are all defined in static form. It can be called directly in the main function through the Math class.
21. What is the difference between floor, round and ceiling in Math?
ceil: Returns the smallest integer greater than or equal to the guidance parameter (for example: Math.ceil(23.2) ==24 instead of rounding)
floor: Returns the largest integer less than or equal to the guidance parameter (for example: Math.ceil(23.7) ==23 instead of rounding)
round: It means rounding, the algorithm is Math.round(x 0.5), that is, add 0.5 to the original number and then round down. So, Math.round(11.4) is equal to 11, Math.round(11.5) is equal to 12, and Math.round(-11.5) is equal to -11.
22. What is the Character class? What are the methods of this class?
Character: It is a wrapper class provided by the Java language for the built-in basic data type char.
The main methods of Character are: isLetter()—whether it is a letter; toString—returns the length of the string, the string length is only 1; isUpperCase()—whether it is an uppercase letter; isLowerCase()—whether are lowercase letters.
23. What are the escape characters represented by characters preceded by a backslash (\)?
Commonly used escape characters are: \t (insert a tab key at this point in the text)
\d (insert a back key at this point in the text)
\n (insert a tab key at this point in the text) Insert a newline)
\r (Insert a carriage return at this point in the text)
24. What are the precautions for Java's String class?
Strings are objects in Java, and Java provides the String class to create and manipulate strings. The String class cannot be changed. Once a String object is created, its value cannot be changed. If you need to modify the string, you should use the StringBuffer or StringBuilder class.
25. What is the difference between length() method, length attribute and size() method?
The length() method is for strings. If you want the length of a string, you must use its length() method;
The length() attribute is for arrays in Java. , if you require the length of the array, you can use its length attribute;
size() in java is for generic collections. If you want to see how many elements this generic has, just call this method to check!
26. What are the methods of connecting strings?
There are two types:
(1), String 1.concat (String 2)
(2), more commonly used is to use the ' ' operation to concatenate strings, such as: " Hello" "Word" "!";
27. What is the difference between the StringBuffer and StringBuilder classes in Java?
The StringBuilder class was proposed in Java 5. The biggest difference between it and StringBuffer is that the StringBuilder method is not thread-safe (cannot be accessed synchronously). Since StringBuilder has a speed advantage over StringBuffer, in most cases Use StringBuilder. However, in cases where the application requires linear safety, the StringBuffer class must be used.
28. How does StringBuffer implement object modification?
String Buffer mainly has the append() method to complete the connection, the insert() method to complete the addition; the reverse() method to complete the inversion; the replace() method to complete the replacement.
Such as: buf.append("hi");
buf.insert(0,"Hello"); //Add before the first content
buf.insert(buf.length,'Hello '); //Insert data at the end
String str = buf.reverse().toString(); //Reverse the content and convert it to a string
buf.replace(6,11,"yes ”); //Replace the content of word
29. Can arrays be passed as parameters to methods?
Yes
30. How to get the current time and customize the time?
Print the current time: Data data = new Date(); data is the current time!
Set date and time format, SimpleDateFormat
SimpleDateFormat sc = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
System.out.printf(sc.format (Time to convert))
31. How does Java sleep?
Sleep() causes the current thread to enter a stagnant state (blocking the current process) and gives up the use of the CPU. The purpose is to prevent the current thread from occupying the CPU resources obtained by the thread alone, leaving a certain amount of time for Opportunity for other threads to execute. You can put the program to sleep for a few milliseconds. Tread.sleep(1000*3) //Sleep for 3 seconds
32. How to set the specific part of the date format, such as year, month, day, day, minute and second?
is to use the Calender class. The Calender class is an abstract class that implements objects of specific subclasses in actual use. The process of creating objects is transparent to programmers, and only needs to be created using the getInstance method.
#33. Are there any classes or methods to use?
The java.util.regex package mainly includes the following three classes:
Pattern class: The Pattern object is a compiled representation of a regular expression. The Pattern class has no public constructor. To create a Pattern object, one must first call its public static compiled method, which returns a Pattern object.
Matcher class: The Matcher object is an engine that compiles and matches input strings.
PatternSyntaxExeption: PatternSyntaxExeption is a non-mandatory exception class that represents a syntax error in a regular expression pattern.
34. What is the connection between constructors and methods?
The concept of constructor method: When creating an object, the system will automatically call the constructor method. When there is no custom constructor, the system will call the default constructor. Constructors can be overloaded but cannot be rewritten. Different constructors have the same name but different parameter lists. The parameter list is the basis and standard for identification, similar to a person's name, which may be the same but the ID card is different.
When customizing the constructor, the system automatically matches the constructor to initialize the object based on the type and quantity of parameters passed in.
35. What is the Scanner class? How to create a Scanner object
java.util.Scanner is a new feature of java5. We can get input from the user.
Scanner sc = new Scanner();
36. What is the difference between the next() and nextLine() methods of the Scanner class to obtain the input string?
next():
(1). The input must be completed only after valid characters are read;
(2) If a blank is encountered between valid characters for input, the input will be terminated. Automatically removed;
(3) Only by entering valid characters can the space entered later be used as a separator or terminator;
(4) Next() cannot obtain a string with spaces;
nextLine ():
(1), with Enter as the end character, that is, enter all characters before the carriage return;
(2), you can get blanks;
37, Java three What type of exception is it?
Check-time exception: The most common checked exceptions are exceptions caused by user errors or problems, which cannot be foreseen by the programmer. For example, when you want to open a file that does not exist, an exception occurs. These exceptions cannot be simply ignored at compile time.
Runtime exceptions: Runtime exceptions are exceptions that can be avoided by programmers. In contrast to checked exceptions, runtime exceptions can be ignored at compile time.
Error: Errors are not exceptions, but problems out of the programmer's control. Errors are usually ignored in the code. For example: when the stack overflows, an error occurs that cannot be checked during compilation.
All exception types in Java are subclasses of the built-in class java.lang.Throwable class, that is, Throwable is located at the top level of the exception class hierarchy. There are two exception branches under the Throwable class, Exception and Error, as shown in the figure.
38. What is the difference between exception and error?
All exceptions inherit the Throwable class, which means that all exceptions are an object.
Generally speaking, exceptions can be divided into two parts:
(1) Error: refers to an error that cannot be handled by the program, indicating a major error that occurs when the application is running. For example, OutOfMemoryError that occurs when jvm is running and the port is occupied when programming Socket and other errors that cannot be handled by the program
(2) Exception: Exceptions can be divided into runtime exceptions and compilation exceptions. There are two main exception classes. Subclasses: IOException class and RuntimeException class
39. What is catching exceptions?
Use the try and catch keywords to catch exceptions, and place the try/catch code block where the exception may occur. The code within the try/catch block becomes protected code.
40. What is the difference between throws and throw keywords?
If a method does not catch a checked exception, then the method must be declared using the throws keyword. The throws keyword is placed at the end of the method signature. You can also use throw to throw an exception, whether it is the latest instantiation or just caught.
A method can be declared to throw multiple exceptions, separated by commas.
41. How to customize exceptions in Java?
You can write your own exception class:
(1). All exceptions must be subclasses of the Throwable class;
(2) If you want to write a check-time exception, you need to inherit Exception ;
(3) If you need to write a runtime exception, you need to inherit the RuntimeException() exception
42. What is inheritance? What are the characteristics of inheritance?
Inheritance is when a subclass inherits the characteristics and behaviors of the parent class, so that the subclass object (instance) has the instance fields and methods of the parent class, or the subclass inherits the methods from the parent class, so that the subclass has the same characteristics as the parent class the behavior of.
Features:
(1). The subclass has the non-private attributes and methods of the parent class;
(2) The subclass can have its own attributes and methods, that is, the subclass can extend the parent class. ;
(3) Subclasses can have their own way to implement the methods of the parent class;
(4) Java inheritance can only be single inheritance, but multiple inheritance is possible. Single inheritance means that a subclass can only inherit A parent class, multiple inheritance is: A inherits B, B inherits C, so according to the relationship, class C is the parent class of class B, and B is the parent class of A. This is a feature of Java inheritance difference from c.
43. What are the keywords of inheritance?
Inheritance can be achieved using the two keywords extends and Implements. Moreover, all classes inherit from java.lang.Object. When a class does not have the inherited keyword, it inherits the Object class by default (this class is in the java.lang package, so no package import is needed).
super keyword: The super keyword can be used to access parent class members and is used to refer to the parent class inherited by the current object.
this keyword: refers to a reference to itself.
final keyword: Declaring a class can define the class as a class that cannot be inherited, that is, a final class; or it can be used to modify a method, which cannot be overridden by subclasses
44. What are the characteristics of the constructor of the parent class?
Subclasses cannot inherit the constructor (constructor and constructor (with parameters)) of the parent class. However, if the constructor of the parent class has parameters, they must be explicitly declared in the constructor of the subclass. The constructor of the parent class is called through the supper keyword and the appropriate parameter list:
If the parent class has a no-argument constructor, use it in the constructor of the subclass It is not necessary for supper to call the parent class. If the super keyword is not used, the system will automatically call the parameterless constructor of the parent class.
45. What is override, what is overload, and what is the difference between them?
Rewrite: The subclass rewrites and writes the implementation process of the method of the parent class that allows access to . The return value and parameters cannot be changed, that is, the shell cannot Change, core change. The advantage of overriding is that subclasses can customize their own behavior as needed. In other words, subclasses can implement the methods of the parent class as needed. Overriding methods cannot throw checked exceptions or exceptions that are broader than the overriding method declaration.
Overloading: Overloading is in a class, the method name is the same, but the parameters are different, and the return type can be the same or different. Each overloaded method (or constructor) must have a unique list of parameter types. The most common one is constructor overloading.
Difference: Method rewriting and overloading are different manifestations of Java polymorphism. Rewriting is a manifestation of polymorphism between parent classes and subclasses. Overloading can be understood as polymorphism. the specific expression of the state.
(1) Method overloading is a class that defines multiple methods with the same name and different parameters or the same number of parameters, different types and different orders, which becomes an overloading of the method.
(2) Method overriding is a method that has the same name as the parent class method in the subclass, and the number and type of parameters are the same, and the return value is also the same, which is called rewriting
(3) , Method overloading is a polymorphic manifestation of a class, and method overriding is a polymorphic manifestation of a subclass and a parent class.
46. What is an abstract class? How to define abstract classes and methods?
Abstract class: Except that abstract classes cannot instantiate objects, other functions of the class still exist. The access methods of member variables, member methods and constructors are different from ordinary classes. Since abstract classes cannot instantiate objects, abstract classes must be inherited before they can be used:
The parent class contains common methods for collections of subclasses, but because The parent class itself is abstract, so these methods cannot be used. In Java, abstract classes represent an inheritance relationship. A class can only inherit one abstract class, but a class can implement multiple interfaces.
Define abstract class: Use abstract class to define abstract classes in the Java language.
Define abstract method: If you want to design a class that contains a special member method, and the specific implementation of the method is determined by its subclass, then you can declare the method in the parent class method. The Abstract keyword is also used to declare abstract methods. Abstract methods only contain a method name and no method body (abstract methods are not defined, and the method name is directly followed by a semicolon instead of curly braces). If a class has an abstract method, it must be an abstract class
47. What are the consequences of declaring an abstract method?
(1) If a class contains abstract methods, then the class must be an abstract class
(2) Any subclass must override the abstract method of the parent class, or declare itself as an abstract class .
(Recommended tutorial: java course)
48. What is encapsulation and what are its advantages? How is Java encapsulated?
Encapsulation: refers to a method of packaging and hiding the implementation details of an abstract functional interface. Encapsulation can be thought of as a protective barrier that prevents the code and data of the class from being randomly accessed by code defined by the external class.
Advantages:
(1) Good encapsulation can reduce coupling;
(2) The structure inside the class can be modified freely;
(3) Members can be modified Variables for more precise control;
(4), Hide information and implementation details;
Encapsulate :
(1) Modify the visibility of attributes to limit access to attributes (Generally limited to private);
(2) Provide public method access to the external interface for each value attribute. That is, for access to private properties. (Usually these methods are called getter and setter methods, such as entity classes under development)
49. What are the similarities and differences between interfaces and classes?
Same:
(1), an interface can have multiple methods;
(2), the interface file is saved in a file ending with .java
(3), the interface Bytecode files are saved in files ending with .class
Differences:
(1) Interfaces cannot instantiate objects (same as abstract classes)
(2) Interfaces have no construction methods;
(3) All methods in the interface must be abstract methods;
(4) The interface cannot contain member variables;
(5) The interface cannot be inherited (implemented by the class);
( 6). Interface supports multiple inheritance;
50. What is the difference between abstract class and interface?
(1) Methods in abstract classes can have method bodies, which means they can implement the specific functions of the methods, but methods in interfaces cannot.
(2). Member variables in abstract classes can be of various types, while member variables in interfaces can only be of public static final type;
(3) Interfaces cannot contain static code blocks and Static methods (methods modified with static), while abstract classes can have static code blocks and static methods
(4). A class can only inherit one abstract class, and a class can implement multiple interfaces.
Interfaces are abstract. When declaring an interface, you do not need to use the abstract keyword. Each method in the interface is also implicitly abstract, and there is no need to add abstract when declaring it. Methods in an interface There are classes in the interface that implement the interface to implement the methods in the interface.
As a fresh Java student, the basics of Java are crucial and will definitely be asked. If you can master these basics well, then the chance of passing our interview will be very slim. Let’s review the basics of Java together!
1、Java到底是什么东西?
Java是一款面向对象的编程语言,是SUN(斯坦福大学网络公司)1995年推出的,在2010年被ORACLE收购
2、Java这么热门它有什么特点呢?
Java是跨平台性的语言(一处编译,到处执行)。
例如:Java在Windows平台中编写hello.java文件—>编译成hello.class文件;在不同的操作系统中安装对应的Java虚拟机(所有的系统平台必须有JVM才可以运行Java编译的文件),就可以直接运行
3、Java的三种技术架构
Java三种基本技术架构分别是:JavaSE、JavaEE、JavaME
JavaSE:是JavaEE与JavaME的基础,是非常平面话的
JavaEE:适合开发者的平台主要针对WEB应用系统的开发
JavaME:开发小型的电子消费品;比如:手机上的APP;机器上的语言(电梯、扫地机器人)
4、在编写Java程序时的注意点
(1)、Java是大小写敏感的,对应的Hello和hello是不同的
(2)、Java对于所有的类来说,类的首字母应该大写、若类名有多个单词组成,则每个单词首字母都应该大写。如:MyFirstJava
(3)、Java所有的方法名首字母都应该小写,如有多个单词组成,则后面的单词首字母要大写。如:findByName
(4)、源文件必须与类名一致
5、Java有那几个基本数据类型
Java有八种基本数据类型:byte、short、int、long、float、double、char、boolean(六种数字类型:四个整型(byte、short、int、long),两个浮点型(float、double))
byte:数据类型是8位、有符号的,以二进制补码表示的整数。用于大型数组中节约空间,用为byte变量占用的空间只有int类型的四分之一。对应的包装类:Byte,取值(27- 27-1)
short:数据类型是16位、以二进制补码表示的整数。short数据类型也可以像byte那样节约空间。一个short变量是int型变量的二分之一。对应的包装类:Short。取值(215- 215-1)
int:数据类型是32位、有符号的,以二进制补码表示的整数。一般的整型变量默认为int类型。取值(231- 231-1)
long:数据类型是64位,有符号的,以二进制补码表示的整数。这种数据类型主要使用在需要比较大整数的系统上。取值(263- 263-1)
float:数据类型是单精度、32位的浮点数。float在存储大型浮点数组的时候可以节约内存空间。默认值是0.0f。浮点数不能用来表示精确的值,如货币。
double:数据类型是双精度、64位的浮点数。浮点数的默认类型位double类型。double类型同样不能表示精确的值,如货币。默认值是0.0d。
char:类型是一个单一的16位Unicode字符。char数据类型可以存储任何字符。但只能存储一个字符
boolean:数据类型表示一位数字信息,只有两个取值:true和false。这种类型只作为一种标志来记录true\false情况,默认值是false。
6、访问权限修饰符分别是什么?
访问权限修饰符有:public、protected、default(默认不写)、private
public:最大访问权,用于对外的接口
protected:用于保护子类传递给子类一种继承的东西
default:是针对与本包的访问而设计的
private:访问权限仅限于类的内部,不能被外层的类访问
7、怎样才能运行一个程序?
所有的Java程序都是由public static viod main(String []args){}方法开始执行。
8. What are the objects often mentioned in Java?
An object is an instance of a class, with state and behavior.
For example: a dog is an object, its status includes: color, name, breed; behaviors include: wagging tail, barking, eating, etc.
Software objects also have state and behavior. The objects of software are attributes, and behaviors are reflected through methods
9. What is a class?
A class is a template, which describes the behavior and status of a class of objects. A class can have multiple methods
10. How to construct the methods in a class?
When creating an object, at least one constructor must be called. The name of the constructor must be the same as the class. A class can have multiple constructors.
11. How to create an object?
Objects are created based on classes. In Java, use the keyword new to create a new object. Three steps are required to create an object:
Declaration: Declare an object, including the name of the object and the type of the object.
Instantiation: Use the keyword new to create an object
Initialization: When using new to create an object, the constructor method will be called to initialize the object
12. Source file Are there declaration rules for declarations?
(1) The source file can only have one public class
(2) There can be multiple non-public classes
(3) The name of the source file must have the same name as the class
(4) If the source file is defined in a package, the import package should be on the first line of the source file.
(5) If the source file contains an import statement, then it is defined between the package statement and the class. If there is no package statement, the import statement should be at the front of the source file
(6), Import statement and package statement Valid for all classes defined in the source file. In the same source file, different package declarations cannot be defined for different classes
13. What are variables?
Variables apply for memory to store values. In other words, when creating a variable, you need to apply for space in memory. The memory management system allocates space according to the type of the variable, and the allocated space can only be used to store data of that type.
14. What is the function of defining variables?
By defining different types, it can be used to store different types of numbers (such as integers, decimals, characters)
15. Can the various types be converted?
From low to high:
byte, short, char——>int——>long——>float——>double
can be converted automatically.
(1). Type conversion cannot be performed on the boolean type.
(2) Object types cannot be converted into objects of unrelated classes.
(3) Types with large capacity can be converted into types with small capacity. Must cast (type) value type. The conversion process may cause overflow or loss of precision
(4) Automatic type conversion must satisfy that the number of digits of the data before conversion is smaller than the number of digits of the data type after conversion.
(5). The conversion from floating point to integer is obtained directly by discarding the decimal part instead of rounding.
For example: (int)23.7 == 23, (int)-23.7 == -23
16. What are the java operators?
(·1) Arithmetic operators: similar to those in mathematics, mainly - * \ % -- (a first adds 1 to the original basis and then performs the operation, a– operates first and then subtracts 1 )
(2) Logical operators: mainly && ||!
(3) Assignment operator: It mainly plays the role of an assignment. Commonly used ones are = = -=
(4) Conditional operator: It is also called the ternary operator. This operator has three operands and needs to evaluate the value of a Boolean expression. The main purpose of this operator is to determine which value should be assigned to the variable
For example: int a = (20==40)? 30 : 50;
17. The three main loop structures of java yes?
There are three main loop structures in Java: while loop, do...while loop, for loop
(1). while is the most basic loop, and its structure is:
while(Boolean Expression){
//Loop content
}
As long as the Boolean expression is true, the loop will continue.
(2) The do...while loop is familiar to the while loop. The difference is that the do...while loop will be executed at least once.
do{
//Loop content
}while (Boolean expression)
(3). The number of times the for loop is executed is determined before execution
for (initialization ;Boolean expression; update){
//Code statement
}
18. Are there any keywords for loop structures?
Mainly include: break and continue;
break: mainly used in loop statements or switch statements to jump out of the entire statement block; break jumps out of the current loop and continues to execute the statements below the loop.
continue: Applicable to any loop control structure, its function is to allow the program to immediately jump to the next iteration of the loop. In the for loop, the continue statement causes the program to jump immediately to the update statement.
In while and do...while loops, the program immediately jumps to the judgment statement of the Boolean expression.
19. What is the Number class?
When a built-in data type is used as an object, the compiler will box the built-in type into a wrapper class. Number class belongs to java.lang package. All wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number.
20. What does the Math class in Java look like?
Contains properties and methods for performing basic mathematical operations, such as elementary exponents, objects, square roots, and trigonometric functions. Math methods are all defined in static form. It can be called directly in the main function through the Math class.
21. What is the difference between floor, round and ceiling in Math?
ceil: Returns the smallest integer greater than or equal to the guidance parameter (for example: Math.ceil(23.2) ==24 instead of rounding)
floor: Returns the largest integer less than or equal to the guidance parameter (for example: Math.ceil(23.7) ==23 instead of rounding)
round: It means rounding, the algorithm is Math.round(x 0.5), that is, add 0.5 to the original number and then round down. So, Math.round(11.4) is equal to 11, Math.round(11.5) is equal to 12, and Math.round(-11.5) is equal to -11.
22. What is the Character class? What are the methods of this class?
Character: It is a wrapper class provided by the Java language for the built-in basic data type char.
The main methods of Character are: isLetter()—whether it is a letter; toString—returns the length of the string, the string length is only 1; isUpperCase()—whether it is an uppercase letter; isLowerCase()—whether are lowercase letters.
23. What are the escape characters represented by characters preceded by a backslash (\)?
Commonly used escape characters are: \t (insert a tab key at this point in the text)
\d (insert a back key at this point in the text)
\n (insert a tab key at this point in the text) Insert a newline)
\r (Insert a carriage return at this point in the text)
24. What are the precautions for Java's String class?
Strings are objects in Java, and Java provides the String class to create and manipulate strings. The String class cannot be changed. Once a String object is created, its value cannot be changed. If you need to modify the string, you should use the StringBuffer or StringBuilder class.
25. What is the difference between length() method, length attribute and size() method?
The length() method is for strings. If you want the length of a string, you must use its length() method;
The length() attribute is for arrays in Java. , if you require the length of the array, you can use its length attribute;
size() in java is for generic collections. If you want to see how many elements this generic has, just call this method to check!
26. What are the methods of connecting strings?
There are two types:
(1), String 1.concat (String 2)
(2), more commonly used is to use the ' ' operation to concatenate strings, such as: " Hello" "Word" "!";
27. What is the difference between the StringBuffer and StringBuilder classes in Java?
The StringBuilder class was proposed in Java 5. The biggest difference between it and StringBuffer is that the StringBuilder method is not thread-safe (cannot be accessed synchronously). Since StringBuilder has a speed advantage over StringBuffer, in most cases Use StringBuilder. However, in cases where the application requires linear safety, the StringBuffer class must be used.
28. How does StringBuffer implement object modification?
String Buffer mainly has the append() method to complete the connection, the insert() method to complete the addition; the reverse() method to complete the inversion; the replace() method to complete the replacement.
Such as: buf.append("hi");
buf.insert(0,"Hello"); //Add before the first content
buf.insert(buf.length,'Hello '); //Insert data at the end
String str = buf.reverse().toString(); //Reverse the content and convert it to a string
buf.replace(6,11,"yes ”); //Replace the content of word
29. Can arrays be passed as parameters to methods?
Yes
30. How to get the current time and customize the time?
Print the current time: Data data = new Date(); data is the current time!
Set date and time format, SimpleDateFormat
SimpleDateFormat sc = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
System.out.printf(sc.format (Time to convert))
31. How does Java sleep?
Sleep() causes the current thread to enter a stagnant state (blocking the current process) and gives up the use of the CPU. The purpose is to prevent the current thread from occupying the CPU resources obtained by the thread alone, leaving a certain amount of time for Opportunity for other threads to execute. You can put the program to sleep for a few milliseconds. Tread.sleep(1000*3) //Sleep for 3 seconds
32. How to set the specific part of the date format, such as year, month, day, day, minute and second?
is to use the Calender class. The Calender class is an abstract class that implements objects of specific subclasses in actual use. The process of creating objects is transparent to programmers, and only needs to be created using the getInstance method.
#33. Are there any classes or methods to use?
The java.util.regex package mainly includes the following three classes:
Pattern class: The Pattern object is a compiled representation of a regular expression. The Pattern class has no public constructor. To create a Pattern object, one must first call its public static compiled method, which returns a Pattern object.
Matcher class: The Matcher object is an engine that compiles and matches input strings.
PatternSyntaxExeption: PatternSyntaxExeption is a non-mandatory exception class that represents a syntax error in a regular expression pattern.
34. What is the connection between constructors and methods?
The concept of constructor method: When creating an object, the system will automatically call the constructor method. When there is no custom constructor, the system will call the default constructor. Constructors can be overloaded but cannot be rewritten. Different constructors have the same name but different parameter lists. The parameter list is the basis and standard for identification, similar to a person's name, which may be the same but the ID card is different.
When customizing the constructor, the system automatically matches the constructor to initialize the object based on the type and quantity of parameters passed in.
35. What is the Scanner class? How to create a Scanner object
java.util.Scanner is a new feature of java5. We can get input from the user.
Scanner sc = new Scanner();
36. What is the difference between the next() and nextLine() methods of the Scanner class to obtain the input string?
next():
(1). The input must be completed only after valid characters are read;
(2) If a blank is encountered between valid characters for input, the input will be terminated. Automatically removed;
(3) Only by entering valid characters can the space entered later be used as a separator or terminator;
(4) Next() cannot obtain a string with spaces;
nextLine ():
(1), with Enter as the end character, that is, enter all characters before the carriage return;
(2), you can get blanks;
37, Java three What type of exception is it?
Check-time exception: The most common checked exceptions are exceptions caused by user errors or problems, which cannot be foreseen by the programmer. For example, when you want to open a file that does not exist, an exception occurs. These exceptions cannot be simply ignored at compile time.
Runtime exceptions: Runtime exceptions are exceptions that can be avoided by programmers. In contrast to checked exceptions, runtime exceptions can be ignored at compile time.
Error: Errors are not exceptions, but problems out of the programmer's control. Errors are usually ignored in the code. For example: when the stack overflows, an error occurs that cannot be checked during compilation.
All exception types in Java are subclasses of the built-in class java.lang.Throwable class, that is, Throwable is located at the top level of the exception class hierarchy. There are two exception branches under the Throwable class, Exception and Error, as shown in the figure.
38. What is the difference between exception and error?
All exceptions inherit the Throwable class, which means that all exceptions are an object.
Generally speaking, exceptions can be divided into two parts:
(1) Error: refers to an error that cannot be handled by the program, indicating a major error that occurs when the application is running. For example, OutOfMemoryError that occurs when jvm is running and the port is occupied when programming Socket and other errors that cannot be handled by the program
(2) Exception: Exceptions can be divided into runtime exceptions and compilation exceptions. There are two main exception classes. Subclasses: IOException class and RuntimeException class
39. What is catching exceptions?
Use the try and catch keywords to catch exceptions, and place the try/catch code block where the exception may occur. The code within the try/catch block becomes protected code.
40. What is the difference between throws and throw keywords?
If a method does not catch a checked exception, then the method must be declared using the throws keyword. The throws keyword is placed at the end of the method signature. You can also use throw to throw an exception, whether it is the latest instantiation or just caught.
A method can be declared to throw multiple exceptions, separated by commas.
41. How to customize exceptions in Java?
You can write your own exception class:
(1). All exceptions must be subclasses of the Throwable class;
(2) If you want to write a check-time exception, you need to inherit Exception ;
(3) If you need to write a runtime exception, you need to inherit the RuntimeException() exception
42. What is inheritance? What are the characteristics of inheritance?
Inheritance is when a subclass inherits the characteristics and behaviors of the parent class, so that the subclass object (instance) has the instance fields and methods of the parent class, or the subclass inherits the methods from the parent class, so that the subclass has the same characteristics as the parent class the behavior of.
Features:
(1). The subclass has the non-private attributes and methods of the parent class;
(2) The subclass can have its own attributes and methods, that is, the subclass can extend the parent class. ;
(3) Subclasses can have their own way to implement the methods of the parent class;
(4) Java inheritance can only be single inheritance, but multiple inheritance is possible. Single inheritance means that a subclass can only inherit A parent class, multiple inheritance is: A inherits B, B inherits C, so according to the relationship, class C is the parent class of class B, and B is the parent class of A. This is a feature of Java inheritance difference from c.
43. What are the keywords of inheritance?
Inheritance can be achieved using the two keywords extends and Implements. Moreover, all classes inherit from java.lang.Object. When a class does not have the inherited keyword, it inherits the Object class by default (this class is in the java.lang package, so no package import is needed).
super keyword: The super keyword can be used to access parent class members and is used to refer to the parent class inherited by the current object.
this keyword: refers to a reference to itself.
final keyword: Declaring a class can define the class as a class that cannot be inherited, that is, a final class; or it can be used to modify a method, which cannot be overridden by subclasses
44. What are the characteristics of the constructor of the parent class?
Subclasses cannot inherit the constructor (constructor and constructor (with parameters)) of the parent class. However, if the constructor of the parent class has parameters, they must be explicitly declared in the constructor of the subclass. The constructor of the parent class is called through the supper keyword and the appropriate parameter list:
If the parent class has a no-argument constructor, use it in the constructor of the subclass It is not necessary for supper to call the parent class. If the super keyword is not used, the system will automatically call the parameterless constructor of the parent class.
45. What is override, what is overload, and what is the difference between them?
Rewrite: The subclass rewrites and writes the implementation process of the method of the parent class that allows access to . The return value and parameters cannot be changed, that is, the shell cannot Change, core change. The advantage of overriding is that subclasses can customize their own behavior as needed. In other words, subclasses can implement the methods of the parent class as needed. Overriding methods cannot throw checked exceptions or exceptions that are broader than the overriding method declaration.
Overloading: Overloading is in a class, the method name is the same, but the parameters are different, and the return type can be the same or different. Each overloaded method (or constructor) must have a unique list of parameter types. The most common one is constructor overloading.
Difference: Method rewriting and overloading are different manifestations of Java polymorphism. Rewriting is a manifestation of polymorphism between parent classes and subclasses. Overloading can be understood as polymorphism. the specific expression of the state.
(1) Method overloading is a class that defines multiple methods with the same name and different parameters or the same number of parameters, different types and different orders, which becomes an overloading of the method.
(2) Method overriding is a method that has the same name as the parent class method in the subclass, and the number and type of parameters are the same, and the return value is also the same, which is called rewriting
(3) , Method overloading is a polymorphic manifestation of a class, and method overriding is a polymorphic manifestation of a subclass and a parent class.
46、什么是抽象类,如何定义抽象类与方法?
抽象类:抽象类除了不能实例化对象之外,类的其它功能依然存在,成员变量,成员方法和构造方法的访问方式和普通类不一样。由于抽象类不能实例化对象,所以抽象类必须被继承,才能被使用:
The parent class contains common methods for child class collections, but because the parent class itself is abstract, these methods cannot be used. In Java, abstract classes represent an inheritance relationship. A class can only inherit one abstract class, but a class can implement multiple interfaces.
Define abstract class: Use abstract class to define abstract classes in the Java language.
Define abstract method: If you want to design a class that contains a special member method, and the specific implementation of the method is determined by its subclass, then you can declare the method in the parent class method. The Abstract keyword is also used to declare abstract methods. Abstract methods only contain a method name and no method body (abstract methods are not defined, and the method name is directly followed by a semicolon instead of curly braces). If a class has an abstract method, it must be an abstract class
47. What are the consequences of declaring an abstract method?
(1) If a class contains abstract methods, then the class must be an abstract class
(2) Any subclass must override the abstract method of the parent class, or declare itself as an abstract class .
48. What is encapsulation and what are its advantages? How is Java encapsulated?
Encapsulation: refers to a method of packaging and hiding the implementation details of an abstract functional interface. Encapsulation can be thought of as a protective barrier that prevents the code and data of the class from being randomly accessed by code defined by the external class.
Advantages:
(1) Good encapsulation can reduce coupling;
(2) The structure inside the class can be modified freely;
(3) Members can be modified Variables for more precise control;
(4), Hide information, implementation details;
Encapsulate :
(1), Modify the visibility of attributes to limit access to attributes (Generally limited to private);
(2) Provide public method access to the external interface for each value attribute. That is, for access to private properties. (Usually these methods are called getter and setter methods, such as entity classes under development)
49. What are the similarities and differences between interfaces and classes?
Same:
(1), an interface can have multiple methods;
(2), the interface file is saved in a file ending with .java
(3), the interface Bytecode files are saved in files ending with .class
Differences:
(1) Interfaces cannot instantiate objects (same as abstract classes)
(2) Interfaces have no construction methods;
(3) All methods in the interface must be abstract methods;
(4) The interface cannot contain member variables;
(5) The interface cannot be inherited (implemented by the class);
( 6). Interface supports multiple inheritance;
50. What is the difference between abstract class and interface?
(1) Methods in abstract classes can have method bodies, which means they can realize the specific functions of the methods, but methods in interfaces cannot.
(2). Member variables in abstract classes can be of various types, while member variables in interfaces can only be of public static final type;
(3) Interfaces cannot contain static code blocks and Static methods (methods modified with static), while abstract classes can have static code blocks and static methods
(4). A class can only inherit one abstract class, and a class can implement multiple interfaces.
Interfaces are abstract. When declaring an interface, you do not need to use the abstract keyword. Every method in the interface is also implicitly abstract, and there is no need to add abstract when declaring it. Methods in an interface There are classes in the interface that implement the interface to implement the methods in the interface.
Related recommendations:Getting started with java
The above is the detailed content of java intern interview questions. For more information, please follow other related articles on the PHP Chinese website!