2 - Learn Java - Variables Cheatsheet - Codecademy
2 - Learn Java - Variables Cheatsheet - Codecademy
Variables
Strings
A String in Java is a Object that holds multiple characters. // Creating a String variable
It is not a primitive datatype.
String name = "Bob";
A String can be created by placing characters between a
pair of double quotes ( " ).
To compare Strings, the equals() method must be used // The following will print "false"
instead of the primitive equality comparator == .
because strings are case-sensitive
System.out.println(name.equals("bob"));
float k = (float)12.5;
double pi = 3.14;
Static Typing
In Java, the type of a variable is checked at compile time. int i = 10; // type is int
This is known as static typing. It has the advantage of
char ch = 'a'; // type is char
catching the errors at compile time rather than at
execution time.
Variables must be declared with the appropriate data j = 20; // won't compile, no
type or the program will not compile.
type is given
char name = "Lil"; // won't compile,
wrong data type
final Keyword
The value of a variable cannot be changed if the variable // Value cannot be changed:
was declared using the final keyword.
final double PI = 3.14;
Note that the variable must be given a value when it is
declared as final . final variables cannot be changed;
any attempts at doing so will result in an error message.
result = a - b; // 10
result = a * b; // 200
result = a / b; // 2
result = a % b; // 0
Comparison Operators
Comparison operators can be used to compare two int a = 5;
values:
int b = 3;
> greater than
< less than
>= greater than or equal to boolean result = a > b;
<= less than or equal to // result now holds the boolean value true
== equal to
!= not equal to
They are supported for primitive data types and the result
of a comparison is a boolean value true or false .
Order of Operations
The order in which an expression with multiple operators
is evaluated is determined by the order of operations:
parentheses -> multiplication -> division -> modulo ->
addition -> subtraction.
Print Share