In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces the relevant knowledge of "what are the basic knowledge of Java introduction". The editor shows you the operation process through actual cases, the operation method is simple and fast, and it is practical. I hope this article "what is the basic knowledge of Java introduction" can help you solve the problem.
Java is a high-level programming language introduced by Sun Microsystems in May 1995.
Java can run on multiple platforms, such as Windows, Mac OS, and many other UNIX versions of systems.
Create a java file (the file name must be the same as the class name)
Http:/ / www.iis7.com/b/wzjk/
Both String args [] and String [] args can be executed, but String [] args is recommended to avoid ambiguity and misreading.
:::
Introduction to Java
Java is the general name of Java object-oriented programming language and Java platform introduced by Sun Microsystems in May 1995. It was jointly developed by James Gosling and colleagues and officially launched in 1995.
Java is divided into three systems:
JavaSE (J2SE) (Java2 Platform Standard Edition,java platform Standard Edition)
JavaEE (J2EE) (Java 2 Platform,Enterprise Edition,java platform Enterprise Edition)
JavaME (J2ME) (Java 2 Platform Micro Edition,java platform Micro Edition).
In June 2005, the JavaOne conference was held, and SUN made Java SE 6 public. At this point, various versions of Java have been renamed to cancel the number "2": J2EE has been renamed to Java EE, J2SE has been renamed Java SE,J2ME to Java ME.
.
Main characteristics
1. Java language is simple:
The syntax of Java language is very similar to C language and C++ language, which makes it easy for most programmers to learn and use. On the other hand, Java discards difficult and confusing features rarely used in C++, such as operator overloading, multi-inheritance, and automatic casting. In particular, the Java language does not use pointers, but references. It also provides automatic garbage collection so that programmers do not have to worry about memory management.
2. Java language is object-oriented:
Java language provides object-oriented features such as classes, interfaces and inheritance. For simplicity, it only supports single inheritance between classes, but supports multiple inheritance between interfaces, and supports the implementation mechanism between classes and interfaces (keyword is implements). Java language fully supports dynamic binding, while C++ language only uses dynamic binding for virtual functions. In a word, Java is a pure object-oriented programming language.
3. Java language is distributed:
Java language supports the development of Internet applications. There is a network application programming interface (java net) in the basic Java API, which provides class libraries for network application programming, including URL, URLConnection, Socket, ServerSocket and so on. Java's RMI (remote method Activation) mechanism is also an important means of developing distributed applications.
4. Java language is robust:
Java's strong typing mechanism, exception handling and automatic garbage collection are important guarantees for the robustness of Java programs. Discarding pointers is a wise choice for Java. The security checking mechanism of Java makes Java more robust.
5. Java language is secure:
Java is usually used in the network environment, for this reason, Java provides a security mechanism to prevent malicious code attacks. In addition to many of the security features of the Java language, Java has a security mechanism (ClassLoader-like loader) for classes downloaded over the network, such as assigning different namespaces to prevent replacing local classes of the same name, bytecode checking, and providing a security management mechanism (class SecurityManager) to allow Java applications to set security sentinels.
6. The Java language is architecture neutral:
Java programs (files with the suffix java) are compiled into an architecture-neutral bytecode format (files with the suffix class) on the Java platform, and can then be run on any system that implements the Java platform. This approach is suitable for heterogeneous network environment and software distribution.
7.The Java language is portable:
This portability stems from architectural neutrality, and Java strictly specifies the length of each basic data type. The Java system itself also has strong portability. The Java compiler is implemented in Java and the running environment of Java is implemented in ANSI C.
8. The Java language is interpretive:
As mentioned earlier, Java programs are compiled into bytecode format on the Java platform and can then be run on any system that implements the Java platform. At run time, the Java interpreter in the Java platform interprets and executes these bytecodes, and the classes needed during the execution are loaded into the runtime during the join phase.
9. Java is of high performance:
Java is indeed high-performance compared to those interpreted high-level scripting languages. In fact, the running speed of Java is getting closer and closer to that of C++ with the development of JIT (Just-In-Time) compiler technology.
10. The Java language is multithreaded:
In the Java language, a thread is a special object that must be created by the Thread class or its descendant class. There are usually two ways to create a thread: one is to wrap an object that implements the Runnable interface into a thread using a constructor of type Thread (Runnable), and the other is to derive a subclass from the Thread class and override the run method, and the object created using that subclass is a thread. It is worth noting that the Thread class already implements the Runnable interface, so any thread has its run method, and the run method contains the code that the thread wants to run. Thread activity is controlled by a set of methods. The Java language supports simultaneous execution of multiple threads and provides a synchronization mechanism between multiple threads (keyword is synchronized).
11. Java language is dynamic:
One of the design goals of Java language is to adapt to the dynamic environment. The classes needed by Java programs can be dynamically loaded into the runtime environment, or the required classes can be loaded through the network. This is also conducive to software upgrade. In addition, the classes in Java have a run-time representation that can perform run-time type checking.
.
History of development
On May 23, 1995, the Java language was born.
In January 1996, the first JDK-JDK1.0 was born.
In April 1996, the 10 leading operating system vendors announced that they would embed JAVA technology in their products.
In September 1996, about 83000 web pages were created using JAVA technology.
On February 18, 1997, JDK1.1 released
On April 2, 1997, the JavaOne meeting was held with more than 10, 000 participants, setting a record for similar meetings in the world at that time.
In September 1997, the members of the JavaDeveloperConnection community exceeded 100, 000
In February 1998, JDK1.1 was downloaded more than 2000000 times.
JAVA2 enterprise platform J2EE was released on December 8, 1998.
In June 1999, SUN released three versions of Java: the Standard Edition (JavaSE, formerly J2SE), the Enterprise Edition (JavaEE formerly J2EE), and the Micro Edition (JavaME, formerly J2ME)
On May 8, 2000, JDK1.3 released
JDK1.4 released on May 29th, 2000
On June 5, 2001, NOKIA announced that it would sell 100 million Java-enabled mobile phones by 2003.
On September 24th, 2001, J2EE1.3 released
On February 26th, 2002, J2SE1.4 released, since then the computing power of Java has been greatly improved.
On Sept. 30th, 2004, the release of J2SE 1.5 of 18 00PMMJ became another milestone in the history of Java language development. To show the importance of this version, J2SE1.5 changed its name to Java SE 5.0
In June 2005, the JavaOne conference was held, and SUN made Java SE 6 public. At this point, various versions of Java have been renamed to cancel the number "2": J2EE renamed Java EE,J2SE to Java SE,J2ME renamed Java ME
In December 2006, SUN released JRE6.0
On April 20, 2009, Oracle acquired Sun for $7.4 billion. Obtain the copyright of java.
In November 2010, Apache threatened to quit Java because of Oracle's unfriendliness to the JCP community.
On July 28th, Oracle released the official version of java7.0.
On March 18, 2014, Oracle released Java SE 8.
.
JDK environment configuration:
1. Download JDK from the official website
two。 Install (just follow the prompts)
3. Turn on my computer-Advanced system Settings-system variables
Add JAVA_HOME: add according to your actual installation path
Add CLASSPATH:.;% JAVA_HOME%\ lib\ dt.jar;%JAVA_HOME%\ lib\ tools.jar; / / remember that there is a "."
Edit the path of the system variable: add:% JAVA_HOME%\ bin;%JAVA_HOME%\ jre\ bin at the beginning
Then find cmd and enter java-version,java,javac at the beginning to see if the build is successful.
.
Java development tools
The Java language tries to ensure that there is more than 1G in the system. Other tools are as follows:
Linux system, Mac OS system, Windows 95, 98, 2000, XP, win, 7, and 8 systems.
Java JDK 7, 8...
Notepad editor or other editor.
IDE:Eclipse
After installing the above tools, we can output Java's first program, "Hello World!"
:::
Basic syntax of Java
A Java program can be thought of as a collection of objects that work together by calling each other's methods. The following briefly describes the concepts of classes, objects, methods, and instance variables.
Object: an object is an instance of a class that has state and behavior. For example, a dog is an object, its status is: color, name, breed; behavior: wagging tail, barking, eating and so on.
Class: a class is a template that describes the behavior and state of a class of objects.
Method: a method is a behavior, and a class can have many methods. Logical operations, data modifications, and all actions are done in the method.
Instance variables: each object has unique instance variables, and the state of the object is determined by the values of these instance variables.
.
Basic grammar
When writing Java programs, you should pay attention to the following points:
Case-sensitive: Java is case-sensitive, which means that the identifier Hello is different from hello.
Class name: for all classes, the first letter of the class name should be capitalized. If the class name consists of several words, the first letter of each word should be capitalized, such as MyFirstJavaClass.
Method name: all method names should start with lowercase letters. If the method name contains several words, the first letter of each subsequent word is capitalized.
Source file name: the source file name must be the same as the class name. When saving a file, you should use the class name as the file name (keep in mind that Java is case-sensitive), with the suffix .java. (if the file name and class name are different, it will result in a compilation error)
Main method entry: all Java programs are executed by the public static void main (String [] args) method.
.
Java identifier
All components of Java need names. Class names, variable names, and method names are all called identifiers.
With regard to Java identifiers, there are the following points to note:
All identifiers should start with a letter (Amurz or amurz), a dollar sign ($), or an underscore (_).
The first character can be followed by a letter (Amurz or amurz), a dollar sign ($), an underscore (_), or any combination of numbers
Keyword cannot be used as an identifier
Identifiers are case sensitive
Examples of legal identifiers: age, $salary, _ value, _ _ 1_value
Examples of illegal identifiers: 123abc,-salary
.
Java modifier
Like other languages, Java can use modifiers to modify methods and properties in a class. There are two main types of modifiers:
Access control modifiers: default, public, protected, private
Non-access control modifiers: final, abstract, strictfp
.
Java variable
There are mainly the following types of variables in Java
Local variable
Class variable (static variable)
Member variables (non-static variables)
.
Java array
An array is an object stored on a heap that can hold multiple variables of the same type.
.
Java enumeration
Java 5. 0 introduces enumerations, which limit variables to pre-set values. Use enumerations to reduce the bug in your code.
For example, we design a program for juice shops that will limit juice to small, medium and large. This means that customers are not allowed to order fruit juices other than these three sizes.
Note: enumerations can be declared separately or in a class. Methods, variables, and constructors can also be defined in enumerations.
.
Java keyword
The Java reserved words are listed below. These reserved words cannot be used for the names of constants, variables, and any identifiers.
Keyword description
Abstract abstract methods, modifiers for abstract classes
Assert asserts whether the condition is met
Boolean Boolean data type
Break jumps out of a loop or label code snippet
Byte8-bit signed data type
A condition of caseswitch statement
Catch and try work together to capture abnormal information.
Char16-bit Unicode character data type
Class definition class
Const is not in use
Continue does not execute the rest of the loop body
Default branch in default switch statement
Do loop statement, the loop body executes at least once
Double 64-bit double precision floating point number
Branch executed when the else if condition does not hold
Enum enumerated type
Extends indicates that one class is a subclass of another class
Final means that a value cannot be changed after initialization, that a method cannot be overridden, or that a class cannot have subclasses.
Finally is designed to complete the executed code, mainly for the robustness and integrity of the program, regardless of whether an exception occurs or not.
Float 32-bit single precision floating point number
For for loop statement
Goto is not in use
If conditional statement
Implements represents a class that implements an interface
Import Import Class
Instanceof tests whether an object is an instance of a class
Int 32-bit integers
Interface interface, an abstract type with only methods and constants defined
Long 64-bit integers
Native representation is implemented in non-java code
New assigns a new class instance
Package consists of a series of related classes to form a package
Private represents private fields, methods, etc., and can only be accessed from within the class
Protected means that fields can only be accessed through a class or its subclasses, subclasses or other classes in the same package
Public represents a common property or method
The return method returns a value
Short 16-digit number
Static means defined at the class level and shared by all instances
Strictfp floating point numbers use strict rules
Super represents the base class
Switch select statement
Synchronized represents a block of code that can only be accessed by one thread at a time
This means to call the current instance or to call another constructor
Throw throws exception
Throws defines exceptions that may be thrown by a method
Transient decorates fields that are not serialized
Try indicates that the code block needs to do exception handling or works with finally to indicate whether or not to throw an exception executes the code in finally
The void tag method does not return any value
Volatile tag fields may be accessed by multiple threads at the same time without synchronization
While while cycle
.
Java comment
, / / single-line comments in java
In java, / * multiline comments * /
Similar to CumberCandle annotations Java also supports single-line as well as multi-line comments. The characters in the comment will be ignored by the Java compiler.
.
Java blank line
Blank lines, or lines with comments, are ignored by the Java compiler.
.
Inherit
In Java, one class can be derived from other classes. If you are creating a class and there is already a class with the properties or methods you need, you can inherit the newly created class.
With inherited methods, you can reuse the methods and properties of existing classes without having to rewrite the code. An inherited class is called a super class, and a derived class is called a subclass.
.
Interface
In Java, an interface can be understood as a protocol for objects to communicate with each other. Interfaces play an important role in inheritance.
The interface defines only the methods to be used by the derivation, but the specific implementation of the method depends entirely on the derived class.
:::
Java objects and classes
Java is an object-oriented language. The following basic concepts are supported:
Polymorphisms
Inheritance
Encapsulation
Abstract
Class
: object
: an example
Methods
Message parsing
.
Let's first study the concepts of objects and classes.
Object: an object is an instance of a class that has state and behavior. For example, a dog is an object, its status is: color, name, breed; behavior: wagging tail, barking, eating and so on.
Class: a class is a template that describes the behavior and state of a class of objects. (abstract classes: such as animals, people, etc.)
. . .
Objects in Java
Now let's take a closer look at what an object is. If you look at the real world around you, you will find that there are many objects, cars, dogs, people and so on. All of these objects have their own state and behavior.
Take a dog as an example, its status is: name, breed, color, behavior: barking, wagging tail and running.
Compared with real objects and software objects, they are very similar.
Software objects also have states and behaviors. The state of the software object is the property, and the behavior is reflected by the method.
In software development, the method manipulates the change of the internal state of the object, and the mutual call of the object is also accomplished through the method.
. . .
Classes in Java
Class can be thought of as a template for creating Java objects.
Understand the definition of a class in Java through the following simple class:
Public class Dog {
String breed
Int age
String color
Void barking () {
}
Void hungry () {
}
Void sleeping () {
}
}
A class can contain the following types of variables:
Local variables: variables defined in methods, constructors, or statement blocks are called local variables. Variable declaration and initialization are in the method, and after the method ends, the variable is automatically destroyed.
Member variables: member variables are defined in the class, outside the body of the method. This variable is instantiated when the object is created. Member variables can be accessed by methods, constructors, and statement blocks of a specific class.
Class variables: class variables are also declared in the class, outside the method body, but must be declared as a static type.
A class can have multiple methods, and in the above example: barking (), hungry (), and sleeping () are all methods of the Dog class.
. . .
Construction method
Every class has a constructor. If you do not explicitly define a constructor for a class, the Java compiler will provide a default constructor for the class.
At least one constructor must be called when creating an object. The name of the constructor must be the same as the class, and a class can have more than one constructor.
The following is an example of a constructor:
Public class Puppy {
Public Puppy () {
}
Public Puppy (String name) {
/ / this constructor has only one parameter: name
}
}
. . .
Create object
The object is created from the class. In Java, use the keyword new to create a new object. Creating an object requires the following three steps:
Declare: declare an object, including the object name and object type.
Instantiation: use the keyword new to create an object.
Initialization: when you create an object using new, the constructor is called to initialize the object.
Here is an example of creating an object:
Public class Puppy {
Public Puppy (String name) {
/ / this constructor has only one parameter: name
System.out.println ("Passed Name is:" + name)
}
Public static void main (String [] args) {
/ / the following statement creates a Puppy object
Puppy myPuppy = new Puppy ("tommy")
}
}
Compiling and running the above program will print out the result on the right: Passed Name is: tommy
. . .
Access instance variables and methods
Access member variables and member methods through the objects you have created, as follows:
/ * instantiate object * /
ObjectReference = new Constructor ()
/ * access the variables * /
ObjectReference.variableName
/ * access methods in the class * /
ObjectReference.MethodName ()
. . .
Example
The following example shows how to access instance variables and call member methods:
Public class Puppy {
Int puppyAge
Public Puppy (String name) {
/ / this constructor has only one parameter: name
System.out.println ("Passed Name is:" + name)
}
Public void setAge (int age) {
PuppyAge = age
}
Public int getAge () {
System.out.println ("Puppy's age is:" + puppyAge)
Return puppyAge
}
Public static void main (String [] args) {
/ * create an object * /
Puppy myPuppy = new Puppy ("tommy")
/ * set age by method * /
MyPuppy.setAge (2)
/ * call another method to get age * /
MyPuppy.getAge ()
/ * you can also access member variables as follows * /
System.out.println ("Variable Value:" + myPuppy.puppyAge)
}
}
Compile and run the above program to produce the following results:
Passed Name is: tommy
Puppy's age is: 2
Variable Value: 2
. . .
Source file declaration rules
Let's learn the declaration rules of the source file. Pay special attention to these rules when multiple classes are defined in a source file, and there are import statements and package statements.
There can be only one public class in a source file
A source file can have multiple non-public classes
The name of the source file should be consistent with the class name of the public class. For example, if the class name of the public class in the source file is Employee, then the source file should be named Employee.java.
If a class is defined in a package, the package statement should be on the first line of the source file.
If the source file contains an import statement, it should be placed between the package statement and the class definition. If there is no package statement, then the import statement should come first in the source file.
Import statements and package statements are valid for all classes defined in the source file. You cannot declare different packages for different classes in the same source file.
Classes have several levels of access, and classes are divided into different types: abstract classes, final classes, and so on.
In addition to the types mentioned above, Java also has some special classes, such as inner classes and anonymous classes.
. . .
Java package
Packages are mainly used to classify classes and interfaces. When developing Java programs, hundreds of classes may be written, so it is necessary to classify classes and interfaces.
. . .
Import statement
In Java, if you give a complete qualified name, including package name and class name, then the Java compiler can easily locate the source code or class. The import statement is used to provide a reasonable path so that the compiler can find a class.
For example, the command line on the right will command the compiler to load all classes under the java_installation/java/io path, import java.io.*
A simple example.
In this example, we create two classes: Employee and EmployeeTest.
First open the text editor and paste the following code in. Be careful to save the file as Employee.java.
The Employee class has four member variables: name, age, designation, and salary. This class explicitly declares a constructor that has only one parameter.
Import java.io.*
Public class Employee {
String name
Int age
String designation
Double salary
/ / the constructor of the Employee class
Public Employee (String name) {
This.name = name
}
/ / set the value of age
Public void empAge (int empAge) {
Age = empAge
}
/ * set the value of designation * /
Public void empDesignation (String empDesig) {
Designation = empDesig
}
/ * set the value of salary * /
Public void empSalary (double empSalary) {
Salary = empSalary
}
/ * print information * /
Public void printEmployee () {
System.out.println ("Name:" + name)
System.out.println ("Age:" + age)
System.out.println ("Designation:" + designation)
System.out.println ("Salary:" + salary)
}
}
Programs are executed from the main method. In order to run this program, you must include the main method and create an instance object.
Here is the EmployeeTest class, which instantiates two instances of the Employee class and calls the method to set the value of the variable.
Save the following code in the EmployeeTest.java file.
Import java.io.*
Public class EmployeeTest {
Public static void main (String args []) {
/ * create two objects using the constructor * /
Employee empOne = new Employee ("James Smith")
Employee empTwo = new Employee ("Mary Anne")
/ / call the member methods of these two objects
EmpOne.empAge (26)
EmpOne.empDesignation ("Senior Software Engineer")
EmpOne.empSalary (1000)
EmpOne.printEmployee ()
EmpTwo.empAge (21)
EmpTwo.empDesignation ("Software Engineer")
EmpTwo.empSalary (500)
EmpTwo.printEmployee ()
}
}
By compiling the two files and running the EmployeeTest class, you can see the following results:
C: > javac Employee.java
C: > vi EmployeeTest.java
C: > javac EmployeeTest.java
C: > java EmployeeTest
Name:James Smith
Age:26
Designation:Senior Software Engineer
Salary:1000.0
Name:Mary Anne
Age:21
Designation:Software Engineer
Salary:500.0
:
Java basic data type
The variable is to request memory to store the value. That is, when you create a variable, you need to apply for space in memory.
The memory management system allocates storage space for variables according to the type of variables, and the allocated space can only be used to store that type of data.
Therefore, by defining different types of variables, you can store integers, decimals, or characters in memory.
Two big data types of Java: built-in data type and reference data type
. . .
Built-in data type
The Java language provides eight basic types. Six numeric types (four integers, two floats), one character type, and one Boolean type.
Byte:
The byte data type is an 8-bit, signed integer represented by a binary complement
The minimum value is-128 (- 2 ^ 7)
The maximum value is 127 (2 ^ 7-1)
The default is 0
The byte type is used to save space in large arrays, mainly instead of integers, because the byte variable takes up only 1/4 of the space of the int type.
Example: byte a = 100 byte b =-50.
Short:
The short data type is a 16-bit, signed integer represented by a binary complement
The minimum value is-32768 (- 2 ^ 15)
The maximum is 32767 (2 ^ 15-1)
Short data types can also save as much space as byte. A short variable is 1/2 of the space occupied by an int variable.
The default is 0
Example: short s = 1000 short r =-20000.
Int:
The int data type is a 32-bit, signed integer represented by a binary complement
The minimum value is-2147483648 (- 2 ^ 31)
The maximum is 2147483647 (2 ^ 31-1)
Generally speaking, integer variables default to int type.
The default is 0
Example: int a = 100000, int b =-200000.
Long:
The long data type is a 64-bit, signed integer represented by a binary complement
The minimum is-9223372036854775808 (- 2 ^ 63)
The maximum is 9223372036854775807 (2 ^ 63-1)
This type is mainly used in systems that require large integers.
The default value is 0L
Example: long a = 100000L Magi long b =-200000L.
Float:
The float data type is a single-precision, 32-bit floating-point number that conforms to the IEEE 754 standard
Float saves memory space when storing large floating-point arrays
The default value is 0.0f
Floating point numbers cannot be used to represent exact values, such as currency
Example: float F1 = 234.5f.
Double:
The double data type is a double-precision, 64-bit, IEEE 754-compliant floating-point number
The default type of floating point number is double.
The double type also cannot represent an exact value, such as currency
The default value is 0.0d
Example: double D1 = 123.4.
Boolean:
The boolean data type represents the information of one bit
There are only two values: true and false
This type is only used as a flag to record true/false.
The default value is false
Example: boolean one = true.
Char:
The char type is a single 16-bit Unicode character
The minimum value is'\ u0000' (that is, 0)
The maximum is'\ uffff' (that is, 65535)
The char data type can store any character
Example: char letter ='A'.
We do not have to force to remember the range of values of the basic types of numeric types, because their values are already defined in the corresponding wrapper class in the form of constants.
The minimum and maximum values of Float and Double are output in scientific notation, and the "E + number" at the end indicates that the number before E is multiplied by the "number" power of 10. For example, 3140 is 3.14x10003140314Emur3 is 3.14Universe 0.00314.
In fact, there is another basic type in JAVA, void, which also has a corresponding wrapper class java.lang.Void, but we cannot manipulate them directly.
. . .
Reference type
Reference type variables are created by the constructor of the class and can be used to access the referenced object. These variables are specified as a specific type when declared, such as Employee, Pubby, and so on. Once a variable is declared, the type cannot be changed.
Objects and arrays are reference data types.
The default value for all reference types is null.
A reference variable can be used to reference any type that is compatible with it. Example: Animal animal = new Animal ("giraffe").
. . .
Java constant
A constant is a fixed value. They do not need to be calculated and directly represent the corresponding values.
A constant is a quantity that cannot be changed. Use the final flag in Java and declare it in a manner similar to that of variables:
Final double PI = 3.1415927
Although constant names can also be lowercase, uppercase letters are usually used to represent constants for ease of identification.
Literals can be assigned to any built-in type of variable. For example:
Byte a = 68
Char a ='A'
Byte, int, long, and short can all be represented in decimal, hexadecimal, and octal.
When using constants, the prefix 0 indicates octal, while the prefix 0x represents hexadecimal. For example:
Int decimal = 100
Int octal = 0144
Int hexa = 0x64
Like other languages, Java's string constant is a sequence of characters enclosed between two quotation marks. Here is an example of string literals:
"Hello World"
"two\ nlines"
"\" This is in quotes\ ""
Both string constants and character constants can contain any Unicode character. For example:
Char a ='\ u0001'
String a = "\ u0001"
The Java language supports some special sequences of escape characters.
Symbolic character meaning
\ nLine feeds (0x0a)
\ r enter (0x0d)
\ f Page feed character (0x0c)
\ b backspace (0x08)
\ s space (0x20)
\ t Tab character
\ "double quotation marks
\ 'single quotation marks
\ backslash
\ ddd octal character (ddd)
\ uxxxx16 binary Unicode character (xxxx)
:
Java variable type
In the Java language, all variables must be declared before they are used. The basic format for declaring variables is shown on the right: type identifier [= value] [, identifier [= value].]
Format description: type is the Java data type. Identifier is the name of the variable. You can declare multiple variables of the same type with commas separated.
Some declaration examples of variables are listed below. Note that some include initialization procedures.
Int a, b, c; / / declares three int integers: a, b, c.
Int d = 3, e, f = 5; / / declare three integers and assign initial values.
Byte z = 22; / / declare and initialize z.
Double pi = 3.14159; / / declared pi.
The value of the variable x is the character'x', which is char x ='x'; / /.
The variable types supported by Java language are: local variable, instance variable, class variable.
. . .
Java local variable
-Local variables are declared in methods, constructors, or statement blocks
-Local variables are created when methods, constructors, or statement blocks are executed, and when they are completed, the variables are destroyed
-access modifiers cannot be used for local variables
-A local variable is visible only in the method, constructor, or statement block that declares it
-Local variables are assigned on the stack.
Local variables have no default values, so after local variables are declared, they must be initialized before they can be used.
Example 1
In the following example, age is a local variable. It is defined in the pupAge () method, and its scope is limited to this method.
Public class Test {
Public void pupAge () {
Int age = 0
Age = age + 7
System.out.println ("Puppy age is:" + age)
}
Public static void main (String args []) {
Test test = new Test ()
Test.pupAge ()
}
}
The compilation and running results of the above example are as follows: Puppy age is: 7
Example 2
In the following example, the age variable is not initialized, so there is an error at compile time.
Public class Test {
Public void pupAge () {
Int age
Age = age + 7
System.out.println ("Puppy age is:" + age)
}
Public static void main (String args []) {
Test test = new Test ()
Test.pupAge ()
}
}
The compilation and running results of the above examples are as follows:
Test.java:4:variable number might not have been initialized
Age = age + 7
^
1 error
. . .
Java instance variable
-instance variables are declared in a class, but outside methods, constructors, and statement blocks
-when an object is instantiated, the value of each instance variable is determined
-instance variables are created when the object is created and destroyed when the object is destroyed
-the value of the instance variable should be referenced by at least one method, constructor, or statement block, so that the external can obtain the instance variable information in these ways
-instance variables can be declared before or after use
-access modifiers can modify instance variables
Instance variables are visible to methods, constructors, or statement blocks in a class. In general, you should set the instance variable to private. You can make instance variables visible to subclasses by using access modifiers
-instance variables have default values. The default value for numeric variables is 0, for Boolean variables is false, and for reference type variables is null. The value of a variable can be specified at declaration or in the constructor
-instance variables can be accessed directly through the variable name. But in static methods and other classes, you should use the fully qualified name: ObejectReference.VariableName.
Practical examples:
Import java.io.*
Public class Employee {
/ / this member variable is visible to subclasses
Public String name
/ / Private variables, visible only in this class
Private double salary
/ / assign values to name in the constructor
Public Employee (String empName) {
Name = empName
}
/ / set the value of salary
Public void setSalary (double empSal) {
Salary = empSal
}
/ / print information
Public void printEmp () {
System.out.println ("name:" + name)
System.out.println ("salary:" + salary)
}
Public static void main (String args []) {
Employee empOne = new Employee ("Ransika")
EmpOne.setSalary (1000)
EmpOne.printEmp ()
}
}
The compilation and running results of the above examples are as follows:
Name: Ransika
Salary: 1000.0
. . .
Java class variables (static variables)
Class variables, also known as static variables, are declared with the static keyword in the class, but must be outside methods, constructors, and statement blocks.
No matter how many objects a class creates, the class has only one copy of the class variable.
-static variables are rarely used except when declared as constants. Constants are variables that are declared as public/private,final and static types. The constant cannot be changed after initialization.
-static variables are stored in static storage. It is often declared as a constant and variables are rarely declared using static alone.
-static variables are created at the beginning of the program and destroyed at the end of the program.
-has similar visibility to instance variables. However, in order to be visible to the consumers of the class, most static variables are declared as public types.
-the default value is similar to the instance variable. The default value for numeric variables is 0, for Boolean variables is false, and for reference types is null. The value of a variable can be specified at declaration time or in the constructor. In addition, static variables can be initialized in static statement blocks.
-static variables can be accessed through: ClassName.VariableName.
-when a class variable is declared as a public static final type, the class variable name must be in uppercase letters. If static variables are not of public and final types, they are named in the same way as instance variables and local variables.
Practical examples:
Import java.io.*
Public class Employee {
/ / salary is a static private variable
Private static double salary
/ / DEPARTMENT is a constant
Public static final String DEPARTMENT = "Development"
Public static void main (String args []) {
Salary = 1000
System.out.println (DEPARTMENT+ "average salary:" + salary)
}
}
The compilation and running results of the above examples are as follows:
Development average salary:1000
Note: if other classes want to access this variable, you can access it like this: Employee.DEPARTMENT.
:::
Java modifier
The Java language provides many modifiers, which are mainly divided into two categories: access modifiers and non-access modifiers
Modifiers are used to define classes, methods, or variables, usually at the front of the statement. Let's use the following example to illustrate:
Public class className {
/ /...
}
Private boolean myFlag
Static final double weeks = 9.5
Protected static final int BOXWIDTH = 42
Public static void main (String [] arguments) {
/ / method body
}
. . .
Access control modifier
In Java, access controllers can be used to protect access to classes, variables, methods, and constructors. Java supports four different access rights.
-the default, also known as default, is visible in the same package without any modifiers.
-Private, specified with the private modifier, visible within the same class.
Common, specified with the public modifier, visible to all classes.
-protected, specified with the protected modifier, visible to classes and all subclasses in the same package.
1. Default access modifier-do not use any keywords
Variables and methods declared with the default access modifier are visible to classes in the same package. Variables in the interface are implicitly declared as public static final, while methods in the interface have access permissions of public by default.
Example:
As shown in the following example, variables and methods can be declared without any modifiers.
String version = "1.5.1"
Boolean processOrder () {
Return true
}
two。 Private access modifier-private
Private access modifiers are the strictest access level, so methods, variables, and constructors declared as private can only be accessed by the class to which they belong, and classes and interfaces cannot be declared as private.
Variables declared as private access types can only be accessed by external classes through public getter methods in the class.
The use of Private access modifiers is mainly used to hide the implementation details of the class and protect the data of the class.
The following classes use private access modifiers:
Public class Logger {
Private String format
Public String getFormat () {
Return this.format
}
Public void setFormat (String format) {
This.format = format
}
}
Instance, the format variable in the Logger class is a private variable, so other classes cannot directly get and set the value of the variable. To enable other classes to manipulate the variable, two public methods are defined: getFormat (), which returns the value of format, and setFormat (String), which sets the value of format.
3. Public access modifier-public
Classes, methods, constructors, and interfaces declared as public can be accessed by any other class.
If several public classes that access each other are distributed in different packages, you need to import the package where the corresponding public class resides. Because of the inheritance of the class, all public methods and variables of the class can be inherited by its subclasses.
The following functions use public access control:
Public static void main (String [] arguments) {
/ /...
}
The main () method of the Java program must be set to public, otherwise the Java interpreter will not be able to run the class.
4. Protected access modifier-protected
Variables, methods, and constructors declared as protected can be accessed by any other class in the same package or by subclasses in different packages.
Protected access modifiers cannot modify classes and interfaces, methods and member variables can be declared as protected, but interface member variables and member methods cannot be declared as protected.
Subclasses can access the methods and variables declared by the Protected modifier, thus protecting unrelated classes from using these methods and variables.
The following parent class uses the protected access modifier, and the child class overloads the parent class's openSpeaker () method.
Class AudioPlayer {
Protected boolean openSpeaker (Speaker sp) {
/ / implementation details
}
}
Class StreamingAudioPlayer {
Boolean openSpeaker (Speaker sp) {
/ / implementation details
}
}
If you declare the openSpeaker () method as private, classes other than AudioPlayer will not be able to access the method. If you declare openSpeaker () as public, then all classes can access the method. If we only want the method to be visible to the subclasses of its class, declare the method as protected.
. .
Access control and inheritance
Note the rules inherited by the following methods:
Methods declared as public in the parent class must also be public in the subclass.
Methods declared as protected in the parent class are either declared as protected or public in the subclass. Cannot be declared as private.
Methods declared by default modifiers in the parent class can be declared as private in the subclass.
Methods declared as private in the parent class cannot be inherited.
.
Non-access modifier
To implement some other functions, Java also provides a number of non-access modifiers.
The static modifier is used to create class methods and class variables.
Final modifiers are used to modify classes, methods, and variables. Final-modified classes cannot be inherited, modified methods cannot be redefined by inherited classes, and modified variables are constants and cannot be modified.
Abstract modifier, which is used to create abstract classes and abstract methods.
Synchronized and volatile modifiers, mainly for thread programming.
. . .
1. Static modifier
Static variable:
The static keyword is used to declare static variables independent of objects, and no matter how many objects a class instantiates, its static variables have only one copy. Static variables are also called class variables. Local variables cannot be declared as static variables.
Static method:
The static keyword is used to declare static methods independent of the object. Static methods cannot use non-static variables of a class. The static method takes the data from the parameter list and calculates the data.
Access to class variables and methods can be directly accessed using classname.variablename and classname.methodname.
2. Final modifier
Final variable:
Final variables can be explicitly initialized and can only be initialized once. References to objects declared as final cannot point to different objects. But the data in the final object can be changed. That is, the reference to the final object cannot be changed, but the value inside can be changed.
The final modifier is usually used with the static modifier to create class constants.
. .
Final method
Final methods in a class can be inherited by subclasses, but cannot be modified by subclasses.
The main purpose of declaring the final method is to prevent the contents of the method from being modified.
. .
Final class
The final class cannot be inherited, and no class can inherit any feature of the final class.
3. Abstract modifier
Abstract classes:
Abstract classes cannot be used to instantiate objects, and the only purpose of declaring an abstract class is to extend it in the future.
A class cannot be modified by both abstract and final. If a class contains abstract methods, the class must be declared as an abstract class, otherwise a compilation error will occur.
Abstract classes can contain abstract and non-abstract methods.
. .
Abstract method
An abstract method is a method without any implementation, and the concrete implementation of this method is provided by subclasses. Abstract methods cannot be declared as final and static.
Any subclass that inherits an abstract class must implement all abstract methods of the parent class, unless the subclass is also an abstract class.
If a class contains several abstract methods, the class must be declared abstract. An abstract class may not contain abstract methods.
The declaration of an abstract method ends with a semicolon, for example: public abstract sample ()
4. Synchronized modifier
Methods declared by the synchronized keyword can only be accessed by one thread at a time. The Synchronized modifier can be applied to four access modifiers.
5. Transient modifier
When the serialized object contains an instance variable decorated by transient, the java virtual machine (JVM) skips that specific variable.
This modifier is included in the statement that defines the variable and is used to preprocess the data type of the class and variable.
6. Volatile modifier
Each time a volatile-decorated member variable is accessed by a thread, it forces the value of the member variable to be reread from shared memory. Also, when a member variable changes, the thread is forced to write back the change value to shared memory. So that at any time, two different threads always see the same value of a member variable. A volatile object reference may be null.
:::
Java operator
One of the most basic uses of computers is to perform mathematical operations. As a computer language, Java also provides a rich set of operators to manipulate variables. We can divide the operators into the following groups:
1. Arithmetic operator
two。 Relational operator
3. Bit operator
4. Logical operator
5. Assignment operator
6. Other operators
. . .
Arithmetic operator
Arithmetic operators are used in mathematical expressions, and they play the same role as in mathematics. The following table lists all the arithmetic operators.
The following example assumes that the value of integer variable An is 10 and that of variable B is 20:
Operator description example
The values A + B on both sides of the + addition-addition operator are equal to 30
-subtraction-left Operand minus right Operand A-B equals-10
* multiplication-the values A * B on both sides of the multiplication operator are equal to 200
/ Division-left Operand divided by right Operand B / An equals 2
% modulo-the remainder of the left Operand divided by the right Operand B% An equals 0
+ + self-increment-the value of the Operand increases by 1 B or + B equals 21
-- self-subtraction-- the value of the Operand is reduced by 1 B color-or-B equals 19
. . .
Relational operator
The following are the relational operators supported by Java
The value of the integer variable An in the following example is 10 and the value of variable B is 20:
Operator description example
= = check whether the values of the two operands are equal, and if so, the condition is true. (a = = B) is false (not true).
! = check whether the values of the two operands are equal, and if the values are not equal, the condition is true. (a! = B) is true.
> check whether the value of the left Operand is greater than that of the right Operand. If so, the condition is true. (a > B) untrue.
< 检查左操作数的值是否小于右操作数的值,如果是那么条件为真。 (A = 检查左操作数的值是否大于或等于右操作数的值,如果是那么条件为真。(A>= B) false.
2 gets 15, that's 1111.
>. The value of the left Operand shifts to the right by the number of digits specified in the right Operand, and the resulting vacancy is filled with zero. A > 2 gets 15 that is 0000 1111
. . .
Logical operator
The basic operations of logical operators are listed below, assuming that Boolean variable An is true and variable B is false
Operator description example
& & is called logic and operator. The condition is true if and only if both operands are true. (a & B) is false.
| | called logic or operator. If either of the two operands is true, the condition is true. (a | | B) is true.
! Is called a logical non-operator. Used to reverse the logical state of operands. If the condition is true, the logical non-operator will get false.! (a & B) is true.
. . .
Assignment operator
Here are the assignment operators supported by the Java language:
Operator description example
= simple assignment operator, assigning the value of the right Operand to the left Operand C = A + B will assign the value obtained by A + B to C.
The + = addition and assignment operator, which adds and assigns the left Operand to the left Operand C + = An is equivalent to C = C + A.
The-= subtraction and assignment operator, which subtracts the left and right operands to the left Operand C-= An is equivalent to C = C-A.
* = multiplication and assignment operator, which multiplies the left Operand and the right Operand to the left Operand C * = An is equivalent to C = C * A
The / = division and assignment operator, which divides the left Operand from the right Operand to the left Operand C / = An is equivalent to C = C / A.
(%) = modulus and assignment operator, which modulates the left and right operands and assigns values to the left Operand C% = An is equivalent to C = C% A.
> = 2 is equivalent to C = C > > 2
& = bitwise and the assignment operator C = 2 is equivalent to C = C = 2
^ = bitwise XOR assignment operator C ^ = 2 is equivalent to C = C ^ 2
| | = bitwise or assignment operator C | = 2 equals C = C | 2 |
. . .
Conditional operator (?:)
Conditional operators are also known as ternary operators. The operator has three operands and needs to determine the value of the Boolean expression. The main purpose of this operator is to determine which value should be assigned to the variable.
Variable x = (expression)? Value if true: value if false
. . .
InstanceOf operator
This operator is used to manipulate an object instance to check whether the object is of a specific type (class type or interface type).
The instanceof operator uses the format such as right: (Object reference variable) instanceOf (class/interface type)
If the object referred to by the variable on the left side of the operator is an object of the class or interface (class/interface) on the right side of the operator, the result is true.
. . .
Java operator precedence
When multiple operators appear in an expression, who comes first? This involves the priority of operators. In a multi-operator expression, different operator precedence can lead to a big difference in the final result.
For example, (1: 3) + (3: 2) * 2, if this expression is calculated by the plus sign first, the answer is 18, and if the multiplication sign is first, the answer is 14.
For example, x = 7 + 3 * 2, where x gets 13 instead of 20, because the multiplication operator has a higher priority than the addition operator, so calculate 3 * 2 to get 6, and then add 7.
The operator with the highest precedence is at the top and the operator with the lowest precedence is at the bottom.
Category operator relevance
Suffix () []. (dot operator) left to right
One yuan + -! ? From right to left
Multiplicative * /% left to right
Additive +-left to right
Shift > =
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.