Difference between revisions of "Java 1: Basics"

From Deep Blue Robotics Wiki
Jump to: navigation, search
(Hello World)
(Hello World: Use syntaxhighlight extension)
Line 18: Line 18:
  
 
<span style="color:#20AB7E">
 
<span style="color:#20AB7E">
  <nowiki>
+
  <syntaxhighlight lang="java">
 
package helloworld;
 
package helloworld;
  
 
public class HelloWorld {
 
public class HelloWorld {
  
}</nowiki>
+
}</syntaxhighlight>
 
</span>
 
</span>
 
Inside the { and } of the HelloWorld class write the main method. Code contained between the { and } of the main method is executed when the program is run. Do not worry about how the main method works yet; methods will be covered in a later section. The code for the main method is:
 
Inside the { and } of the HelloWorld class write the main method. Code contained between the { and } of the main method is executed when the program is run. Do not worry about how the main method works yet; methods will be covered in a later section. The code for the main method is:

Revision as of 06:28, 6 October 2016

Before you start programming robots, you must first learn the basics of the Java language. In this section, you will learn some fundamental Java concepts that will allow you to write simple programs.

Developer Tools

Before you can start programming you need to download some developer tools.

Eclipse - Eclipse is a program used for writing and running code. You can download the latest version of the Java Development Kit (JDK) here and the Eclipse Integrated Development Environment (Eclipse IDE) here.

GitHub - GitHub stores all of our code in an online repository, so that we can easily collaborate on projects, access code from any computer, save a record of past versions of the code (version control), and branch off into different projects during development. Follow this tutorial to install and use GitHub.

Hello World

Follow these steps to write a simple program that prints out the text "Hello, world." However, before we begin you should learn about Java's naming conventions. In general, when naming things in Java you should avoid using spaces, and instead use camelCase (i.e. capitalizingTheFirstLetterOfEachWordExceptTheFirst). You also cannot start names with a number, or include any punctuation besides underscores. Additionally, there are certain restricted words that already have a meaning in the Java language, so they cannot be used as names either.

  1. Create a project - In the Eclipse menu bar go to: File > New > Java Project. Enter a name for your project (e.g. "HelloWorld") and click Finish. Your project name can be anything you want because the normal naming rules don't apply.
  2. Create a package - A package is a collection of files; essentially a folder to group code together. In the Package Explorer, right click on your project and go to New > Package. Package names should be entirely lowercase (e.g. "mypackage" or "helloworld"). Enter a name and click Finish.
  3. Create a class - Classes are ".java" text files in which you put code. In the Package Explorer, right-click on your package and go to New > Class. The name of your class should start with a capital letter. Give your class a name and click Finish.
  4. Write the program - Open the file that has appeared in your project. The class should look like this:

package helloworld;

public class HelloWorld {

}

Inside the { and } of the HelloWorld class write the main method. Code contained between the { and } of the main method is executed when the program is run. Do not worry about how the main method works yet; methods will be covered in a later section. The code for the main method is:

   public static void main(String[] args) {

   }

Inside of the main method write System.out.println(); This line of code prints out text to the output log. The text you want to print out goes in quotation marks inside of the parenthesis. Notice that there is a semicolon at the end of the line. Semicolons signify the end of a line of code; they are the Java equivalent of periods.

      System.out.println("Hello, World!");

Your complete class should now look something like this:

package helloworld;

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

5. Run the program - Press the run button (the green arrow). The text "Hello, world!" should appear in the output log.

Data Types

There are many different ways to store data in Java. These are some of the most basic ones. You will learn how to utilize these data types in your code in the next section, variables.

Primitive types

The most basic data types in Java. There are 8 primitive types: byte, short, int, long, float, double, boolean, and char.

  • byte: An 8-bit integer between -128 and 127 (-27 to 27-1).
  • short: A 16-bit integer between -32,768 and 32,767 (-215 to 215-1).
  • int: A 32-bit integer between -231 and 231-1. The most commonly used type of integer.
  • long: A 64-bit integer between -263 and 263-1. Usually used for very large numbers. Required to have an L after the number (e.g. 87932658723L).
  • float: A 32-bit floating-point number (i.e. a decimal). Required to have an F after the number (e.g. 56.3424F). Floating point numbers work by keeping track of the position of the decimal point (like scientific notation).
  • double: A 64-bit floating-point number (i.e. a decimal). More commonly used than floats. Named double because it is twice the size of a float.
  • boolean: Either true or false.
  • char: A 16-bit unicode character. Surrounded by single quotes (e.g. ‘A’ or ‘÷’).

String

A line of text. Surrounded by double quotes (e.g. “Hello, world.”). Can be thought of as a group of chars. Not a primitive type, which is why it is capitalized whereas the primitive types are lower case.

For more information on how the data is actually stored in the computer, see the 2's Complement and Floating Point pages on Wikipedia.

Variables

Variables are used to store and manipulate data. A variable has three parts: a name, a value, and a data type. The name provides a way to refer to the variable in the code. The value is the information stored in the variable. The data type is the type of information that the variable can store. For example, you could have a variable named “x” that holds the value 42. The data type of the variable would be an int, because 42 is an integer. Then, whenever you type “x” in your program, the code will know that you are referring to the value 42. By storing values in variables, you can easily refer to values that your program used earlier, or even values that you don’t know until the program actually runs.

Declaration

Before using a variable, it must be declared. The main purpose of declaring a variable is to tell the program what type of data your variable can store. Note that variable names should always start with a lowercase letter (unlike classes, which are capitalized). The basic format to declare a variable is the datatype of the variable followed by the variable's name.

int number;

Assignment

The value of a variable can be set using an equal sign, called the assignment operator. The variable on the left of the equal sign will be assigned the value on the right of the equal sign.

number = 42;

The declaration and assignment can be combined into a single statement:

int number = 42;

A value can also be another variable:

int variable1 = 42;
int variable2 = variable1; // variable2 is set to 42

Multiple variables of the same type can be declared at once using commas:

int a = 1, b = 2, c = 3;

Multiple variables can by assigned the same value at once using chained equal signs. All of the variables will be assigned the rightmost value:

a = b = c = 42; // a, b, and c are all set to 42

Operators

Operators allow you to perform various operations on variables.

Arithmetic Operators

Basic mathematic operations

Operation Notation Description Example
Addition + Same as normal math 5 + 5 = 10
Subtraction - Same as normal math 10 - 5 = 5
Multiplication * Same as normal math 5 * 5 = 25
Division / Same as normal math, but the quotient of two integers will be truncated an integer (always rounded down) 5.0 / 2.0 = 2.5

5 / 2 = 2

Modulus  % Finds the remainder when dividing the first number by the second number 10 % 3 = 1

10 % 2 = 0

Arithmetic Shorthand

Faster ways to perform mathematical operations on variables

Shorthand Equivalent
a++ a = a + 1
a += b a = a + b
a-- a = a - 1
a -= b a = a - b

Note that the *=, /=, and %= operators can be used in the same way as the += and -= operators.

Equality/Relational Operators

Operations that compare two numbers and return a boolean

Operator Notation Example Returns
Equal to == 3==4 false
Not equal to  != 3!=4 true
Less than < 3<4 true
Less than or equal to <= 3<=4

4<=4

true

true

Greater than > 3>4 false
Greater than or equal to >= 3>=4

4>=4

false

true

Conditional Operators

Operators that compare boolean expressions and return a single boolean

Operator Notation Description Example Returns
and && True if and only if both conditions are true 3<5 && 3==4 false
or | | True if and only if at least one condition is true 3==5 | | 1<2 true
not  ! True if and only if the condition is false  !(1<5) false


Bitwise Operators - Operators used to perform bitwise operations on integers. These operators are fairly complicated and rarely used, so they will not be covered in this tutorial. If you are still interested, see the Oracle Bitwise Tutorial.

Type Comparison Operator - The operator instanceof returns true if and only if a value is of a given data type. For example, "Hello" instanceof String would be true.

Order of Operations - In general, not conditional operations occur first, then arithmetic operations (PEMDAS), then relational operations and type comparisons, then the and and or conditional operations (in that order), then lastly assignment operations. Operations with the same priority proceed from left to right. See the Oracle Order of Operations Tutorial for more detail. When in doubt, you can always manually group operations using parentheses.

Control Statements

Normally a program runs sequentially; when one line of code finishes the next line of code starts. However, control statements allow you to redirect the flow of the program. Note that any variables declared inside of a control statement cannot be used outside of that control statement. If the statement only contains a single line of code, the brackets are not necessary.

If-Statement

If-statements take a condition that resolves to either true or false and execute the code inside if it resolves to true.

if (3 < 5) {
    System.out.println("I can do math!");
}
if (3 == 3 || 4 < 1) {
    System.out.println("I can't do math, but that's ok!");
}

Else-Statement

Else-statements are appended to if-statements to execute if the condition in the if-statement resolves to false.

Else-if is another version of an if-statement which presents another condition if the first condition resolves to false. If the else-if also resolves to false, then the next else-if or else will be evaluated.

In this example, since 1 is not less than 2, the code inside the first set of brackets will not be executed. Then the code will check if one equals two. Since this is also false, the code inside the final else statement will execute, and "one is less that two" will be printed.

if (1 > 2) {
    System.out.println("one is greater than two");
} else if (1 == 2) {
    System.out.println("one equals two");
} else {
    System.out.println("one is less than two");
}

While-Loop

While-loops will continuously execute the code inside of it as long as its argument resolves to true.

In this example, all of the integers from 1 to 10 will be printed out. However, when the number reaches 11, the condition number<=10 will be false, so the loop will terminate.

int number = 1;
while (number <= 10) {
    System.out.println(number);
    number++;
}

While-loops can also be used to create infinite loops if the condition is always true. For example, this code will print out numbers starting at one and continuing on to infinity until the program is manually terminated. Always be careful not to accidentally create infinite loops in your code, or your program will never finish.

int number = 1;
while (true) {
    System.out.println(number);
    number++;
}

One way to prevent infinite loops is to terminate a loop early using break. This keyword tells the compiler to exit the current innermost control statement that is not an if- or else-statement. This example will print out the numbers from 1 to 10, then break from the loop because number==10 will be true.

int number = 0;
while (true) {
    System.out.println(number);
    number++;
    if (number == 10) break;
}

There is another keyword, continue, that skips to the end of the current iteration of a loop. This code will only print out the even numbers from 1 to 10.

int number = 1;
while (number <= 10) {
    if (number%2 == 1) continue;
    System.out.println(number + " is even");
}

Do-While Loop

Do-while loops work similarly to while-loops. The main difference is that in a do-while loop, the code is executed once before the condition is evaluated.

In this example, although 1>2 evaluates to false, since the code is executed before the argument is checked, the code will still print out "one is greater that two" one time.

do {
    System.out.println("one is greater than two");
} while (1>2);

For-Loop

For-loops are another type of loop that keeps track of a value and continually executes code according to that value. A for-loop has three arguments. The first argument declares and assigns a variable, usually an int. The second gives a condition for which the loop will execute code. The third argument describes how the value will change with each execution of the bracketed code.

This for-loop is another way to print the integers from one to ten. The variable a starts at one. Every time the for-loop executes, the value of a increases by one. The loop terminates once a equals eleven, which invalidates the condition that a<=10, so 11 will not be printed.

for (int a = 1; a <= 10; a++) {
    System.out.println(a);
}

Note that a for-loop is essentially just a shorthand for a while-loop that executes a set number of times. The same code could be created using the while-loop from earlier.

int a = 1;
while (a <= 10) {
    System.out.println(a);
    a++;
}

Switch-Statement

Switch statements are given an argument and execute different code depending on the value of that argument, called the "case".

This code will execute depending on the value of day. If day is not equal to any of the provided cases, then the default case will execute. After each case, put the line break; This line of code tells the compiler to exit the control statement rather than continuing on to the other cases.

int day = 1;
switch (day) {
    case 1: System.out.println("Today is Monday"); break;
    case 2: System.out.println("Today is Tuesday"); break;
    case 3: System.out.println("Today is Wednesday"); break;
    case 4: System.out.println("Today is Thursday"); break;
    case 5: System.out.println("Today is Friday"); break;
    case 6: System.out.println("Today is Saturday"); break;
    default: System.out.println("Today is Sunday");
}

Comments

Commented code is ignored by the compiler. Comments are essential to document and keep track of your code and help other people understand it. They are also often used to temporarily remove code for debugging purposes.

Single-line Comments - Compiler ignores all code on the line after a // symbol

// This code will not be executed

Multi-line Comments - Compiler ignores all code between the /* and */ symbols

/*
   This code will not
   be executed either
*/

Javadoc Comments - Comments that start with /** span multiple lines and can use Javadoc to document code. When your cursor is over something that has a Javadoc comment a tool-tip will appear that has information from the comment on it (the tool-tip is an Eclipse feature, not part of the Java language).

/**
 * A javadoc comment.
 */


Next Lesson: Object-Oriented Programming