Jump to content

Basic Java Language: Difference between revisions

From IdeaWazaWiki
wikademia>Cremisis13
wikademia>Cremisis13
No edit summary
Line 1: Line 1:
This lesson needs some more information...
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=
==Variables==
Everything, in Java, is done inside classes. Essentially, in a brief talk, classes are bodies of statements, methods (you will learn these later), and variables. 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:
Variables are used to store data into your computer memory, that can change. All you need to worry about is that you can create a variable and change its value. 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".
<pre>
[Protection] class [Name] [Extend/Implements...]
</pre>
Right now, worry about the first 3. Protection will be discussed later. "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:
<pre>
public class NAME
</pre>
NAME, again,is the identifier.
 
Classes also have a body - where you actually put the things. To create the body you have a { and }. For example:
<pre>
public class NAME
{
 
}
</pre>
This, essentially creates a class. All the code goes between { and }.


=Protection=
Java allows you to create a "protection value". This means you can set who (or what - your program, other people's programs, etc.) can access the variable, method, or class that you set to a protection. You have already seen where this goes in a class, and will learn where in variables and methods. Right now, just call everything public. Here is a chart (which you might not understand right now).
<center>
{| border=1 cellspacing=0 cellpadding=5
| '''Name'''
| '''Desc.'''
| '''Example + Meaning'''
|-
| private
| Variable only accessible from class it is in
| private int myInt;//myInt can only be edited and viewed from the class it is in
|-
|
| (No modifier) - only accessible from class and subclass
| int myInt;//A subclass can access it, as the class it is in
|-
| protected
| Accessible from package, subclass, and class
| protected int myInt;//Class, subclass, and package classes can access it
|-
| public
| Fully accessible
| public int myInt;//Any class can access it
|}
</center>
=Statements=
All calculations are done in statements. Every statements end 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 on 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 data into your computer memory, that can change. All you need to worry about is that you can create a variable and change its value. 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==
To declare a variable, use this syntax:
<pre>
[protector] [classname] [identifier]
</pre>
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:
<pre>
public int myInt
</pre>
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. Primitives consist of numbers, letters and strings of letters (more than one letter in one variable). The following table shows all the types of primitives.
Primitives are the simplest type of data. Primitives consist of numbers, letters and strings of letters (more than one letter in one variable). The following table shows all the types of primitives.
Line 51: Line 106:
</center>
</center>


==Declaring and Setting Variables==
==Operators==
In a nutshell, declaring a variable has this syntax:
<pre> [variable type] [identifier];</pre>
This works for both reference variables and primitive variables. [variable type] is the type of variable, like '''int''' or '''char'''. [identifier] is the name for the variable you wish to create, for example, ''password'' or ''number_of_fish''. If you wanted to create a '''int''' variable called ''age'', you would type this:
<pre>int age;</pre>
Notice the semicolon at the end of the statement. All statements in Java must end in this, otherwise you will get a compiler error.
 
You can set the values of variables while declaring them, like this:
<pre>int age = 100;</pre>
You can declare multiple variables on one line, if you wish:
<pre> boolean a, b;</pre>
Also, you can change variables after you already give them a value.
<pre>[v you want to change] = [v you want it to be];</pre>
===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 $.
 
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. Here is a list of all the [http://en.wikipedia.org/wiki/Java_keywords Java Keywords].  [[Flashcards for Java keywords]] provides some assistance in memorizing the concepts behind specific keywords.
 
==Statements==
A statement in Java is a chunk of code that does something specific completely. Statements are ended by a semicolon ;. An example of a statement is the declaration of a variable like we saw before.
 
<pre>private int static numberOfObjectsInstantiated;</pre>
 
The above declares a single memory location per class which may be incremented each time an object of that class is instantiated by calling its constructor method.
 
Another example you will recall from the "Hello World" program we made in Lesson 1.
<pre>System.out.println("Hello World");</pre>
This line of code prints ''Hello World'' onto the console.
 
A third example
 
<pre>if (ourShip.speed<10) then ourShip.mainThrustPulse(2);</pre>
 
The above checks a ship object's speed and if it is less than ten then it commands the ship object to fire two pulses from its main propulsion rockets.  It is a single specific application task completed at the semi-colon when it moves to the next chunk of code.


==Comments==
===Assignment Operator '='===
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 written using two forward slashes
<pre>//This is a comment</pre>
Comments can be written at the end of a line
<pre>System.out.println("I love comments"); //This is also a comment</pre>
Comments can also be written on multiple lines by starting with '''/*''' and ending with'''*/'''.
<pre>/* Comment 1
Comment 2
Comment 3 */</pre>
:Sun recommends the above form be reserved for information intended for automatic JavaDoc documentation.
 
==Operators==
===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 109: Line 117:
b = 6;
b = 6;
a = b; //a equals 6</pre>
a = b; //a equals 6</pre>
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.
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 '''is''' now 6. You can also set a variable and declare it on the same line:
<pre>
int a = 6;
</pre>


===Addition Operator +===
===Addition Operator +===
Unlike the = operator, a statement that simply uses the addition operator and two other values on either side does not do anything significant. For example, neither of the following three lines of code do anything.
The addition operator is different from the = operator. It does not set anything. You would need the = operator to do any setting.
<pre>5 + 6;
 
a + 9;
a + b;</pre>
If you want to you want to use the addition operator to add 6 to the value of ''a'', it would be used like this:
If you want to you want to use the addition operator to add 6 to the value of ''a'', it would be used like this:
<pre>a = a + 6;</pre>
<pre>a = a + 6;</pre>
Line 146: Line 155:
a = a-b/c*d;
a = a-b/c*d;
</pre>
</pre>
You would then use the order or operations, otherwise known as [http://en.wikipedia.org/wiki/PEMDAS PEMDAS], to find the result of "a"; which would be:
The Java Programming Language would use the order of operations in this example.
<pre>
a = a - (b/c)d
or
        b
a = a - ---
      (c*d)


(either way the result is the same)
Here is a shortcut for subtracting a value from int myInt:
</pre>
Or if you prefer actual numbers, it would look like so:
<pre>
<pre>
int a = 1;
myInt -= 4;
int b = 2;
int c = 2;
int d = 1;
 
a = 1-2/2*1;
 
thus:
 
a = 1 - 1
or
a = 0;
</pre>
</pre>
==Public, Private - What are they?==
=Valid Identifiers=
These statments are used to protect data. For example, "private int myInt" will make myInt only accessible from the class it is in. Here is a complete description:<br>
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 $.  


<center>
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. Here is a list of all the [http://en.wikipedia.org/wiki/Java_keywords Java Keywords].  [[Flashcards for Java keywords]] provides some assistance in memorizing the concepts behind specific keywords.
{| border=1 cellspacing=0 cellpadding=5
=Compiling and Running your program=
| '''Name'''
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>.
| '''Desc.'''
| '''Example + Meaning'''
|-
| private
| Variable only accessible from class it is in
| private int myInt;//myInt can only be edited and viewed from the class it is in
|-
|
| (No modifier) - only accessible from class and subclass
| int myInt;//A subclass can access it, as the class it is in
|-
| protected
| Accessible from package, subclass, and class
| protected int myInt;//Class, subclass, and package classes can access it
|-
| public
| Fully accessible
| public int myInt;//Any class can access it
|}
</center>
=Make a Class=
Since you do not know classes and objects yet, you can put everything like this:
 
<pre>
 
public class NAME
{
  public static void main(String args[])
  {
      //CODE HERE
  }
}
 
</pre>
 
You will also later learn about methods. Note that this file must be saved into NAME.java. You can change NAME to any name you want (that is valid). This way, you can test all of your programs. In the command line, type:
<pre>
javac NAME.java
java NAME
</pre>
Note that NAME is still the program's name!
=Convenient Statements=
System.out.println("TEXT HERE"); -- Prints text onto command console (include quotes)


JOptionPane.showMessageDialog(null, "TEXT HERE"); -- Opens a message box with the text in the quotes
Note that if the compiler gives errors with your code, you must fix them.


String message = JOptionPane.showInputDialog(null, "TEXT HERE"); -- See above; also allows user to input something. In this case, the input goes to String message
If, when running, it says invalid class file, perhaps the compiler did not create a file. It might have given error messages.
=Exercises=
A. Create a program that creates a String with the value "ABC". Then print the value using System.out.println(StringIdentifierHere). You could also do System.out.prinln("ABC"), but we are focusing on creating variables.


=Finalizing the Basics=
B. Do the above with a long set to 10000. Note that you have to say System.out.println(LongIdentifier + "").
Let this information sink through before continuing to the next chapter. Take the time to test out some things you learned (see Make a Class). Then you'll really understand some of it.
<br><br><hr>
<br><br><hr>
You are ready to move on! [[Java Decision Structures]]<br>
You are ready to move on! [[Java Decision Structures]]<br>

Revision as of 23:07, 27 November 2006

This lesson discusses the basics of the Java language, including variables, primitives, operators, statements and Java writing conventions.

Touch on Classes

Everything, in Java, is done inside classes. Essentially, in a brief talk, classes are bodies of statements, methods (you will learn these later), and variables. 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, worry about the first 3. Protection will be discussed later. "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.

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 { and }.

Protection

Java allows you to create a "protection value". This means you can set who (or what - your program, other people's programs, etc.) can access the variable, method, or class that you set to a protection. You have already seen where this goes in a class, and will learn where in variables and methods. Right now, just call everything public. Here is a chart (which you might not understand right now).

Name Desc. Example + Meaning
private Variable only accessible from class it is in private int myInt;//myInt can only be edited and viewed from the class it is in
(No modifier) - only accessible from class and subclass int myInt;//A subclass can access it, as the class it is in
protected Accessible from package, subclass, and class protected int myInt;//Class, subclass, and package classes can access it
public Fully accessible public int myInt;//Any class can access it

Statements

All calculations are done in statements. Every statements end 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 on 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.

Variables

Variables Variables are used to store data into your computer memory, that can change. All you need to worry about is that you can create a variable and change its value. 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

To declare a variable, use this syntax:

[protector] [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

Primitives are the simplest type of data. Primitives consist of numbers, letters and strings of letters (more than one letter in one variable). The following table shows all the types of primitives.

Primitive Description Values
byte A brief, 8-bit integer Whole numbers -128 through 127
short A short, 16-bit integer Whole numbers -32,768 through 32,767
int A 32 bit integer Whole numbers -2,147,483,648 through 2,147,483,647
long A long, 64 bit integer Whole 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 true or false
String A group of characters Any formation of characters

Operators

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

int a;
a = 5;

Fairly simple, right? Here is where it can get a little 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 is now 6. You can also set a variable and declare it on the same line:

int a = 6;

Addition Operator +

The addition operator is different from the = operator. It does not set anything. You would need the = operator to do any setting.

If you want to you want to use the addition operator to add 6 to the value of a, it would be used like this:

a = a + 6;

Or you can use a shortcut in order to reach the same result as the above.

a += 6;

There are shortcuts to all of the operators, which will be shown in the following sections.

Subtraction -, Division / and Multiplication * Operators

Just like the addition operator, the Subtraction, Division, and Multiplication operators are used as follows:

int a;

a = a-1;
a = a/1;
a = a*1;

The result of "a" in each example would be simply

1st a - "a" minus 1
2nd a - "a" divided by 1
3rd a - "a" multiplied by 1

When all of the operators are used at once, for example:

int a, b, c, d;

a = a-b/c*d;

The Java Programming Language would use the order of operations in this example.

Here is a shortcut for subtracting a value from int myInt:

myInt -= 4;

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 $.

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. Here is a list of all the Java Keywords. Flashcards for Java keywords provides some assistance in memorizing the concepts behind specific keywords.

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: javac NaMe.java where NaMe is your class name. To run, type java NaMe.

Note that if the compiler gives errors with your code, you must fix them.

If, when running, it says invalid class file, perhaps the compiler did not create a file. It might have given error messages.

Exercises

A. Create a program that creates a String with the value "ABC". Then print the value using System.out.println(StringIdentifierHere). You could also do System.out.prinln("ABC"), but we are focusing on creating variables.

B. Do the above with a long set to 10000. Note that you have to say System.out.println(LongIdentifier + "").




You are ready to move on! Java Decision Structures
Back to Java Main Page