Java Basics
Computers store numbers, text, pictures, and other data as chains of 1's and 0's.
Each one or zero is a bit.
If you have 2 bits, you can represent the numbers 0 through 3:
That is called binary. Each column represents 2 raised to the power of the column number:
2 raised to power | 2^7 | 2^6 | 2^5 | 2^4 | 2^3 | 2^2 | 2^1 | 2^0 |
value | 0 or 128 | 0 or 64 | 0 or 32 | 0 or 16 | 0 or 8 | 0 or 4 | 0 or 2 | 0 or 1 |
example == 6 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 |
example == 45 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | 1 |
example == 255 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
Compare to decimal, which operates on the same logic, except it is 10 raised to the power, and each “bit” can store ten values (0-9), not just 2 (0 or 1).
10 raised to power | 10^7 | 10^6 | 10^5 | 10^4 | 10^3 | 10^2 | 10^1 | 10^0 |
value | 10,000,000 | 1000000 | 100000 | 10000 | 1000 | 100s | 10s | 0-9 |
example == 5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5 |
example == 45 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 5 |
A boolean is one bit, which can be on (1) or off (0). But in java we refer to it as true or false.
boolean b = true;
An int, or Integer has 32 bits, and can store numeric whole numbers ranging from -2,147,483,648 to + 2,147,483,648.
int i = 1024;
How are negative numbers represented in binary? They take the first (left-most) bit, and use that for the sign. 0 means positive, and 1 means negative. So the number part of an int really only uses 31 bits. For each bit you add, you double the amount of numbers that it can store (since it is binary).
A 32 bit computer processor means that the processor can operate on 32 bits at a time (during each processor cycle). So essentially it can “read” an int in one step.
A long is used when you need to store a larger range of whole numbers:
To signify that a numeric value is to be stored as a long instead of an int, you can add an “L” character after the number:
long bigvalue = 12345146L;
Use a double when you need more precision than just whole numbers.
double d = 1.243523; //you can also use scientific notation: double d2 = 3.24e2; //same as 324
A double uses 64 bits to store values, and has a range of: 4.94e-324..1.79e308
A float is like a double except it only uses 32 bits. It doesn't have as much precision as a double, but is much faster for a (32 bit) computer processor to operate on. Hence floats are often used in applications like 3D games, where speed is of the essence. Add an “f” character at the end of the value to signify that it is a float:
float f = 1.2f;
chars (characters) are 16-bit numbers used to represent letters and numbers for text (strings).
Each letter (lower-case and upper-case) and other special characters can be represented by a number. See ASCII & Unicode: http://en.wikipedia.org/wiki/ASCII
Letter or symbol | ASCII/Unicode values |
A to Z | 65-90 |
a to z | 97-122 |
0-9 | 48-57 |
$ | 36 |
\r (return) | 32 |
\n (newline) | 10 |
\t (tab) | 9 |
(space) | 32 |
You declare a char by surrounding the character with single quotes.
char c1 = 'a'; char c2 = 'B'; char unicodeExample = '\u00A9'; //copyright symbol
An array is a chain of objects or primitive data types.
You add two square brackets after the type name to denote this is an array instead of a single object:
And when instantiating the space for an array, you put the size in the brackets:
int[] numberArray = new int[10]; //an empty 10 item array of ints double[] doubleArray = new double[10];
To get or set the value of an item in an array, put the item number in the brackets, and zero refers to the first item, not one.
numberArray[0] = 100; //set first item in array numberArray[1] = 200; //set second item in array System.out.println(numberArray[1]); //print value of 2nd item
You can initialize multiple items in an array at once:
int[] threeItems = {150, 250, 350};
Strings (text) are similar to an array of characters. In fact in other languages like C or C++, strings ARE merely char arrays.
char javaChars = {'j', 'a', 'v', 'a'};
Strings
Strings are text, used for messages and the like. You use double quotes with strings.
String s = "some text";
String is a Java class, which has its own methods, like length(), or indexOf(char):
System.out.println(s.length());
You can “add” strings together to combine (concatenate) them:
String s2 = s + “ and some more” + “ text.”;
But see also the StringBuffer class:
Converting strings to numbers and back
null
If you don't initialize primitive numeric types, they default to zero:
int x; //default value is 0
Booleans default to false.
For objects and strings though (reference types), if you don't initialize them, the default value is "null" or nothing.
String s;
Dog d;
if (s == null) {...
More commonly, you check if something is NOT null first, otherwise you'll get a nullpointerexception error:
if (s != null) { ...
Operators
* times (can't use “x” since x is a letter)
/ divide (careful if you divide to ints, since it rounds down: 1 / 2 == 0, not 0.5, but 1.0/2.0==0.5 because the latter are doubles, not ints)
% modulus – modulus means “remainder”.
int r = 10 % 3; //equals 1, since 10 divided by 3 has a remainder of 1
Boolean even = (val % 2 == 0); //most common use of modulus, to check if number is even or odd Boolean odd = (val % 2 == 1);
== equals, or equivalent
&& and
Boolean a = true;
Boolean b = false;
Boolean c = true;
if (a && b) { //a and b true? -- no, false
if (a || b) { //a or b true? -- yes true
if (a && c) { //true because both a and c are true
if (!a) { //not a, false
if (!b) { //not b which is false, and not false equals true
Assignment
int x = 2;
in place assignments, these combine assignment plus math operators:
double d = 1.0; d += 1.5; //d == 2.5 d *= 4; //d == 10.0 d /= 2; //d == 5.0 d -= 1.0; //d == 4.0
instanceof – Is this object of this type (or a subclass of this type)?
if (cat instanceof Cat) //true if cat is an instance of Cat class if (cat instanceof Animal) //true if cat is an instance of a subclass of Animal
Operator Precedence
If you have multiple operators chained together, Java has rules for which operators have more precedence.
int v1 = 2 + 4 / 2; //equals 4, //because multiplication/division has precedence over add/subtract
But in general, use parentheses to make expressions with multiple operators more clear:
int v2 = (2 + 4) / 2; //equals 3
Control Flow
if (an expression is true) {
//do this if expression is true
} else {
//do this if not true
}
You can chain if statements:
if (expression1 is true) {
//do this if expression1 is true
} else if (expression2 is true) {
//do this if expression2 is true
} else {
//do this if neither expression 1 or 2 are true
}
while (expression is true) {
//keep repeating this until expression is false
}
There are 2 kinds of for loops.
for (declaration; expression; increment) {
//repeat this until the expression is false,
//and do the increment after each loop
}
//example:
for (int i=0; i<10; i++) {
//repeats from i==0 to i==9
}
The second kind is for looping through items in an array or collection:
(think of it as a “for each” loop. “For each item (named x or item or whatever) in this array, do this”)
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("This array item value is: " + item);
}
break & continue in a loop
When you insert a break; statement, the loop exits immediately.
If you insert a continue; statement, it skips the rest of the code in the loop and starts again on the next loop (other languages use the keyword skip instead of continue).
String[] names = {“Bill”, “Bob”, “Betty”, “Bubba”};
for (String name: names) {
if (name == “Betty”) {
foundIt = true;
break; //exit the loop, we found what we were looking for
}
}
switch..case
Not used that often, it lets you chain many many if tests.
Disclaimer
Any opinions expressed here, except as specifically noted, are those of the individual authors or commenters and do not necessarily represent the views or policies of the Department of Instructional Technology and Learning Sciences, the Emma Eccles Jones College of Education and Human Services, or Utah State University.