Java Tutorial/Variables

From Wikiversity

Jump to: navigation, search

Note: Some examples in this section do not have the class declaration and main method declaration parts. You can copy this from the previous lesson and place any code within the main method.

You can assign, edit, and retrieve data from variables. Before doing any of this, however, you must declare them, as follows:

type name;

Contents

[edit] Basic Data Types

The basic "types" you can use are as follows:

Name Description
int An integer
float A number with a decimal
double A double precision number with a decimal
boolean A value that represents true or false
char A character, like 'c'
String Text, like "Hello, World!"

Therefore, you can declare integer myInteger like:

int myInteger;

To assign a value to a variable (that has been declared) you can use the assignment operator "=":

int myInteger;
myInteger = 3;

You can also use a shorter method by providing a variable initializer:

int myInteger = 3; //combine two steps into one

You can retrieve the value of a variable simply by typing its name, like:

int myInteger = 3;
System.out.println(myInteger); //print the integer

[edit] Math with Numbers

There are several variables you can use with numbers, and here are two:

Arithmetic Operators
Symbol Description Example
+ Adds two numbers together myInt + otherInt; would add myInt and otherInt together
- Subtracts one number from another myInt - otherInt would subtract otherInt from myInt
* Multiplies two numbers myInt * otherInt
/ Divides one number by another myInt / otherInt
% Divides one number by another and produces the remainder myInt % otherInt

For example (including class and main method declarations):

public class AddTwoNumbers {
    public static void main(String[] args) {
        float num1 = (float) 1.5;   // The "(float)" "casts" the number as a single precision number
        float num2 = (float) 1.7;   // Without the cast, the Java compiler will interpret a number with a decimal point
                                    // as a double precision constant.
        System.out.println(num1 + num2); // would output 3.2
    }
}

Note: Java uses order of operations in its math.

[edit] Arrays

(To be added)

[edit] Data Structures

(To be added)

[edit] Excercises

  • Add, subtract, multiply, and divide numbers and see what weird things you get (like dividing integers, and storing into another integer when it isn't exact)
  • Check out the remainder operator, for example: 5 % 4
Previous: Hello World! Up: Java Tutorial Next: Control Structures I - Decision structures