Java No detours tutorial (2.hello,java!)

Source: Internet
Author: User
Tags class definition uppercase letter

2.hello,java!
Welcome to the world of Java, in the previous chapter, we have completed the basic DOS operation learning and Java Environment Building, in this chapter we Java to complete a simple DOS program.

2.1 hello,java!
First, we create a file named Mynotepad.java, saved to c:\work\001,
The contents of the file are as follows: (Note the file name and the document contents of the case, no longer prompt)

Then start the DOS environment and enter the following command:
CD c:\work\001
Javac Mynotepad.java
Java Mynotepad

You can see the output: hello,java!
If you execute Java mynotepad again, you do not need to compile again.

OK, we have completed a simple DOS program, please carefully understand this process, because the next part of this tutorial will be the continuous expansion of the process until the completion of Java learning.

2.2 Viewing the contents of a file
Now there's a simple need:
Enter the following command to view the contents of the file A.txt:
Java Mynotepad a.txt

Let's briefly introduce the Mynotepad.java we just wrote.

In the above program, semicolons represent the end of a line, and curly braces represent the end of a chunk.
Mynotepad is the class name, main is the class entry, string[] args is used to receive the parameters of the program, because the program will have multiple parameter names such as
Java mynotepad a.txt b.txt c.txt
So the type of the variable args is defined as an array that can receive multiple strings (string) to receive multiple arguments, as shown in:

We use [] to indicate that the parameter is an array.
You can use the following method to get the value of each element in the array:
ARGS[0],ARGS[1],ARGS[2] ...

Note: The first element in Java is labeled 0

We try to take the input parameters and output to the DOS interface:

Note: A plus sign is used to connect two strings

Run after compilation: Java Mynotepad a.txt
Output Hello,a.txt

/////////////////////////////////////
Take a break and let's see how this process is done:
1. Create the file Mynotepad.java and write the program.
2. Enter the command Javac Mynotepad.java to compile the program into a class file (Mynotepad.class)
We call Mynotepad.java the source file, Mynotepad.class as the target file (execute file)
The compilation process is as shown

In this case, you can delete the Mynotepad.java because the program execution is done by parsing the target file (. class file).
We open the. class file with Notepad and look at the contents of it, do not understand ... , yes, because it's machine-readable. Compared to people,
Machine reading a class file is easier than reading a Java file.
So we need a compile process to translate Java files into class files, and the process of translating class files into Java files is called anti-compilation, and this tutorial does not discuss the content of decompile.

3. We run the Java program and pass in the parameter Mynotepad a.txt
In this procedure, the Java program first looks for the class definition named Mynotepad, which is defined by the CLASSPATH in the environment variable mynotepad the parameters passed in.
Because we set the current directory. In the environment variable classpath, the Java program finds the Mynotepad class definition in the current directory, and then calls the class's fixed entry main method,
and a.txt the subsequent arguments to the args variable passed to main.
Note: In the new version of the JDK, without setting the environment variable classpath, the compiler will automatically find the relevant library file, which is no longer explained.

4.main the first incoming parameter of args args[0] (a.txt) and the previous string hello are stitched together to generate a new string, Hello A.txt, and then as a parameter
Passed to the Syste.out.println method, which outputs the passed parameter "Hello a.txt" to the DOS interface.

Summarize:
So far we have been exposed to the following concepts:
Classes, Functions/methods, parameters
Note: Functions and methods are the same concept
Can be expressed by:
public class class Name {
-Function 1
-Function 2
-Function 3
...
-Main Function Main
}

Where the function is defined as follows
public static return value function name (argument type parameter name) {}

where {} represents the beginning and end of a chunk, such as class definition, function definition.
When you run a Java program with the following command, a function named main is called by default, and subsequent arguments are passed to the main function. (We call main function/Main method)
Java class name

The return value of the function is described later in this article.

//////////////////////////////////////////////

Next we continue to expand this program

For System.out.println, we will explain in the following chapters, because at this stage we can not understand the specific meaning of this sentence, so we will temporarily hide him.
To hide what we don't want to see, the first thing to think about is to turn him into a method call, and our program becomes this:

For static functions that call a class, the class name is generally used directly. The function name () format, if the current class can omit the class name, such as the above program.
We renamed the formal format as follows:
Note: Static functions, which are included in the function definition, are added to the static keyword, which we will describe in subsequent chapters.

Still don't feel clear enough, I want to put this method in another class.
Create a new file Myutil.java as follows:

Modify the Mynotepad.java as follows:

Compile myutil and Mynotepad separately, and test the run.
Note: Compiling Mynotepad is also possible, because the associated myutil is compiled automatically.

OK, the program is basically clear, the file can be generated or in the same directory, I want to put this tool class or the Help function in a separate folder, as a class library to use.
We continue to expand:
Current directory is c:\work\001
We create a new directory under the current directory util and Main
Then put the Myutil.java into the Util directory, Mynotepad.java into the main directory

We call the directory c:\work\001 the project root directory, and the program runs in the root directory of the project, because the classpath is set from the current path (.). Start to find the class file.
When compiling and executing, we will add the directory name to the class name, as follows:
Javac Main\mynotepad.java
Java Main. Mynotepad

Don't run, not finished yet.

You see that Javac is followed by the path to the file, so use the Windows directory format to locate the file.
Java is followed by the class name, because the Java program will automatically load the. class file.
The directory name before the class name we call the package name, which prevents the same file from being located in different directories.

So the formal class name is the package name. Class Name

So we want the program to declare its own package (directory), modify Mynotepad.java as follows:


Note: The call to Myutil also uses the full name

Modify the Myutil as follows:

Compile, run:
Javac Main\mynotepad.java
Java Main. Mynotepad A.txt
Output: Hello a.txt

Observe the call to Util.myutil in Mynotepad.java, and if there are many calls to Util.myutil, we write the full name Util.myutil each time.
Considering the simplicity of the program, I want to write only myutil, so I need to add a statement to the header of the file:
Import util.*

All class files that mean importing Util packages (directories)

So the program becomes this:

OK, now we don't have to worry about the implementation of the output of System.out.println, only the function/method call is required.

Continue to expand our program:
For the following statement
Myutil.println ("Hello" +args[0]);
We can modify it into:
String message = "Hello" +args[0];
MYUTIL.PRINTLN (message);

In the above statement we complete the Declaration and assignment of the variable, that is, declaring the variable message as a string type and assigning the result of "Hello" +args[0] to the message.

The format of the variable declaration is as follows:
Variable type variable name;

The format of the variable assignment is as follows:
Variable name = value;

where the Declaration and assignment of a variable can be written together:
Variable type variable name = value;

There are three major types in Java, basic types, custom types, String
Note: Because string is special and commonly used, we temporarily present him as a single type.
Basic types include: char,boolean,byte,short,int,long,float,double
One of the things we need to focus on for the moment: char,boolean,int (all lowercase)
The custom type is the class name declared by the class, which begins with an uppercase letter, including many system classes, which are not listed here.

So for the time being, we are looking at the following types: String,char,boolean,int, custom classes (including many system classes)
Our program turns out this way:

I added a method to read the file in Myutil, which is defined as follows:
public static string Getfilecontent (String fileName)
He can read the files in the current directory and return the contents of the file based on the file name passed in.
We don't care about the implementation, we just need to call it. The Myutil code is as follows:

1  Packageutil;2 3 ImportJava.io.*;4 5  Public classMyutil {6     7      Public Static voidprintln (String message) {8 System.out.println (message);9     }Ten      One      Public Staticstring Getfilecontent (String fileName) { AStringBuffer content =NewStringBuffer (); -InputStream FIS =NULL; -InputStreamReader ISR =NULL; theBufferedReader br =NULL; -         Try { -FIS = myutil.class. getResourceAsStream ("/" +fileName); -             if(FIS = =NULL) { +System.out.println ("File not found:[" + FileName + "]"); -                 returncontent.tostring (); +             } AISR =NewInputStreamReader (FIS, "UTF-8"); atBR =NewBufferedReader (ISR); -String line =NULL; -              while(line = Br.readline ())! =NULL) { - Content.append (line); -Content.append ("\ r \ n"); -             } in}Catch(Exception e) { - e.printstacktrace (); to             return""; +}finally { -             Try { the                 if(BR! =NULL) { * br.close (); $                 }Panax Notoginseng                 if(ISR! =NULL) { - isr.close (); the                 } +                 if(FIS! =NULL) { A fis.close (); the                 } +}Catch(Exception e) { - e.printstacktrace (); $             } $         } -         returncontent.tostring (); -     } the}
Myutil.java

We then complete the objectives of this chapter by amending the procedure as follows:

Put A.txt into c:\work\001, compile and run the following program:
Javac Main\mynotepad.java
Java Main. Mynotepad A.txt
Output: ABC

Very simple? Yes, because things like reading files, output, and so on are encapsulated in the tool class, so here you just need to master the environment to build, run, declare variables, assign values, and call functions.
For the time being, let's not care what I encapsulated into the myutil, how it was written, whether it was right or not.
You just need to know how to call, what parameters to pass in, and what results to return.
Because program manufacturing is a huge project that requires teamwork, a programmer can't understand everything, so you need to be concerned about the correctness of your own programs, the input and output, how to invoke the interfaces provided by others, and not all of the concerns.
It is important to ensure that you fully understand the procedures within your scope and that it is essential to write down the elegance and simplicity of the program.

Note: This tutorial only chuanjiang Java learning Main Line content and learning methods, if you have difficulty with the knowledge involved in this tutorial, please supplement the relevant knowledge points in the reading process.

Copyright Notice: This tutorial copyright belongs to JAVA123.VIP All, prohibit any kind of reprint and reference.

Java No detours tutorial (2.hello,java!)

Related Article

Contact Us

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

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

A Free Trial That Lets You Build Big!

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

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

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