Java Programming related summary (II) __ Programming

Source: Internet
Author: User
Tags array length constant naming convention null null true true try catch value of pi java keywords
Java Programming related summary (ii)

Java Programming related Summary is a continuous update of the series, is my own years of work to use the Java experience of a summary, is also a new understanding of the temperature, because a lot of the foundation of things after so many years, peacetime work will be forgotten, so read the book, on the Internet, check the information, It is also a record of their own notes, after a period of time to see is also pretty good, but also hope to help the people are learning, this series will summarize some: object-oriented programming Ideas Java basic Syntax some interesting framework analysis The whole idea of actual combat project code optimization and performance tuning of several other missing things as well as the basic syntax to supplement Java

In conjunction with the previous section, we started with the most basic class, first of all, the classic Hello word case:

Package Com.klsstt.helloword; 

public class helloword{public  
    static void Main (String [] args) {  
     System.out.println ("Hello Word!");  
    }  
}  

This case outputs "Hello Word!", where the keyword class is used to create the class, and public is the access modifier, which represents the access to the class, Helloword is the name of the class, and the generic class is named after the first-letter hump naming method. Package is a package declaration that indicates the package path for the current class, and the static keyword represents the method as a static method, and main is the method name, and the main method is the executable method that the Java program generates by default. Case Sensitivity

Java is a case-sensitive language, which means that Hello and hello in Java represent different meanings.
Java keywords are always lowercase
Avoid using variable names that differ only in case. Name of Class

The first letter of all classes must be capitalized.
Always ensure that the class name matches your code and the Java file name.
If the class name contains several words, the first letter of each word is capitalized.
such as class Helloword Java identifiers

Identifiers are symbols that are used to name variables, classes, methods, and so on in Java programs.
There are several rules to follow when using identifiers:

Identifiers can consist of letters, numbers, underscores (_), dollar characters ($), but cannot contain other special characters, such as @,%, space, and so on, and cannot begin with a number. such as: 123name

Identifiers cannot be Java keywords and reserved words (Java reserved keywords, which may be keywords in future upgrades), but can contain keywords and reserved words. For example: Void can not be used as an identifier, but myvoid can. Identifiers are strictly case-sensitive. Be sure to distinguish between Hello and Hello is two different identifiers oh. The name of the identifier is best to reflect its role, do see the name known. Java Modifiers

access modifiers : default, public, protected, private
non-access modifiers : final, abstract, strictfp Java keyword list

Access Control :
Private privacy
Protected protected.
Public publicly.

class, method, and variable modifiers :
Abstract Declaration Abstraction
Class classes
Extends expansion, inheritance
Final final, immutable
Implements implementation
Interface interface
Native Local
New Create
Static statically
STRICTFP Strict, accurate
Synchronized threads, synchronizing
Transient short
Volatile is easy to lose

Program Control Statements :
Break Jump Loop
Continue continue
return returns
Do run
While loop
If if
else otherwise
For loop
instanceof Instance
Switch switch
Case returns the result of the switch
Default Defaults

Error Handling :
Try catch exception
Catch handling Exceptions
Finally there is no exception to execute
Throw throws an exception object
Throws declares an exception may be thrown
Assert assertion

Package Related :
Import introduced
Package Bag

Basic Type :
Boolean Boolean type
BYTE-byte
char character type
Double dual precision,
float float
int integral type
Long Integral type
Short shorter integral type
NULL NULL
True True
False false
Enum enum

Variable Reference :
Super Parent class, Super class
This class
void no return value

Keywords (51) + reserved word (const,goto) a total of 53 Java variables and Constants

There is a large amount of data in the program to represent the state of the program, some of the data in the process of running the value will change, some data in the process of running the value can not be changed, the data in the program are called variables and constants.
In the actual program, you can choose whether to use a variable representation or a constant, depending on how the data is changed in the program's operation.

variable
The variable represents the state of the program. The program changes the state of the whole program by changing the value of the variable, or even more, that is, the functional logic of the implementation program.
In order to conveniently reference the value of the variable, you need to set a name for the variable in the program, which is the variable name.
For example, in a 2D game program, you need to represent the position of the person, you need 2 variables, one is the x coordinate, one is the y coordinate, the value of the two variables will change during the program running.

Because the Java language is a strongly typed language, variables must first be declared before they are used, and the syntax for declaring variables in a program is as follows:
data type variable name;
For example: int x;
In this syntax format, the data type can be any type in the Java language, including the basic data types described earlier and the composite data types that will be introduced later. The variable name is the identifier for the variable, which requires a naming convention that conforms to the identifier, and in practice, the name generally corresponds to the purpose of the variable, making it easier to read the program. The data type and the variable name are separated by spaces, with no limit on the number of spaces, but at least 1 are required. The statement uses ";" as the end.
You can also set the value of the variable while declaring the variable, with the following syntax format:
data type variable name = value;
For example: int x = 10;
In this syntax format, the preceding syntax is consistent with what is described above, and subsequent "=" represents the assignment, where the "value" represents the specific data, noting that the difference between "= =" represents the equality of the judge. In this syntax format, the type of the requirement value needs to match the data type of the variable being declared.
In a program, the value of a variable represents the state of the program, in which you can refer to the value stored in the variable by the name of the variable, or you can assign a value to the variable. For example:
int n = 5;
n = 10;
In the actual development process, it is necessary to declare what type of variables, how many variables need to be declared, what values need to be assigned to the variable, all according to the program logic, here are listed only the expression of the format.

Constant

A

constant represents a value that cannot be changed while the program is running.
Constants have 2 main functions in the process of running a program:
1. Represents a constant that facilitates the modification of the program (for example, the value of pi)
2. Enhances the readability of the program (for example: constant up, down, left, and right resolution represent up and down, with values of 1, 2, respectively, 3 and 4)
The syntax format and variable type of the constant, just add the keyword to the final before the syntax format of the variable. In the Java encoding specification, the constant name must be capitalized.
The syntax format of the constants is as follows:
Final data type constant name = value,
Final data type constant Name 1 = value 1, constant Name 2 = value 2, ... Constant name n = value n;
For example:
Final Double PI = 3.14
Final char male= ' M ', female= ' F ';
in Java syntax, constants can be declared first and then assigned, but only Can assign a value once, the sample code is as follows:
final int up;
up = 1; about final details

Final is used to declare properties (constants), methods, and classes that represent properties that must be initialized once the memory space is allocated (no default initialization, local variables, and so on, with the default initialization of only ordinary non-final member properties for static (no final modification) class variables, Class connection has a default initialization, for like private int A; When the class is instantiated, the constructor defaults to 0, in short, the variable must be initialized before it is available, which is one of the security of Java.
Final this keyword means "This is immutable" or "final State".
So why stop the change?
The creator of the Java language may prevent changes for two purposes:
1. Efficiency issues:
Some of the classes in the JDK are not allowed to be overwritten by the user, and the designer may think that the method is already the best method, or that the user overwrites it privately or inadvertently overwrites it, affecting the JVM or system's ability;
2. Design Requirements:
It is well known that some situations must use the final keyword, such as parameter passing of an anonymous inner class in a method
Modifier variable:
Final member variables represent constants that can only be assigned once, and values are not changed after assignment.
"Cosmetic Method":
The final method cannot be overridden by a quilt class method, but can be inherited.
"Cosmetic class":
The final class cannot be inherited, no subclasses, and all methods in the final class are final. (such as String Class)

Property variables of classes that are final decorated without being modified by static can only be initialized in two cases (must be initialized):
A. Assigning values when it is declared
B. Initializing in a constructor
Explanation: When this property is decorated to final rather than static, it belongs to the resource (instance constant) of the instance object of the class, and when the class is loaded into memory, the property does not allocate memory space, but only defines a variable a, It is only when the class is instantiated that the attribute is allocated memory space, and the instantiation executes the constructor at the same time, so the attribute is initialized, and the condition that it needs to initialize when it is allocated memory space is not changed.

Property variables for classes that are static-decorated and not final-decorated can only be initialized in two cases (can not be initialized):
A. Assigning values when it is declared
B. Initializing in static or non-static fast
Explain:
When a class's properties are modified to be static at the same time, he belongs to the class's resources (class variables), after the class is loaded, to connect, in three steps: First verify, then prepare, prepare, first allocate memory, then the default initialization, can be resolved. Finally, class initialization, class initialization, must ensure that its parent class has been initialized, so the first initialization of the superclass, for the interface, do not have to initialize its parent interface. Class is initialized, the IT puts class-variable initialization statements and static initialization statements into class initialization methods, so if there are no two statements, there is no class initialization method, and constructors are executed when the class is instantiated, so using constructors, This property is not initialized at this time. The program will have an error. The static block is executed when the class is loaded and is executed only once, so it can be initialized in the static block.

Property variables of classes that are decorated with final and static can only be initialized in two cases (must be initialized):
A. At the time it was defined
B. Initializing in a static block of a class
C. In particular, when initializing a constructor that throws an exception, it is initially noted, especially when implementing a single case pattern (this can only be initialized)
Such as:

Class a{ 
    private final static A;
    static{
        try{
            a=new A ();
        } catch (Exception e) {
            throws new RuntimeException (e);          Must have, otherwise the correct initialization of the constants cannot be completed
        }
    Private A () throws exception{}
}

Explain:
When the properties of a class are modified to be static and final at the same time, he belongs to a class of resources (class constants), so that when the class is loaded into memory (that is, when the application starts), it must have allocated memory for this property, so the attribute already exists and it is final decorated. Therefore, the value must be initialized after the attribute has been defined. The constructor is executed when the class is instantiated, so the constructor is not initialized. The program will have an error. The static block is executed when the class is loaded and only executed this time, so the can be initialized in a static block.

Final variable = = constant in Java
"Change and invariant of final variable": final indicates the value or reference of the variable is unchanged
It is said that the final variable is immutable after it is assigned, and this variable can be the base data type +string or an object
So what does this constant mean?
This invariant refers to the reference, which is the address, and the contents of the referenced object are still mutable.
Note: If you are an object, note that the class initialization condition
That is, the final variable always points to an object, a constant pointer, not a pointer to a constant.
"Specific application of final keyword":
"Final+ variable":
In practical applications, this form is very rare.
For example, logger is OK, but seemingly not very practical, perhaps users still want to change the logger variable by setter.
"Static+final+ variable":
constants, often used.
"Final+ Method":
JDK, but they are not used in their own use.
"Final+ class":
Helper classes are often used.
"Final parameter passing for anonymous inner classes":
Often used in multithreaded testing.
"Final parameters for method":
Not commonly used. Java Arrays

An object with multiple identical variable types is stored in an

array. However, the number itself is also an object in the heap. We're going to learn how to declare, build, initialize an array.
defines the array
1. (Recommended, more able to indicate array type)
type[] Variable name = number of elements in new type[array];
For example:
int[] A = new int[10]; The
array name, which refers to a and points to the first address of the array element.
2. (same as C)
type variable name [] = number of elements in the new type[array];
such as:
int a[] = new INT[10];
3. Direct initialization of
type[variable name = new type[]{comma-separated initialization value};
where the red part can be omitted, there are two more:
int[] a = {1,2,3,4};
Int[] A = new int[]{1,2,3,4}; The second square bracket of the
where int[] a = new int[]{1,2,3,4} does not include the length of the array because the number of elements is determined by the contents of the trailing curly braces.

base of array application
Array Length
Each array in Java has a property named length that represents the length of the array.
The length property is public final int, that is, length is read-only. Once the array length is determined, the size cannot be changed.
two-dimensional array
A two-dimensional array is an array of arrays.
There are two types of basic definitions, such as:
type[][] i = new type[2][3]; (recommended)
Type i[][] = new TYPE[2][3];
A variable-length two-dimensional array
Each element of a two-dimensional array is a one-dimensional array, and these arrays are not necessarily equal in length.
When declaring a two-dimensional array, you can specify only the first dimension, the size of the second dimension, and then the array of different lengths. Note, however, that the first dimensional size cannot be empty (you cannot specify only the number of columns without specifying the number of rows).
A two-dimensional array can also be initialized at the time of definition, with the nesting of curly braces, which does not specify the size of two dimensions, and can generate array elements of different lengths depending on the number of initialization values. Java Collections

Collection Class description and differences
Collection
├list
│├linkedlist
│├arraylist
│└vector
│└stack
└set
Map
├hashtable
├hashmap
└weakhashmap Collection Interface

Collection is the most basic set interface, and a collection represents a set of object, the collection element (Elements). Some collection allow the same elements while others do not, some can sort and others do not.

The Java SDK does not provide classes that directly inherit from collection, and the Java SDK provides classes that inherit from collection such as list and set. All classes that implement the collection interface must provide two standard constructors: parameterless constructors are used to create an empty collection, and a constructor for a collection parameter is used to create a new collection. This new collection has the same element as the incoming collection. The latter constructor allows the user to replicate a collection.

How to traverse every element in the collection. Regardless of the actual type of collection, it supports a iterator () method that returns an iteration that can be used to access each element of the collection one at a time. Typical usage is as follows:
Iterator it = Collection.iterator (); To get an iterative child
while (It.hasnext ()) {
Object obj = It.next (); Get the next element
}
The two interfaces that are derived from the collection interface are list and set. List interface

The list is an ordered collection, using this interface to precisely control where each element is inserted. The user can access the elements in the list, similar to the Java array, by using the index (the position of the element in the list, similar to the array subscript).
Unlike the set mentioned below, the list allows the same elements.

In addition to the iterator () method with the collection interface prerequisites, the list also provides a listiterator () method that returns a Listiterator interface, compared to the standard iterator interface, There are a number of add () listiterator that allow adding, deleting, setting elements, and traversing forward or backwards.

Common classes that implement the list interface are Linkedlist,arraylist,vector and stack. LinkedList class

LinkedList implements the list interface, allowing null elements. Additionally LinkedList provides additional Get,remove,insert methods at LinkedList's header or tail.
These operations enable LinkedList to be used as stacks (stack), queues (queue), or bidirectional queues (deque).
Note that LinkedList does not have a synchronization method. If multiple threads access a list at the same time, you must implement access synchronization yourself. A workaround > Construct a synchronized list when the list is created:
List List = Collections.synchronizedlist (new LinkedList (...)); ArrayList class

ArrayList implements a variable sized array. It allows all elements, including null. ArrayList is not synchronized.
The Size,isempty,get,set method runs at a constant time. But the Add method cost is the shared constant,
The time of O (n) is required to add n elements. The other methods run at a linear time.
Each ArrayList instance has a capacity (Capacity), which is the size of the array used to store the elements. This capacity increases automatically with the addition of new elements >, but the growth algorithm is not defined. When you need to insert a large number of elements, you can call the >ensurecapacity method before inserting to increase the capacity of the ArrayList to increase the insertion efficiency.
Like LinkedList, ArrayList is also unsynchronized (unsynchronized). Vector class

Vectors are very similar to ArrayList, but vectors are synchronized. Iterator created by vector, although the same interface was created with ArrayList, but because vectors are synchronized, and when one iterator is created and is being used, another thread changes the state of the vector (for example, Add or remove some elements), the concurrentmodificationexception is thrown when the iterator method is invoked, so the exception must be caught.
-Stack Class
Stack inherits from the vector, implementing a LIFO stack. Stack provides 5 additional methods that allow vectors to be used as stacks. Basic push and Pop methods, and Peek method to get the top of the stack elements, empty method test stack is empty, the search method detects an element in the stack position. Stack is just created after stack is empty. Set interface

A set is a collection that contains no duplicate elements, that is, any two elements E1 and E2 have E1.equals (E2) =false,set have a maximum of one null element.
Obviously, the constructor of the set has a constraint, and the incoming collection parameter cannot contain duplicate elements.
Note: You must be careful to manipulate variable objects (mutable object). If a variable element in a set changes its state, causing the Object.Equals (Object) =true to cause some problems.
-MAP Interface

Note that the map does not inherit the collection interface, and the map provides a mapping of key to value. A map cannot contain the same key, and each key can map only one value. The map interface provides a view of 3 collections, which can be treated as a set of key sets, a set of value sets, or a set of key-value mappings. Hashtable class

Hashtable inherits the map interface and implements a hash table of key-value mappings.
Typically, the default load factor 0.75 achieves a better balance of time and space.
Increasing the load factor saves space but the corresponding lookup time increases, which can affect operations like get and put.
Using Hashtable for example, place 1,2,3 in Hashtable, their key is "one", "two", "three":

    Hashtable numbers = new Hashtable ();
Numbers.put ("One", New Integer (1));
Numbers.put ("Two", New Integer (2));
Numbers.put ("Three", New Integer (3));

To remove a number, such as 2, use the corresponding key:

Integer n = (integer) numbers.get ("two");
System.out.println ("two =" + N);

Because an object that is a key will determine the location of its corresponding value by calculating its hash function, any object that is a key must implement the Hashcode and Equals methods.
The hashcode and Equals methods inherit from the root class object, and if you use a custom class as a key, be very careful, as defined by the hash function, if two objects are the same, that is, Obj1.equals (OBJ2) =true, Their hashcode must be the same, but if two objects are different, their hashcode is not necessarily different, and if the hashcode of two different objects is the same, this phenomenon is called conflict, and the conflict causes the time overhead of manipulating the hash table, so as to define the hashcode () method to speed up the operation of the hash table.
If the same object has a different hashcode, the operation of the hash table will have unexpected results (the expected GET method returns null), to avoid this problem, you need to keep in mind one: you have to copy both the Equals method and the Hashcode method, not just one.
The Hashtable is synchronized. HashMap class

HashMap is similar to Hashtable, except that HashMap is unsynchronized and allows NULL, that is, null value and null key. , but when HashMap is treated as collection (the values () method returns collection), its iterative child operation time cost is proportional to the capacity of the HashMap. Therefore, if the performance of an iterative operation is significant, do not set the HASHMAP initialization capacity too high, or the load factor too low. Weakhashmap class

Weakhashmap is an improved hashmap, which implements a "weak reference" to key, and if a key is no longer referenced externally, the key can be reclaimed by GC.

Summary

If you are involved in stacks, queues, and other operations, you should consider using the list, for the need to quickly insert, delete elements, should use LinkedList, if you need to quickly randomly access elements, you should use ArrayList.
If the program is in a single-threaded environment, or if access is only done in one thread, it is more efficient to consider a class that is not synchronized, and should use a synchronized class if multiple threads might be working on a class at the same time.
Special attention should be paid to the operation of the hash table, where the object of the key is correctly hashcode the Equals and the method.
Try to return the interface instead of the actual type, such as returning a list instead of ArrayList, so that if you need to replace ArrayList with LinkedList later, the client code does not have to change. This is for abstract programming.

Sync Sex

Vectors are synchronized. Some of the methods in this class ensure that the objects in the vector are thread safe. ArrayList is asynchronous, so the objects in ArrayList are not thread safe. Because the requirements of synchronization can affect the efficiency of execution, it is a good choice to use ArrayList if you do not need a thread-safe collection, which avoids the unnecessary performance overhead of synchronization.
Data Growth
From an internal implementation mechanism, both ArrayList and vectors use Arrays (array) to control objects in the collection. When you add elements to both types, if the number of elements exceeds the current length of the internal array they all need to extend the length of the internal array, vector by default automatically increases the original one times the length of the array, ArrayList is the original 50%, so the most The space you get from this collection is always larger than you actually need. So if you want to save a lot of data in a collection, there are some advantages to using vectors because you can avoid unnecessary resource overhead by setting the initialization size of the collection.
usage Patterns
In ArrayList and vectors, it takes the same amount of time to look up data from a specified location (through the index) or to add and remove an element at the end of the collection, which we use O (1). However, if an element is added or removed elsewhere in the collection, the time it takes to grow linearly increases: O (n-i), where n represents the number of elements in the collection, and I represents the index position of the element's increase or removal.
Why is that so? It is assumed that all elements after the first and first elements of the collection will perform the action of displacement when the above actions are performed.
What does all this mean?
This means that you are simply looking for elements in a particular location or adding and removing elements only at the end of the collection, so you can use vectors or ArrayList. If it's a different operation, you'd better choose a different collection action class. For example, does the Linklist collection class spend the same amount of time adding or removing elements from any location in the collection? O (1), but it is in the index the use of an element is relatively slow-o (i), where I is the location of the index. It's also easy to use ArrayList because you can simply use an index instead of creating an iterator object. Linklist also creates objects for each inserted element, and all you have to understand is that it will incur additional overhead.
Finally, in the book "Practical Java", Peter Haggar suggests using a simple array to replace vectors or ArrayList. This is particularly true for procedures that require high efficiency in implementation. The use of arrays (array) avoids synchronization, additional method calls, and unnecessary reallocation of space.Java Enumeration Values

The enumeration was introduced in the Java5.0 version. Enumerations limit the variables to some predefined values. The values in the enumeration list are called enumerated values.
Using enumeration values can greatly reduce vulnerabilities in your code.
For example, if we want to make a program for a freshly squeezed juice store, we can limit the size of the cup to small and large. So that we can make sure that people don't set a small size

Class Freshjuice {
   enum freshjuicesize{SMALL, MEDIUM, LARGE}
   freshjuicesize size;
}
public class Freshjuicetest {public
   static void Main (String args[]) {
      Freshjuice juice = new Freshjuice ();
      Juice.size = Freshjuice. Freshjuicesize.medium;
      System.out.println ("Size:" + juice.size);
   }

Output the following results: Size:medium

Note: Enumerations can be declared themselves or declared in a class. Method variables and constructors can also be defined in enumeration values. Annotations in Java

Java supports single or multiline annotations, and the letters in all comments are ignored by the Java compiler.
Line Comment:
Begin

Block Comment:
/* Start
*/End

Javadoc comments: When you generate Javadoc, such annotations are generated with standard JAVAAPI annotations that can span multiple lines

/**
*
* * The branch statement break statement in Java
The break statement has two forms: a label and a non-label. In the previous switch statement, the break statement that you see is a non label form. You can use a non-label break to end a for,while,do-while loop, such as the following Breakdemo program:

Class Breakdemo {public
    static void Main (string[] args) {

        int[] arrayofints = 
            {3, 589,
              12, 1076, Watts,
              8, 622, 127};
        int searchfor =;

        int i;
        Boolean foundit = false;

        for (i = 0; i < arrayofints.length i++) {
            if (arrayofints[i] = = searchfor) {
                Foundit = true;
                break;
            }
        }

        if (foundit) {
            System.out.println ("Found" + searchfor + "at index" + i);
        } else {
            System.out.println (searchfor + "not in the" array);}}

This program finds the number 12 at the end of the array. The break statement, such as the bold on, ends the for loop when only one is found. The control flow jumps to the statement following the for loop. Program Output is:

Found at index 4
The no-label break statement ends the innermost switch,for,while,do-while statement. And the label break ends the outermost statement. The next program, Breakwithlabeldemo, resembles the previous program, but uses nested loops to look for a value in a two-dimensional array. But after the value is found, the label break statement ends the outermost for loop (labeled "Search"):

Class Breakwithlabeldemo {public
    static void Main (string[] args) {

        int[][] arrayofints = { 
            32, 87, 3, 589} ,
            {1076, Watts, 8},
            {622, 127, 955}
        };
        int searchfor =;

        int i;
        int j = 0;
        Boolean foundit = false;

    Search: For
        (i = 0; i < arrayofints.length. i++) {for
            (j = 0; j < Arrayofints[i].length;
                 J + +) {
                if (arrayofints[i][j] = = searchfor) {
                    Foundit = true;
                    Break search;
                }
            }

        if (foundit) {
            System.out.println ("Found" + searchfor +
                               "at" + i + "," + j);
        } else {
            System.out.println (searchfor + "not in the"
                               array);
        }
    }

Program Output is:

Found at 1, 0
The break statement ends the label statement, which is not a transfer control flow to the label. Control is sent to the tag (terminate) declaration immediately following. Continue statement

The continue statement ignores the current iteration of the for,while,do-while. Non-tagged mode, ignoring the innermost loop body, and then calculating the Boolean expression of the loop control. The next procedure, Continuedemo, passes through a string of steps to calculate the number of occurrences of the letter "P". If the current character is not a p,continue statement skips the other code of the loop, then the next character is processed. If the current character is P, the program increases the number of characters.

Class Continuedemo {public
    static void Main (string[] args) {

        String SearchMe 
            = "Peter Piper picked a" +
              "Peck of pickled peppers";
        int max = Searchme.length ();
        int numps = 0;

        for (int i = 0; i < max; i++) {
            //interested only in P ' s
            if (Searchme.charat (i)!= ' P ')
                continue;

            Process P ' s
            numps++;
        }
        System.out.println ("Found" +
            numps + "P ' s in the string.");
    }

Here is the program output: Found 9 P ' s in the string.
To see the effect more clearly, try removing the Continue statement and recompiling. To run the program, Count will be wrong, the output is 35, not 9.

The label continue statement ignores the current iteration of the outer loop of the label tag. The following program example, Continuewithlabeldemo, uses nested loops to search for strings in a string of characters Fu. Requires two nested loops: An iterative string, a string that is being searched by an iteration. The following program Continuewithlabeldemo, using the Continue label form, ignores the outermost loop.

Class Continuewithlabeldemo {public
    static void Main (string[] args) {

        String SearchMe 
           = ' Look for a substring In me ";
        String substring = "Sub";
        Boolean foundit = false;

        int max = Searchme.length ()- 
                  substring.length ();

    Test: for
        (int i = 0; I <= max; i++) {
            int n = substring.length ();
            int j = i;
            int k = 0;
            while (n--! = 0) {
                if (Searchme.charat (j + +)
                    != Substring.charat (k++)) {
                    continue test;
                }
            }
            Foundit = true;
                Break test;
        }
        System.out.println (foundit?
            ) Found it ":" didn ' t find it ");
    }

Here is the program output: Found It return statement

The last branch statement is the return statement. The return statement exits from the current method, and the control flow is returned to the method call.
The return statement has two forms: one is the returned value and one is not the return value.
In order to return a value, simply put the value in (or put an expression to compute) after the back keyword
return ++count;
The data type of the value of the return, which must match the type of the returned value of the method declaration.
When a method is declared void, the return value is not required to use the following form.
Return footnotes

Reprint please specify the source, the blog Sync Update in my personal blog site. 1. My blog site: www.klsstt.com. ↩

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.