int foo = 5; // Integer
float bar = 40.25; // Float
boolean myBool = true; // Boolean
String message = "Hello World!"; // String
char grade; // Declaration
grade = 'B'; // Initialization
/* Other data types: byte, double, long */
int foo = 100;
foo++;
int bar = 10;
foo = foo - bar;
/*
+ : Addition - : Subtraction
* : Multiplication / : Division
% : Modulus Division
++ : Increase by 1 -- : Decrease by 1
*/
foo += 5; // Addition assignment operator
foo -= 8; // Subtraction assignment operator
if (age == 10) {
message = "one decade old";
}
if (age > 21)
{
message = "over 21";
}
else if (age < 21)
{
message = "under 21";
}
else
{
message = "exactly 21";
}
/*
== : Equal to != : Not Equal to
> : Greater than < : Less than
>= : Greater than or equal to <= : Less than or equal to
*/
int num = 0;
// While Loop
while (num < 100) {
num++;
}
int sum = 0;
// For Loop
for (int i = 0; i < 50; i++) {
sum += i; // adds all values from 0 to 49
}
// Creates an empty "scores" array that can store 20 integers
int[] scores = new int[20];
scores[0] = 92;
scores[1] = 87;
System.out.println( scores[0] ); // Prints 92
// Insert values at instantiation
// Size of array automatically matches number of items
string[] friends = { "Chris", "Jill", "Alex" };
public class Person {
public string name;
public int age;
private int ssn; // can't be accessed from outside instance
float wage; // fields are private by default
}
Person man = new Person();
man.name = "John";
man.age = 30;