Re-learning Java-Basic Java programming structure (1)

Source: Internet
Author: User
Tags integer division mathematical functions

I recently saw students busy looking for job interviews and written tests in the lab. I felt deeply at my own shortcomings and decided to study the book "Java core technology" again. I used to rely on this book to enter the world of Java, however, there are also a lot of places I have missed, so it is also a sort, and then carefully learn again.

1. Simple Java applications
            System.out.println("Hello, World!"  }

This program is very simple, but illustrates some of the most important basic knowledge in Java:

If the file is named correctly and there are no errors in the source code, after compiling the source code, you will get a class containingBytecode. The Java compiler automatically names the file name. class.

2. annotations in Java

Java Annotations do not appear in executable programs. Therefore, you can add any number of comments without worrying that executable code will expand. In Java, there are three ways to write comments:

System.out.println("Hello, World!");  
3. Java Data Type

Java isStrong typeLanguage, which indicates that a type must be declared for a variable. There are eight basic types, four of which are Integer type and two floating point type.Unicode encodingChar and 1 boolean type that represents the true value.

Integer 3.1
Type Storage Requirements Value Range
Int 4 bytes -2147483648--2147483647 (approximately 2 billion)
Short 2 bytes -32768--32767
Long 8 bytes -9223372010954775808--923337201095477807
Byte 1 byte -128--127

 

 

 

 

 

Generally, int type can meet most of our requirements. Byte and short are usedSuch as underlying file processing or a large array that needs to control the amount of space occupied by characters. In Java, the Integer Range is irrelevant to the machine running Java code, which solves the problem of cross-platform porting. After a long integer value, there is an L (such as 400100000000l), The hexadecimal prefix 0x (such as 0 xCAFE), and The octal prefix 0 (such as 010 ). SuggestionsNot applicable to octal ConstantsBecause it is easy to confuse. And JavaNo unsigned type.

3.2 floating point type
Type Storage Requirements Value Range
Float 4 bytes About ± 3. 40282425e + 38F (6-7 digits)
Double 8 bytes About ± 1. 79769313486231570E + 308 (the valid digits are 15 digits)

 

 

 

Most applicationsAll should be usedDoubleType, onlyFew casesUseFloatType, such as the need to quickly process single-precision data, or the need to store a large amount of data. Float has a suffix F (such as 3.402F), and double can be suffixed with D or not. In JDK5.0, you can use hexadecimal notation to represent floating point values.Floating point numbers are not suitable for financial calculation that prevents rounding errors.The reason is that the floating point uses binary and cannot accurately represent the score of 1/10. UseBigDecimalClass.

There are three special floating point values used to indicate one point and an error:

  • Positive infinity Double. POSITIVE_INFINITY
  • Negative infinity Double. NEGATIVE_INFINITY
  • NaN (not a number) Double. NaN
 (x == Double.NaN)  (Double.isNaN(x)) 
3.3 char type

Char represents a single character. It is often used to represent a character constant.'A'It is a character constant corresponding to encoding 65.""Is A string containing character. Unicode encoding is represented in hexadecimal notation from \ u0000 to \ Uffff. In Java, the char type isUTF-16Encoding describes a code unit. We recommend that youChar is not used in the program.

The transfer sequence of special characters is as follows: \ B Indicates backspace, \ t indicates indicator, \ n indicates line feed, \ r indicates carriage return, \ "indicates double quotation marks, \ 'indicates single quotation marks, \ indicates the backslash.

3.4 boolean Type

Boolean has two values: false and true for logical judgment. Between integer and BooleanNoEnough for mutual conversion (C ++ is acceptable, but Java is not)

4. Java Variables

In Java, each variable belongs to a type (either a basic type, a structure, or a class) A variable name must start with a subtitle in a sequence composed of numbers and letters (no Unicode character, such as + and ①, no space), or use a reserved word in Java.Case Sensitive.

 i, j; 
4.1 Initialization of Variables

After declaring a variable, you must use the value assignment statement to initialize the display of the variable.

 

JavaCode declaration can be placed anywhere. C ++ distinguishes declaration and definition of variables, but Java does not.

4.2 Constants

Using keywords in JavaFinalDeclare a constant (C ++ uses const, but Java sets const as a reserved word, but it is not used). Once copied, it cannot be changed. Traditionally, constant names are usedUppercase. If you want constants to be used in multiple methods of a class, you can use keywordsStatic fianlIn this way, the constant belongs to the static member of the entire class.

     PI = 3.14
5. Operators

In Java, use + ,-,*,/.When both operands involved in the operation are integers, the integer division is used. Otherwise, the floating point division is used.% Is used for the remainder operation. If the integer is 0, an exception occurs. If the floating point is 0, an infinite number or NaN is returned.

You can use a simplified format to write Binary Arithmetic Operators: x + = 4; equivalent to x = x + 4;

Running the same operation on different virtual machines makes it difficult for floating point computing to obtain the same result. The reason is that double uses 64-bit storage, while some processors use 80-bit floating-point registers, which increases the computing accuracy of the intermediate process. AvailableStrictfpKeyword marking method or class, so that the method must use strict floating point calculation to generate an ideal record.

5.1 auto-increment and auto-subtraction Operators

In programming languages, the addition of 1 and subtraction of 1 are the most common operations for numerical variables. Therefore, the auto-increment and subtraction operators are provided: n ++ adds 1 to the current value of the variable, n -- subtract 1 from the current value. Auto-increment and auto-increment are divided into prefix (++ n) and suffix (n ++. If it appears in an expression, the suffix first adds 1 to the variable and then runs the expression. The prefix first performs expression operations and then adds 1 to the variable.

M = 7 n = 7 a = 2 * ++ m; B = 2 * n ++; // do not use the ++ symbol inside the expression, which may lead to confusion, and generate unexpected bugs
5.2 Relational operators and boolean operators

Java contains various Relational operators. = Check for equality ,! + Check whether the values are not equal, and <, >,< =,> =.

& Indicates logical "and", | indicates logical "or",! Indicates the logic "not". Java logic operations"Short Circuit"If the first operand can determine the value, the second operator is not calculated.

 a =  b = 1 (a && (--b < 1) == ) {} 

Does Java support ternary operators? :. Condition? Expression1: expression2;

 x < y ? x : y; 
5.3-bit operator (I cannot figure it myself)

ProcessingInteger valueYou can directly operate on each bit. Bitwise operators include: & (and), | (OR), ^ (XOR ),~ (Not ). & | Used for boolean values,Do not press Short CircuitCalculation. Use ">" and "<" to move right or left. "> "Fill the high position with 0"> "fill the high position with the symbol bit. Perform the modulo 32 operation on the right side of the shift operator and modulo 64 on the left side, so 1 <35 and 1 <3 are the same.

In C ++, it cannot be determined> whether it is a formula shift or a logic shift, the execution will automatically choose a type with high efficiency.> It is actually defined as a non-negative number. Java eliminates this ambiguity.

5.4 mathematical functions and constants

The Math class contains various mathematical functions. You can easily perform mathematical calculations.

 y = y =  java.lang.Math.* y = pow(x, a);

Math classes also have cross-platform issues in floating-point computing. If you want to get the same results on different platforms, you should use the StrictMath class for operations.

5.5 conversion between numeric types

When running the program, you often need to convert one numeric type to another.

Conversion without information loss: byte to short, short to int, char to int, int to long, int to double;

Possible conversion with loss of precision: int to float, long to float, long to double;

 n = 123456789 f = n; 
5.6 forced type conversion

The conversion between the numeric types described in the previous section is automatic conversion. But sometimes we need to convert the double type to the int type. Java allows this type of conversion, but some information may be lost. It needs to be implemented through the forced conversion operation.

 x = 9.997 nx = () x; 
 x = 9.997 nx = () Math.round(x); 

If you try to forcibly convert a value from one type to another, but it is out of the range of the target type, the result will become a completely different value, such as (byte) the value 300 is 44.

5.7 Enumeration type

Sometimes, the value of a variable is intended to be within a finite set. For example, clothing size S, M, L, X and so on, if you use a common string or basic type to save, there is a certain risk, for example, a wrong value is transmitted.

   String SMALL = "SMALL"   String MEDIUM= "MEDIUM"   String LARGE= "LARGE"   String EXTRA_LARGE= "EXTRA_LARGE"clothe.setSize("Small");

In this case, you can customize the enumeration type, for example

clothe.setSize(Size.MEDIUM);

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.