Learning Java/Basic Java Language

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

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.

The first line is always of the general form:

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

Protection or Access Levels
Java provides two types of access levels.
 * Class access: public or package level (no modifier)
 * Member access: public, protected, package (no modifier or default), and private

A class with public modifier is visible by all other classes. Class with no modifier has package level protection. It means that only other classes within the same package can see it.

Member access levels control visibility of member data or methods from its own class, within package, subclass, or the world. See table below for the summary.

However, in order to get started without being bogged down by choosing one, just declare all of your classes as. 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, first, it is easy to rewrite the structure of a class without changing the external application, and second, 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.

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 !

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  is not the same as. You could, if you wanted have two different classes, one called  and the other called , however this might get confusing and so is strongly discouraged. In fact, in order to try and make things less confusing, there is a convention amongst Java programmers that all words in a class name start with a capital letter, and the rest are lower case letters. eg.  or

Extends/Implements
Extends/Implements not complete yet. Soon.. Every java class has a parent class, if it has not been specified then the default parent class is.

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:. 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 Comments can be written at the end of a line Comments can also be written on multiple lines by starting with /* and ending with*/.

A multi-line comment that opens with two asterisks

is called a Javadoc comment. These comments are used to generate documentation for your code, and they generally appear at the beginning of a class or a method definition. A special program (also named javadoc) can be used to automatically create documentation from the Javadoc comments, usually in the form of a set of HTML files. It is generally good practice to fully document your code by using Javadoc comments, but it is not required. 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.

Using what you have learned, you may have guessed how to create these primitives:

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

Assignment Operators
An assignment operator assigns a value to a certain variable after evaluating the expression to be assigned.

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 Fairly simple, right? Here is where it can get a slightly more tricky.

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:

However, you can't say  to set a character to 'y'. That would set the character variable  to the value stored in the character variable. To set  equal to the character y, use a character literal — a technical term for "a character in single-quotes":. Note that a  primitive can only hold a single character. is illegal.

Finally, what's so special about s and  s? Doubles and floats can have decimals:. (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, i.e., to access at a later time.

Addition Operator '+'
The addition operator returns the sum of 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:

Subtraction, multiplication, and division, you have seen before, but the modulus operator is much less commonly used. Actually, it is commonly used, but is 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 in the same statement, for example:

the Java language would use the order-of-operations in this case.

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:

The following lines are equivalent: (a = a + 5;) is the same as (a += 5;)

Minus-equals, multiply-equals, divide-equals, and mod-equals
Minus-equals, multiply-equals, divide-equals, and mod-equals (, ,  , and  , respectively) 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.

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.

Identifiers should also be meaningful, while maintaining practicality. If calculating the sum of a set of numbers,  is better than , but   might be too short.

System.out
It is often useful (and necessary) to view the output of your program, especially when you are just getting started or when you are debugging. Java provides a way to do this. System.out is a static member (don't worry about what this means for right now) which contains various methods which allow programmers to output text to the console. Two commonly used methods are System.out.print and System.out.println. The first allows you to print text without a line break, and the second inserts a new line after every call.

Using System.out.println is extremely simple, though C/C++ programmers may find it cumbersome to type up compared to simply typing printf. The method println takes one parameter, the variable you wish to output, and writes it to the console. 3h55523f6h66f5698hf+++h 555555 hh0..0h33g ..23h3266h/syntaxhighlight>. 2 2232 The6 56plus sign would be mistaken for the addition operator for adding numeric values. So to print out "5432", you would have to type:

165023System.out.println( 54 + "" + 32 );

Now you can do calculations and print the result! For example, say you want to evaluate 6*6*6*6 and then print the result ("1296"). Here is the code:

Compiling and running your program
To compile your program, go to the directory you saved it in. Note that if your class was named NaMe then your file must be named NaMe.java. Notice that Java is case-sensitive. Anyways, type:  where NaMe is your class name in a command-line window. To run the program, type. 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.

User Input
The first way to get user input is from the keyboard without using the swing gui. You must first import the Scanner package first like so. Once you have done that you will have to create a Scanner object. Finally after the user has entered the input asked for you retrieve using your Scanner object. For example if we wanted a string as input we could use the following code.

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

Now, let's go on to asking the user to enter a number and doing calculations on it. Basically:. 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:. Now lets say that after you get the string you want to print it. Just like regularly, add the following line:.

Now you probably want to be able to enter a number. Java provides a method of changing a String to an. It is. So lets say you want the user to enter a number and you print it. Do:

And now, of course, you can do whatever you want with that...