Java Certification Course (1 ~ 4) -pconline.com.cn

zhaozj2021-02-16  117

About this course

The main goal of this book is to provide you with the knowledge and skills necessary for object-oriented programming for Java applications and Java Applets; and teach Java programming language syntax and object-oriented concepts, many of the characteristics of Java operating environment, graphics User Interface (Guis), multi-threaded and network support, etc. This course includes the knowledge necessary to participate in the Sun Certified Java Programmer and Sun Certified Java Developer exams.

First, the course overview

Course Overview

This course mainly includes the following:

- Java programming language syntax

- Applying object-oriented concepts for Java programming languages

- Graphical User Interface (GUI) Programming

- Create an applet

- Multithreading

- The internet

This course first discusses the Java runtime and Java programming language syntax, then elaborates the object-oriented concepts applied to the Java programming language; with the progress of the course will also discuss more advanced features about the Java platform.

This course is subject to the ability to use Java programming languages ​​or other languages, which is "Non-Programmer Java Programming" ("Java Programming For Non-Program", SL-110) course continues.

Although the Java programming language is independent of the operating system, the graphical user interface (GUI) it produces may depend on the operating system that executes its code. The code used in this course is running on the Solaris TM operating system, so the graphics in this manual have Motif GUI. If you run these code in a Windows 95 operating system, Microsoft Windows 95 GUI can be generated. The content of this course is suitable for all Java operating system ports.

Second, the course

Each module begins with a course graph, so that students can master their learning progress. The full course setting flow chart is as follows:

Third, overview of each module

Overview of each module

- Module 1 - start

- Module 2 - identifier, keyword, and type

- Module 3 ─ Expression and Process Control

- Module 4 - Array

- Module 5 ─ Objects and Class

- Module 6 ─ Advanced Language Characteristics

- Module 7 ─ Abnormal

- Module 8 ─ Establish Guis

- Module 9 ─ AWT Event Model

- Module 10 ─Awt Component Library

- Module 11 - Java Foundation Class

- Module 12 - Java Applets Introduction

- Module 13 ─ ─ thread

- Module 14 - Flow I / O and Files

- Module 15 - Network

- Module 1 - start

This module outlines the main features of the Java programming language and Java applications, elaborating the concept of classes and packages, and introduces some common Java packages.

- Module 2 - identifier, keyword, and type

The Java programming language is similar to the C language with many programming configurations. This module generally introduces these structures and teaches the general syntax required for each structure. In addition, object-oriented methods for data association using the set data type are also described.

- Module 3 ─ Expression and Process Control

This module describes expressions including operators and Java programs to control syntax.

- Module 4 - Array

This module explains how to declare, create, initialize, and copy the Java array.

- Module 5 ─ Objects and Class

This module is based on the module 2, and the concept of Java objects is further elaborated, including overload, coverage, subclasses, and constructors.

- Module 6 ─ Advanced Language Characteristics

This module is the continuation of the module 5, it further explains the Java object-oriented programming module, including some new JDK1.1 characteristics - downgrade and internal classes. The module also introduces the concept of new collection in Java Development Kit JDKTM 1.2. - Module 7 ─ Abnormal

This module provides a Java programmer with a mechanism to capture errors when running a Java program and expounds predefined exceptions and user-defined exceptions.

- Module 8 ─ Establish Guis

In the Java programming language, all graphical user interfaces are built on the concept of frames and panels. This module describes the concept of layout management and container.

- Module 9 ─ AWT Event Model

The most important change of the Java Programming Language version 1.1 is to send events to changes in the Java components. This module illustrates the difference between JDK1.0 and 1.1 event models and demonstrates how to establish a small event handle (Compact Event Handler).

- Module 10 ─Awt Component Library

This module describes the Abstract Window Kit (AWT) component for establishing Java Guis and demonstrates how Java AWT components and 1.1 event model work together.

l Module 11 - Java Basic Class Introduction

This module focuses on an important feature of JDK1.2 - Java Foundation Class (JFC), which expounds the Swing component and their pluggable appearance and feeling of the sensory architecture, and introduces basic Swing applications and other JFC others. Features, such as applications such as two-dimensional graphics, accessibility, and drag and droap.

- Module 12 - Java Applets Introduction

This module demonstrates the difference between Applet and application development, and introduces the sound enhancement function of JDK 1.2.

- Module 13 ─ ─ thread

Thread is a complex topic. This module describes thread problems related to Java programming language and introduces a simple thread communication and synchronous transmission instance.

- Module 14 - Flow I / O and Files

This module describes classes that can read and write data and read and write text files, and introduce the concept of object streams.

- Module 15 - Network

This module describes the Java network programmer package and demonstrates the Transfer Control Protocol / Internet Protocol (TCP / IP) customer - server model.

Fourth, the course goal

After completing the study of this course, you should be able to:

- Describe the main features of the language

- Compile and run Java applications

- Understand and use online hypertext Java technical files

- Description Language syntax elements and constructors

- Understand object-oriented examples and use this language

- understand and use anomalies

- Develop graphical user interface

- Describe the abstract window kit for establishing Guis on the Java technology platform

- Enter from GUI

- Understanding event processing

- Describe the main features of Swing

- Develop Java Applets

- Read and write files and other data sources

- Perform input and output for all data sources without using the GUI

- understand multithreading foundation

- Develop multithreaded Java applications and Applets

- Develop Customer and Server Programs Using TCP / IP and User Data News Agreement (UDP)

V. Skills obtained from each module

The left side of the table below shows the relevant Java application programming skills, and the black gy on the right indicates the relevant modules that explain the corresponding skills on the left, and the gray gauge represents the relevant modules of the corresponding skills on the left.

Module

Skills Gained1

2

3

4

5

6

Seduce

8

9

10

11

12

13

14

15

Describe Key Language Features

Compile and Run A Java Application

Understand and use the the online Hypertext Java Technology Documentation

Describe Language Syntactic Elements and Construction

Understand The Object-Oriented Paradigm and Use Object-Oriented Features

Understand and use exceptions

Develop A Gui

Describe The Java Technology Platform's Abstract Window Toolkit from Which Guis Are Built

Take Input from A Graphical User Interface

Understand Event Handling

Describe the main features of swing

Develop java applets

Understand the Basics of Multithreading

Develop Multithreaded Java Applications and Applets

Perform I / O To All Sources without the use of a gui

Read and Write to Files and Other Data Sources

Develop Java Client and Server Programs Using TCP / IP and UDP

Six, class arrangements

The following table gives a rough course progress

Module Day Day Day day day

1 2 3 4 5

About this course A.m.

Module 1-getting started A.m.

Module 2-Identifiers, Keywords, And Types A.m.

Module 3-Expressions and Flow Control P.m.

Module 4-Arrays P.m.

Module 5-Objects and Classes A.m.

Module 6-Advanced Language Features P.m.

Module 7-Exceptions A.m.

Module 8-Building Guis A.m.

Module 9-The AWT Event Model P.m.

Module 10-The AWT Component Library A.m.

Module 11-Introduction To JFC A.M.

Module 12-Introduction To Applets P.m.

Module 13-Threads A.M.Module 14-Stream I / O and FILES P.M.

Module 15-Networking P.m.

Seven, the topic that is not included

Topics not included

- General programming concept. This course is not set for people who have never been programmed.

- Generally object-oriented concept.

This course is not included in the topic, and other courses provided by Sun Educational Services (SES) include the above.

- Object-oriented concept - See OO-100: Object - Oriented Technology And Concept

- Object-oriented design and analysis - see OO-120-oriented design and analysis

- General programming concept - see SL-110: Non-programmer Java programming

8. How to prepare?

How to prepare?

Before studying this course, you should have completed the following contents:

- SL-110 non-programmer Java programming

- Create a compiler with C or C

- Create and edit text files with text editor

- Using World Wide Web (WWW) browser, such as Netscape NavigatorTM

Before studying this course, you should have completed the following contents:

- SL-110 non-programmer Java programming

Or you can:

- Create a compiler with C or C

- Create and edit text files with text editor

- Using World Wide Web (WWW) browser, such as Netscape NavigatorTM

Nine, self-introduction:

Self introduction

- Name

- the company

- Directors, responsibilities

- Programming experience

- Reasons for participating in this course

- expectations for this course

Now you have entered this course, please introduce each other and fill in the table above.

Ten, how to use this textbook

How to use this textbook

- Courseware

- related question

--P 页图 图 图

- Tutorial

- Exercise

- Check your progress

- thinking

In order to make you learn this course, this textbook has adopted a teaching model including the following major projects:

l Courseware - Each module starts from a content outline so you can understand that the module acts in achieving the entire course goal.

l Related Issues - Part of the related issues of each module provides you with some questions about the module for discussion, and encourage you to think about your interest in the Java application programming process.

l Taps - Page Maps help you keep up with the teacher's progress in a timely manner. It doesn't appear in each page

l Tutorial - Teachers will provide you with unique information about modules, which will help you master the knowledge and skills needed to do exercises.

l Practice - exercises will provide you with the opportunity to test your skills and application. The examples provided in this tutorial also help you complete exercises.

l Check your progress - In this part, the target of the module is re-mentioned, sometimes it appears in the form of a problem. In this way, you can check if you have completed the goal required for this module before you enter the next module. l Thinking - Challenging issues help you apply the contents of the module you have learned or predict the content of the waiting module.

XI, chart and printing case

The following charts and printing systems represent different meanings:

Auxiliary resources - represents accessibility to access.

Discussion - It is recommended that it is recommended to discuss in groups or classes.

Exercise goals - indicate the goal of exercises, this practice is suitable for the content being discussed.

Caution - Attach important information, emphasize information, interesting or special information

Warning - Potential damage to data or machines

Printing system

The font Courier is used to indicate the command name, file name, and directory name, and also means that the computer screen output. E.g:

Use ls -al to all files.

System% you have mail

The black body bold is used to represent the characters and numbers you print.

E.g:

SYSTEM% SU

PASSWORD:

Body ITALIC system uses to represent variables and command lines, which can be replaced by actual names or values.

E.g:

To delete a file, Type RM FileName.

Slablasting Palatino is used to express a title, new word or term or the word that needs to be emphasized.

E.g:

Read Chapter 6 in User's Guide.

THESE Are Called Class Options

You must be root to do this.

Chapter 1

This module has a general description of Java programming languages, including Java virtual machines, garbage collection, and security.

Section 1 related issues

Discussion - The following issues are related to this module

- Is the Java programming language a complete language? Is it only used to write a web program?

- Why do you need another programming language?

- How does the Java platform improve performance on other language platform?

Second section

After completing this module, you should be able to:

- Describe the main features of the Java programming language

- Describe the main features of the Java virtual machine

- How to describe how garbage collection is

- list three tasks implemented by the Java platform that handles code security

- Define Class, Package, Applets and Applications

- Write, compile and run simple Java applications

- Method for using the Java Technical Application Programming Interface (API) to identify the Java. LANG package.

Reference

Auxiliary resources - the following reference materials provide more detailed supplements for the issues discussed in this module

Lindholm and Yellin. 1997. The Java Virtual Machine Specification. Addison-Wesley.

- Yellin, Frank. Low-Level Security In Java, White Paper. [Online]. Available:

Http://www.javasoft.com/sfaq/verifier.html.

Section 3 What is Java programming language?

What is a Java programming language?

Java is:

- a programming language

- a development environment

- an application environment

- a deployment environment

- Syntax is similar to C , semantics is similar to Small Talk - used to develop Applets, and use to develop Applications

Java is:

- a programming language

- a development environment

- an application environment

- a deployment environment

The syntax of the Java programming language is similar to the syntax of C , and semantics is similar to the SMALL Talk TM. Java programming languages ​​can be used to create applications that can be created any regular programming languages.

In the relevant introduction of the World Wide Web (WWW) and the browser called Applets program, people often refer to the Java programming language. Applets is a program stored in a Java programming language stored in the WWW server, which is usually downloaded from the browser to the client system and runs through the browser. Applets is usually smaller to reduce download time, which is called by the Web page of Hypertext Identity Language (HTML).

Java Applications is an independent program that does not require any web browser to execute. They are typical general programs; they can run in devices with Java operating environments.

1.3.1 Main goals of Java programming languages

The main goal of Java programming language

Provide an explanation environment

- Improve development speed

- Code portability

- User can run more than one activity thread

- When the program is running, it can dynamically support the program to change.

Provide better security

The main goal of designing Java programming languages ​​is

Provide a language that is easy to program, thus

Ú Eliminate other languages ​​in a defect that affects robustness in terms of pointer operations and memory management.

Ú Use the object-oriented concept to truly become visualization

Ú provides a way to make the code as clear as possible, concise and smooth

The main goal of Java programming language

The main goal of designing Java programming languages ​​is

Provide a language that is easy to program

- Eliminating other languages ​​in defects affecting robustness in terms of pointer operations and memory management.

- Use the object-oriented concept to truly become a visualization program

- Provide a method for making the code as clear as possible, concise and smooth

The main goal of Java programming language (continued)

- Provide an interpretation environment for obtaining the following two benefits

Ú Improve the development speed - eliminate compilation - link - loading - test cycle.

Ú Code portability - to make the operating environment for system-level calls

- provides a way for programs that run more than one activity thread

- A dynamic support program change can be dynamically supported by allowing the download code module to run when the program is running.

- provides an inspection method for the code modules that ensure safety.

The main goal of Java programming language

The following features make these goals into achieved:

- Java Virtual Machine (JVM)

- garbage collection

- Code security

The main goal of Java programming language (continued)

The well-developed Java technology architecture provides guarantees for the achievement of the above objectives. The following features of Java make these goals to be implemented

- Java virtual machine

- garbage collection

- Code security

1.3.2 Java virtual machine

Java virtual machine

- Provide hardware platform specifications

- Interpretation of the compiled bytecode independent of the platform

- Can be implemented as software or hardware

- Implementation on Java technology development tools or web browsers

The Java Virtual Machine Specification is the following definitions as the Java Virtual Machine (JVM): an imaginary machine that implements software simulation in a real machine. The Java virtual machine code is stored in the .class file; each file contains up to one public class.

The Java virtual machine specification provides a specific example of compiling Java technology code for different hardware platforms. This specification makes Java software independently of the platform, because compiling is for "general machine" as a virtual machine, this "general machine" available Software simulates and runs in a variety of existing computer systems, but also hardware is implemented.

Java virtual machine

JVM is defined for the following

- Instruction set (central processor [CPU])

- Registration set

- Class file format

- Stack

- Garbage collection

- Storage area

Java virtual machine (continued)

After obtaining the source code for the Java application, the compiler generates a zodical code, which is a machine code instruction generated for JVM. Each Java interpreter, whether it is a Java technology development tool, or can run the Applets web browser, JVM can be implemented.

JVM is defined for the following

- Instruction set (equivalent to central processing unit [CPU])

- Registration set

- Class file format

- Stack

- Garbage collection

- Storage area

Java virtual machine

- Formation code from the bytecode that keeps the appropriate type constraint

- Most types of checks are completed when compiling code

- Each JVM approved by Sun TM must be able to run any slave class file

Java virtual machine (continued)

The JVM code format consists of a tightening valid bytecode. The program written by the JVM byte code must maintain the appropriate type constraint. Most types of types are completed at compile time.

Any subordinate Java technology interpreter must be able to run any programs with class files, which should comply with the class file format specified in the Java virtual machine specification.

1.3.3 garbage collection

Garbage collection

- Distribution memory that is no longer needed should cancel allocation

- In other languages, cancel allocation is the responsibility of programmers

- Java programming language provides a system-level thread to track storage area allocation

- garbage collection

- Check and release memory that no longer needs

- Automatically complete the above work

- Can not think of changes in the JVM implementation cycle

Many programming languages ​​allow for dynamic allocation of memory during program runtime, allocating memory changes due to language syntax, but always returns the pointer to the starting position of the storage area

When allocating a memory is no longer required (the memory pointer has overflow range), the program or the run environment should unassign the memory.

In C, C or other languages, the programmer is responsible for unassigning a memory. Sometimes this is a very difficult thing. Because you don't always know when the memory should be released in advance. When there is no memory that can be assigned in the system, the program can be caused, which is called a memory vulnerability.

The Java programming language relieves the programmer to cancel the memory of the memory, which provides a system-level thread to track allocation of each memory. In the Java virtual machine idle period, garbage collection thread check and release those memory that can be released.

Garbage is automatically carried out in the life cycle of the Java technology program, which unsociates the demand of the memory, and avoids memory vulnerabilities. However, garbage collection can have an unexpected change in the cycle of the JVM implementation.

1.3.4 Safety Overview of Code

The figure below shows the operational environment of Java technology and how to enhance code security.

The Java source file is "compiled", in your feelings, it is like converting them from programmers to a group of bytes. The bytecode is stored in the .class file.

The bytecode constituting the Java software program is loaded, verified and running in the interpreter at runtime. When running Applets, bytecode can be downloaded and then interpreted by JVM built in the browser. The interpreter has two functions, one is to perform bytecode, and the other is to properly call the underlying hardware.

In some operational environments using Java technology, partial code codes are compiled into original machine code and run directly on the hardware platform. This allows the Java software code to run at C or C , just when loading, because it is delayed as the original machine code.

Note - SUN MicrosystemSTM has further improved performance of Java virtual machines by adopting new technologies. This new virtual machine is called a HotSpottm virtual machine, which has the potential to quickly run the Java programming language like compiling C . The HotSpot virtual machine has a local multi-thread support capability for the operating system, not a virtual multi-thread. Thus, the HotSpot virtual machine guarantees that this capability is not necessarily a code to an application. HotSpot technology solves the challenge between performance and transplantability.

Java operating environment

Implement three tasks

- Load code

- Calibration code

- Execute code

Code security (continued)

Java operating environment

A Java technology running environment can run the JVM compiled code and execute the following three tasks:

- Load code - execution by the class loader

- Calibration code - executed by the word code verifier

- Execute code - executed by the runtime interpreter

Class loader

The class loader is required for the execution of the program. The class loader separates the class namespace of the local file system to the class namespace from the network source to increase security. Since the local class is always loaded, any "Trojan horse" can be restricted.

When all classes are loaded, the memory format of the executable file is determined. At this time, the specific memory address is assigned to the symbol reference and creates a search form. Since the memory format appears at runtime, the Java technology interpreter adds protection to prevent illegal entry of the restriction code area.

Bytecode verification

Guarantee

- The code is in line with the JVM specification

- Code does not damage system integrity

- The code will not cause overflow or underflow on the operating counting stack.

- Accuracy of the parameter type of all operating code

- No illegal data conversion (integer to the conversion of pointers)

Code security (continued)

Byte code verifier

The Java software code has been tested several times before actual operation. JVM Enter the code into a band code checkler to test the code segment format and check the fake pointer, violate object access rights or attempt to change the illegal code of the object type.

Note --- All types of files from the network must pass by:

Code security (continued)

Check process

The bytecode verifier checks the program code, which ensures that the code is in line with the JVM specification and does not destroy the integrity of the system. If the verifier does not return an error message after completing the four-pass check, the following points can be guaranteed:

- Class file format for class complies with JVM specification

- No access limit violation

- The code has not caused an operation count stack overflow or underflow

- The parameter type of all operating code will always be correct

- No illegal data conversion, such as converting integers to object reference

- Object Domain Access is a legitimate Section 4 A basic Java application

Like other programming languages, Java programming languages ​​are also used to create applications. A common small application example is a string "Hello World!" On the screen. The following code gives this Java application.

1.4.1 HelloWorldApp

1.//

2.// Sample HelloWorld APPLICATION

3.//

4.public class helloworldapp {

5.public static void main (string args []) {

6.System.Out.println ("Hello World!");

7.}

8.}

The above programs are printed on your screen to print the minimum components required for "Hello World!".

1.4.2 Description HelloWorldApp

1-3

1-3 lines in the program are comment lines

1 //

2 // Sample HelloWorld APPLICATION

3 //

Line 4

The fourth line declares named HelloWorldApp. Classname is specified in the source file, which creates a classname · class file on the same directory as the source code. In this example, the compiler creates a file called HelloWorldapp.class, which contains the compile code of public class HelloWorldApp.

4 public class helloworldapp {

Line 5

Chapter 5 is the starting point of the program execution. The Java Technology Interpreter must discover this strict definition point, otherwise the runtime will be rejected.

Other programs (especially C and C ) also use main () declarations as the starting point of the program execution. Different parts of this statement will be introduced in the later part of this course.

If any arguments are given in the command line of the program, they will be passed to the String array called Args in the main () method. In this example, an argument is not used.

5 public static void main (string args []) {

- Public- method main () can be accessed by any program, including Java technology interpreters.

- static- is a notification compiler main () is a keyword for functions in the class HelloWorldApp. In order to make main () start running before procedure, this keyword is necessary.

- Void- indicates that main () does not return any information. This is important because Java programming languages ​​should be cautious, including checking the method that does not return the type declared by these methods.

- String args [] - is a statement of a string array that will contain the arguments in the command lines below the class name.

Java HelloWorldApp Args [0] Args [1] ····

Line 6

Chain 6 declares how to use class names, object names, and method calls. It prints the string "Hello World!" To the standard output using the println () method of the PrintStreamout object referenced by the SYSTEM class's OUT member.

6 System.out.println ("Hello World!");

In this example, the println () method is entered a string independent variable and writes it on the standard output stream.

Chapter 7-8

The 7-8 lines of this program are methods main () and the lower brackets of the class HelloWorldApp.

7}

8 }

1.4.3 Compile and run HelloWorldApp

Compile and run HelloWorldApp

- Compile helloworldapp.javajavac helloworldapp.java

- Run app

Java HelloWorldApp

- Judgment the common error of compilation and operation

Compile

After you create a HelloWorldapp.java source file, compile with the following procedures:

C: / student / javac helloworldapp.java

If the compiler does not return any prompt information, the new file helloworldapp.class is stored in the same directory as the source file, unless otherwise specified.

If you encounter problems in compilation, see the error indicator information section of this module.

run

To run your HelloWorldApp application, you need to use Java interpreters and Java in bin directory:

C: / student / java helloworldapp

Hello World!

Note - must set the PATH environment variable to find Java and Javac, confirm that it includes c: /jdk1.2/bin

1.4.4 compile error

Compile time error

The following is a common mistake at compile

- Javac: Command Not Found

The PATH variable is not set correctly to include a Javac compiler. The Javac compiler is located in the bin directory under the JDK directory.

- helloworldapp.java: 6: Method Printl (java.lang.string)

Not found in class java.io.printStream.system.

OUT.PRINTL ("Hello World!");

Method Name PrintLn appears print error.

- In Class HelloWorldapp: Main Must Be Public or Static

The occurrence of this error is because the word Static or Public is placed outside of the row of the MAIN method.

Running error

- can't find class helloworldapp (this error is generated when printing Java HelloWorldApp)

Typically, it represents the spelling of the class names specified in the command line and the spelling of the filename.class file. The Java programming language is a language that is subject to differentiated languages.

For example: public class helloworldapp {

Created a HellLoworldapp.class, which is not a class name expected by the compiler. Class.

- Name

If the Java file includes a public class, it must use the same file name as that public class. For example, the definition of classes in the precedent is

Public Class HelloWorldApp

Source file name must be HelloWorldapp.java

- Class count

You can only define a public class each time in the source file.

Source file layout

Source file layout

Contains three "top" elements

- A selectable package declaration

- any number of input statements

- Class and interface declaration

A Java source file can contain three "top" elements:

- a package statement (optional)

- any number of input statements

- Class and interface declaration

The three elements must appear in the above order. That is, any input statement appears before all class definitions; if you use a packet declaration, the package declaration must appear before the class and the input statement.

Section 5 and package introduction

Class and package introduction 1. What is a class and package? 2. Several important packages in the Java class library java.lang java.awt java.applet java.net java.io java.util class is a general term describing a module that provides a function. Java Development Set (JDK) gives a set of standard classes (called class libraries), which can perform most of the necessary basic behaviors not only for programming tasks (for example, the class can provide basic mathematical functions, arrays and characters. Strings) and is graphics and networks.

The class library is organized into a number of packages, and each package contains several classes. The following is some important packages:

Java.lang contains some classes that form language, such as String, Math, Integer, and Thread.

Java.aw contains classes that make up the Abstract Window Toolkit (AWT), which is used to build and manage the graphical user interface of the application.

The Java.applet contains classes that can perform Applet special behavior.

Java.net includes classes that perform classes related to network-related operations and process interfaces and unified resource locator (URLs).

Java.io contains classes that process I / O files.

Java.util contains utility classes for task settings, such as random numbers, define system features, and functions related to date calendar.

Section 6 Using Java API Documents

Use Java API documentation

1. A set of hypertext Identity Language (HTML) files provide information about APIs

2. A package contains hyperlinks for all types of information

3. A class document includes a class level, a class description, a group of member variables, and constructor, etc.

A group of HTML files provide information about the API in the form of a document. The layout of this document is a hierarchy, so the homepage lists all packages for hyperlinks. If a hot link for a special package is selected, the class as the member of the package will be listed. The hot link selected from a package page will submit a page about that class information.

Figure 1-1 shows such a class document

Picture 1-1

The main parts of a class document include:

- Class level

- General purpose description of classes and classes

- list of members variables

- Constructor list

- Method list

- Variable detailed list and purpose and purpose description

- Constructor detailed list and description

- Method detailed list and description

Exercise: basic task

Exercise Objective - In this exercise, you will use the Java API document exercise how to identify packets, classes, and methods and practice standard input and output methods. You will also write, compile and run two applications that use these methods.

First, ready

Understanding the concepts and terms present in this module are critical to understanding the documentation and using document information.

Second, the task

Level 1: Reading Documents

1. Your teacher will guide you how to start the API browser and open the index page of the Java API online document.

2. Find the java.lang package

3. What classes are defined in this package? How do you have those methods in the System class? Is the system.out.println method defined in what package? What is the standard input method call?

Level 2: Create a Java application

1. Use any text editor to create an application that prints a string you selected to you.

2. Compile the program and correct the error.

3. Use the interpreter to run the program.

Level 3: Use standard input and standard output

Write a application called Mycat that will read a row from stdin and write this line back to stdout. Whether stdin is still stdout in a java.lang.system class.

Third, check your progress

Before entering the next module, please confirm that you have been able to: - Describe the main features of the Java programming language

- Description JVM

- How to describe how garbage collection is

- List three tasks performed by the Java platform that process code security

- Define terminology, pack, applets and application

- Written, compile and run a simple Java application

- Using the Java Technical Application Programming Interface (API) to identify the method in the java.lang package.

Fourth, thinking

What benefits will be brought to your work using the Java programming language?

Chapter II identifier, keywords and types

This module illustrates the basic elements used in the Java Technical program, including variables, keywords, original types, and class types.

Section 1 related issues

Discussion - The following issues are related to the topics described in this module.

- How did you understand the class?

- How do you understand an object?

Second section

After completing this module, you should be able to:

- Use declarations in a source program

- distinguish effective and invalid identifiers

- Confirm the Java technical keyword

- List eight original types

- Define text values ​​for digital types and text types

- Definition Terminology Class, Object, Member Variable and Reference Variable

- Create a class definition for a class containing the original member variable

- Declare class type variable

- Construct an object using the New

- Describe the default initialization

- Visit a member variable of an object using a point symbol

- Describe the meaning of a reference variable

- Specify the results of allocation class type variables

Third quarter

Comment

Three allowed Java Technical Program Notes

// Comment on one line

/ * Comment on one

or more line * /

/ ** Documenting Comment * /

2.3.1 Overview

There are three allowable styles of insertion comments:

// Comment on one line

/ * Comment on one or more line * /

/ ** Documenting Comment * /

Document comments before declaring (variables, methods or classes) indicate that comments should be placed in an automatically generated document (HTML file generated by the javadoc command) as a description of the declaration item.

Note ------ For the format of these comments, please see the DOCS / ToolDocs / Win32 directory of the JDK1.2 API file for the Javadoc tool.

2.3.2 Section, block and blank

Sequel, block and blank

- A statement is the code to terminate a line of semicolons (;)

Totals = A B C D E F;

- A block is the set of statements that are brackets and lower brackets

{

X = y 1

Y = x 1

}

In the Java programming language, the statement is the code that is terminated by the semicolon (;).

E.g

Totals = A B C D E F;

In the same formula

Total = A B C

D E F;

A block (block) or a compound statement is the set of statement borders and lower brackets ({}); block statements are also used to combine a statement that belongs to a class.

Sequel, block and blank (continued)

Sequel, block and blank - a block can be used in a definition of a class

Public class date {

Int day;

Int Month;

Int year;

}

- block statement can be nested

- Allow any gaps in the Java program

The sentence block can be nested. The HelloWorldApp class consists of the main method. This method is a statement block. It is a stand-alone unit that can act as one of a set of transactions in the class HelloWorldApp block.

Examples of other block statements or groups are as follows:

// a Block Statement

{

X = Y 1;

Y = x 1;

}

SEMICOLONS, Blocks, And Whitespace

// a block buy in a class definition

Public class mydate {

Int day;

Int Month;

Int year;

}

// AN EXAMPLE OF A Block Statement Nested within

// another block statement

While (i

A = a i;

IF (a == max) {

B = B a; // Nested block is here

A = 0;

}

}

Allow blank between the source code elements, the number of blank is not limited. Blank (including spaces, tabs, and new rows) can improve your visual feelings for source code.

{

INT X;

X = 23 * 54;

}

{

Int x

X = 23 54;

}

Section 4 identifier

Identifier

- is the name of the variable, class and method

- Starting with one letter, underscore (_) or dollar sign ($)

- is the difference between case, and no maximum length

In the Java programming language, the identifier is a name that gives a variable, class, or method. The identifier can start from one letter, underline (_) or dollar sign ($), and then follow the numbers. The identifier is the case where the case is different and the maximum length is not specified.

The effective identifier is as follows:

- Identifier

- Username

- User_name

- _SYS_VARL

$ CHANGE

The Java Technical Source program uses a valid 16-bit double-byte character coding standard (Unicode) instead of 8-bit ASCII text. Thus, a letter has a broader definition, not just A to Z and A to Z.

Carefully treat non-ASCII characters because Unicode supports seemingly the same and actual different characters.

The identifier cannot be a keyword, but it can contain a keyword as part of its name. For example, thisone is a valid identifier, but this is not because this is a Java keyword. Java keywords will be discussed later.

Note ─ The keywords containing the dollar symbols ($) are usually used, although it has a wide range of applications in the Basic and VAX / VMS system languages. Because they are not well known, it is best to avoid using them in the identifier unless there is a habit or other reason why you use it locally.

Section 5 Java keyword

Table 2-1 lists the keywords used in the Java programming language.

Abstract Do Implements Private throw

Boolean Double Import Protected THROWS

Break else instanceof public transientbyte extends int Return True

Case False Interface Short Try

Catch Final Long Static Void

Char Finally Native Super Volatile

Class Float New Switch While

Continue for null synchronized

Default if package this

Keywords have special meanings for Java Technical Compiler, which identifies data type names or constructs names.

Here are important considerations about keywords:

- True, false and null are lowercase instead of uppercase in the C language. Strictly speaking, they are not keywords, but text. However, this difference is theoretical.

- There is no SizeOF operator; all types of length and representation are fixed, independent of execution.

- GOTO and ConST are not the keywords used in the Java programming language.

Section 6 Basic Java Types

Java programming language defines eight original types - logical class Boolean - Text class char - integer class Byte, Short, int, long - floating point Double, float

2.6.1 Original Type

The Java programming language defines a text value for eight raw data types and a special type. The original type can be divided into four types:

- Logic Boolean

- Text class char

- Integer class Byte, Short, int, long

- Floating point Double, Float

2.6.2 Basic Java Types

Logical class - Boolean

Logical class - Boolean

The Boolean data type has two text values: True and False.

For example: boolean truth = true;

The above statement declares that the variable truth is the Boolean type, which is assigned to TRUE.

There are two logic values, ie "ON" and "OFF" or "TRUE" and "False" or "" "or" no ", such a value is represented by the Boolean type. Boolean has two word values, namely true and false. The following is a statement and initialization of Boolean type variables:

Boolean Truth = true; // Declares the Variable Truth

// as boolean type and assigns it

// the value true

Note - No conversion calculation between integer types and Boolean types. Some languages ​​(especially true emphasizes C and C ) allow for converting numeric values ​​to logic values, which is not allowed in the Java programming language; Boolean types are allowed to use Boolean values.

2. Text class - CHAR and STRING

Text class - Char and string char - represent a 16-bit unicode character

- Must include text referenced by single quotes ('')

- Use the following symbols: 'a'

'/ T' a tab

'/ U ????' a special Unicode character, ???? Should be strictly used for replacement

Use a char type to represent a single character. A char represents a 16-bit unsigned (regardless of positive and negative) Unicode characters. A char text must be included in single quotes ('').

'A'

'/ T' a tab

'/ U ????' A special Unicode character. ???? Should be replaced in strict accordance with four 16 credits

String is not an original type, but a class (Class) that is used to represent a character sequence. The character itself is in line with the Unicode standard, and the anti-slope symbol of the above CHAR type is suitable for String. Unlike C and C , String cannot use / 0 as the end.

Text class - CHAR and STRING

String

- Not an original data type, it is a class

- With the text referenced by double quotation

"The Quick Brown Fox Jumped Over The Lazy Dog."

- can be used as follows:

String Greeting = "Good morning !! / n";

String Err_meg = "Record Not Found!";

Text class --char and string (continued)

String's text application double quotes closed, as shown below:

"The Quick Brown Fox Jumped Over The Lazy Dog."

The declaration and initialization of CHAR and STRING type variables are as follows:

CHAR CH = `a '; // Declares and Initializes a char variable

CHAR CH1, CH2; // Declares Two Char Variables

// Declare Two String Variables and Initialize them

String Greeting = "Good morning !! / n";

String Err_msg = "Record Not Found!";

String str1, str2; // Declare Two string variables

2.6.3 integer class - Byte, Short, Int, long

Integer - Hyte, Short, Int, Long

l use three kinds of enrollment - decimal, octal and 16

2 decimal value is 2

077 first 0 means this is an octave value

0xBAAC's first 0x indicates that this is a 16-based value

l Have default int

l Define Long with letters "L" and "L"

There are four integer types in the Java programming language, and each type can be declared using any of keywords Byte, Short, Int, and long. The characters of integer types can be represented using decimal, octal and 16, as follows:

2 decimal value is 2

077 first 0 means this is an octave value

0xBAAC's first 0x indicates that this is a 16-based value

Note - Integer types in all Java programming languages ​​are numbers with symbols.

Integer class - Byte, Short, Int, long (continued)

Integer class text is int type unless thereafter follows a letter "L" directly. L Represents a long value. Note that it is equivalent to using uppercase or lowercase l in the Java programming language, but because lowercase L is easily confused, it is not a wise choice to use lowercase. The form of the above text is as follows: 2L decimal value is 2, is a long

077L first 0 indicates that this is an octave value

0xBAACL prefix 0x indicates this is a 16-en-product value

Integer - Hyte, Short, Int, Long

Each integer data type has the following range:

Integer Length Name or Type Range

8 BITS BYTE-2 7 ... 2 7-1

16 BITS SHORT -2 15 ... 2 15-1

32 Bit Int -2 31 ... 2 31-1

64 BITS long-2 63 ... 2 63 -1

Integer class - Byte, Short, Int, long (continued)

The length and scope of the four integer types are shown in Table 2-2. The scope representation is defined by the Java programming language specification and does not depend on the platform.

Table 2-2 Integer Data Type - Range

Integer Length Name or Type Range

8 BITS BYTE-2 7 ... 2 7-1

16 BITS SHORT -2 15 ... 2 15-1

32 Bit Int -2 31 ... 2 31-1

64 BITS long-2 63 ... 2 63 -1

2.6.4 Floating Point - FLOAT and DOUBLE

Floating point - FLOAT and DOUBLE

- By default Double

- Floating point text includes one of the decimal points or one of the following

- e or e (increase the index value)

- f or f (float)

- D or D (double)

3.14 A simple floating point value (a double)

4.02E23 a large floating point value

2.718F a simple float length value

123.4e 306d a big Double value with redundant D

Floating point variables can be declared with keyword float or double, which is an example of floating point numbers. If a digital text includes a decimal point or an index portion, or after the number with letters F or F (FLOAT), D or D (Double), the number text is a floating point.

3.14 A simple floating point value (a double)

4.02E23 a large floating point value

2.718F a simple float length value

123.4e 306d a big Double value with redundant D

Floating-Point - FLOAT and Double floating point data types have the following range:

Floating point length name or type

32 BITS FLOAT

64 Bits Double

Floating point - FLOAT and DOUBLE (continued)

Table 2-3 Type of floating point data - range

Floating point length name or type

32 BITS FLOAT

64 Bits Double

Note ─ Floating point unless explicitly declares that FLOAT, otherwise Double Section 7 variables, statements and assignments

The format of the floating point number of Java technical specification is defined by the Power Electronics Engineer (IEEE) 754, which uses the length of Table 2-3 and is independent of the platform.

The following programs show how to declare and assign values ​​for integers, floating points, Boolean, characters, and string type variables.

Public class assign {

2. Public static void main (String args []) {

3. Int x, y; // Declare Int

// Variables

4.Float Z = 3.414F; // Declare and Assign

// Float

5.Double w = 3.1415; // Declare and assign

// Double

6.Boolean Truth = true; // Declare and Assign

// boolean

7.Char C; // Declare Character

// variable

8.String Str; // Declare String

9.String str1 = "bye"; // Declare and assign

// String variable

10.c = 'a'; // Assign Value to char

// variable

11.Str = "Hi out there!"; // Assign Value To

// String variable

12.x = 6;

13.y = 1000; // Assign Values ​​to int Variables

14 ....

15.}

16.}

Example of illegal assignment

y = 3.1415926; // 3.1415926 is not an int.

// Requires Casting and Decimal Will

// be truncated.

W = 175,000; // THE COMMA SYMBOL (,) Cannot Appear

Truth = 1; // a Common Mistake Made by EX- C / C

// programmers.

Z = 3.14156; // can't Fit Double Into A

// float. Requires casting.

Section 8 Java coding conventions

Java coding agreement

L class:

Class Accountbook

Class Complexvariable

l Interface:

Interface Account

l method:

BalanceAccount ()

Addcomplex ()

Some coding agreements in the Java programming language are:

Classes - class names should be nouns, sensitive can be mixed, but the first letter should be capitalized. E.g:

Class Accountbook

Class Complexvariable

Interface - Interface Case Size is the same as class name.

Interface Account

Method - method name should be verbs, sensitization can be mixed, but the first letter should be lowercase. In each method name, uppercase letters separate the word and limit the use of underscores. E.g:

BalanceAccount ()

Addcomplex ()

Java coding agreement

L variable

CurrentCustomer

l constant

HEAD-COUNT

Maximum-size

Java coding agreement

Variables - all variables can be used in cases, but the first character should be lowercase. The word is separated by uppercase letters, limits the underline, limits the use of dollar symbols ($) because this character has special meaning on the internal class.

CurrentCustomer

Variables should represent a certain meaning, and it can communicate to the reader to use it. Try to avoid using a single character unless it is a variable that is temporarily "即 即 即" (for example, using I, J, K as a cyclic control variable)

Constant - the original constant should be on top of the uppercase and use the underline to divide the word; the object constant can be used.

HEAD-COUNT

Maximum-size

Control Structures - When the statement is part of the control structure, even a single statement should be enclosed using parentheses ({}). E.g:

IF (Condition) {

Do Something

} Else {

Do Something else

}

Spacing - only writes a statement per line and uses four indent spaces to make your code more readily read.

Comments - uses comments to explain those unambiguous code paragraphs; use // separator for general comments, while the code can be used / * / * / separator. Use / ** ··· * / to form a document, and enter Javadoc to generate an HTML code document.

// a comment this takes up only one line.

/ * Comments That Continue Past One Line and Take Up Space on Multiple Lines ... * /

/ ** a comment for documentation purposes.

@see another class for more information

* /

Note ─ @ See is a special Javadoc tag ("see also") for classes or methods. For more information on Javadoc, see "The Design of Distributed Hyperlinked Programming Documentation" (LISA) About the document system's full definition. This information can be obtained from the following address: http://www.javasoft.com/doc/api_documentation.html.

Section 9 understands the object

Understanding

l Review the history of the object

l Create a new type, such as Date

Public class date {

Int day;

Int Month;

Int year;

}

l Declare a variable

Date Mybirth, Yourbirth

l Access member

Mybpter.day = 26;

Mybpter.month = 11;

YourBpter.Year = 1960;

2.9.1 Review the history of the object

Earlier programming languages ​​and primary programmers regard each variable as an entity that mutually irrelevant. For example, if a program needs to handle a certain date, you must declare three separate integers:

Int day, month, year;

The above statement makes two things, and when the program needs the day, the month or year is related information, it will operate an integer; the other is to assign a memory for those integers.

Although this approach is easy to understand, it has two major defects. First, if the program needs to record several dates at the same time, three different statements are required. For example, to record two birthdays, you may use: int mybirdhday, mybpterhmonth, mybpteryear;

Int Yourbirthday, YourbpterMonth, YourBpteryear;

This method will soon cause confusion because the names needed.

The second defect is that this method ignores the connection between days, months, and years and uses each variable as a separate value, each variable is part of the independent unit (Date in this example) and Handled accordingly.

2.9.2 Creating a new type

To overcome the above two defects, the Java programming language uses classes to create new types. Please see the following original type declaration:

Int day;

The Java programming language is used to assign a certain amount of memory and explain the content of the memory. So, to define a new type, you must point out how much memory is needed and how to explain the memory content. This is not done based on the order and meaning of the byte or bit, but is done according to other types already defined.

For example, to define a type of date, you need enough memory to store three integer variables; in turn, the meanings of days, months and years are given by these integer variables. As follows:

Class mydate {

Int day;

Int Month;

Int year;

}

The word Class is a keyword for the Java programming language, and must be written. The name MyDate is dealt with in case of case, not by the language requirements.

Note ----- Class is more than just a collection data type, which will also be discussed further after this issue.

A variable can be declared to be attributed to type mydate, so that the day, month, and year parts will be implied. E.g:

MyDate mybirth, yourbirth;

With this statement, the Java programming language allows the variables to be accessed by calling members and using points (•) operators. E.g:

Mybpter.day = 26;

Mybpter.month = 11;

YourBpter.Year = 1960;

2.9.3 Creating an object

Create an object

- Original type declaration can allocate memory space

- Non-original type declaration does not allocate memory space

- The declared variable is not the data itself, but the reference (or pointer)

When any original type (such as Boolean, Byte, Short, CHAR, INT, LONG, FLOAT, or DOUBLE type) is declared, the memory space is also assigned as part of the above operation. The declaration of variables using non-original types such as String or Class is not allocating memory spaces for objects.

In fact, variables with Class type declarations are not the data itself, but the reference to the data (Reference).

Note ---- You can also think that the reference is a pointer, which may help your understanding. In fact, in most implementations, it is indeed thus considered. It is worth noting that the Java programming language does not actually support pointer data types.

The actual memory must be assigned before you can use the variable. This job is implemented by using the keyword NEW. As follows:

Mydate mybirth;

Mybpter = new mydate ();

The first statement (declaration) is only assigned enough space for reference, and the second statement assigns space by calling the object to the three integers constituting myDate. The object's assignment makes the variable mybirth re-references the new object. After these two operations are completed, the contents of myDate objects can be accessed via Mybirth.

If you define any Class XXXX, you can call new xxxx () to create any more objects, and the object is separated. A reference to an object can be stored in a variable, so a "variable point member" (such as Mybirth.day) can be used to access individual members of each object. Note that there is a possibility that the object is still possible without an object reference, such an object is called an "anonymous" object. 2.9.4 Creating an object ---- Memory Assignment and Layout

Create an object ---- memory allocation and layout

A statement is only a reference distribution memory

MyDate Today

Today = new mydate ();

Today

????

In a method body, statement

MyDate Today

Today = new mydate ();

Only one reference allocation memory

????

Today

Keyword new means allocation and initialization of memory

Mydate today;

Today = new mydate ();

Assignment creates reference variables so that it can properly reference new creation objects.

Mydate today;

Today = new mydate ();

It is also possible to use a statement to allocate space for reference to Today and object assignments referred to by reference Today.

Mydate today = new mydate ();

2.9.5 Assignment of reference type

Reference variable assignment

Consider the following code snippet:

INT x = 7;

INT Y = X;

String s = "hello";

String t = s;

In the Java programming language, variables with a type declared with class are specified as reference type because it is incorporated in a non-original type, which is important for assignment. Please see the following code snippet:

INT x = 7;

INT Y = X;

String s = "hello";

String t = s;

Four variables were created: two original type int and two reference types String. The value of x is 7, and this value is copied to Y; X and Y are two separate variables and any of the further changes are not effectively affected.

As for the variables S and T, there is only one String object exists, which contains text "Hello", S and T reference this single object.

Redefine the variable T, the new object world is created, and T references this object. The above process is described as follows:

2.9.6 Term Review

Terminology review

- Class

- Object

- Reference Type

- MEMBER

Several terms have been introduced in this module, simply as follows:

- Class ---- - Define a new type of way in the Java programming language. Class declarations can define new types and describe how these types are implemented. There are many other features that have not been discussed.

- Object ------ an example of a class. Classs can be considered a template ------ You are describing an object model. An object is the result of the instance of creating a class every time you use New.

- Quote Type ------ A user-defined type, which can reference classes, interfaces, and arrays.

- Member ----- constitutes one of the elements of an object. This word is also used as an element (Elements) that defines the class. Member Variabl, instance variable (Field) is often used interchangeably.

Exercise: use objects

Exercise goals - use Java keywords correctly, write a program that created a class and creates an object from the class. Compile and run the program, then check whether the reference is assigned and checks whether the reference is operated as described in this module.

First, ready

In order to successfully complete this practice, you must be able to compile and run the Java program, and you need to be familiar with the concept of object-oriented concepts and references for classes and objects. Second, the task

Level 1: Create a class and corresponding object

1. One point available X and Y coordinate descriptions. Define a class called MyPoint to express the above idea. Why should you call this file?

2. Write a class method in your class, then declare two variables for type mypoint, refer to the variables as start and end; create objects with new mypoint () and give the reference value to the variable START and END.

3. Give the value 10 to the members x and y of the object START;

4. Give the value 20 to the x value of the object End, and give the value 20 to the Y value of the object End.

5. Print the member value (x and y) of the MyPoint object (START and END).

Note ---- To complete step 5, you need to learn more about the SYSTEM class. System.Println () with variable string can output String and start a new line, and system.out.print () does not start a new line. If you use system.out.print (), you should call system.out.println () or system.out.flush () before this application, otherwise you will find that the last line of the output is not displayed. .

To display the numbers, you can use the following form (discussions will be discussed later)

System.out.println ("Start mypoint = x:" start.x "y" start.y);

Note - If an operand is already a string, the plus sign ( ) converts another operand to String.

6. Compile and run the program.

Level 2: Inspection and reference assignment

Use your MyPoint class in the previous exercise to increase the code to the main () method to complete the following:

1. Declare a new variable for type mypoint, called stray. Give Stray in the reference value of the existing variable End;

2. Print the value of members x and y of end and stray variables;

3. Give the Variable Stray member X and Y new value;

4. Print the value of the members of End and Stray; compile and run the MyPoint class. The value of the end reflects the changes in Stray, indicating that the two variables reference the same MyPoint object;

5. Give the members x and y of the Start variable to a new value;

6. Print member values ​​for start and end; compile and run the MyPoint class again, Start's value is still independent of strey and end, indicating that the Start variable is still referenced by a MyPoint object, and this object is called with strey and end references different.

Third, practice summary

Discussion - A few minutes to discuss the experience, feelings and discovery of your experience in the above exercises.

Experience explanation summary application

Fourth, check your progress

Before entering the next module, please confirm that you have been able to:

- Use comments in the source program

- distinguish effective and invalid identifiers

- Identify Java technology keyword

- List eight original types

- Define text values ​​for numbers and text types

- Define the terms Class, Object, Member, Variable, Referrence Variable

- Create a class definition for a class containing the original member variable

- Declare class type variable - constructed an object using new

- Describe the default initialization

- Visit a member variable of an object using a point symbol

- Describe the meaning of reference variables

- Staten out the results of allocation class type variables

V. Thinking

In your existing app, can you conceive an example of using classes and objects?

Chapter III Expression and Process Control

This module discusses variables, operators, and arithmetic expressions, and lists different management running program paths.

Section 1 related issues

Discussion - The following issues are related to the topics described in this module.

- What type of variables are useful to programmers (for example, how other languages ​​want to know how Java programming languages ​​define and process global variables and local variables)?

- Can the composite class have the same name of the same name? If you can, how big is their scope?

- Lists control structures for other languages; what method uses for general languages ​​for flow control and interrupt flow (such as in loop or switching statements)?

Second section

After completing this module, you should be able to:

- Differential variables and local variables;

- How to describe how instance variables are initialized;

- Confirm and correct the compiler error;

- Identify, describe and use Java software operators;

- Differentiate legal and illegal original type assignment;

- Confirm that the Boolean expression and their requirements in the control structure;

- Identify the compatibility compatibility and the necessary calculations in the basic type;

- Use the IF, Switch, For, WHILE and DO sentence structure and BREAK and CONTINUE as the process control structure in the program.

Section 3 expression

3.3.1 Variables and scope

Variables and scope

- Local variables are variables defined within a method, also known as automatic, temporry or stack variable.

- When a method is executed, the local variable is created; when a method is terminated, the local variable is cleared.

- Local variables must be initialized before use, otherwise it will be wrong when compiling

You have seen two variables: the original type variable and the reference type variable. You also see the location of the variable being declared: within the method (the method is object-oriented term, it can reference function or subroutines, such as: main ()) or within the method but within the class definition. Variables can also be defined as method parameters or constructor parameters.

The parameters defined within the method are called local (local) variables, sometimes used as automatic, temporal (Temporary) or stack variables.

The variable defined outside the method is created when it is constructed using new xxxx () calls. Two variables can be created when constructing an object. One is class variable, it is declared with static keyword; as long as the object is required, the class variable will exist. Second, instance variables, it does not need to declare the Static keyword; as long as the object is used as a reference, the instance variable will exist. Example variables are sometimes used as a member variable because they are members of the class.

Method parameter variable defines the arguments transmitted in one method call. Each time the method is called, a new variable is created and has always been run to the program run skip from the method.

When a method is performed, the local variable is created. When the method is performed, the local variable is canceled. Thus, local variables are sometimes referenced as "temporary or automatic" variables. The variable defined in the member function is "local" on the member variable, so you can use the same variable name in several member functions to represent different variables. The application is shown below: Class Ourclass {

INT I; // Instance Variable of class ouclass

INT firstMethod () {

INT j = 0; // local variable

// Both I and J Are Accessible from

// this point

...

Return 1;

} // end of firstmethod ()

INT SecondMethod (float f) {// method parameter

INT j = 0; // local variable. Different from the

// j Defined in firstmethod ().

// scope is limited to the body of

// SecondMethod ().

// Both I (Instance Variable of The

// Class Ourclass) and J (Local

// Variable of this method

// Accessible from this point.

....

Return 2;

} // end of secondmethod ()

} // End of class ouclass

3.3.2 Variable initialization

In the Java program, any variable must be used after initialization. When an object is created, instance variables are initialized by the following values ​​while allocating the memory:

Byte

0

Short

0

int

0

Long

0L

Float

0.0F

Double

0.0D

charr

'/ u0000' (NULL)

Boolean

False

All Reference Types

NULL

Note ─ A reference with null values ​​does not quote any object. Objects attempt to use it will cause an exception. An exception is an error in runtime, which will be discussed in the module 7 "exception".

The variable defined outside the method is automatically initialized. Local variables must be "handmade" initialization before use. If the compiler can confirm that a variable can be used before initialization, the compiler will report an error.

Public void docomputation () {

INT x = (int) (Math.random () * 100);

Int Y;

Int z;

IF (x> 50) {

y = 9;

}

z = y x; // Possible Use Before Initialization

}

3.3.3 Operator

The Java software operator is very similar to C and C in style and function. Table 3-1 lists various operators ("L TO R" represents left to right, "R to L" indicates right-left binding.

Separator [] ();,

R to L - - ~! (Data type)

L to r * /%

L to r -

L to r << >> >>>

L to r <> <=> = instanceof

L to r ==! =

L to r &

L TO R ^

L TO R |

L to r &&l r ||

R to L?:

R to L = * = / =% = = - = << = >> = >>> = & = ^ = | =

Note - allStanceOf is an operator-specific operator in Java programming language, which will be discussed in module 5 "objects and classes".

3.3.4 Logical Expression

Logical expression

The supported bit operator is as follows:

! ─ NOT & --AND

| ─ ─ ^ ─ha

The Boolean operator is as follows:

~ ─ ─complement & --and

^ ─ ─ or | | ─

Most Java operators are the same from other languages ​​and are the same as those in general expectations.

Relationships and logical operators return Boolean results, int to Boolean cannot be automatically converted.

INT i = 1;

IF (i) // Generates a Compile Error

IF (i! = 0) // Correct

The supported operator is! , &, |, ^, Supported Boolean logic operators are NOT, AND, XOR, and OR. Each calculation returns to Boolean results. Operators && and || are Boolean equivalents of operators & and |. The Boolean logic operator will be discussed in the next page.

3.3.5 Operations

The Java programming language supports the bit operation of integer data types, their operators ~, &, ^, and | indicate NOT (forgiveness), bit and bit xor, and bit OR, respectively, respectively. The shift operator will be discussed in this course later.

3.3.6 Boolean logic operator

Boolean logic operator

l operator is && (and) and || (or)

l Operator Example:

See 3-11 Program

Operators && (defined for AND) and | (defined as OR) Perform a Boolean logical expression. Please see the example below:

Mydate d = null;

IF ((D! = null) && (d, day ()> 31)) {

// Do Something with d

}

The Boolean expression forming the IF () statement is legal and safe. This is because the second sub-expression is skipped when the first sub-expression is fake, and when the first sub-expression is fake, the entire expression will always be, so it is not necessary to consider the second child expression. The value of the formula. Similarly, if the || operator is used, and the first expression is returned, the second expression does not have to be evaluated, because the entire expression has been considered true.

3.3.7 String link with plus ( )

String link with plus sign ( )

Operator can:

l Take String link

l Generate a new String

E.g:

String Salutation = "Dr.";

String name = "jack" "arthur";

String title = SALUTATION NAME;

The result of the last row is:

Dr. Jack Arthur

A self-variable must be a String object

Non-string is automatically converted to String objects

Operators can link links to String objects and generate a new String:

String Salutation = "Dr.";

String name = "jack" "arthur";

String title = SALUTATION NAME;

The result of the last row is:

Dr. Jack Arthur

If there is a String object in the operator, other independent variables will be converted to String. All objects can be automatically converted into string, although this result may be meaningful. Not a string is the equivalent of the string by using the toString () member function.

3.3.8 Right shift operator >> and >>>

Right shift operator >> and >>>

The right movement of the arithmetic or symbol is as follows:

See page 3-13

l During shift, the symbol bit is copied

Logic or non-symbol right shift operator (>>>)

l acting on bitmap

l During shift, the symbol bit is not copied.

Java programming language provides two right shift operators

Operators >> Mode or symbol right shift. The result of shifting is that the first operand is applied by the power of 2, and the value of the index is given by the second number. E.g:

128 >> ​​1 GIVES 128/2 1 = 64

256 >> 4 GIVES 256/2 4 = 16

-256 >> 4 gives -256/2 4 = -16

Logic or non-symbol right shift operators >>> Mainly acting on bitmap, not a value of arithmetic meaning; it always puts zero in the most important bit. E.g:

1010 ... >> 2 GIVES 111010 ...

1010 ... >>> 2 GIVES 001010 ... In the process of shift, the >> operator is copied by the symbol bit.

Note - Shift operator simplifies the operand 32 on the right side to the INT type left operand, and the mode 64 is simplified to the LONG type right side operand. Thus, any INT X, X >>> 32 can result in the constant X value, not zero you may expect.

Note ------ It is important to be praised to: >>> The operator is only allowed to be used in an integer type and is only valid for the int and long values. If you are used on a Short or Byte value, the value will be upgraded to an int. In view of this, unsigned shifts usually have become a symbol shift.

3.3.9 Left Displacement Operators (<<)

Left shift operator (<<)

128 << 1 equal to 128 * 21 = 256

16 << 2 equal to 16 * 22 = 64

Operator << Execute a left shift. The result of the shift is that the first operand multiplied by 2 power, the value of the index is given by the second number. E.g:

128 << 1 gives 128 * 21 = 256

16 << 2 gives 16 * 22 = 64

3.3.10 Type conversion

Type conversion

l If the value of the value is lost, the programmer must use the method to confirm the assignment.

l The value between Short and Char needs an explicit transformation

See 3-16 Program

Where the assigned information may be lost, the compiler requires the programmer to confirm the value with the type conversion (TypeCast). For example, it can "squeeze" a long value into an INT variable. Explicit transformation is as follows: Long BigValue = 99L;

INT Squashed = (int);

In the above procedure, the expected target type is placed in parentheses and is regarded as a prefix of an expression, which must be changed. In general, it is recommended that all expressions that need to be transformed with parentheses. Otherwise, the priority of the transformation operation may cause problems.

Note - Relive the range of SHORT is: -215 to 215-1; the range of Char is: 0 to 215-1.

Thus, the assignment between SHORT and CHAR always needs an explicit transformation.

3.3.11 Type conversion of upgrade and expression

Type conversion of upgrades and expressions

- Variables are automatically upgraded to a longer form (such as INT to long upgrade)

- If the variable type is at least as large as the expression type (the same number is the same), the expression is assignd.

When there is no information loss, variables can be automatically upgraded to a longer form (such as INT to long upgrade)

Long bigval = 6; // 6 is an Int Type, OK

INT Smallval = 99L; // 99L IS A Long, Illegal

Double z = 12.414f; // 12.414f is float, ok

FLOAT Z1 = 12.414; // 12.414 is Double, Illegal

In general, if the variable type is at least as large as the expression type (the same number), you can think that the expression is compatible.

For the operator, when the two operands are the original data type, the results have at least one int, and there is a calculated by lifting the operand to the result type, or by lifting the result to a wider amount of operand. Value, this may result in overflow or accuracy loss. E.g:

Short A, B, C

a = 1;

B = 2;

C = a b;

The above program will be erroneously enhances each SHORT to INT before operating the SHORT. However, if C is declared as an int, or by using the following operations:

c = (short) (a b);

The above code will be successfully passed.

Section 4 branch statement

Branch statement

IF, ELSE statement

IF (Boolean expression) {

Statements or blocks;

}

IF (condition is true) {

Statements or blocks;

} Else {

Statements or blocks;

}

Conditional statements make some programs to be selectively performed according to certain expressions. Java programming language supports dual IF and multiple Switch branch statements.

3.4.1 IF, ELSE statement

The basic syntax of the IF, ELSE statement is:

IF (Boolean expression) {

Statements or blocks;

} Else {

Statements or blocks;

}

example:

INT country;

1.count = getCount (); // a method defined in the program

2.IF (count <0) {

3.System.out.println ("Error: Count Value is Negative."); 4.} else {

5.System.Out.println ("There Will BE" Count

6. "People for Lunch Today.");

7.}

In the Java programming language, if () uses a Boolean expression, not a numeric value, this is different from C / C . As mentioned earlier, the Boolean type and digital type cannot be converted to each other. Therefore, if the following cases occur:

IF (x) // x is Int

You should use the following statements to replace:

IF (x! = 0)

The entire ELSE part is selective, and if the test condition is false, the ELSE portion can be omitted.

3.4.2 Switch statement

Branch statement

SWITCH statement

The syntax of the Switch statement is:

Switch (expr1) {

CASE EXPR2:

STATEMENTS;

Break;

Case EXPR3:

STATEMENTS;

Break;

DEFAULT:

STATEMENTS;

Break;

}

The syntax of the Switch statement is:

Switch (expr1) {

CASE EXPR2:

STATEMENTS;

Break;

Case EXPR3:

STATEMENTS;

Break;

DEFAULT:

STATEMENTS;

Break;

}

Note ─ In the Switch (EXPR1) statement, Expr1 must be assigned with the int type; Byte, Short or Char types can be upgraded; no floating point or long expression is allowed.

When the value of the variable or expression cannot match any Case value, the optional default provision (DEFAULT) indicates the program code that should be executed. If there is no Break statement as an end sentence of a CASE code segment, the execution of the program will continue to the next case without checking the value of the Case expression.

example 1:

Switch (colornum) {

2.case 0:

3.SetBackground (Color.Red);

4.break;

5.case 1:

6.SetBackground (color.green);

7.break;

8.default:

9.SetBackground (color.black);

10.break;

11.}

Example 2:

Switch (colornum) {

2.case 0:

3.SetBackground (Color.Red);

4.case 1:

5.SetBackground (Color.green);

6.default:

7.SetBackground (Color.Black);

8.Break;

9.}

Example 2 Sets the background color to black without considering the value of the Case variable colorNum. If the value of the colorNum is 0, the background color will be set to red, then green, and then black.

Section 5 cycle statement

loop statement

For statement

For (init_expr; boolean testexpr; alter_expr) {

Statement or Block

}

The loop statement makes the execution of the statement or blocks repeated. Java programming language supports three cyclic constructs: For, While and Do Loops. The FOR and WHILE cycle are testing the loop condition before performing the cyclic body, and the Do Loops are testing the loop condition after executing the cyclic body. This means that the FOR and the While cycle may not be executed at a time, while the DO LOOPS will perform at least one cycle. 3.5.1 for loop

The syntax of the for loop is:

For (init_expr; boolean testexpr; alter_expr) {

Statement or Block

}

E.g:

For (int i = 0; i <10; i ) {

System.out.Println ("Are you finished yet?");

}

System.out.println ("FINALLY!");

Note - Java programming language allows using a comma as a separator in the FOR () loop structure. For example, for (i = 0, j = 0; j <10; i , j ) is legal; it initials I value to zero, and increases their value once after each cycle is performed.

3.5.2 While cycle

loop statement

While cycle

While (Boolean expression) {

Statement or block

}

The syntax of the While loop is:

While (Boolean expression) {

Statement or block

}

E.g:

INT i = 0;

While (i <10) {

System.out.Println ("Are you finished yet?");

i ;

}

System.out.println ("FINALLY!");

Make sure that the loop control variable has been properly initialized before the cyclic body is started, and confirms that the loop control variable is true, the cyclic body begins to execute. The control variable must be updated correctly to prevent death cycles.

3.5.3 DO cycle

loop statement

Do / While statement

Do {

Statements or blocks;

}

While (Boolerance test)

The syntax of the DO loop is:

Do {

Statements or blocks;

}

While (Boolerance test)

E.g:

INT i = 0;

Do {

System.out.Println ("Are you finished yet?");

i ;

} while (i <10);

System.out.println ("FINALLY!");

Like the While loop, confirm that the loop control variable is properly initialized and tested in the cyclic body and updated by time.

As a program convention, the FOR cycle is generally used in the case where the number of cycles is prior, while the While and DO are in advance in advance of the number of cycles.

Section 6 Special Circulatory Process Control

Special cycle process control

l Break [label];

l Continue [label];

l Label: statement; // where statement must be any

// Legal statement.

The following statements can be used in a deeper control cycle statement:

l Break [label];

l Continue [label]; l Label: statement; // where statement must be any

// Legal statement.

The BREAK statement is used to exit from the Switch statement, the loop statement, and a block pre-given Label.

The Continue statement is used to skip the end of the cyclic body.

The Label can identify any effective statement that needs to be converted, which is used to identify the composite statement of the loop configuration.

E.g

LOOP: While (true) {

For (int i = 0; i <100; i ) {

Switch (c = system.in.read ()) {

Case -1:

Case `/ n`:

// jumps out of while-loop to line # 12

Break loop;

....

}

} // end for

} // End while

TEST: for (...) {

....

While (...) {

IF (j> 10) {

// jumps to the increment portion of

// for-loop at line # 13

Continue test;

}

} // End while

} // end for

Exercise: use expressions

Exercise Goals - You will write, compile and run two algorithms that use identifiers, expressions, and control structures.

First, ready

To successfully complete this practice, you must have the ability to compile and run the Java program and are familiar with the process control structure.

Second, the task

Level 1: Create a step-by-step application

A number of steps (usually referred to as X!) Is equal to x * (x-1) * (x-2) ... * 1. For example, 4! Is equal to 4 × 3 × 2 × 1 = 24.

Create a application called Factor, using the application to print the steps of 2, 4, 6, and 10.

Level 2: Solving a geometric program

One right triangle is known that the length of the string (longest side) is given by the following formula:

Write a Java software called Hypotenuse, the longest side is calculated from the right angle of the known right triangle.

Tip: From the template solution provided in the Mod3 / Templates directory, enter from the command line; pay attention to the java.lang.math class.

Third, practice summary

Discussion - A few minutes to discuss the experience, feelings and discovery of your experience in the above exercises.

Experience explanation summary application

Fourth, check your progress

Before entering the next module, please confirm that you have been able to:

- Differential variables and local variables;

- How to describe how instance variables are initialized;

- Confirm and correct the compiler error of "Possible assignment";

- Identify, describe and use Java software operators;

- Differentiate legal and illegal original type assignment;

- Confirm that the Boolean expression and their requirements in the control structure;

- Identify assignment compatibility and necessary transformation in basic types;

- Use the IF, Switch, For, While and DO sentence structure and Break and Continue labels as the process control structure.

V. Thinking

- What data type is used in most programming languages ​​to set similar data elements?

- How do you make the same operation (such as an array) for a set of elements?

Java programming language What data type is used?

Chapter 4 array

This module describes how to define, initialize, and use arrays in the Java programming language.

Section 1 related issues

Discussion - The following issues are related to the topics described in this module:

- What is the use of an array?

Second section

After completing this module, you should be able to:

- Declare and create original array, category or array type

- Explain why the elements of the array need to initialize

- give an array definition and initialize array elements

- Determine the number of elements in an array

- Create a multi-dimensional group

- Write copy code from an array type to another array type value value

Declaration of the array of third quarters

Declaration array

- The same type of group data object

- Original type or class type array declaration

- Create space for a reference

- Array is an object instead of a memory for the original type of reserves

A typical array is used to set the same type of object and reference this collection through a name.

You can declare any type of array - Original Type or Class Type:

CHAR S [];

Point P []; // Where point is a class

In the Java programming language, even if the array is composed of original type, or even with other types, the array is also an object. The declaration cannot create the object itself, and create a reference, which can be used to reference an array. The actual memory used by array elements can be dynamically allocated by a New statement or array initialization software.

In the following sections, you will see how to create and initialize an actual array.

The above format of the declaration array after placing square brackets in the variable name is the standard format for C, C , and Java programming languages. This format will make the format of the declaration is more difficult, and thus, the Java programming language allows an alternative format, the square brackets in this format are located on the left side of the variable name:

CHAR [] S;

Point [] P;

The result is that you can think that the type portion is on the left, and the variable name is right. The above two formats are coexisting, you can choose a way you habits. The declaration does not point out the actual size of the array.

Note ---- When the square brackets declared by the array, the square parentheses can be applied to all right variables.

Section IV Create an array

Create an array

Create an array object using keyword NEW

S = New char [20];

P = new point [100];

P [0] = new point ();

p [1] = new point ();

·

·

·

You can create an array using the keyword NEW like a creating object.

S = New char [20];

P = new point [100];

The first line created an array of 20 char values, and the second line created a 100-type POINT variable. r However, it does not create 100 Point objects; the work of creating 100 objects must be completed separately:

P [0] = new point ();

p [1] = new point ();

·

·

·

The subscript used to indicate a single array element must always start from 0, and remain within legal scope - greater than 0 or equal to 0 and less than the array length. Any attempt to access array elements other than the above limits will cause an error when running. Here are some better array initialization methods.

Section 5 initialization array

Initialization array

- Initialize an array element

- Create an array with initialization values

String names [] = {

"Georgianna",

"Jen",

"Simon",

}

Each element is initialized when an array is created. In the example of the CHAR array S, each value is initialized to a 0 (/ U0000-NULL) character; in an example of the array P, each value is initialized to Null, indicating that it has not been referenced to a Point object. After assigning P [0] = New Point (), the first element of the array is referenced to the actual POINT object. Note - Initialization of all variables (including array elements) is the basis for ensuring system security, and variables must never be used in an unaptured state.

The Java programming language allows you to quickly create arrays using the following form:

String names [] = {

"Georgianna",

"Jen",

"Simon",

}

The result is equivalent to the following code:

String names [];

Names = new string [3];

Names [0] = "georgianna";

Names [1] = "jen";

Names [2] = "simon";

This "short diak" method can be used in any element type. E.g:

Myclass array [] = {

New myclass (),

New myclass (),

NEW myclass ()

}

The constant value of the appropriate class type can also be used:

Color Palette [] = {

Color.Blue,

Color.Red,

Color.White

}

Section 6 multi-dimensional array

Array INT Twodim [] [] = new int = new int = new int = new int = new int = new int =

Twodim [0] = new int in

Twodim [1] = new int rt [5];

INT Twodim [] [] = new int [] [4]; illegal

Each array has a number of four arrays of more than five integer types

Int twodim [] [] = new int [4] [5];

Twodim [0] = new int in

Twodim [1] = new int rt [5];

The Java programming language does not provide a multi-dimensional array like other languages. Because an array can be declared as having any basic type, you can create an array of arrays (arrays of arrays, etc.). A two-dimensional array is shown in the following example:

INT Twodim [] [] = new int [4] [];

Twodim [0] = new int in

Twodim [1] = new int rt [5];

The object created for the first time, is an array that contains four elements. Each element is a NULL reference for the element of the type ARRAY OF INT and must initialize each point of the array.

Note - Although the declaration format allows square brackets to be left or right, such flexibility does not apply to other aspects of array syntax. For example: new int [] [4] is illegal.

Multidimensional Arrays

l Array in non-rectangular array

Twodim [0] = new int in

Twodim [1] = new int rt [4];

Twodim [2] = new int rt [6];

Twodim [3] = new int rt [8];

l Each array has a number of 4 arrays of 5 integer types.

Int twodim [] [] = new int [4] [5];

Multidimensional Arrays

Because this is initialized for each element, an array of non-rectangular arrays may be created. That is, the Element of Twodim can be initialized as follows:

Twodim [0] = new int [2]

Twodim [1] = new int rt [4];

Twodim [2] = new int rt [6];

Twodim [3] = new int rt [8];

Due to this initialization method, the array of rectangular arrays is the most universal form, thereby producing a "quick notes" method to create a two-dimensional array. E.g:

Int twodim [] [] = new int [4] [5];

Can be used to create an array of four arrays of five integer types per array.

Seventh section array boundaries

Array boundaries all arrays from 0 Int list [] = new int [10];

For (int i = 0; i

System.out.println (List [i]);

In the Java programming language, all the subscripts of all arrays start from 0. The number of elements in an array is stored as a portion of the array object with the Length attribute; this value is used to check the boundaries of all runtime access. If an access to the limit is happened, then the error is reported to occur.

Examples using the Length attribute are as follows:

Int list [] = new int [10];

For (int i = 0; i

System.out.println (List [i]);

Using the Length property makes the program's maintenance makes it easier.

Section 8 copy array

Copy array

- Cannot adjust the size of the array

- Use the same reference variable to reference a new array

INT Elements [] = new int [6];

Elements = new int [10];

Once the array is created, its size is not adjustable. However, you can use the same reference variable to reference a new array:

Int MyArray [] = new int [6];

MyArray = New Int [10];

In this case, the first array is effectively lost unless otherwise reserved elsewhere.

Copy array

System.ArrayCopy () method

// ORIGINAL ARRAY

1.int myarray [] = {1, 2, 3, 4, 5, 6};

2.

3.//new larger array

4.int Hold [] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};

5.// Copy All of the MyArray Array to the Hold

6.// array, starting with the 0th index

7.System.Arraycopy (MyArray, 0, Hold, 0,

8.myArray.Length;

Copy array

The Java Programming Language provides a special method copy array in the System class, which is called ArrayCopy (). For example, ARAYCOPY can be used as follows:

// ORIGINAL ARRAY

1.int myarray [] = {1, 2, 3, 4, 5, 6};

2.

3.//new larger array

4.int Hold [] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};

5.// Copy All of the MyArray Array to the Hold

6.// array, starting with the 0th index

7.System.Arraycopy (MyArray, 0, Hold, 0,

8.myArray.Length;

At this point, the array HOLD has the following: 1, 2, 3, 4, 5, 6, 4, 3, 2, 1.

Note - When processing an object array, system.araycopy () copies the reference, not an object. The object itself does not change. Exercise: Use arrays

Exercise Target - After defining and initializing the array, you will use an array in the program.

First, ready

For successful completion of this practice, be sure to understand the basic matrix concept and learn how to locate a array to get its value.

Second, the task

Level 1: Basic array of use

1. Create a class called BasicArray, declare two variables in the ... main () method, one is THISARRAY, the other is ThataRray, which belongs to the type of Array Of Int.

2. Create an array with 10 int values, range from 1 to 10. Assign this reference to the variable THISARRAY.

3. Use the for () loop to print all the values ​​of the THISARRAY. How to control the number of cycles?

4. Compile and run the program. How much value is printed? What is these values?

5. Each of the elements of each THISARRAY establishes the value of the value of the index value. Print the value of an array.

6. Compile and run the program.

7. Assign THISARRAY to the variable ThataRray. Print all the elements of ThataRray.

8. Compile and run the program. How many values ​​of Tyatarray is displayed? What is these values? Where do they come from.

9. Modify some elements of THISARRAY to print the value of ThataRray.

10. Compile and run the program; what did you notice in ThataRray?

11. Create an array with 20 int values. Assign the reference to the new array to the variable ThatArray, print the value of ThataRray.

12. Compile and run the program. How many values ​​are displayed each array? What is these values?

13. Copy the value of thisaaRray to ThataRray. What method call you will use? How will you limit the number of copies? ThatArray elements 10 to 19 changes?

14. Print the value of ThataRray.

15. Compile and run the program. Are you displayed correctly? If not, do you know that there are those content to understand?

16. Change some of ThatArray; print THISARRAY and THATARRAY.

17. Compile and run the program. These values ​​are what you expect?

Level 2: array of arrays

1. Create a class called Array2D, declare a variable called Twod in the main () method, which should belong to the type of Array of Array Of Int.

2. Create an array of element type INT, which should include four elements and assign each other to Elements [0] of the variable Twod.

3. Write two nested for () loop statements to print all values ​​for Twod. Arrange the output in a matrix (you can use the system.out.print () method).

4. Compile and run the program. You should find that there is an operation error (empty pointer exception), which is because Twod's Elements [1] to [3] are not initialized.

5. Create an int array of 5, 6, and 7 elements, respectively assign Twod Elements [1], [2], and [3], and confirm that the code to complete the above operation is in the third The nested FOR () cycle described will be inserted before.

6. Compile and run the program. This time you should see a zero value non-rectangular layout.

7. Give an obvious non-zero value for each element of the Twod array (prompt: using math.random () to get a random value).

8. Declare a variable called OneD of Array Of Int. Then, create an INT array including 4 elements. The references of the array give arrays Array Twod and OneD. After assigning, print the One and Twod arrays. 9. Compile and run the program. Note that the single array displayed by printing the value of the ONED is the same as the Element of the Twod array.

Level 3: Crossword

1. Create a application called WordScRambler, which has an error (maximum length of 8 characters), uses it to make letters of one word (rearrangement order), then form a new word.

2. Allow users to see the patchwork process of the word, and decompose the running process of 5 games.

Third, practice summary

Discussion - A few minutes to discuss the experience, feelings and discovery of your experience in the above exercises.

l Experience interpretation summary application

Fourth, check your progress

Before entering the next module, please confirm that you have been able to:

- Declare and create original array, category or array type

- Explain why the elements of the array need to initialize

- give an array definition and initialize array elements

- Determine the number of elements in an array

- Create a multi-dimensional group

- Write copy code from an array type to another array type value value

V. Thinking

How do you create a three-dimensional array?

What is the disadvantage of using an array?

转载请注明原文地址:https://www.9cbs.com/read-8106.html

New Post(0)