Notes on Java
- Printing
- Variable
- Data Types
- Operators
- Conditionals
- Loops
- Exception handling
- Scanner: User input
- Reference
System.out.print("Hello World")
System.out.println("Hello World") // Adds new line character
It has two parts that needs to be defined: setting the data type and the variable name.
String my_variable;
- Java does not allow different variables to have the same name - regardless of data type.
- Additionally, Java does not allow spaces in variable names - either user camelCase or snake_case to separate words.
- Since Java variables are case sensitive, var and Var are different variables.
We can either assign variables combined with the declaration, or assign or re-assign values after the declation step.
int value;
value = 5;
int new_value = 10;
Here are the basic rules for variable names:
- Start with a letter, dollar sign or underscore
- Remainder of variable name is letters, numbers, or underscores
- Cannot use a Java keyword
- Variables are case sensitive
int number = 5000;
float
uses 4 bytes and double
uses 8 bytes.
double fraction = 0.5;
boolean thisIsTrue = true;
boolean thisIsFalse = false;
String
variable value must be surrounded by quotation marks. Single quotation mark does not work.
String words = "This is a string";
Concatenate strings with +
sign.
String variable = "This is " + "a concatenated string.";
// convert int to a double
int a = 5;
int b = 2:
System.out.println((double) a / b) // cast variable a from type int to type double
// The result will be "53" because Java will convert 5 into a String
int a = 5;
String b = "3";
System.out.println(a + b);
// The result will be 8 because Integer.parseInt(b) will convert b from String to int
int a = 5;
String b = "3";
System.out.println(a + Integer.parseInt(b));
- Parse a String to a different type:
Integer.parseInt()
Double.parseDouble()
Boolean.parseBoolean()
- Convert a different type to a String
String.valueOf()
-
=
: Assign value to a variable.
-
+
: Addition operator -
-
: Subtraction operator -
a++
: Increment the variablea
by 1. Decrement variablea--
. -
a+=x
: Increment the variablea
by x. Decrement variable a by xa-=x
. -
/
: Division operator. -
a/=b
:a = a / b
- Interger division: Division between two
int
returns andint
by removing the decimal part. -
%
: Performs the division but returns the remainder -
*
: Performs multiplication -
a *= b
:a = a * b
- Java uses the PEMDAS method for determining order of operations.
- P: Parentheses
- E: Exponents: powers and square roots
- MD: Multiplication and division - left to right
- AS: Addition and Subtraction - left to right
-
==
: Check if two values are equal -
!=
: Check if two values are not equal -
<
and<=
: Less and less than or equal operator -
>
and>=
: Greater and greater than or equal operator -
&&
: and operator -
||
: or operator -
!
: not operator - Short-circuting: If Java can determine the result of a boolean expression before evaluating the entire thing, it will stop and return the value.
- When evaluating complex boolean expresssions involving arithmetic operators
- Evaluate all arithmetic operators according to PEMDAS
- Evaluate all boolean operators (order: parenthesis, not, and, or)
- If statements in Java must contain the following items:
- the keyword if
- a boolean expression in parentheses
- curly braces surrounding all lines of code that will run if the boolean expression is true
- It is best practice to also indent the lines of code inside the curly braces to visually differentiate them from the commands that will always run.
// Example of if statement
if(5 > 4) {
System.out.println("1st command if true");
System.out.println("2nd command if true");
}
System.out.println("I will always print!");
// Example of if statement using a compound conditional statement
int num = 16;
if (num % 2 == 0 && num > 10) {
System.out.println("Even and greater than 10");
}
// Example of if else statement
if (5 > 4) {
System.out.println("The boolean expression is true");
}
else {
System.out.println("The boolean expression is false");
}
Nesting if else statements is more efficient than writing many if statements because nesting will interrupt the search as soon as one of the conditions is satisfied, while all the if statements are executed independent of conditions being satisfied.
int grade = 62;
if(grade < 60) {
System.out.println("F"); }
else if(grade < 70) {
System.out.println("D"); }
else if(grade < 80) {
System.out.println("C"); }
else if(grade < 90) {
System.out.println("B"); }
else if(grade <= 100) {
System.out.println("A"); }
- Here are the rules for writing a switch case statement:
- Start with
switch
followed by the variable that is going to be tested in parentheses()
- All of the cases are surrounded by curly braces
{}
- Each case is followed by a value (numeric or String) and a colon
:
- After each
:
write the code that should run if the variable is equal to that value - After each section of code, include
break;
- As the very last case, use
default:
and specify what should happen if none of the above cases are true
- Start with
// Switch case example
int dayOfWeek = 3;
switch(dayOfWeek) {
case 1: System.out.print("Sunday"); //only prints if dayOfWeek == 1
break;
case 2: System.out.print("Monday"); //only prints if dayOfWeek == 2
break;
case 3: System.out.print("Tuesday"); //only prints if dayOfWeek == 3
break;
case 4: System.out.print("Wednesday"); //only prints if dayOfWeek == 4
break;
case 5: System.out.print("Thursday"); //only prints if dayOfWeek == 5
break;
case 6: System.out.print("Friday"); //only prints if dayOfWeek == 6
break;
case 7: System.out.print("Saturday"); //only prints if dayOfWeek == 7
break;
default : System.out.print("Invalid"); //only prints if none of the above are true
}
// Switch case example with same command accross multiple cases
int grade = 62;
int letterGrade = grade / 10;
switch(letterGrade) {
case 10: case 9: System.out.print("A");
break;
case 8: System.out.print("B");
break;
case 7: System.out.print("C");
break;
case 6: System.out.print("D");
break;
default : System.out.print("F");
}
- If Else is used for ranges - Switch Case is for values
- If Else is used for handling multiple variables
- Switch case can only compare against values - not variables.
- If Else is used for compound conditionals
for(int i = 0; i < 5; i++) {
System.out.println("Loop #" + i);
}
- Same result implemented with for loop and while loop
// Example with for loop
for (int i = 0; i < 5; i++) {
System.out.println("Loop#: "+i);
}
// Same example with while loop
int i = 0;
while (i < 5) {
System.out.println("Loop# "+i);
i++;
}
- When to use a
while
loop-
while
loops are actually more useful when you are waiting for a certain event to occur but you don't know how many iterations it will take.
-
- Infinite loop with break statement
while(true){
System.out.println("This is an infinite loop");
int randNum = random.nextInt(100) + 1; // random integer between 1 and 100
if(randNum > 75){
System.out.println("The loop has ended");
break; // stop and exit the loop
} // close if condition
} // close while loop
// Nested loop example
for(int row = 0; row < 10; row++){
for(int col = 0; col < 10; col++) {
System.out.print("#");
}
System.out.println(""); //adds new line
}
// Example using exception handling via try and catch
double result = 0;
double input;
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Enter a number to add to sum. ");
System.out.println("Or enter a non-number to quit and calculate sum.");
try {
input = Double.parseDouble(sc.next());
result = result + input;
}
catch (NumberFormatException ignore) {
System.out.println("Sum = " + result);
break;
}
}
sc.close();
// Example using user input with Scanner
double result = 0;
double input;
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Enter a number to add to sum. ");
System.out.println("Or enter a non-number to quit and calculate sum.");
try {
input = Double.parseDouble(sc.next());
result = result + input;
}
catch (NumberFormatException ignore) {
System.out.println("Sum = " + result);
break;
}
}
sc.close();