Java FAQ (Novice must SEE) __java

Source: Internet
Author: User
Tags goto inheritance naming convention visibility stringbuffer

Excerpt from Donkeyzheng's Blog

First, prepare the article

Q1.1 What is Java, Java2, JDK. What happened to the 1.3, 1.4 version number behind the JDK.
A: Java is a generic, concurrent, strongly typed, object-oriented programming language (excerpt from the Java specification second
Version
)。
The JDK is a free Java development toolkit distributed by Sun, officially named J2SDK (java2softwaredevelop
K
IT).
Includes a basic Java toolkit and a standard class library.
Until now (July 2003), Java has 3 major versions, namely 1.0,1.1,2.0;
JDK has 1.0,1.1,1.2,1.3,1.4 five versions.
From JDK1.2, Sun felt that Java changes were large enough to raise the Java language version number to 2.0.
The different JDK is mainly provided by different class libraries. As a study you can download the latest JDK1.4.2.
Real development should consider forward compatibility, such as 1.3. Please go to http://java.sun.com for download.
JDK1.5 is expected to launch in 2004, which will include a number of new features.

Q1.2 what is jre/j2re.
A: J2re is java2runtimeenvironment, the Java Runtime Environment, sometimes referred to as JRE.
If you only need to run a Java program or applet, download and install it.
If you want to develop your own Java software, please download the JDK. The JRE is included with the JDK.
Note Because Microsoft's support for Java is incomplete, do not use IE's own virtual machine to run the applet
Will
Install a JRE or JDK.

Q1.3 Learn what Java tools are better.
A: The authors recommend using the jdk+ text editor first, which helps you understand the following basic concepts: path,
Classp
Ath,package
And familiar with basic commands: Javac and Java. and download the same API help as your JDK version.
If you are unsure of the use of a class or function, consult the API first instead of posting for help.
When you are familiar with Java, you can consider starting with an IDE.
The author recommends eclipse, download URL http://www.eclipse.org. Because Eclispe is free, plug-in
Of

The main disadvantage of ECLISPE is the lack of a visual desktop program development tool,
Fortunately, IBM has donated some of its code to the Eclipse Organization in November 2003, and it can be expected that this shortcoming will soon
Yes
be made up.
In any case, do not use Microsoft's vj++. It is well known that Microsoft has never seriously supported
Java

Last but not least, have a good reference book, and English to pass.

Q1.4 Learn what good reference books Java has.
A: The author first recommended Thinkinginjava, Chinese name "Java programming thought", has the Chinese version.
The current version is the third edition.
The English version can be downloaded for free in http://64.78.49.204.
The first chapter of the book introduced a lot of object-oriented programming ideas, as a novice should read carefully.
In addition, the books O ' relly and Wrox publishers are good. The author does not like the books of the mainland authors.
Maybe you think English is too difficult, but most of the information on the Internet is in English. In addition, you need to consult the API frequently, and
That
Also in English.

Q1.5java and C + + which is better.
A: This question is a very inappropriate question. You should ask: Java and C + + which is more suitable for my project.
Java is as obvious as its pros and cons.
Cross-platform is the main advantage of Java, but the cost is the decline in the speed of operation.
VC and Windows platforms are well integrated and fast enough, but can only be limited to Windows platforms.
Java is faster than C + +, and developers don't run into a lot of error-prone features.
But VB programmers even need to assemble the module on it.

Q1.6 what is j2se/j2ee/j2me.
A: J2SE is the general Java.
J2ME is for embedded devices, such as Java-enabled handsets, and it has its own JRE and SDK.
Java EE is a set of specifications and class libraries for enterprise program development that uses the J2SE JRE.

Ii. Order Articles

Q2.1 I wrote the first Java program, how it should be compiled/run.
A: First, please save the program as a Xxx.java file, and note that you may need to modify the file suffix name.
Then use the Javacxxx.java command under the DOS window, and you'll find a xxx.class text in the directory.
Thing

With the javaxxx command, your Java program starts running.

Q2.2 I did what you said, but what happened? "' Javac ' is not an internal or external command, nor is it operational
Of
program or batch file. ”。
A: You're having a path problem. The operating system searches for javac.exe within a certain range (path), but cannot find
To.

Please edit your operating system environment variable, add a Java_home variable, set to your JDK installation directory,
Then edit the path variable, plus a%java_home%/bin.
Then save and open a new DOS window, and you can use the Javac and Java commands.

Q2.3 environment variable how to set.
A: Please consult the people around you.

Q2.4 what I showed in Javacxxx.java, "unreportedexception.
Java.io.IOExcepti
On; ".
A: See Q4.8 to learn about the exception mechanism in Java.

Q2.5javacxxx.java went through, but Javaxxx show what
"Noclassdeffounderr
or ".
A: 1. You're having a classpath problem. Java command searches within a certain range (CLASSPATH) for you directly or between
Pick up
The class file used, but could not be found.
First, make sure you're not knocking the Javaxxx.class,
Second, check your CLASSPATH environment variable, but you don't need to set the variable,
But if you set the variable and don't include the. Item (representing the current directory),
That's the problem you're going to run into. Please add an item to your CLASSPATH environment variable. Or simply delete the variable.

2. If you use a standard package that is not a JDK, such as a javax.servlet.* package, you will also encounter this problem,
Please
Add the appropriate jar file to the classpath.
3. If you have defined package in the Java source file, see Q2.11.


Q2.6 I Show "Exceptioninthread" Main in javaxxx.
Java.lang.NoSuchMetho
Derror:main ".
A: First of all, in your program each Java file has and can only have a public class,
The class name of this class must be exactly the same as the case of the file name.
Second, there is only one publicstaticvoidmain (String[]args) side in the class you want to run.
Method

This method is your main program.


Q2.7 "Exceptioninthread" main "when javaxxx."
Java.lang.NullPointerEx
Ception ".
A: In the program you try to invoke a method on an object variable that is NULL, check your program to make sure that your object
be properly initialized.
See Q4.8 for exception mechanisms in Java.


What does q2.8package mean. How to use.
A: In order to uniquely identify each class and group, Java uses the concept of package.
Each class has a full name, for example, the full name of String is java.lang.String, where Java.lang is the package name.
S
Tring is a short name. According to the Java naming convention, the package name is all lowercase, and the first letter of the class name is uppercase.
So, if you define a class string of the same name yourself, you can put it in the MyPackage,
MyPackage by using the full name. String and java.lang.String to differentiate between these two classes.
At the same time, placing logically related classes in the same package can make the program structure clearer.
To define the package, all you have to do is add a line "Packagemypackage" to the beginning of the Java file.
Note that packages are not nested or contain relationships, mypackage packages and mypackage.mysubpackage packages are and
A column of two packages (although developers can
Can imply the inclusion of a relationship).

Q2.9 I didn't declare any package what would happen.
A: Your class is considered to be placed in the default package. The full name and the short name are consistent.

Q2.10 How to use other classes in a class.
A: If you use a Java.lang package or a class in the default package, you don't have to do anything.
If your class is in a MyPackage package and you want to invoke other classes in the same package, you don't have to do anything.
If you use a class in another package, after the package declaration, the class declaration uses the import
Otherpackage1. Class
1; or importotherpackage2.*;
Here. * Represents the introduction of all the classes in this package. Then you can use the short name of the other class in the program.
If there is a duplicate name conflict between the short names, you must use the full name to differentiate.
Note that when using classes in other packages, you can use only public classes and interfaces, see Q5.4.

Q2.11 I used the package to show "Noclassdeffounderror", but I removed all package
Of
Time to run normally.
A: Organize your Java files by package name.
For example, your working directory is/work, and your class is package1. Class1, then store it
For/work/package1
/class1.java.
If the package is not declared, put it directly under/work.
Execute Javacpackage1/class1.java under/work, then execute Javapackage1.class1, and you will find
One
Cut normal.
Also, if you have more than the number of classes you need to use to organize the package, you can consider starting to use
Ide.

Q2.12 I want to compile Java into EXE file, how to do.
A: JDK can only compile Java source files into class files.
A class file is a Cross-platform byte code that must be run by a platform-dependent JRE. Java in order to achieve the cross
Flat
Table sex.
Some development tools can compile Java files into EXE files. The author opposes this practice, because it cancels the cross
Flat
Table sex.
If you are sure that your software is running on only the Windows platform, you can consider using c++/c# to program.

Q2.13 I encountered what "Deprecatedapi" at compile time, what meaning.
A: The so-called deprecated refers to the outdated, but still retained for the sake of forward compatibility.
These methods may cancel support at a later time. You should switch to a newer method.
The API will show you how you should replace it.

Third, I/O article

Q3.1 How do I add a startup parameter to a Java program, just like dir/p/w.
Answer: Remember Publicstaticvoidmain (String[]args). The args here is your startup reference.
Number

At run time you enter Javapackage1.class1arg1arg2,args with two strings, the first
Is
Arg1, the second one is arg2.

Q3.2 How do I enter a int/double/string from the keyboard.
A: Java I/O operations are more complex than C + +. If you want to enter from the keyboard, the sample code is as follows:
Bufferedreadercin=newbufferedreader (Newinputstreamreader (
system.in));

Strings=cin.readline ();
So you get a string, if you need a number to use it again:
Intn=integer.parseint (s); or doubled=double.parsedouble (s);
To convert the string "534" to an int or double.

Q3.3 How do I output a int/double/string.
Answer: Use SYSTEM.OUT.PRINTLN (n) or System.out.println ("Hello") and so on.

Q3.4 I've found that some books are typed directly with system.in, much simpler than you.
A: Java uses Unicode, which is double-byte. The system.in is a single byte stream.
If you want to enter double-byte text such as Chinese, please use the author's approach.

Q3.5 How do I input/output a int/double/string from a file.
A: Similar to the input from the keyboard, but instead
Bufferedreaderfin=newbufferedreader (Newfilereader ("myFileName"));
Printwriterfout=newprintwriter (Newfilewriter ("myFileName"));
In addition, if you have not yet downloaded the API, please start downloading and reading the contents of the Java.io package.

Q3.6 I want to read and write to the specified location of the file, what to do.
Answer: Java.io.RandomAccessFile can meet your needs.

Q3.7 How to judge that the document to be read has come to an end.
A: In reader's Read method, it is clear that return-1 indicates the end of the stream.

Iv. Key Words and articles

Q4.1java How to define macros inside.
A: Java does not support macros because macro substitution does not guarantee type safety.
If you need to define a constant, you can define it as a staticfinal member of a class. See Q4.2 and Q4.6.


Q4.2java can't use Const.
Answer: You can use the final keyword. such as finalintm=9. A variable declared final cannot be
Fu
Value. The only exception is the so-called blankfinal, as shown in the following example:
publicclassmyclass1{
Privatefinalinta=3;
Privatefinalintb;//blankfinal

PublicMyClass1 () {
a=5;//is not valid, final variable cannot be assigned again.
b=4;//is valid, this is the first time that B is assigned a value.
b=6;//is not valid, B cannot be assigned again.
}
}
Final can also be used to declare a method or class, and a method or class declared as final cannot be inherited.
Note that const is a reserved word for Java to expand.

Q4.3java inside also cannot use Goto.
A: Even in a process-oriented language, you can use no goto at all. Please check that your program flow is reasonable.

If you need to jump out of a multi-layer loop quickly, Java enhances the break and continue work (compared to C + +)
Yes
Supports label.
For example:
Outer
while (...)
{
Inner
For (...)
{
... breakinner;
... continueouter;
}
}
As with const, Goto is also a reserved word for Java to expand.

Q4.4java inside can not overload operator.
Answer: No. The + number of the string is the only built-in overloaded operator. You can actually do this by defining interfaces and methods.
Is
Similar functionality.

Q4.5 I have a new object, but I can't delete it.
A: Java has automatic memory recycling mechanism, that is, the so-called garbargecollection. You don't need to delete objects. You'll
Also
Do not worry about pointer errors, memory overflow.

Q4.6 I want to know why the main method must be declared as publicstatic. Why not in the Main method
Adjustable
With a non-static member.
A: Declaring public is for this method to be called externally, see Q5.4 for details.
Static is to associate a member variable/method with a class (class) rather than an instance (instance).
You do not need to create an object to directly use the static members of this class, so you cannot in a static member
Adjustable
With a non-static member because the latter is associated to an object instance (instance).
Static members that call Class B in Class A can use B.staticmember.
Note that the static member variable of a class is unique and is shared by all of the class objects in multithreaded programming
In particular, be careful.
The static members of a class are initialized the first time the class is loaded by the JRE.
You can use a non-static member by using the following methods:
Publicclassa
{
Privatevoidsomemethod ()//non-static member
{}
Publicstaticvoidmain (Stringargs)
{
Aa=newa ()//Create an object instance
A.somemethod ()//Now you can use the non-static method.
}
}


What is the difference between Q4.7throw and throws.
A: Throws is used in a method declaration to declare which exceptions a method throws. And throw is actually in the method body
Execution throws an exception.
Action.
If you throw an exception in the method, but you do not declare it in the method declaration, the compiler will make an error.
Note that the error and runtimeexception subclasses are exceptions and do not require a special declaration.

Q4.8 what is an exception.
A: The exception was first introduced in the ADA language to dynamically handle errors and recover in the program.
You can intercept the underlying exception and handle it in the method, or you can throw it to a higher level module to handle it.
You can also throw your own exception indicating that something abnormal has occurred. Common blocking processing code is as follows:
Try
{
...//The following is a code that may have an exception
...//The exception is thrown by you or the low-level API, the execution process is interrupted and the Intercept code is turned.
......
}
catch (EXCEPTION1E)//If Exception1 is a subclass of Exception2 and you want to do special processing, you should arrange the
Ago
Surface
{
Intercepted by this segment when Exception1 occurs
}
catch (EXCEPTION2E)
{
Intercepted by this segment when Exception2 occurs
}
finally//this is optional.
{
Executes this code regardless of whether the exception occurred
Even if a new exception,finally segment is thrown out of the catch segment, it is executed.
}

What is the difference between q4.9final and finally.
A: final please see Q4.2. Finally for the exception mechanism, see Q4.8.

V. Object-oriented articles

What is the difference between q5.1extends and implements.
A: For class, extends is used (single) to Inherit a class (class), whereas implements is used to implement
An interface (Interf
ACE).
Interface is introduced to partially provide multiple inheritance functions.
In interface, you simply declare the method header and leave the method body to the implemented class.
The instances of the class that are implemented can be treated as interface instances.
The relationship between interface can also be declared as extends (multiple inheritance).
Note that a interface can extends multiple other interface.

Q5.2java How to achieve multiple inheritance.
Answer: Java does not support explicit multiple inheritance.
Because in an explicit, more inherited language such as C + +, a subclass is forced to declare the ancestor virtual base class constructor.

This is a violation of the object-oriented encapsulation principle.
Java provides interface and implements keywords to partially implement multiple inheritance. See Q5.1.

What Q5.3abstract is.
A: A method declared abstract does not need to give the method body, leaving the subclass to implement it.
And if there is an abstract method in a class, then the class must also be declared abstract.
A class declared abstract cannot be instantiated, although it can define a constructor method for use by subclasses.

What's the difference between q5.4public,protected,private?
A: These keywords are used to declare the visibility of classes and members.
Public members can be accessed by any class,
Protected members are limited to themselves and subclass access,
Private members are limited to their own access.
Java also provides a fourth kind of default visibility, commonly called packageprivate, when there is no
Public,protected,private modifier, the member
is visible within the same package.
A class can be decorated with public or by default.

What is the difference between q5.5override and overload.
A: Override refers to the inheritance of methods between the parent class and the subclass, which have the same name and parameter class
Type

Overload refers to the relationship between different methods in the same class, which can be defined in subclasses as well as in the parent class,
These methods have the same name and different parameter types.


Q5.6 I inherited a method, but now I want to invoke the method defined in the parent class.
A: Use Super.xxx () to invoke the parent class method in the subclass.

Q5.7 I want to invoke the constructor method of the parent class in the constructor method of the subclass.
A: Call Super (...) in the first line of the subclass construction method. Can.

Q5.8 I've defined several constructs in the same class and want to call another in one of the constructor methods.
A: Call this (...) in the first line of the constructor method.

Q5.9 I didn't define the construction method.
A: Automatically obtain a method of constructing without parameters.

Q5.10 I called the parameterless construction method failed.
A: If you define at least one construction method, there is no longer an automatically supplied parameterless construction method.
You need to explicitly define an argument-free construction method.
Another possibility is that your construction method or class is not public, see Q5.4 to understand the visibility in Java.

Q5.11 How do I define a destructor similar to C + + (destructor).
A: Provide a voidfinalize () method. The party is called when the object is reclaimed by Garbargecollector
Method.

Note that it's really hard to tell when an object will be recycled. The author never felt the need to use the method.


Q5.12 I want to convert a parent class object to a subclass object.
A: Force type conversions. Such as
Publicvoidmeth (Aa)
{
bb= (B) A;
}
If a is not actually an instance of B, it throws a classcastexception. So please make sure that A is really a B real
Cases.


Q5.13 In fact, I'm not sure if A is a B instance, can be dealt with in a separate case.
Answer: You can use the instanceof operator. For example
if (AINSTANCEOFB)
{
bb= (B) A;
}
Else
{
...
}

Q5.14 I modified the value of an object in the method, but after exiting the method I found that the object's value did not change.
A: It is very likely that you have assigned an incoming parameter to a new object, such as the following code that causes this error:
PUBLICVOIDFUN1 (Aa)//a is a local parameter that points to an external object.
{
A=newa ();//a points to a new object, decoupling from the external object. If you want to make a as
Outgoing variables,
Don't write this sentence.
A.setattr (attr)//modified the value of the new object, the external object has not been modified.
}
This is also the case with the base type. For example:
Publicvoidfun2 (INTA)
{
a=10;//only for this method, the outside variables will not change.
}

Six, Java.util article

Q6.1java can dynamically allocate arrays.
Answer: Yes. such as intn=3; Language[]mylanguages=newlanguage[n];

Q6.2 How do I know the length of the array.
Answer: Use the length attribute. As in the example above, the Mylanguages.length is 3.

Q6.3 I also want to have the length of the array automatically changed to add/remove elements.
Answer:--java.util.list interface with sequential table.
You can choose to use ArrayList or LinkedList, the former is an array implementation, the latter is a linked list implementation.
For example: Listlist=newarraylist () or listlist=newlinkedlist ();

Q6.4 What is a linked list. Why should there be ArrayList and linkedlist two kinds of list.
A: Please cram data structure.

Q6.5 I want to use the queue/stack.
Answer: Use Java.util.LinkedList.

Q6.6 I hope not to have duplicate elements.
Answer: Use the Set--java.util.set interface. For example: Setset=newhashset ().

Q6.7 I want to traverse the collection/map.
Answer: Use Java.util.Iterator. See API.

Q6.8 I also want to be able to sort.
Answer: Use Java.util.TreeSet. For example: Setset=newtreeset (). The elements that are put in are automatically arranged
Order

You need to implement the comparable interface for the element, and you may also need to provide the Equals () method, the CompareTo () method,
H
Ashcode () method.

Q6.9 but I want to sort the array.
A: The Java.util.Arrays class contains practical methods such as sort.

Q6.10 I want to sort by different ways.
A: Define a sort class that implements the interface comparator for each method and combine with arrays or treeset
Use.


What's the use of Q6.11map?
A: Store key-value keyword-value pairs, you can quickly access the corresponding value by keyword.

The Q6.12set method is fine, but the Get method returns object.
A: Force types to be converted to the type you need. See Q5.12.

What is the difference between q6.13arraylist and vector? What is the difference between HashMap and Hashtable.
A: ArrayList and HashMap are multi-threaded, and accessing the same ArrayList object in multiple threads can
Yes
Can cause conflicts and cause errors.
Vector and Hashtable are multi-threaded and secure, even if the same vector object is accessed simultaneously in multiple threads
No
can cause mistakes.
It looks like we should use vector and Hashtable, but the vector and Hashtable are actually too
Poor
So if you're not using multiple threads, you should still use ArrayList and HashMap.

Q6.14 I'm going to get a random number.
Answer: Use the Java.util.Random class.

Q6.15 me to compare two string is always false, but they are obviously "abc".
A: Compare string must use Equals or Equalsignorecase method, do not use = =.
= = Compares whether two references (variables) point to the same object, rather than comparing its contents.

Q6.16 I want to modify a string but the edit method is not found in the string class.
Answer: Use the StringBuffer class.
Stringstr= "...";/the string to be processed
Stringbufferbuffer=newstringbuffer (str);//Use this string to initialize a
Stringbuf
Fer
Buffer.append ("...");//Call StringBuffer related API to edit string
Stringstr2=buffer.tostring ()//Gets the edited string.
In addition, if you need to connect multiple strings, try to avoid using the + number to connect directly, but instead use the
Strin
Gbuffer.append () method.

Q6.17 I want to deal with date/time.
Answer: Use the Java.util.Date class. You can use the Java.text.SimpleDateFormat class to come in string and
Da
The TE is converted to each other.
Simpledateformatformatter=newsimpledateformat ("Yyyy-mm-ddhh:mm:ss");
Rules
Fixed date format
Datedate=formatter.parse ("2003-07-2618:30:35");//Converts a string that matches the format
For
Date
Strings=formatter.format (date)//convert date to a string that matches the format
For more information about defining date formats, see the API.

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.