search
HomeBackend DevelopmentPHP TutorialJava Basics FAQ_PHP Tutorial

Java Basics FAQ_PHP Tutorial

Jul 13, 2016 pm 05:34 PM
dirfaqjavathreeaddparameterstart upBasehowIprogram

Java Basic FAQ

Java Basic FAQ

3. I/O Chapter

18
How do I add startup to the java program Parameters, like dir /p/w?
Answer: Do you remember public static void main(String[] args)? The args here are your startup parameters.
When you enter java package1.class1 -arg1 -arg2 at runtime, there will be two Strings in args, one is arg1 and the other is arg2.

19 How do I enter an int/double/string from the keyboard?
Answer: Java’s I/O operations are a little more complicated than C++. If you want to input from the keyboard, the sample code is as follows:

BufferedReader cin = new BufferedReader( new InputStreamReader( System.in ) )
;
String s = cin.readLine ();


This way you get a string, if you need numbers add:

int n = Integer.parseInt( s );


or

double d = Double.parseDouble( s );



20 How do I output an int/double/string?
Answer: Write at the beginning of the program:

PrintWriter cout = new PrintWriter( System.out );


Write when necessary: ​​

cout.print(n);


or

cout.println("hello")


Wait.

21 I found that some books directly use System.in and System.out for input and output, which is much simpler than yours.
Answer: Java uses unicode, which is double bytes. System.in and System.out are single-byte streams. If you want to input and output double-byte text such as Chinese, please use the author's approach.

4. Keywords

25
How to define macros in java?
Answer: Java does not support macros because macro substitution cannot guarantee type safety. If you need 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.
Answer: You can use the final keyword. For example final int m = 9. Variables declared final cannot be assigned again. It 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.
Answer: Even in process-oriented languages ​​you can do without goto at all. Please check whether your program flow is reasonable. If you need to quickly jump out of a multi-level loop, Java has enhanced break and continue functions (compared to C++).
For example:

outer :
while( ... )
{
inner :
for( ... )
{
... break inner; ...
... continue outer; ...
}
}


Like const, goto is also a reserved word of Java for expansion.

28 Can operators be overloaded in java?
Answer: No. String's + sign is the only built-in overloaded operator. You can achieve similar functionality by defining interfaces and methods.

29 I created a new object, but I cannot delete it.
Answer: Java has an automatic memory recycling mechanism, the so-called Garbarge Collector. You never have to worry about pointer errors again.

30 I want to know why the main method must be declared as public static?
Answer: The purpose of declaring it as public is so that this method can be called externally. For details, see Object-Oriented Chapter 37.
Static is to associate a member variable/method with a class rather than an instance. You can directly use the static members of this class without creating an object. To call the static members of class B in class A, you can use the writing method B.staticMember. Note that the static member variables of a class are unique and shared by all objects of the class.

31 What is the difference between throw and throws?
Answer: throws is used to declare which exceptions a method will throw. Throw is the actual action of throwing an exception in the method body. If you throw an exception in a method but do not declare it in the method declaration, the compiler will report an error. Note that subclasses of Error and RuntimeException are exceptions and do not need to be specifically declared.

32 What is an exception?
Answer: Exceptions were first introduced in the Ada language and are used to dynamically handle errors and recover in programs. You can intercept the underlying exception in the method and handle it, or you can throw it to a higher-level module for processing. You can also throw your own exception to indicate that something unusual has occurred. Common interception processing codes are as follows:

try
{
... //The following is the code where exceptions may occur
... //The exception is thrown out, the execution flow is interrupted and diverted to the interception code.
 ...
}

catch(Exception1 e) //If Exception1 is a subclass of Exception2 and needs special processing, it should be ranked first
{
//When Exception1 occurs, it is intercepted by this section
}
catch(Exception2 e)
 {
 //When Exception2 occurs, it is intercepted by this section
}
Finally //This is possible Selected
{
//Execute this code regardless of whether an exception occurs
}

33 What is the difference between final and finally?
Answer: Please see 26 for the final. finally is used for exception mechanism, see 32.


5. Object-oriented

34 What is the difference between extends and implements?
Answer: extends is used to (singlely) inherit a class, while implements is used to implement an interface. The interface was introduced to partially provide the functionality of multiple inheritance.
Only declare the method header in the interface, leaving the method body to the implementing class. Instances of these implemented classes can be treated completely as instances of interface. What is interesting is that the relationship between interfaces can also be declared as extends (single inheritance).

35 How to implement multiple inheritance in java?
Answer: Java does not support explicit multiple inheritance. Because in explicit multiple inheritance languages ​​such as C++, there will be a problem where subclasses are forced to declare ancestor virtual base class constructors, which violates the object-oriented encapsulation principle. Java provides the interface and implements keywords to partially implement multiple inheritance. See 34.

36 What is abstract?
Answer: Methods declared as abstract do not need to give a method body, leaving it to subclasses to implement. 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 constructors for use by subclasses.

37 What is the difference between public, protected and private?
Answer: 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 subclasses, and
private members are limited to themselves.
Java also provides a fourth type of default visibility, generally called package private. When there are no public, protected, or private modifiers, members are visible in the same package. Classes can be modified with public or default.

38 What is the difference between Override and Overload?
Answer: Override refers to the inheritance relationship of methods between parent class and subclass. These methods have the same name and parameter type. Overload refers to the relationship between different methods in the same class (which can be defined in subclasses 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.
Answer: Use super.xxx() to call parent class methods in subclasses.

40 I want to call the constructor of the parent class in the constructor of the subclass. What should I do?
Answer: Just call super(...) on the first line of the subclass constructor.

41 I have defined several constructors in the same class and want to call another constructor from one constructor.
Answer: Call this(...) in the first line of the constructor.

42 What happens if I don’t define a constructor?
Answer: Automatically obtain a parameterless constructor.

43 My call to the parameterless constructor failed.
Answer: If you define at least one constructor, there is no longer an automatically provided parameterless constructor. You need to explicitly define a parameterless constructor.

44 How should I define a destructor similar to that in C++?
Answer: Provide a void finalize() method. This method will be called when the Garbarge Collector recycles the object. Note that it is actually difficult to tell 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?
Answer: Forced type conversion. For example,

public void meth(A a)
{
B b = (B)a;
}


If a is not actually an instance of B, it will throws ClassCastException. So make sure a is indeed an instance of B.

46 Actually, I am not sure whether a is an instance of B. Can it be handled according to the situation?
Answer: You can use the instanceof operator. For example

if( a instanceof B )
{
B b = (B)a;
}
else
{
...
}

47 I modified the value of an object in the method, but after exiting the method I found that the value of the object has not changed!
Answer: It is very likely that you reassigned the incoming parameters to a new object. For example, the following code will cause this error:

public void fun1(A a) //a is a local parameter, pointing 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 be used as an outgoing variable, don't write this sentence.
a.setAttr(attr);//The value of the new object is modified, and the external object is not modified.
}


This will also happen with basic types. For example:

public void fun2(int a)
{
a = 10;//Only affects this method, external variables will not change.
}



6. java.util

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/508516.htmlTechArticleJava Basics FAQ Java Basics FAQ 3. I/O Chapter 18 How do I add startup parameters to a java program, like dir /p/w like that? Answer: Remember public static void main(String[] args)? The args here are...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function