Learning Java/Basic Java Language

From Wikiversity
Jump to navigation Jump to search

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

Touch on Classes[edit | edit source]

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.

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

The first line is always of the general form:

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

Protection or Access Levels[edit | edit source]

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

Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

class[edit | edit source]

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[edit | edit source]

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 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. public class VeryUseful or public class CompanyDepartment

Extends/Implements[edit | edit source]

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[edit | edit source]

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 | edit source]

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. 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[edit | edit source]

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 | edit source]

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 | edit source]

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 | edit source]

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

Assignment Operators[edit | edit source]

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

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, i.e., to access at a later time.

Addition Operator '+'[edit | edit source]

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:


The addition operator also works with variables:


Note, this operator is not to be confused with the concatenation operator, which we will discuss later.

Subtraction '-', multiplication '*', division '/', and modulus '%' operators[edit | edit source]

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

int a, b, c, d;
a = a-b/c*d;

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

Plus-equals[edit | edit source]

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.


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

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

Minus-equals, multiply-equals, divide-equals, and mod-equals[edit | edit source]

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[edit | edit source]

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 | edit source]

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
do double 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.

System.out[edit | edit source]

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.

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 );


The plus sign would be mistaken for the addition operator for adding numeric 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 evaluate 6*6*6*6 and then print the result ("1296"). 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 | edit source]

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

User Input[edit | edit source]

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. import java.util.Scanner; Once you have done that you will have to create a Scanner object. Scanner scan1 = new Scanner(System.in); 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.

import java.util.Scanner;
public class GettingStringInput
   public static void main(String[]args)
       String yourinput = new String();
       Scanner scan1 = new Scanner(System.in);
       System.out.print("Please enter a string: ");
       yourinput = scan1.nextLine();

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 | edit source]

Activity: Printing variables
Create a program that stores a String with the value "ABC". Then print the value using System.out.println(StringIdentifierHere). Don't use System.out.println("ABC"), as we are focusing on creating variables.

Activity: Printing number variables
Do the above with a long set to 10000. Note that you have to say System.out.println(LongIdentifier).

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