one of the main reason that java is such an important language in the coding world is because it is a object-oriented-programming (OOP) language.
it offers a structure that is easy to solve big problems. but i think that we all know that so lets skip to the real deal.
Block Comments- The compiler will ignore any text between /* and */
line comments- Same as above but // ignores one line
Class Declaration - identifies the name, the start and the end of the class. the class name must match the file name. (case sensitive)
main Method- controls all of the action in the program.
system.out- objects that generate output to the console
system.out.print- prints what ever you out inside the ()
system.out.println- prints whatever is one the screen and moves to the next line to print out the next action. basically hits enter after it prints out.
tip: add “<classname>.main(null)
” at the end of your code to see the output in your jupyter notebook.
/* this is a
code block */
// code: printing out hello world.
public class greeting {
public static void main (String [] args) {
System.out.println("Hello, World!");
System.out.print("Hello,");
System.out.print(" World!");
}
}
greeting.main(null)
Hello, World!
Hello, World!
Examples:
public class stingLiterals {
public static void main (String [] args) {
System.out.println("This is a string literal.");
System.out.println("and so are these");
System.out.println("1234567890");
System.out.println("&^&*%^$&%$#^%W#*^$%&(*^)");
}
}
stingLiterals.main(null)
This is a string literal.
and so are these
1234567890
&^&*%^$&%$#^%W#*^$%&(*^)
public class syntaxError {
public static void main (String [] args) {
System.out.println("This is a syntax error.")
//missing semicolon
}
}
syntaxError.main(null)
| System.out.println("This is a syntax error.")
';' expected
public class logicError {
public static void main (String [] args) {
System.out.println("This is a leogic error.");
}
}
logicError.main(null)
This is a leogic error.
public class exceptionError {
public static void main(String[] args) {
try {
int result = 2 / 0;
System.out.println("Result: " + result);
} catch (ArithmeticException e) { //this just makes the error more verbose
e.printStackTrace();
}
}
}
exceptionError.main(null)
java.lang.ArithmeticException: / by zero
at REPL.$JShell$20$exceptionError.main($JShell$20.java:19)
at REPL.$JShell$21.do_it$($JShell$21.java:16)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:578)
at io.github.spencerpark.ijava.execution.IJavaExecutionControl.lambda$execute$1(IJavaExecutionControl.java:95)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)
at java.base/java.lang.Thread.run(Thread.java:1623)
Boolean, takes up 1 bit.
Int, take up 32 bit
Doubles, AKA Floating point numbers. 64 bit
String
Reference Purposes
(the collegeboard person used bows as reference so will i.)
Choices:
1. int
2. double
3. boolean
4. String
__ False
__ "ryan gosling"
__ 1738
__ 4.26
what type of data should be used to store
someones bank number and cvc?
someones mother’s maiden name and their name?
the first 16 digits of pi
if you want to transact one million $.
A name given to a memory location that is holding a specified type of value.
may consists of letters, digits, or an underscore (case sensitive)
use camel casing when naming a variables.
thisIsCamelCasing
The three primitiva data types in Java:
int
double
boolean
dataType varibleName;
int total;
boolean outcome;
double firstFifteenPi;
add final in front of the declaration:
final double PI;
final boolean WORKOUT_DECISION;
for final variables, use all caps and underscore when naming them.
int value;
double 4eva;
boolean private;
integer sum;
double wow!;
boolean foundIt;
int numberOfStudents;
double chanceOfRain;
boolean #mortNews; # <—— THIS IS THE ODD ONE
int count;
bool isFriday;
final int DOZEN;
public class demo {
public static void main(String[] args) {
// Whats is the outputs between these two pieces of code
//
//
//
System.out.println("3" + "3");
System.out.println(3 / 2);
System.out.println(2.0 * 1.5);
}
}
demo.main(null);
33
1
3.0
public class demo2 {
public static void main(String[] args) {
// Print a math equation that goes through these steps
// Adds 19 + 134
// Multiplies that value by 5
// Then takes the mod of that value by 2
// It should print 1
System.out.println( (19 + 134) * 5 % 2);
}
}
demo2.main(null);
public class OddEven {
// Without changing any varibles
// Print only odd numbers
public static void main(String[] args) {
int num = 2;
int i = 0;
while (i <= 10) {
if (i % num == 0) {
System.out.println(i + " is even");
}
i++;
}
}
}
OddEven.main(null);
look at storing items in variables with assignment statemt.
also look at compound assignment operators (+=, -= etc) to modify values stored in variables in one step
+= adds value to existing variable value
x += 7 is equivalent to x = x + 7; x -= 5 is equivalent to x = x - 5;
same for all compound assignment operators.
public class CompoundDemo {
public static void main(String[] args) {
int x = 6;
x += 7; // 6 + 7 = 13
x -= 3; // 13 - 3 = 10
System.out.println(x);
x *= 10; // 10 * 10
x /= 5; // 100 / 5 = 20
System.out.println(x);
x %= 3; // remainder of 100/3 = 2
System.out.println(x);
}
}
CompoundDemo.main(null);
// NOTE: going through these compound assignments with comments is called tracing,
// when we do what the compiler does, and go through the code step by step. Should be
//done on the AP test to avoid human error.
10
20
2
IMPORTANT: THE USE OF INCREMENT AND DECREMENT OPERATORS IN THE PREFIX FORM (++X) AND INSIDE OTHER EXPRESSIONS (ARR[X++]) IS OUTSIDE THE SCOPE OF THE COURSE AND THE AP EXAM
public class incdecDemo {
public static void main(String[] args) {
int x = 1;
int y = 1;
x++; // x = x + 1, x = 2;
y--; // y = y - 1, y = 1 - 1 = 1;
System.out.println(x);
System.out.println(y);
}
}
incdecDemo.main(null);
// NOTE: going through these compound assignments in order is important to
// ensure you get the correct output at the end
the following code segment has comments that describe the line of code the comment is on. Look at how the code is described.
public class behaviorDemo {
public static void main(String[] args) {
int x = 20; // define an int variable x and set its initial value to 23
x *= 2; // take the current value of x, multiply it by 2, assign the result back to x
x %= 10; // take the current value of x, find x modulus 10 (remainder x divided by 10),
//assign result back to x
System.out.println(x); // display the current value of x
}
}
behaviorDemoDemo.main(null);
public class Numbers {
public static void main(String[] args) {
int x = 777;
// challenge: think of 2 compound assignment operators that can be used in tandem to get the following outputs
// example: if we wanted output of 1 with 2 compound assigment operators, using x++; and x /= 777 would work. now how would we do that for:
// 100?
x /= 7;
x -= 11;
System.out.println(x);
// 779?
x += 679;
System.out.println(x);
// 2?
x-=777;
System.out.println(x);
}
}
Numbers.main(null);
100
779
2
public class CompoundDemo {
public static void main(String[] args) {
int x = 758;// initial value
x += 423; // add this
x -= 137; // subtract this
x *= 99; // multiply by this
x /= 33; // divide by this
x %= 111; // calculate remainder
System.out.println(x);// print
}
}
CompoundDemo.main(null);
24
int x = 5;// x is 5
x++; // x+1 = 6
x /= 2;// 6/2 = 3
System.out.println(x);// This is to print out the outcome of x
3
compound operators perform an operation on a variable and assign the result to the variable
ex: x /= 25; would take x and divide it by 25, then assign the result to x.
if x = 100, then the result of x/= 25; would be 4.
increment and decrement operators take x and either increment it or decrement it by 1, then assign the value to x.
x++; would take x and add 1 to it, then assign the value to x.
x–; takes x and subtracts 1 from x, then assigns the value to x.
public class CompoundAssignment {
public static void main(String[] args) {
int sum = 0;
for (int i = 0; i < 2; i++) { // i = i + 1 each iteration, 1st iteration i = 0
for (int j = 0; j < 2; j++) { // j = j + 1 each iteration, 1st iteration j = 0
System.out.println("i: " + i);
System.out.println("j: " + j);
sum += i + j; // sum = sum + (i + j) each iteration, 1st iteration sum = 0 + (0 + 0)
System.out.println(sum);
}
}
System.out.println("Sum: " + sum);
} }
CompoundAssignment.main(null);
i: 0
j: 0
0
i: 0
j: 1
1
i: 1
j: 0
2
i: 1
j: 1
4
Sum: 4
public class CompoundOperatorsExample {
public static void main(String[] args) {
int x = 5;
int y = 10;
// Using compound operator to increase x by 3
x += 3; // x becomes 8
// Conditional check and using compound operator
if (x > y) {
y *= 2; // y becomes 20 if this condition is true
} else {
x *= 2; // x becomes 16 if this condition is true
}
// Using compound operator to decrease y by 5
y -= 5; // y becomes 15
// Conditional check and using compound operator
if (x < y) {
x += y; // x becomes 31 if this condition is true
} else {
y += x; // y becomes 35 if this condition is true
}
System.out.println("x: " + x);
System.out.println("y: " + y);
}
}
CompoundOperatorsExample.main(null);
x: 16
y: 21
CASTING
"Change the data type of variable from one type to another."
public class CastingNumbers {
public static void main(String[] args) {
System.out.println(6 / 4);
System.out.println (6.0 / 4);
System.out.println(6 / 4.0);
}
}
CastingNumbers.main(null)
1
1.5
1.5
int: Stored by using a finite amount (4 bytes) of memory.
Max: 2,147,483,647
Min: -2,147,483,648
up to 14 - 15 digits for storage
only 2 (true and false)
/*
* Purpose: Demonstrate Integer Range
*/
public class TooBigNumber {
public static void main(String[] args) {
int posInt = 2147483647;
int negInt = -2147483648;
System.out.println(posInt + " ");
System.out.println(negInt);
}
}
TooBigNumber.main(null);
/*
* Purpose: Demonstrate Integer.MAX_VALUE and Integer.MIN_VALUE.
*/
public class IntMinMax {
public static void main(String[] args) {
int posInt = Integer.MAX_VALUE;
int negInt = Integer.MIN_VALUE;
System.out.println(posInt + " ");
System.out.println(negInt);
}
}
IntMinMax.main(null);
/*
* Purpose: Demonstrate Integer Overflow
*/
public class TooBigNumber {
public static void main(String[] args) {
int posInt = Integer.MAX_VALUE;
int negInt = Integer.MIN_VALUE;
System.out.println(posInt + 1);
System.out.println(negInt - 1);
}
}
TooBigNumber.main(null);
import java.util.Scanner;
public class Sum_forABC {
public static void main(String args[]) {
int a = 70;
int b = 63;
int c = 82;
int total = a + b + c;
double avg = total / 3;
System.out.println("a\tb\tc");
System.out.println(a+"\t"+b+"\t"+c);
System.out.println("total:" + total);
System.out.printf("average: %.2f", avg);
}
}
Sum_forABC.main(null);
<!DOCTYPE html>
1. what will be the output of (int) (2.5 * 3.0)
2. what will be the output of (double) 25 / 4
3. what will be the output of 6 / (double) 5
4. what will be the output of (int) (-8.63 - 0.5)
Winner of the game is represented by gameWin. Player 1 score is represented by int variable x, and Player 2 score is represented by int variable y
public class Game {
int x = 0;
int y = 0;
boolean XgameWin = false;
boolean YgameWin = false;
}
public class Game {
int x = 0;
int y = 0;
boolean XgameWin = false;
boolean YgameWin = false;
public void gameWinchange(boolean X, boolean Y) {
//insert code here
if (X == true) {
UpdateScore(x,y);
X = true;
} else {
UpdateScore(y,x);
Y = true;
}
}
}
Write a method to update score for Player 1 and Player 2, The player that wins gain a point, the player that loses minus a point If a player hits 10 points, reset values
public class Game {
//pretend previous method is above
public int UpdateScore(int Wscore, int Lscore) {
Wscore += 1;
Lscore -= 1;
if (Wscore == 10) {
Wscore = 0;
Lscore = 0;
}
if (Lscore == 10) {
Wscore = 0;
Lscore = 0;
}
}
}
public class BasketballGame {
public static void main(String[] args) {
int homePoints = 0;
int awayPoints = 0;
homePoints += 2;
awayPoints += 3;
homePoints += 1;
System.out.println("Score: Home " + homePoints + " - " + awayPoints + " Away");
}
}
BasketballGame.main(null);
Score: Home 3 - 3 Away
public class BasketballGame {
public static void main(String[] args) {
int homePoints = 0;
int awayPoints = 0;
homePoints += 2;
awayPoints += 3;
homePoints += 1;
System.out.println("Score: Home " + homePoints + " - " + awayPoints + " Away");
int totalPoints = homePoints + awayPoints;
double averagePoints = (double) totalPoints / 2;
homePoints += 6;
System.out.println("Updated Score: Home " + homePoints + " - " + awayPoints + " Away");
System.out.println("Total Points: " + totalPoints);
System.out.println("Average Points per Game: " + averagePoints);
}
}
BasketballGame.main(null);
Score: Home 3 - 3 Away
Updated Score: Home 9 - 3 Away
Total Points: 6
Average Points per Game: 3.0