Java Surface Examination Question finishing two (turn gray ash + gray ash)

Source: Internet
Author: User

Java Development interview Problem small finishing (ii)

Anonymous Inner Class (anonymous inner Class) can inherit other classes? Is it possible to implement an interface?

A: You can inherit other classes or implement other interfaces, which are commonly used in swing programming and Android development to implement event snooping and callbacks.

The inner class can reference its members of the containing class (The outer Class)? Are there any restrictions?

A: An internal class object can access the members of the external class object that created it, including private members.

What are the uses of the final keyword in Java?

A: (1) Modifier class: Indicates that the class cannot be inherited;

(2) Modification method: Indicates that the method cannot be rewritten;

(3) Modifier variable: Indicates that the value cannot be modified (constant) after the variable can be assigned only once.

The operation results of the following program are indicated.

Class A {    static {        System.out.print ("1");    }    Public A () {        System.out.print ("2");}    } Class B extends a{    static {        System.out.print ("A");    }    Public B () {        System.out.print ("B");}    } public class Hello {public    static void Main (string[] args) {        A ab = new B ();        AB = new B ();}    }

A: Execution result: 1a2b2b. When you create an object, the constructor is called in the order that it initializes the static member, then calls the parent class constructor, initializes the non-static member, and finally calls itself the constructor.

Tip: If you can't give the correct answer to this question, the 21st question of Java class loading mechanism is not fully understood, and then look at it.

convert between data types:
-How do I convert a string to a base data type?
-How do I convert a base data type to a string?

For:
-Call the method Parsexxx (string) or valueof (string) in the wrapper class corresponding to the base data type to return the corresponding base type;
-One way to do this is to concatenate the base data type with an empty string ("") to get its corresponding string, or to call the ValueOf () method in the string class to return the corresponding string.

How do I implement a string reversal and substitution?

A: There are many ways to write your own implementation or you can use the methods in string or Stringbuffer/stringbuilder. One common interview topic is recursive implementation of string inversion, as shown in the following code:

    public static String reverse(String originStr) {        if(originStr == null || originStr.length() <= 1) return originStr; return reverse(originStr.substring(1)) + originStr.charAt(0); }

How do I convert a GB2312 encoded string to a iso-8859-1 encoded string?

A: The code looks like this:

String s1 = "你好";String s2 = new String(s1.getBytes("GB2312"), "ISO-8859-1");

Date and time:
-How do I get the date, hour and minute seconds?
-How to get the number of milliseconds from January 1, 1970 0:0 0 seconds to now?
-How to get the last day of a month?
-How do I format a date?

For:
Issue 1: Create a Java.util.Calendar instance, call its get () method to pass in a different parameter to get the value corresponding to the parameter. Java 8 can be obtained using Java.time.LocalDateTimel, as shown in the code below.

public class Datetimetest {public    static void Main (string[] args) {        Calendar cal = Calendar.getinstance ();        System.out.println (Cal.get (calendar.year));        System.out.println (Cal.get (Calendar.month));    0-11        System.out.println (Cal.get (calendar.date));        System.out.println (Cal.get (Calendar.hour_of_day));        System.out.println (Cal.get (Calendar.minute));        System.out.println (Cal.get (Calendar.second));        Java 8        LocalDateTime dt = Localdatetime.now ();        System.out.println (Dt.getyear ());        System.out.println (Dt.getmonthvalue ());     1-12        System.out.println (Dt.getdayofmonth ());        System.out.println (Dt.gethour ());        System.out.println (Dt.getminute ());        System.out.println (Dt.getsecond ());}    }

Issue 2: The following methods are available for this number of milliseconds.

Calendar.getinstance (). Gettimeinmillis (); System.currenttimemillis (); Clock.systemdefaultzone (). Millis (); Java 8

Issue 3: The code is shown below.

Calendar time = Calendar.getinstance (); Time.getactualmaximum (Calendar.day_of_month);

Issue 4: Use the format (date) method in Java.text.DataFormat subclasses (such as the SimpleDateFormat Class) to reformat dates. In Java 8, you can use Java.time.format.DateTimeFormatter to format the time date, as shown in the code below.

Import Java.text.simpledateformat;import Java.time.localdate;import Java.time.format.datetimeformatter;import Java.util.date;class dateformattest {public    static void Main (string[] args) {        SimpleDateFormat oldformatter = New SimpleDateFormat ("Yyyy/mm/dd");        Date date1 = new Date ();        System.out.println (Oldformatter.format (date1));        Java 8        DateTimeFormatter newformatter = Datetimeformatter.ofpattern ("Yyyy/mm/dd");        Localdate date2 = Localdate.now ();        System.out.println (Date2.format (Newformatter));}    }

Add: Java time and date API has always been criticized for something, in order to solve this problem, Java 8 introduced a new time and date API, including Localdate, LocalTime, LocalDateTime, Clock, instant and other classes, The design of these classes uses the invariant pattern and is therefore a thread-safe design. If you don't understand these things, you can refer to my other article, "summarizing and thinking about Java concurrency programming."

A. print the current moment of yesterday.

For:

Import Java.util.calendar;class yesterdaycurrent {public    static void Main (string[] args) {        Calendar cal = Calendar.getinstance ();        Cal.add (Calendar.date,-1);        System.out.println (Cal.gettime ());}    }

In Java 8, you can implement the same functionality with the following code.

Import Java.time.localdatetime;class yesterdaycurrent {public    static void Main (string[] args) {        LocalDateTime Today = Localdatetime.now ();        LocalDateTime yesterday = today.minusdays (1);        System.out.println (yesterday);    }}

compare Java and javasciprt.

A: JavaScript and Java are the two different products developed by the two companies. Java is the object-oriented programming language of the original Sun Microsystems company, especially suitable for Internet application development, while JavaScript is the product of Netscape company, An object-based and event-driven, interpreted language that can be embedded in a Web page, developed to extend the functionality of the Netscape browser. The predecessor of JavaScript was LiveScript, while Java was formerly the Oak language.
The following comparisons are made between the two languages:
-Object-based and object-oriented: Java is a true object-oriented language, and even if you are developing a simple program, you must design the object; JavaScript is a scripting language that can be used to create complex software that is independent of the network and interacts with the user. It is an object-based (object-based) and event-driven (Event-driven) programming language, so it itself provides a very rich internal object for designers to use.
-Interpretation and Compilation: Java's source code must be compiled before it is executed. JavaScript is an explanatory programming language whose source code does not need to be compiled and interpreted by the browser. (Almost all current browsers use JIT (Instant compilation) technology to improve the efficiency of JavaScript)
-Strongly typed variables and weakly typed variables: Java uses strongly typed variables to check that all variables must be declared before they are compiled, that the variables in JavaScript are weakly typed, that they are not even declared before they are used, and that the JavaScript interpreter checks to infer its data type at run time.
-code format is not the same.

add: The four points listed above are the so-called standard answers circulated online. In fact, the most important difference between Java and JavaScript is that one is a static language and one is a dynamic language. The development trend of current programming language is functional language and dynamic language. In Java classes are class-one citizens, and JavaScript functions are a one-off citizen, so JavaScript supports functional programming, you can use lambda functions and closures (closure), and of course Java 8 also began to support functional programming, providing support for lambda expressions and functional interfaces. For such questions, in the interview is best to use their own language to answer will be more reliable, do not recite the online so-called standard answer.

When to use assertions (assert)?

A: Assertions are a common debugging method in software development, and are supported in many development languages. In general, assertions are used to guarantee the most basic and critical correctness of a program. Assertion checking is usually turned on during development and testing. To ensure the execution efficiency of the program, the assertion check is usually closed after the software is released. An assertion is a statement that contains a Boolean expression that is assumed to be true when the statement is executed, and a assertionerror is reported if the value of the expression is false. The assertion is used as shown in the following code:

0); // throws an AssertionError if a <= 0

Assertions can be of two forms:
Assert Expression1;
Assert Expression1:expression2;
Expression1 should always produce a Boolean value.
Expression2 can be any expression that yields a value, which is used to generate a string message that displays more debugging information.

To enable assertions at run time, you can use the-enableassertions or-ea flag when you start the JVM. To choose to disable assertions at run time, you can use the-da or-disableassertions flag when you start the JVM. To enable or disable assertions in a system class, you can use the-esa or-DSA tags. You can also enable or disable assertions on a package basis.

Note: assertions should not change the state of the program in any way. Simply put, if you want to block code execution when certain conditions are not met, you might consider using assertions to block it.

What is the difference between error and exception?

A: Error indicates system-level errors and exceptions that the program does not have to handle, a serious problem in situations where recovery is not impossible but difficult, such as memory overflow, which cannot be expected to be handled by the program, and exception represents an exception that needs to be captured or handled by the program. is a design or implementation problem; That is, it indicates that it will never happen if the program is running normally.

Interview question: Motorola's interview in 2005 once asked such a question "If a process reports a stack overflow run-time error, what's the most possible cause?", gave four options a . lack of memory; B. Write on an invalid memory space; C. recursive function calling; D. Array index out of boundary. Java program may also encounter Stackoverflowerror at run time, this is an unrecoverable error, can only re-modify the code, the answer to the interview question is C. If you write a recursive that does not quickly converge, you are likely to throw a stack overflow error as follows:

Class Stackoverflowerrortest {public    static void Main (string[] args) {        main (null);}    }

tip: When writing programs recursively, be sure to keep two points in mind: 1. recursive formula; 2. The convergence condition (when the recursion is no longer continued).

There is a return statement in try{}, then the code immediately following the try finally{} will not be executed, when executed, before or after the return?

A: Execution occurs before the method returns the caller.

Note: It is not good to change the return value in Finally, because if a finally code block exists, the return statement in the try does not return the caller immediately, but instead records the return value until the finally code block finishes executing and returns its value to the caller. Then, if you modify the return value in Finally, the modified value is returned. Obviously, returning or modifying the return value in the finally will be very disturbing to the program, and C # directly in the way of compiling errors to prevent the programmer to do such a nasty thing, in Java can also raise the compiler's grammar check level to generate warnings or errors, where in eclipse can be set , it is strongly recommended that you set this to a compilation error.

How does theJava language do exception handling, keywords: throws, throw, try, catch, finally how to use each?

A: Java uses an object-oriented approach to exception handling, classifying various exceptions and providing a good interface. In Java, each exception is an object, which is an instance of the Throwable class or its subclasses. When an exception is thrown, a method throws an exception object that contains the exception information, and the method that invokes the object can catch the exception and manipulate it. Java exception handling is achieved through 5 keywords: try, catch, throw, throws, and finally. In general, a program is executed with a try, and if the system throws a (throw) an exception object, it can be caught (catch) by its type, or handled by always executing a code block (finally); try to specify a program that prevents all exceptions The catch clause immediately follows the TRY block to specify the type of exception you want to catch, and the throw statement is used to explicitly throw an exception; throws is used to declare a variety of exceptions that a method might throw (while declaring exceptions, allowing moan) Finally, to ensure that a piece of code is executed regardless of the exception, the try statement can be nested, and whenever a try statement is encountered, the structure of the exception is placed in the exception stack until all the try statements are completed. If the next-level try statement does not handle an exception, the exception stack performs a stack operation until it encounters a try statement that handles the exception or eventually throws the exception to the JVM.

What is the difference between a run-time exception and a inspected exception?

A: An exception indicates an unhealthy state that may occur during a program's operation, a run-time exception that represents an exception that may be encountered during a typical operation of a virtual machine, and is a common running error that usually does not occur if no problem is programmed. The exception that is checked is related to the context in which the program is running, even if it is programmed correctly, and can still be caused by a problem. The Java compiler requires that the method must declare the exception that is expected to be thrown, but does not require that an uncaught run-time exception be declared. Exceptions and inheritance are often misused in object-oriented programming, and the following guidelines are given for the use of exceptions in effective Java :
-Do not use exception handling for normal control flow (well-designed APIs should not force its callers to use exceptions for normal flow of control)
-Use a run-time exception for programming errors when using a inspected exception for a condition that can be recovered
-Avoid unnecessary use of checked exceptions (you can avoid the occurrence of anomalies by means of state detection)
-Preferential use of standard exceptions
-all exceptions thrown by each method must have a document
-Maintaining the atomicity of the anomaly
-Do not ignore the caught exception in the catch

Java Surface Examination Question finishing two (turn gray ash + gray ash)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.