Java Learning-the first day of basic knowledge--static static keywords, code blocks

Source: Internet
Author: User
Tags abs class definition pow

Introduction of today's content

U Knowledge Review

U static keyword

U code block

Chapter 1th Knowledge Review

1.1 Review of methods

1.1.1 Case Code One:

Package com.itheima_01;

/*

* Requirements: Define a method to calculate the number of two and invoke it in the Main method

*

* Method: A program with a specific function in the class, which improves the reusability and maintainability of the code.

* Definition Format:

* public static return value type (no return value write void) method name (parameter type parameter name, parameter type argument name 2) {//formal parameter

* Method body;

* }

* Call Mode:

* There is a definite return value type:

* Assignment call to assign the return value of a method to a variable

* Output calls, using output statements to output the method's return value directly

* Direct call, unable to get the return value of the method

* No explicit return value type:

* Direct Call

* Method Overloading: There are multiple methods with the same name in a class, with different parameters, independent of the return value

*

Note

* Parameter: A variable declared by a method, only a variable, the data passed in when the method call is received

* Arguments: The data that is passed when the method is called, can be a constant, or it can be a variable

*

*/

public class Methodemo {

public static void Main (string[] args) {

Assignment invocation

int sum = SUM (10,20);//argument

SYSTEM.OUT.PRINTLN (sum);

Output call

int a = 10;

int B = 20;

System.out.println (sum (A, b));

}

public static int sum (int a,int b) {

/*//Use variable to receive sum result and return

int sum = a + b;

Return sum;*/

Return the sum result directly

return a + B;

}

}

1.2 Review of arrays

1.2.1 Case code Two:

Package com.itheima_02;

/*

* Requirements: Define an array of element type int, iterate over the array and sum

*

* Array: A container for storing multiple elements

* Features of the array:

* element types must be consistent

* element has an integer index

* Once defined, the length cannot be changed.

* Basic data types can be stored

* Reference data types can also be stored

* Definition Format:

* Dynamic Initialization

* element type [] Array name = new element type [10];

* Static Initialization

* element type [] Array name = {element 1, element 2, element 3};

* element type [] Array name = new element type []{element 1, Element 2, element 3};

*

*/

public class Arraydemo {

public static void Main (string[] args) {

Defining an array with static initialization

Int[] arr = {1,2,3,4,5};

Define a variable to store the sum result

int sum = 0;

Iterating through an array

for (int x = 0;x < arr.length;x++) {

Sum + = arr[x];

}

SYSTEM.OUT.PRINTLN (sum);

}

}

1.3 Standard class definition and usage review

1.3.1 Case Code Three:

Package com.itheima_03;

/*

* Define a standard student class, create an object in the main method, and invoke the

* Name, age, gender 3 member variables

* No reference, two methods of construction

* Define the Getter/setter method for each member variable

* Define a Show method, output member variable

*/

public class Student {

Private String name;//Name

private int age;//Age

Private String gender;//Sex

/*//Non-parametric structure

Public Student () {}

With a reference structure

Public Student (String name,int age,string gender) {

THIS.name = name;

This.age = age;

This.gender = gender;

}

Name

Public String GetName () {

return name;

}

public void SetName (String name) {

THIS.name = name;

}

Age

public int getage () {

return age;

}

public void Setage (int.) {

This.age = age;

}

Gender

Public String Getgender () {

return gender;

}

public void Setgender (String gender) {

This.gender = gender;

}*/

Show: Used to output all the member variables

public void Show () {

SYSTEM.OUT.PRINTLN (name + "," + Age + "," + gender ");

}

Public Student () {

Super ();

TODO auto-generated Constructor stub

}

Public Student (string name, int age, string gender) {

Super ();

THIS.name = name;

This.age = age;

This.gender = gender;

}

Public String GetName () {

return name;

}

public void SetName (String name) {

THIS.name = name;

}

public int getage () {

return age;

}

public void Setage (int.) {

This.age = age;

}

Public String Getgender () {

return gender;

}

public void Setgender (String gender) {

This.gender = gender;

}

}

Package com.itheima_03;

public class Studenttest {

public static void Main (string[] args) {

Create Student objects

Student s = new Student ();

Assigning values to member variables

S.setname ("Zhang San");

S.setage (18);

S.setgender ("male");

S.show ();

System.out.println ("----------");

Student s2 = new Student ("John Doe", 20, "other");

S2.show ();

System.out.println (S2.getname ());

}

}

2nd static statically key word

2.1 Overview of the static

When you define a class, you have the appropriate properties and methods in the class. The properties and methods are called by creating this class of objects. When a method of an object is called, the method does not have access to the object's unique data, and the method creates the object somewhat superfluous. But do not create the object, the method can not be called, then you will think, then we could not create the object, we could call the method?

Yes, we can do that by using the static keyword. static modifier, which is typically used to decorate a member of a class.

2.2 Static characteristics

A: The static modified member variable belongs to the class and does not belong to an object of this class. (That is, when multiple objects access or modify a static decorated member variable, one of the objects modifies the value of the static member variable, and the value of the static member variable in the other object changes, that is, multiple objects share the same static member variable)

B: Members that are modified by static can and recommend direct access through the class name

To access the format of a static member:

Class name. static member Variable name

Class name. Static member Method name (parameter)

C: Static loading takes precedence over objects and loads as classes are loaded

2.2.1 Case Code IV

Package com.itheima_01;

/*

* Static: is a keyword used to modify member variables and member methods

* Characteristics of static:

* Shared by all objects

* Can be called using the class name

* Static loading takes precedence over objects

* Loaded with the load of the class

*

*/

public class Staticdemo {

public static void Main (string[] args) {

Person.graduatefrom = "School of transfer of Wisdom";

Person p = new person ();

P.name = "Xiao Cang classmate";

P.age = 18;

P.graduatefrom = "School of transfer of Wisdom";

P.speak ();

person P2 = new person ();

P2.name = "wavelet classmate";

P2.age = 20;

P2.graduatefrom = "School of transfer of Wisdom";

P2.speak ();

}

}

Class Person {

String name;

int age;

Static String Graduatefrom;//graduated college

public void Speak () {

SYSTEM.OUT.PRINTLN (name + "---" + graduatefrom);

}

}

2.3 Static considerations

A: Static members can only access static members directly

B: Non-static members can access both non-static members and static members

2.3.1 Case Code Five

Package com.itheima_01;

/*

* Static Considerations:

* Static method:

* Static member variables can be called

* Static member methods can be called

* Non-static member variables can not be called

* Non-static member methods can not be called

* Static methods can only invoke static members

* Non-static method:

* Static member variables can be called

* Static member methods can be called

* Non-static member variables can be called

* Non-static member methods can be called

*

* Do you have this object in the static method? No, No.

*

*

*/

public class StaticDemo2 {

public static void Main (string[] args) {

Student.graduatefrom = "School of transfer of Wisdom";

Student.study ();

}

}

Class Student {

String name;

int age;

Static String Graduatefrom;//graduated college

public static void study () {

System.out.println (Graduatefrom);

Sleep ();

SYSTEM.OUT.PRINTLN (name);

Eat ();

}

public static void Sleep () {

System.out.println ("Sleep");

}

public void Eat () {

System.out.println ("eat");

System.out.println (Graduatefrom);

Sleep ();

}

}

2.4 Advantages and disadvantages of static

A: Static Advantages:

Shared data on objects provides a separate space for storage, saving space, without the need for each object to store a copy

Can be called directly by the class name without creating an object in heap memory

Static members can be accessed directly through the class name, making it easy to access the members relative to the object

B: Static drawbacks:

The limitations of access occur. (Static although good, but only static)

2.5 Static applications

The 2.5.1 Math class uses

The A:math class contains methods for performing basic mathematical operations. Classes commonly used in mathematical operations.

The constructor method of the B:math class is private, unable to create the object, and cannot access the members of the math class through the object.

All members of the C:math class are statically decorated, so we can access them directly from the class name.

2.5.1.1 Case Code Three:

Package com.itheima_02;

public class Mathdemo {

public static void Main (string[] args) {

Math: Contains some basic mathematical methods

Static Double PI

System.out.println (Math.PI);

Static double abs (double A): return absolute value

System.out.println (Math.Abs (15)); 15

System.out.println (Math.Abs (-10)); 10

Static double Ceil (double A) ceiling upward rounding

System.out.println (Math.ceil (1.2)); 2

System.out.println (Math.ceil (1.6)); 2

System.out.println (Math.ceil (-1.6));-1

Static double floor (double a) flooring is rounded down

System.out.println (Math.floor (1.2)); 1

System.out.println (Math.floor (1.6)); 1

System.out.println (Math.floor (-1.6));-2

Static Long round (double a): rounding

System.out.println (Math.Round (1.2)); 1

System.out.println (Math.Round (1.6)); 2

Static Double Max (double A, double b)

System.out.println (Math.max (3, 4)); 4

Static Double pow (double A, double b): Returns the second argument of the first argument to the power of a

System.out.println (Math.pow (3, 2)); 8

static double Random (): Returns a random number greater than 0 and less than one

System.out.println (Math.random ());

}

}

2.5.2 Custom Tool Classes

A: Requirements: Customize a tool class that specializes in array operations, with the following features

1. Define a method that can return the largest element in the array

2. Define a method that finds out if the value exists in the array, based on the specified value

exists, returns the index of the value in the array

Not present, return-1

2.5.2.1 Case Code Four:

Package com.itheima_03;

public class Myarrays {

Private Myarrays () {}

/*

* Returns the largest element in the array

*

*/

public static int Getmax (int[] arr) {

int max = 0;//referential

Iterating through an array

for (int x = 0;x < arr.length;x++) {

if (Arr[x] > max) {

max = arr[x];//Replacement Reference

}

}

return Max;

}

/*

* Returns the index of the specified parameter in the array

*

*/

public static int GetIndex (int[] Arr,int a) {

Iterating through an array

for (int x = 0;x < arr.length;x++) {

if (arr[x] = = a) {

return x;

}

}

return-1;//If no parameters are found, return-1

}

}

Package com.itheima_03;

public class Myarraysdemo {

public static void Main (string[] args) {

Int[] arr = {3,5,8,10,1};

int max = Myarrays.getmax (arr);

SYSTEM.OUT.PRINTLN (max);

int index = Myarrays.getindex (arr, 8);

SYSTEM.OUT.PRINTLN (index);

}

}

Analysis of 2.6 class variables and instance variables

A: Class variable: It's actually A static variable.

Define location: Outside the method in the class

Area of Memory: Method area

Life cycle: Loaded as the class loads

Features: No matter how many objects are created, class variables are only in the method area, and only one copy

B: Instance variable: It's actually a non-static variable.

Define location: Outside the method in the class

Area of Memory: Heap

Life cycle: Loaded as objects are created

Features: Each object is created and there is an instance variable in the object in the heap

3rd Chapter code block

3.1 Local code block

A local code block is defined in a method or statement

3.1.1 Case Code VI:

public class Blockdemo {

public static void Main (string[] args) {

Local code block: The Life cycle (scope) of the control variable that exists in the method

{

for (int x = 0;x < 10;x++) {

System.out.println ("I love Java");

}

int num = 10;

}

SYSTEM.OUT.PRINTLN (num);//cannot access num beyond the scope of NUM

}

}

3.2 Building Code Blocks

Constructing a code block is a block of code that defines the position of a member in a class

3.2.1 Case Code VII:

Package com.itheima_04;

Class Teacher {

String name;

int age;

{

for (int x = 0;x < 10;x++) {

System.out.println ("I love Java");

}

System.out.println ("I love Java");

}

Public Teacher () {

System.out.println ("I am a non-parametric structure");

}

Public Teacher (String Name,int age) {

System.out.println ("I am a constructive");

THIS.name = name;

This.age = age;

}

}

3.3 Static code block

A: A static code block is a block of code that is defined at the member location, using the static adornment

3.3.1 Case Code Eight:

Class Teacher {

String name;

int age;

Static code blocks: loaded as the class loads, loading only once, and some initialization needed to load the class, such as loading the driver

static {

System.out.println ("I love Java");

}

Public Teacher () {

System.out.println ("I am a non-parametric structure");

}

Public Teacher (String Name,int age) {

System.out.println ("I am a constructive");

THIS.name = name;

This.age = age;

}

}

3.4 Features of each code block:

3.4.1 Local code block:

A region of code delimited with "{}", at which point you only need to focus on the different scopes

Methods and classes delimit boundaries in a code block way.

3.4.2 Constructing code blocks

Takes precedence over construction method execution, and constructs code blocks to perform initialization actions that are required for all objects

Each object that is created executes a block of construction code at a time.

3.4.3 Static code block

It takes precedence over the execution of the Main method, which takes precedence over the construction of code block execution, when used in any form for the first time to the class.

The static code block executes only once, regardless of how many objects are created.

Can be used to assign a value to a static variable for initialization of a class.

3.4.4 Case Code IX:

Package com.itheima_04;

/*

* Coder Static code block execution---Coder Construction code block execution---Coder null-free construction execution

*

*

* Blocktest static code block execution---Blocktest of the main function performed---Coder Static code block execution---Coder construct code block execution---coder NULL structure execution

* Coder Construction code block execution---Coder null-free construction execution

*

*/

public class Blocktest {

static {

System.out.println ("blocktest Static code block execution");

}

{

SYSTEM.OUT.PRINTLN ("Blocktest Construction Code block execution");

}

Public Blocktest () {

System.out.println ("Blocktest without a reference structure");

}

public static void Main (string[] args) {

SYSTEM.OUT.PRINTLN ("The main function of the blocktest executes");

Coder C = new coder ();

Coder C2 = new Coder ();

}

}

Class Coder {

static {

System.out.println ("Coder Static code block execution");

}

{

SYSTEM.OUT.PRINTLN ("Coder Construction Code block execution");

}

Public Coder () {

SYSTEM.OUT.PRINTLN ("Coder Non-parametric construction execution");

}

}

Java Learning-Basic knowledge advanced first day--static static keywords, code blocks

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.