Basic Java Language: Difference between revisions
wikademia>Remi0o mNo edit summary |
wikademia>Zchenyu No edit summary |
||
| Line 1: | Line 1: | ||
This lesson discusses the basics of the Java language, including variables, primitives, operators, statements and Java writing conventions. | This lesson discusses the basics of the Java language, including variables, primitives, operators, statements and Java writing conventions. | ||
=Touch on Classes= | == Touch on Classes == | ||
Everything in Java is specified inside classes. Classes are bodies of statements, methods, and variables. A statement can be thought of as the smallest standalone element of an imperative programming language (or a language that explicitly specify an algorithm to achieve a goal, opposed to declarative programming, which explicitly specifies a goal and leaves the implementation of that goal to algorithms within the support software). A program is formed by a sequence of one or more statements (e.g. if x, then y). A statement will have internal components (e.g. expressions). A method usually consists of a sequence of statements to perform an action, a set of input parameters to customize those actions, and possibly an output value (called return value) of some kind. There is a method called main that all classes have. This is the start point of your program - where everything must begin. To create a class, the syntax (or basic outline in code) is: | Everything in Java is specified inside classes. Classes are bodies of statements, methods, and variables. A statement can be thought of as the smallest standalone element of an imperative programming language (or a language that explicitly specify an algorithm to achieve a goal, opposed to declarative programming, which explicitly specifies a goal and leaves the implementation of that goal to algorithms within the support software). A program is formed by a sequence of one or more statements (e.g. if x, then y). A statement will have internal components (e.g. expressions). A method usually consists of a sequence of statements to perform an action, a set of input parameters to customize those actions, and possibly an output value (called return value) of some kind. There is a method called main that all classes have. This is the start point of your program - where everything must begin. To create a class, the syntax (or basic outline in code) is: | ||
<pre> | <pre> | ||
| Line 23: | Line 21: | ||
This, essentially creates a class. All the code goes between the {, called the opening brace, and the }, called the closing brace. | This, essentially creates a class. All the code goes between the {, called the opening brace, and the }, called the closing brace. | ||
=Protection= | == Protection == | ||
{{Template:confusing|December 2006}} | {{Template:confusing|December 2006}} | ||
Java allows you to abstract the internal data of a class from other code that uses that class. The idea here is to create a "black box" effect, where classes that use your class have no knowledge of the internal workings of the class. This simplifies changing the class if done consistently, as other classes don't depend on anything within the class. | Java allows you to abstract the internal data of a class from other code that uses that class. The idea here is to create a "black box" effect, where classes that use your class have no knowledge of the internal workings of the class. This simplifies changing the class if done consistently, as other classes don't depend on anything within the class. | ||
| Line 57: | Line 55: | ||
The protected and default levels deal with [[Java/Inheritance|inheritance]] and [[Java Deployment|packages]] respectively; these concepts are dealt with in later lessons. For now, declare all classes public (private classes are only useful — or even possible — when nested, and nested classes definitely comes later). Methods should be public if they're meant to be called by other classes. Declare a method private if it should only be called by its own class. | The protected and default levels deal with [[Java/Inheritance|inheritance]] and [[Java Deployment|packages]] respectively; these concepts are dealt with in later lessons. For now, declare all classes public (private classes are only useful — or even possible — when nested, and nested classes definitely comes later). Methods should be public if they're meant to be called by other classes. Declare a method private if it should only be called by its own class. | ||
=Statements= | == Statements == | ||
All operations are done in statements. Every statement ends in a semicolon: ;. Statements can set a variable with the '=' operator. This sets the variable you wish to set to another variable or a value. Values can only be used on primitive types. As you saw in the HelloWorld program, there was one statement: <code>System.out.println("Hello, World")</code>. This is one type of statement called "calling a method". More will be discussed later. Finally, you can declare a variable. If a class has no statements, it would do nothing. | All operations are done in statements. Every statement ends in a semicolon: ;. Statements can set a variable with the '=' operator. This sets the variable you wish to set to another variable or a value. Values can only be used on primitive types. As you saw in the HelloWorld program, there was one statement: <code>System.out.println("Hello, World")</code>. This is one type of statement called "calling a method". More will be discussed later. Finally, you can declare a variable. If a class has no statements, it would do nothing. | ||
=Variables= | == Variables == | ||
Variables are used to store information in a computer's memory. Like its name implies, variables are values that can be changed. There are two main categories of variables: reference variables and primitive variables. Reference variables are place holders for objects (More on objects in Lesson 4, Java Objects and Classes.) Primitive variables are given a value of a primitive, a basic value. Variables are all given a type when they are declared, such as "int" or "String". | Variables are used to store information in a computer's memory. Like its name implies, variables are values that can be changed. There are two main categories of variables: reference variables and primitive variables. Reference variables are place holders for objects (More on objects in Lesson 4, Java Objects and Classes.) Primitive variables are given a value of a primitive, a basic value. Variables are all given a type when they are declared, such as "int" or "String". | ||
==Declaring Variables== | |||
=== Declaring Variables === | |||
To declare a variable, use this syntax: | To declare a variable, use this syntax: | ||
<pre> | <pre> | ||
| Line 73: | Line 72: | ||
myInt has protection of public. It is of class int, or Integer (see Primitive Types). int is a class in Java. When you say that, you are basically making a primitive object. | myInt has protection of public. It is of class int, or Integer (see Primitive Types). int is a class in Java. When you say that, you are basically making a primitive object. | ||
==Primitive Data Types== | === Primitive Data Types === | ||
Primitives are the simplest type of data. The following table shows all the types of primitives. | Primitives are the simplest type of data. The following table shows all the types of primitives. | ||
<center> | <center> | ||
| Line 124: | Line 123: | ||
<code>double myDouble;</code> | <code>double myDouble;</code> | ||
==Operators== | == Operators == | ||
Operators are the symbols defining a certain operation to be performed/ | |||
===Assignment Operator '='=== | === Assignment Operator '=' === | ||
The assignment operator sets the variable on its left equal to the value on its right. This code creates the variable ''a'' and sets it equal to 5 | The assignment operator sets the variable on its left equal to the value on its right. This code creates the variable ''a'' and sets it equal to 5 | ||
<pre>int a; | <pre>int a; | ||
| Line 145: | Line 145: | ||
Now, why would you want to set a variable? For further use, ie, to access at a later time. For example, you can do calculations with other operators... | Now, why would you want to set a variable? For further use, ie, to access at a later time. For example, you can do calculations with other operators... | ||
===Addition Operator +=== | === Addition Operator '+' === | ||
The addition operator is different from the = operator. It does not set anything. You would need the = operator to do any setting. | The addition operator is different from the = operator. It does not set anything. You would need the = operator to do any setting. | ||
| Line 154: | Line 154: | ||
There are shortcuts to all of the operators, which will be shown in the following sections. | There are shortcuts to all of the operators, which will be shown in the following sections. | ||
===Subtraction | === Subtraction '-', Division '/' and Multiplication '*' Operators === | ||
Just like the addition operator, the subtraction, division, and multiplication operators are used as follows: | |||
Just like the addition operator, the | |||
<pre> | <pre> | ||
int a; | int a; | ||
| Line 185: | Line 184: | ||
</pre> | </pre> | ||
=Valid Identifiers= | == Valid Identifiers == | ||
There are several rules for the naming of your variables. Identifiers can be named using all the letters from A through Z (capital or lowercase, you choose), numbers 0-9 and underscore _ and the dollar sign $. The first character of the identifier cannot be a number, but it can be a letter, _ or $. Identifiers can be no longer than 32 characters. | There are several rules for the naming of your variables. Identifiers can be named using all the letters from A through Z (capital or lowercase, you choose), numbers 0-9 and underscore _ and the dollar sign $. The first character of the identifier cannot be a number, but it can be a letter, _ or $. Identifiers can be no longer than 32 characters. | ||
| Line 259: | Line 258: | ||
Identifiers should also be meaningful, while maintaining practicality. If calculating the sum of a set of numbers, <code>sum<code> is better than <code>cumulativeTotal</code>, but <code>s</code> might be too short. | Identifiers should also be meaningful, while maintaining practicality. If calculating the sum of a set of numbers, <code>sum<code> is better than <code>cumulativeTotal</code>, but <code>s</code> might be too short. | ||
=Using the Displayer with Variables= | == Using the Displayer with Variables == | ||
This section is about printing to the console using <code>System.out.println();</code>. | This section is about printing to the console using <code>System.out.println();</code>. | ||
Using System.out.println() is extremely simple, though C/C++ programmers may find it cumbersome to type up. The method println() takes one parameter, the variable you wish to print out. | |||
<code>System.out.println( myInt )</code> | |||
<code>System.out.println( | |||
You can also | You can also print out multiple variables on the same line: | ||
<code>System.out.println( false + " " + 54 )</code> | |||
Note that this won't work for two literal numeric values: | Note that this won't work for two literal numeric values: | ||
<code>System.out.println(54 + 32)</code>. It would mistake it for the adding operator for values. | <code>System.out.println( 54 + 32 )</code>. It would mistake it for the adding operator for values. So to print out "5432", you would have to type: | ||
<code>System.out.println( 54 + "" + 32 )</code> | |||
Now you can do calculations and print the result! For example, say you want to print 6*6*6*6. Here is the code: | Now you can do calculations and print the result! For example, say you want to print 6*6*6*6. Here is the code: | ||
| Line 295: | Line 285: | ||
</pre> | </pre> | ||
=Comments= | == Comments == | ||
Comments are notes that the developer can insert into their code. This allows the developer to keep track of their code and helps when developers are collaborating on a project. It is good to write a summary of the following code at the beginning of your methods, classes, etc. The Java compiler completely ignores comments, so you can say anything in them | Comments are notes that the developer can insert into their code. This allows the developer to keep track of their code and helps when developers are collaborating on a project. It is good to write a summary of the following code at the beginning of your methods, classes, etc. The Java compiler completely ignores comments, so you can say anything in them | ||
| Line 313: | Line 303: | ||
</pre> | </pre> | ||
is called a '''javadoc comment'''. As a general rule, don't use these unless you mean to run the javadoc program on your code. | is called a '''javadoc comment'''. As a general rule, don't use these unless you mean to run the javadoc program on your code. We won't worry about these kind of comments for now. | ||
=Compiling and | == Compiling and running your program == | ||
To compile your program, go to the directory you saved it. Note that if your class was named NaMe then your file '''must''' be named NaMe.java. Anyways, type: <code>javac NaMe.java</code> where NaMe is your class name. To run, type <code>java NaMe</code>. | To compile your program, go to the directory you saved it. Note that if your class was named NaMe then your file '''must''' be named NaMe.java. Notice that Java is case-sensitive. Anyways, type: <code>javac NaMe.java</code> where NaMe is your class name in a command-line window. To run the program, type <code>java NaMe</code>. Do not forget to include the ".java" extension when compiling the file, and to leave out any extensions when running the program. | ||
If the compiler reports syntax errors with your code, you must look in your source code and fix them. These are usually typos, but can be missing semi-colons or other formatting issues. | |||
If, when running, it reports invalid class file, the compiler might not have created a file. It should have given an error message at compile time. | If, when running, it reports invalid class file, the compiler might not have created a file. It should have given an error message at compile time. | ||
=Asking the | == Asking the user == | ||
''In order for the following to work properly, you must place the following code on the first line of your .java file. Importing packages will be explained later.'' | ''In order for the following to work properly, you must place the following code on the first line of your .java file. Importing packages will be explained later.'' | ||
<code>import javax.swing.JOptionPane;</code> | |||
Now, let's go on to asking the user to enter a number and doing calculations on it. Basically: <code>JOptionPane.showInputDialog( null, "Hello, enter something" )</code>. Try putting that in a class (in the main method, of course) and run it. Currently, we can't do anything with it because the value is deleted. | |||
Now you probably want to be able to enter a number. Java provides a method of changing a String to an int. It is Integer.parseInt(String_Here);. So lets say you want the user to enter a number and you print it. Do: | Because what you enter can consist of letters OR numbers, and any length of them, what is "produced" by that is a String. The following will work: <code>String mine = JOptionPane.showInputDialog( null, "Now I can set a String!" );</code>. Now lets say that after you get the string you want to print it. Just like regularly, add the following line: <code>System.out.println( mine );</code>. | ||
Now you probably want to be able to enter a number. Java provides a method of changing a '''String''' to an <code>int</code>. It is <code>Integer.parseInt( String_Here );</code>. So lets say you want the user to enter a number and you print it. Do: | |||
<pre> | <pre> | ||
int mine = Integer.parseInt(JOptionPane.showInputDialog(null, "Now I can set an | int mine = Integer.parseInt( JOptionPane.showInputDialog( null, "Now I can set an int!" ) ); | ||
System.out.println(mine); | System.out.println( mine ); | ||
</pre> | </pre> | ||
And now, of course, you can do whatever you want with that... | And now, of course, you can do whatever you want with that... | ||
=Exercises= | == Exercises == | ||
{{Activity | {{Activity | ||
| Printing variables | | Printing variables | ||