Основи на езика Java
This lesson discusses the basics of the Java language, including variables, primitives, operators, statements and Java writing conventions.
Touch on Classes
[edit]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 specifies 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). Each 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:
[Protection] class [Name] [Extend/Implements...]
Right now, let's examine the first 3. "[Protection]" refers to permissions of who can access the class, and will be discussed later. The label "class" is required to create a class. "Name" can be any valid identifier (see Valid Identifiers...). The name will be used to create objects (more later...). Here is what you type to create a class, as for now, and all you must worry about:
public class NAME
NAME, again,is the identifier. (Java is case sensitive; so NAME is different from Name. Industry convention suggest naming classes using mixed case, starting with an uppercase letter.[1] For example: NameNumberTwo)
Classes also have a body - where you actually put the things. To create the body you have a { and }. For example:
public class NAME { }
This, essentially creates a class. All the code goes between the {, called the opening brace, and the }, called the closing brace.
Protection
[edit]Template:Confusing 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.
There are three access modifiers and four access levels (one level is the default, used when no modifier appears). If your class attempts to access another class, it will only be able to if it is allowed access. If you don't have access to the code you're trying to access, the compiler will notice and you'll get a compile-time error. The four levels and three modifiers are as follows:
Modifier | Level | Accessible From |
private
|
Private | An object of the exact same class as the declaring class |
Default
|
Default; sometimes called package-private | An object of the same package as the declaring class |
protected
|
Protected | An object of the same or subclass of the declaring class |
public
|
Public | Anywhere |
The declaring class is the class containing the field, method, or nested class being modified. (For example, if the class Foo
contains a method bar()
, Foo
is bar()
's declaring class.)
The protected and default levels deal with inheritance and 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
[edit]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: System.out.println("Hello, World")
. 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.
Comments
[edit]Comments are short 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 written using two forward slashes
// This is a comment
Comments can be written at the end of a line
System.out.println("I love comments"); // This is also a comment
Comments can also be written on multiple lines by starting with /* and ending with*/.
/* Comment 1 Comment 2 Comment 3 */
A multi-line comment that opens with two asterisks
/** Like this */
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.
We will use comments to document and explain our code from now on.
Variables
[edit]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 data type, a fundamental value. Variables are all given a type when they are declared, such as "int" or "float".
Declaring Variables
[edit]To declare a variable, use this syntax:
[protection] [classname] [identifier]
This is one type of statement. The class name is the type of variable you want. Currently, you will only use basic primitive variables, but you will learn about objects soon. Here is an example of declaring a variable:
public int myInt
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
[edit]Primitives are the simplest type of data. The following table shows all the types of primitives.
Primitive | Description | Values |
byte | A brief, 8-bit integer | Integer numbers -128 through 127 |
short | A short, 16-bit integer | Integer numbers -32,768 through 32,767 |
int | A 32 bit integer | Integer numbers -2,147,483,648 through 2,147,483,647 |
long | A long, 64 bit integer | Integer numbers -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807 |
float | Single-precision floating point (32-bit IEEE 754) | Smallest positive non-zero: 14e-45, Largest positive non-zero: 3.4028234e38 |
double | Double-precision floating point (64-bit IEEE 754) | Smallest positive non-zero: 4.9e-324, Largest positive non-zero: 1.797693157e308 |
char | A single character | All Unicode characters |
boolean | A Boolean value(1-bit) | true or false |
Using what you have learned, you may have guessed how to create these primitives:
long myLong;
double myDouble;
Operators
[edit]Operators are the symbols defining a certain operation to be performed.
Addition Operator '+'
[edit]The addition operator returns the sum of the the values to the left, and the value to the right of it.
If you want to evaluate the expression 23 plus 75, you would type:
23+75
The addition operator also works with variables:
myInt+yourInt
Note, this operator is not to be confused with the concatenation operator, which we will discuss later.
Subtraction '-', multiplication '*', division '/', and modulus '%' operators
[edit]Just like the addition operator, the subtraction, multiplication, division, and modulus operators are used as follows:
int a = 9; a-1; // evaluates to 8 a/3; // evaluates to 3 a*2; // evaluates to 18 a%4; // evaluates to 1
Subtraction, multiplication, and division, you have seen before, but the modulus operator is much less commonly used. Actually, it is commonly used, but it known under a different name, the remainder. Nine divided by four gives a remainder of one, so therefore 9 mod 4 evaluates to 1.
When more than one of the operators are used at once, for example:
int a, b, c, d; a = a-b/c*d;
the Java language would use the order-of-operations in this case.
Assignment Operators
[edit]An assignment operator assigns a value to a certain variable after evaluating the expression to be assigned. You have seen one of them in numerous examples so far, can you pick it out?
Equals
[edit]The equals 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
int a; a = 5;
Fairly simple, right? Here is where it can get a slightly more tricky.
int a; int b; b = 6; a = b; //a equals 6
At first glance, you might think that the last statement is setting a equal to the letter "b", but instead it is setting a equal to the value of b, which is 6. Essentially, a holds the value of 6. You can also set a variable and declare it on the same line:
int a = 6;
However, you can't say char myChar = y;
to set a character to 'y'. That would set the character variable myChar
to the value stored in the character variable y
. To set myChar
equal to the character y, use a character literal — a technical term for "a character in single-quotes": char myChar = 'y';
. Note that a char
primitive can only hold a single character. char myChar = 'Yo';
is illegal.
Finally, what's so special about float
s and double
s? Doubles and floats can have decimals: float myFloat = 5.1;
. (The term "float" is short for "floating-point number," referring to the decimal point.)
Now, why would you want to set a variable? You would need to set a variable for further use, ie. to access at a later time.
Plus-equals
[edit]The plus-equals operator ("+=") adds the value on the right, to the variable on the left, and then assigns that value back into the variable on the left.
Example:
int a = 6; // assigns the value 6 to variable a a += 5; // adds 5 to a, and assigns that value back into a, now a is 11
Minus-equals, multiply-equals, divide-equals, and mod-equals
[edit]Minus-equals, multiply-equals, divide-equals, and mod-equals works in the same way as plus-equals, except instead of addition, they do subtraction, multiplication, division, and modulus, respectively.
Concatenation operator
[edit]The concatenation operator (+) looks exactly like the addition operator, however it performs a different operation. The concatenation operator concatenates or "puts together," for lack of a better term, two Strings
.
String myString = "Hello, "; String yourString = "world."; String ourString = myString + yourString; // evaluates to "Hello, world."
Valid Identifiers
[edit]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.
You can't create two variables with the same identifier; all identifiers must be unique. You also can't use an identifier that is a Java keyword, listed below. Flashcards for Java keywords provides some assistance in memorizing the concepts behind specific keywords.
abstract
|
assert
|
boolean
|
break
|
byte
|
case
|
catch
|
char
|
class
|
const
|
continue
|
default
|
else
|
enum
|
extends
|
false
|
final
|
finally
|
float
|
for
|
goto
|
if
|
implements
|
import
|
instanceof
|
int
|
interface
|
long
|
native
|
new
|
null
|
package
|
private
|
protected
|
public
|
return
|
short
|
static
|
strictfp
|
super
|
switch
|
synchronized
|
this
|
throw
|
throws
|
transient
|
true
|
try
|
void
|
volatile
|
while
|
Identifiers should also be meaningful, while maintaining practicality. If calculating the sum of a set of numbers, sum
is better than
cumulativeTotal
, but s
might be too short.
Using the Displayer with Variables
[edit]
This section is about printing to the console using System.out.println();
.
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.
System.out.println( myInt )
You can also print out multiple variables on the same line:
System.out.println( false + " " + 54 )
Note that this won't work for two literal numeric values:
System.out.println( 54 + 32 )
. It would mistake it for the adding operator for values. So to print out "5432", you would have to type:
System.out.println( 54 + "" + 32 )
Now you can do calculations and print the result! For example, say you want to print 6*6*6*6. Here is the code:
public class Multiplying
{
public static void main(String args[])
{
int a = 6;
int b = a*a*a*a;
System.out.println(b + "");
}
}
Compiling and running your program
[edit]
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: javac NaMe.java
where NaMe is your class name in a command-line window. To run the program, type java NaMe
. 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.
Asking the user
[edit]
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.
import javax.swing.JOptionPane;
Now, let's go on to asking the user to enter a number and doing calculations on it. Basically: JOptionPane.showInputDialog( null, "Hello, enter something" )
. 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.
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: String mine = JOptionPane.showInputDialog( null, "Now I can set a String!" );
. Now lets say that after you get the string you want to print it. Just like regularly, add the following line: System.out.println( mine );
.
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:
int mine = Integer.parseInt( JOptionPane.showInputDialog( null, "Now I can set an int!" ) );
System.out.println( mine );
And now, of course, you can do whatever you want with that...
Exercises
[edit]
public class Multiplying
{
public static void main(String args[])
{
int a = 6;
int b = a*a*a*a;
System.out.println(b + "");
}
}
public class Multiplying
{
public static void main(String args[])
{
int a = 6;
int b = a*a*a*a;
System.out.println(b + "");
}
}