Java entry-level problems

Source: Internet
Author: User
Java entry-level question-Linux general technology-Linux programming and kernel information. The following is a detailed description. 1. What are Java, Java2, and JDK? What is the 1.3 and 1.4.2 versions after JDK?

A: Java is a universal, concurrent, and strongly typed, object-oriented programming language (from the second edition of Java specifications). JDK is a free Java Development Tool distributed by Sun, formally named J2SDK (Java2 Softw
Are Develop Kit ).

2 What is JRE/J2RE?
A: J2RE is Java2 Runtime Environment, that is, 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 Java software on your own, download JDK. J2RE is included in JDK.
Note: because Microsoft does not fully support Java, do not use the virtual machine that comes with IE to run the Applet.
Bi'an
Install a J2RE or JDK.

3. What tools are better at learning Java?
A: I suggest using JDK + Text Editor first, which helps you understand the following basic concepts: path, class
Path
, Package
Familiar with basic commands: javac and java. Download the API help that is consistent with your JDK version.

If you are not sure about the usage of classes or functions, check the API instead of posting for help.
After you are familiar with Java, you can consider changing the IDE. Many people recommend JCreator. In fact, JCreator has weak functions.
The author recommended eclipse, download web site http://www.eclipse.org ;. Because eclispe is free of charge.

4. What are the good reference books for learning Java?
A: The author first recommends Thinking in Java, which is named "Java programming ideology" and has a Chinese version.
The first chapter of this book introduces many object-oriented programming ideas that should be carefully read by beginners.
In addition, the books of o'relly and Wrox are also good. The author himself does not like the books of Chinese 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 check the API frequently, and
That's also
It is in English.

5 Which of the following is better for Java and C ++?
A: This is an inappropriate question. You should ask: Which Java and C ++ are more suitable for my project?
If you do not need cross-platform or distributed systems, you need to emphasize the program running speed. C ++ is more suitable.
What is the opposite? You should consider Java.

6. What is J2SE, J2EE, and j2s?


A: J2SE is a general Java.
It is intended for embedded devices, such as Java mobile phones. It has its own SDK. J2EE uses the J2SE SDK.
The J2EE specification is more about the requirements for J2EE servers and the constraints imposed by developers. For details, see the subsequent J2EE FAQ.

Ii. Commands

7. I wrote the first Java program. How should I compile/run it?
A: First, save the program as a xxx. java file,
Then use the javac xxx. java command in the dos window. You will find that there is an additional xxx. class file in this directory.
,
Use the java xxx command to run your java program.

8. I did as you said, but what "'javac' is not an internal or external command or a runable Process
Ordinal or
Batch files. ".
A: You have encountered a path problem. The operating system searches for javac.exe in a specific dimension (path.exe, but cannot find
.
Edit the environment variable of your operating system, add a JAVA_HOME variable, and set it to your JDK installation directory,
Edit the Path variable and add % JAVA_HOME % \ bin.
Close and open a new dos window, and you can use javac and java commands.

9 how to set environment variables?
A: Please contact someone else.

10 javac xxx. java passed smoothly, but what "NoClassDefFoundErro" is displayed in java xxx?
R "? Br>

? Br> A: You have encountered the classpath problem. Search for the java command in a certain range (classpath)
Class File
, But cannot be found.
First, make sure that you have not typed it into java xxx. class,
Second, check your CLASSPATH environment variable. If you have set this variable and it does not contain. (This indicates the current directory.
? Br> Turbo? Br> you will encounter this problem. Add a variable in your CLASSPATH environment .. Another
See section 15.

11 "Exception in thread" main "java. lang. NoSuchMethod displayed in java xxx
Erro
R: main ".
A: First, each java file in your program has only one public class,
The class name must be exactly the same as the file name.
Second, only one public static void main (String [] args) party can be included in the class you want to run.
Method,
This method is your main program.

12 What does package mean? How to use it?
A: to uniquely identify and group each class, java uses the package concept.
Each class has a full name. For example, the full name of String is java. lang. String, where java. lang is the package name,
Stri
Ng is a short name.
In this way, if you define a String, you can put it in the mypackage,
Use the full name mypackage. String and java. lang. String to distinguish these two classes.
At the same time, you can put the logic-related classes in the same package to make the program structure clearer.


All you need to do is add a line "package mypackage;" at the beginning of the java file ;".
Note that the packages are not nested or contain relationships. Package A and Package A. B are two parallel packages for java commands (although developers
Possible? Br> stool view? Link included )?? Br>
13. What if I didn't declare any package?
A: Your class is considered to be in the default package. The full and short names are the same.

14. How to use other classes in one class?
A: If you use classes in the java. lang package, you do not have to do anything.
If you use classes in other packages, use import package1.class1; or import package2 .*;
Here. * Indicates introducing all classes in this package. Then you can use the short names of other classes in the program.
If short names conflict, use the full name to differentiate them.

15 when I use a package, "NoClassDefFoundError" is displayed, but when I remove all packages
Hou Neng
Normal operation.
A: store your java files by package name.
For example, if your working directory is/work and your class is package1.class1, store it as/work/package.
1/cl
Ass1.java.
If no package is declared, put it directly under/work.
Run javac package1/class1.java under/work and then java package1.class1. You will find that
Everything
Normal.
In addition, you can consider using IDE.



16 What should I do if I want to compile java into an exe file?
A: JDK can only compile java source files into class files.
A class file is a cross-platform bytecode that must be run based on the platform-related JRE. Java to achieve cross-region
Platform? Br> bath? Br> some development tools can compile java files into exe files. The author objected to this practice because
In this way, the cross-platform is canceled.
.
If you are sure that your software only runs on Windows, you can use C ++/C # for programming.

17 what does "deprecated API" I encountered during compilation mean?
A: What does deprecated mean? ?? Br>
Method may be removed later. You should use a newer method.
Generally, the API describes how to replace it.

Iii. I/O

18 how do I add startup parameters to a java program, just like dir/p/w?
A: Do you still remember public static void main (String [] args? Here, args is your startup parameter.
Number.
When you run java package1.class1-arg1-arg2, args contains two strings, one
Yesarg
1. The other is arg2.

19 How do I input an int/double/string from the keyboard?


A: java I/O operations are a little more complex than C ++ operations. The sample code is as follows:
BufferedReader cin = new BufferedReader (new InputStreamReader (System. in ))
;
String s = cin. readLine ();
In this way, you get a string. If you need a number, add:
Int n = Integer. parseInt (s); or double d = Double. parseDouble (s );

20 how can I output an int/double/string?
A: start writing in the program:
PrintWriter cout = new PrintWriter (System. out );
Write as needed:
Cout. print (n); or cout. println ("hello.

21 I found that some books directly use System. in And System. out input and output, which is much simpler than you.
A: java uses unicode, which is a double byte. System. in And System. out are single-byte streams.
If you want to input and output double-byte text such as Chinese, use the author's practice.

22. How do I input an int/double/string from a file?
A: It is similar to inputting data from the keyboard.
BufferedReader fin = new BufferedReader (new FileReader ("myFileName "));
PrintWriter fout = new PrintWriter (new FileWriter ("myFileName "));
If you have not downloaded the API, download it and read the content in the java. io package.



23 What should I do if I want to read and write the specified file location?
A: You certainly didn't take the API seriously. Java. io. RandomAccessFile can meet your needs.

24. How can I judge that the object to be read has reached the end?
A: You certainly didn't take the API seriously. In the Reaer's read method, the returned-1 indicates the end of the stream.

4. Keyword

25 how to define Macros in java?
A: java does not support macros, because the replacement of macros cannot guarantee type security.
To define a constant, you can define it as a static final member of a class. See 26 and 30.

26 const cannot be used in java.
A: You can use the final keyword. For example, final int m = 9. Variables declared as final cannot be repeated.
Assignment? Br>? Br> final can also be used to declare methods or classes. Methods or classes declared as final cannot be inherited.
.
Note that const is a reserved word of java for expansion.

27 goto cannot be used in java.
A: You do not need to use goto in process-oriented languages. Check whether your program process is reasonable.
If you need to quickly jump out of multi-tier loops, java enhances the break and continue features (compared with C ++ ).
, Support? Br>? Label.


For example:
Outer:
While (...)
{
Inner:
For (...)
{
... Break inner ;...
... Continue outer ;...
}
}
Like const, goto is a reserved word of java for expansion.

28 Can I overload operators in java?
A: No. The + sign of String is the only built-in overload operator. You can define interfaces and methods to implement
Current class
Function.

29. I have a new object, but cannot delete it.
A: java has an automatic memory reclaim mechanism, namely, Garbarge Collector. You no longer have to worry about pointer errors.
, Inner? Br> are you sure you want to renew your account? Br>
30. I want to know why the main method must be declared as public static?


A: It is declared as public so that this method can be called externally. For details, see article 37 of object.
Static is used to associate a member variable/method to a class rather than an instance ).
You can directly use the static members of this class without creating an object,
You can use B. staticMember to call static members of Class B in Class.
Note that the static member variables of a class are unique and shared by all class objects.

31. What is the difference between throw and throws?
A: throws declares the exceptions thrown by a method. Throw throws an exception during actual execution of the method body.
Actions
.
If you throw an exception in the method but do not declare it in the method declaration, the compiler will report an error.
Note that the subclasses of Error and RuntimeException are exceptions and do not need to be declared.

32. What is an exception?
A: exceptions were first introduced in the Ada Language for dynamic error handling and recovery in the program.
You can intercept and handle underlying exceptions in the methods, or send the exceptions to higher-level modules for processing.
You can also throw your own exception to indicate that some exceptions have occurred. The common interception processing code is as follows:
Try
{
The following code may cause exceptions:
... // The exception is thrown, the execution process is interrupted, and the code is redirected to interception.
......
}


Catch (Exception1 e) // If prediction1 is a subclass of prediction2 and requires special processing
Front
{
// When prediction1 occurs, it is intercepted by this segment.
}
Catch (Exception2 e)
{
// When prediction2 occurs, it is intercepted by this segment.
}
Finally // This is optional
{
// This code segment is executed no matter whether an exception occurs or not.
}

33. What is the difference between final and finally?
A: For final information, see 26. Finally is used for exception mechanisms. For more information, see 32.

V. Object-oriented

34 what is the difference between extends and implements?
A: extends is used to (single) inherit a class, while implements is used to implement an interface (inter
Face
).
The interface is introduced to partially provide the multi-inheritance function.


In the interface, you only need to declare the method header and leave the method body to the implemented class.
These implemented class instances can be treated as interface instances.
Interestingly, interfaces can also be declared as extends (single inheritance) relationships.

35 how does java implement multi-inheritance?
A: java does not support explicit multi-inheritance.
Because in explicit multi-inheritance languages such as c ++, The subclass is forced to declare the ancestor's virtual base class constructor,

This violates the object-oriented encapsulation principle.
Java provides the interface and implements keywords to partially implement multi-inheritance. See section 34.

36. What is abstract?
A: The method declared as abstract does not need to be given as a method body and is left to the subclass for implementation.
If an abstract method exists in a class, the class must also be declared as abstract.
Classes declared as abstract cannot be instantiated, although they can define constructor for subclass.

37. What is the difference between public, protected, and 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 restricted to access by themselves and sub-classes,
Private Members are limited to their own access.
Java also provides the fourth default visibility. When there is no public, protected, or private modifier
Member? Br>? Visible in a package ?? Br>

Class can be modified using public or default.

38 what is the difference between Override and Overload?
A: Override refers to the inheritance relationship between the parent class and the subclass method. These methods share the same name and parameter class.
Type.
Overload refers to the relationship between different methods in the same class (which can be defined in sub-classes or parent classes,
These methods have the same name and different parameter types.

39. I inherited a method, but now I want to call the method defined in the parent class.
A: You can use super. xxx () to call the parent class method in the subclass.

40 What should I do if I want to call the constructor of the parent class in the constructor of the subclass?
A: Call super (...) In the first line of the subclass constructor.

41 I have defined several constructor methods in the same class and want to call another one in one constructor.
A: call this (...) In the first line of the constructor (...).

42 what if I don't define the constructor?
A: automatically obtain a construction method without parameters.

43. I failed to call the construction method without parameters.
A: If you define at least one constructor, there will be no automatically provided parameter-free constructor.
You need to explicitly define a construction method without parameters.



44 how can I define a destructor similar to the destructor in C ++ )?
A: A void finalize () method is provided. This method is called when Garbarge Collector recycles this object.
.
Note that it is difficult to determine when an object will be recycled. The author never felt the need to provide this method.

45 What should I do if I want to convert a parent class object into a subclass object?
A: Forced type conversion. For example
Public void meth (A)
{
B B = (B);
}
If a is not a B instance, ClassCastException is thrown. Therefore, make sure that a is indeed a B instance.
.

46. In fact, I'm not sure if a is a B instance. Can I handle it in different situations?
A: You can use the instanceof operator. For example
If (a instanceof B)
{
B B = (B);
}
Else
{
...


}

47. I modified the value of an object in the method, but after exiting the method, I found that the value of this object has not changed!
A: It is very likely that you have assigned a new object to the input parameter. For example, the following code will cause this error:
Public void fun1 (A a) // a is A local parameter that points to an external object.
{
A = new A (); // a points to a new object and is decoupled from the external object. If you want a to pass
Output
Do not write this sentence.
A. setAttr (attr); // modified the value of the new object. The external object is not modified.
}
This also happens to the basic type. For example:
Public void fun2 (int)
{
A = 10; // only applies to this method, and the variables outside will not change.
}

6. java. util

48 can I dynamically allocate arrays in java?
A: Yes. For example, int n = 3; Language [] myages = new Language [n];

49. How do I know the length of an array?


A: Use the length attribute. In the preceding example, myages. length is 3.

50 I also want to automatically change the length of the array to add/delete elements.
A: Use the sequential table -- java. util. List interface.
You can choose to use ArrayList or ArrayList. The former is array implementation, and the latter is linked list implementation.
For example, List list = new ArrayList (); or List list = new ArrayList ();.

51 What is a linked list? Why are there two implementations?
A: Please study the data structure.

52 I want to use the queue/stack.
A: use java. util. Collections list.

53 I hope there are no repeated elements.
A: Use the java. util. Set interface. For example, Set set = new HashSet ().

54. I want to traverse the set/Map.
A: use java. util. Iterator. See API.

55 I also want to be able to sort.
A: use java. util. TreeSet. For example, Set set = new TreeSet (). The elements are automatically arranged.
.
You need to implement the Comparable interface for the element, and you may also need to provide the equals () method, compareTo () method,
Hash


Code () method.

56 but I want to sort the array.
A: The java. util. Arrays class contains practical methods such as sort.

57. I want to sort by different methods.
A: define a class that implements the interface Comparator for each method and use it in combination with Arrays.

58 what is the use of Map?
A: You can use keywords to quickly access key-value pairs.

59. The set method is correct, but the get method returns the Object.
A: force type conversion to the type you need. See section 45.

60. I want to obtain a random number.
A: Use the java. util. Random class.

61 I always compare two strings with false, but they are all "abc "!
A: To compare strings, you must use the equals or equalsIgnoreCase method. Do not use =!
= Compares whether two references (variables) point to the same object rather than the content.
Related Article

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.