Jump to content

Basic Java Language: Difference between revisions

From IdeaWazaWiki
wikademia>Conrad.Irwin
rewrote touch on classes
Line 185: Line 185:
</pre>
</pre>


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.
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%4 (pronounced "9 mod 4") evaluates to 1.


When more than one of the operators are used at once, for example:
When more than one of the operators are used at once, for example:

Revision as of 05:09, 16 December 2007

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 written in classes. A Class in this context is a section of code that can contain data (variables), and instructions for processing that data (methods). Returning to the Hello World example from the Introduction to Java, the class is defined on the first line, and everything within the curly brackets is within that class.

<source lang="java"> public class HelloWorld {

    public static void main (String[] args) 
    {
         System.out.println("Hello World!");
    }

} </source>

The first line is always of the general form:

[Protection] class [Name] [Extend/Implements...]
{
     /*Class Code Here*/
}

Protection

Java provides several different levels of protection for classes, and each of them has a different purpose. However, in order to get started without being bogged down by choosing one, just declare all of your classes as public. The idea behind protection is that, if only the class itself can make changes to the data stored within itself, the other parts of the program do not need to know where the data is coming from or how it is stored. This is great for two reasons, firstly, it is easy to rewrite the structure of a class without changing the external application, and secondly it allows the class to make assumptions about the data, and do slightly less exception handling. You should know that if your code tried to break the protection of a class, the java compiler will stop and report an error.

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

class

This is the bit that tells the Java compiler we are writing a new class, the only slightly notable thing about it is that it must be written in small letters. It is not Class!

Name

This is the name by which you will reference your class when you use it in your code, it can be called almost anything you want, containing numbers, letters and underscores. Though it must start and end with a letter. One thing to watch out for, is that like everything in Java it is case sensitive. This means that Hello is not the same as hello. You could, if you wanted have two different classes, one called hello and the other called HeLlO, however this might get confusing and so is strongly not recommended. In fact, in order to try and make things less confusing, there is a convention amoungst Java programmers that all words in a class name start with a capital letter, and the rest is lower case letters. eg. public class VeryUseful or public class CompanyDepartment

Extends/Implements

For the moment you can happily forget about this, it was included for completeness. For the object orientated experts, you will be pleased to know that this permits inheritance.



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: 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

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

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

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

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

Operators are the symbols defining a certain operation to be performed.

Addition Operator '+'

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

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%4 (pronounced "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

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

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 floats and doubles? 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

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

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

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

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

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

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

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

Template:Activity

Template:Activity





Project: Java
Previous: Introduction to Java — Basic Java Language — Next: Java Decision Structures