Java Tutorial/Variables
< Java Tutorial
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;
Basic Data Types
The basic "types" you can use are as follows:
intAn integer like 32
floatA number with a decimal like 2.7
doubleA double precision number with a decimal like 3.141
booleanA value that represents true or false
charA character, like 'c' or 'n'
StringText, 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
Math with Numbers
There are several variables you can use with numbers, and here are two:
Arithmetic Operators
+Adds two numbers togethermyInt + otherInt; would add myInt and otherInt together
-Subtracts one number from anothermyInt - otherInt would subtract otherInt from myInt
*Multiplies two numbersmyInt * otherInt
/Divides one number by anothermyInt / otherInt
%Divides one number by another and produces the remaindermyInt % 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.
An array is a set of values.
Each [x] section is one of the "thing". As you can see, they begin not at 1 but at 0. An example of declaring an integer array:
int size = 4;int[] myIntArray = new int[size];
Once the array is created, you can access individual elements in the array as if they were variables (e.g. myIntArray[0], myIntArray[1] and so on.)
The details of arrays will be discussed in a later lesson.
Data Structures
(To be added)
Previous:Hello World!Up:Java TutorialNext:Control Structures I - Decision structures
Last edited on 31 March 2018, at 21:25
Content is available under CC BY-SA 3.0 unless otherwise noted.
Privacy policy
Terms of Use
HomeRandomLog inSettingsDonateAbout WikiversityDisclaimers