[Java Learning Series] Lesson 2nd-Java syntax and object-oriented, java-java

Source: Internet
Author: User

[Java Learning Series] Lesson 2nd-Java syntax and object-oriented, java-java

Address of this Article

 

Sharing outline:

1. Java program features

1.1 Basic syntax

1.2 string

1.3 Variables

1.4 Java Array

1.5 Java Enumeration

1.6 Java Modifier

2. Java object-oriented

2.1 Java classes and objects

Notes of the 2.2 class

2.3 Java Number class

2.4 Java Character class

2.5 Java String class

2.6 Java StringBuffer and StringBuilder classes

2.7 Java Array

3. References

 

This article mainly introduces some features of Java programs (different from PHP) and object-oriented

 

1. Java program features

 

[Sample Code]

1 public class HelloWorld {2/* The first Java program 3 * It will print the String Hello World4 */5 public static void main (String [] args) {6 System. out. println ("Hello World"); // print Hello World7} 8}

  

The execution process is as follows (image Demonstration ):

C : > javac HelloWorld.javaC : > java HelloWorld Hello World

 

1) [basic syntax]

A) [case sensitive]

Java classes and functions are case-sensitive. Unlike PHP, PHP classes and functions are case-insensitive.

B )【Source File Name]

-- A file can only have one class. 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 (remember that Java is case sensitive) and the file name suffix is. java. (If the file name and class name are different, the compilation will be incorrect ).

Whether the answer is equal:

      

-- PHP does not have this requirement, because PHP itself is an interpreted language and does not need to be compiled or generate a file similar to. class.

C )【Main method entry]

-- The main method (static method) must be available: All Java programs are composedPublic static void main (String [] args)Method.

-- [Exceptions]

Java has a lot of knowledge. For java application (java application), the main () function should be used as the entry, but main () function is not required for jsp or applet functions.

D) [define each variable first and define the type]

-- This is also different from the PHP language.

 

2) [String]

A) [must be enclosed by double quotation marks]

B) [connector] The Link character of the string in java is "+", unlike "." in PHP, because "." In Java is the link character of the variable in the class.

    

3) [variable]

A) The variable must be of the execution type and must be defined first.

B) [type]

-- [Overview]

Java has two data types: built-in data types and reference data types.

Built-in data types:

          

Java provides eight basic types. Six numeric types (four integers, two floating point types), one character type, and one boolean type. Byte, short, int, long, float, double, boolean, char

        

Reference data type:

        

-- In Java, variables of the reference type are very similar to pointers of C/C ++. The reference type points to an object, and the variable pointing to the object is the reference variable. These variables are specified as a specific type during declaration, such as Employee and Pubby. Once declared, the type cannot be changed. -- Objects and arrays are reference data types. -- The default values of all reference types are null. -- A reference variable can be used to reference any compatible type. -- Example: Site site = new Site ("Runoob ").

 

        

C) [constant]

-- Use the final keyword in Java to modify constants. The declaration method is similar to that of variables.

 

    

4) [Java array]

A) arrays are objects stored on the stack. Multiple variables of the same type can be saved.

 

5) [Java enumeration]

A) enumeration is introduced in Java 5.0. Enumeration restriction variables can only be pre-set values. Enumeration can be used to reduce bugs in the code.

B) [syntax]

class FreshJuice {   enum FreshJuiceSize{ SMALL, MEDUIM, LARGE }   FreshJuiceSize size;}

 

6) [Java modifier]

--Access ModifierThe categories are as follows:

A) default, also known as default, is visible in the same package without any modifiers. B) private, which is specified by the private modifier and visible within the same class. C) Common, specified with a public modifier, visible to all classes. D) protected, specified with the protected modifier, and visible to the classes and all subclasses in the same package.

 

-- Non-access modifier:

A) [Synchronized modifier]: -- The method 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. -- Public synchronized void showDetails (){.......} b) [Transient modifier]: -- when the serialized object contains the instance variable modified by transient, the java Virtual Machine (JVM) skips this specific variable. -- This modifier is included in the statements defining variables to pre-process the data types of classes and variables. -- Instance public transient int limit = 55; // public int B is not persistent; // persistent c) [Volatile modifier] -- when a member variable modified by volatile is accessed by a thread each time, both force the value of this member variable to be re-read from the shared memory. In addition, when the member variables change, the thread is forced to write the change value back to the shared memory. In this way, two different threads always see the same value of a member variable at any time. -- A volatile object reference may be null.View Code

 

      

 

2. Java object-oriented

[Sample Code]

The file name is TestJavaClass. java, which corresponds to the unique public class name in the file.

The function is to sample a dog object, set the age of the dog, get the age, and then output.

Javac TestJavaClass. java

Java TestJavaClass

1 // 1. entry Test class 2 public class TestJavaClass 3 {// {4 public static void main (String [] args) 5 {// {6 // Note 1: type TestDog 7 for instantiation. // NOTE 2: the string in the java program must be enclosed in double quotation marks with 8 TestDog testDog = new TestDog ("Tom"); 9 testDog. run (); 10} //} 11 12} //} 13 14 // 2. test puppy class 15 class TestDog16 {// {17 String name; 18 int age; 19 // constructor 20 public TestDog (String name) 21 {// {22 System. out. println ("this dog is called" + name); 23} //} 24 25 // run 26 public void run () 27 {// {28 System. out. println ("01 start running \ n"); 29 // Note 3: Write setAge (dogAge) 30 setAge (10) directly to the internal transfer function of the class ); 31 int dogAge = getAge (); 32 System. out. println ("02 The Age of the dog is" + dogAge); 33} //} 34 35 // get 36 public int getAge () 37 {// {38 return age; 39} //} 40 41 // set 42 public void setAge (int ageValue) 43 {// {44 // NOTE 4: The member variables of the internal transfer class of the class are directly written into age45 age = ageValue; 46} // }}47 48 }//}}}View Code

 


1) [Java classes and objects]

A) [Call functions and variables]

Class calls a function, directly the function name itself, directly write setAge (dogAge), the variable is also directly write age

B) [class modification]

In PHP, the class can be modified at most as abstract class, but in Java, a file must have a public class and the file name.

C) [define class functions]

-- Common in PHP isPublic function functionName ()

-- In Java, the description of function is not required, but the type of return value must be executed,Public void functionName ()

 

D) [constructor]

        -- The constructor in PHP is public function _ construct () {}, and only one

-- Java constructor can have multiple constructor methods. When creating an object, at least one constructor must be called. The name of the constructor must be the same as that of the class. A class can have multiple constructor methods to implement different constructor methods in different situations.

For example:

        

Public class A {public A () {System. out. println ("calls A's no-argument constructor");} public A (String mess) {System. out. println ("constructor with parameters of A called \ n" + "parameter content:" + mess );}}

 

2) [Notes for classes]

A) [import Statement]

-- [Location] 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, the import statement should be the first in the source file.

-- [Scope of action] The import and package statements are valid for all classes defined in the source file. Different classes cannot be declared for different packages in the same source file.

3) [Java Number class]

A) [cause]

In the actual development process, we often encounter the need to use objects instead of built-in data types. To solve this problem, the Java language provides a corresponding packaging class for each built-in data type.

B) [packaging]

All packages(Integer, Long, Byte, Double, Float, Short)Are subclasses of the abstract class Number.

C) [Number subclass method]

XxxValue (), compareTo (), etc.

4) [Java Character class]

A) [single Character] The Character class is usedSingle Character.

B) [Sample Code]

      

// Bind the original Character 'a' to Character object ch. Character ch = 'a '; // bind the original character 'X' with the test method // return the value of The binning to 'C' char c = test ('x ');View Code

 

5) [Java String class]

A) [Create a string]

There are 11 constructor methods for the String class. These methods provide different parameters to initialize the String. For example, a character array parameter is provided:

Public class StringDemo {public static void main (String args []) {char [] helloArray = {'R', 'U', 'n', 'O ', 'o', 'B'}; String helloString = new String (helloArray); System. out. println (helloString );}}StringDemo. java

 

B) [unchangeable]

The String class cannot be changed, so once you create a String object, its value cannot be changed.

If you need to make many changes to the string, you should use the StringBuffer & StringBuilder class.

  

6) [Java StringBuffer and StringBuilder classes]

A) [modifiable] the String class cannot be changed. When modifying the String, use the StringBuffer and StringBuilder classes.

B) [difference]

The StringBuilder class is fast, but not thread-safe.

The StringBuffer class is thread-safe. The StringBuilder class is recommended for high speed.

C) [Sample Code]

1 2 3 public class Test {4 public static void main (String args []) {5 StringBuffer sBuffer = new StringBuffer ("Official cainiao tutorial Website:"); 6 sBuffer. append ("www"); 7 sBuffer. append (". runoob "); 8 sBuffer. append (". com "); 9 System. out. println (sBuffer); 10} 11} 12StringBuffer

 

7) [Java array]

A) [Definition]

-- The array provided in Java is used to storeFixed sizeOfSame typeElement.

-- In comparison, PHP arrays are much more powerful, with unfixed sizes and unlimited types.

B) [declare variables]

      

DataType [] arrayRefVar; // the preferred method or dataType arrayRefVar []; // The effect is the same, but not the preferred method

C) [Create an array]

-- Method 1: use the new operator to create an array in Java

ArrayRefVar = new dataType [arraySize];
-- Method 2: directly create
DataType [] arrayRefVar = {value0, value1,..., valuek };

D) [multi-dimensional array]
-- [Definition]: a multi-dimensional array can be regarded as an array. For example, a two-dimensional array is a special one-dimensional array, and each element of it is a one-dimensional array.
-- [Dynamic initialization ]:
1. Directly allocate space for each dimension, for example, int a [] [] = new int [2] [3];
2. From the highest dimension, allocate space for each dimension.
            
// String s [] [] = new String [2] []; s [0] = new String [2]; s [1] = new String [3]; s [0] [0] = new String ("Good "); s [0] [1] = new String ("Luck"); s [1] [0] = new String (""); s [1] [1] = new String ("you"); s [1] [2] = new String ("! ");Dynamic initialization of two-dimensional arrays

 

C) [Arrays class]

-- [Package] the java. util. Arrays class can operate Arrays conveniently. All the methods provided by this class are static.

-- [Common method] value assignment (fill), sorting (sort), comparison (equals), and search (binarySearch)

  

  

        

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.