Home Backend Development PHP Tutorial Java Basics FAQ_PHP Tutorial

Java Basics FAQ_PHP Tutorial

Jul 13, 2016 pm 05:34 PM
dir faq java three add parameter start up Base how I program

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

What are the top ten exchange apps for digital currency? Ranking of the top ten exchange apps in the currency circle What are the top ten exchange apps for digital currency? Ranking of the top ten exchange apps in the currency circle Feb 20, 2025 pm 02:03 PM

This article summarizes the top ten leading exchange applications in the currency circle and highlights their advantages and features. These exchanges include Binance, Huobi, OKX, Binance USA, Coinbase, Kraken, Bitfinex, KuCoin, Gate.io and Crypto.com. They offer a wide range of trading pairs, trading tools and security features that cater to different investors.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

Download the top ten trading digital currency apps in the currency circle. The latest rankings of the four trading apps in the currency circle. Download the top ten trading digital currency apps in the currency circle. The latest rankings of the four trading apps in the currency circle. Feb 20, 2025 pm 06:15 PM

The top ten trading digital currency apps in the currency circle: Binance, OKX, Gate.io, Bitget, Huobi, Bybit, KuCoin, MEXC, Poloniex, BitMart. Among them, the four major trading apps in the currency circle are: Binance, OKX, Gate.io, and Bitget, which provide a wide range of cryptocurrency options, low transaction fees, a powerful trading platform and advanced trading functions.

See all articles