JAVA
=====
Java is a compiled programming language, meaning the code we write in a .java file
is transformed into byte code by a compiler before it is executed by the Java
Virtual Machine on your computer.
A compiler is a program that translates human-friendly programming languages into
other programming languages that computers can execute.
Addition (+=)
Subtraction (-=)
Multiplication (*=)
Division (/=)
Modulo (%=)
numCupcakes = numCupcakes + 8; // Value is now 20
numCupcakes += 8; // Value is now 20
For the purposes of this lesson (as well as good practice) remember to
use .equals() instead of == when comparing objects.
To use it, we call it on one String, by using ., and pass in the String to compare
against in parentheses:
String person1 = "Paul";
String person2 = "John";
String person3 = "Paul";
System.out.println(person1.equals(person2));
// Prints false, since "Paul" is not "John"
System.out.println(person1.equals(person3));
// Prints true, since "Paul" is "Paul"
Concatnate
String username = "PrinceNelson";
System.out.println("Your username is: " + username);
This code will print:
Your username is: PrinceNelson
int balance = 10000;
String message = "Your balance is: " + balance;
System.out.println(message);
This code will print:
Your balance is: 10000
public Store() {
System.out.println("I am inside the constructor method.");
}
// main method is where we create instances!
public static void main(String[] args) {
System.out.println("Start of the main method.");
// create the instance below
Store lemonadeStand = new Store();
// print the instance below
System.out.println(lemonadeStand);
}
}
Parameter:
public class Car {
String color;
int mpg;
boolean isElectric;
// constructor 1
public Car(String carColor, int milesPerGallon) {
color = carColor;
mpg = milesPerGallon;
}
// constructor 2
public Car(boolean electricCar, int milesPerGallon) {
isElectric = electricCar;
mpg = milesPerGallon;
}
}
============Declaration, Initialization, and Assignment==========================
// Declare a 2d array of float values called floatTwoD
float[][] floatTwoD;
// Initialize the 2d array from the last step to an empty 2d array
consisting of 4 arrays with 10 elements each
floatTwoD = new float[4][10];
// Declare and initialize an empty 2d array of integers consisting of
15 rows and 8 columns called dataChart
int[][] dataChart = new int[15][8];
// Create a 2D char array called ticTacToe representing the provided
tic-tac-toe board using initializer lists. Use the characters 'X', 'O', and ' '.
char[][] ticTacToe = {{'X', 'O', 'O'}, {'O', 'X', ' '}, {'X', ' ', 'X'}};
// When no one is looking, you want to modify the game to where you,
'O', wins the game. Replace the game board so that all X’s are O’s and all O’s are
X’s. Do this in one line with initializer lists.
ticTacToe = new char[][] {{'O', 'X', 'X'}, {'X', 'O', ' '}, {'O', ' ', 'O'}};
==================Accessing Elements in a 2D Array================
String[] words = {"cat", "dog", "apple", "bear", "eagle"};
/ Store the first element from the String array
String firstWord = words[0];
// Store the last element of the String array
String lastWord = words[words.length-1];
// Store an element from a different position in the array
String middleWord = words[2];
// Given a 2D array of integer data
int[][] data = {{2,4,6}, {8,10,12}, {14,16,18}};
// Access and store a desired element
int stored = data[0][2];
Ans-6
int[][] intMatrix = {
{1, 1, 1, 1, 1},
{2, 4, 6, 8, 0},
{9, 8, 7, 6, 5}
};
// Access the integer at the first row and fourth column of intMatrix
and store it in a variable called retrievedInt
int retrievedInt = intMatrix [0][3];
// Print 3 times the center value of intMatrix to the console. Make
sure to access the correct element!
System.out.println(3 * intMatrix[1][2]);
====================Modifying Elements in a 2D Array=============
import java.util.Arrays;
public class Modifying {
public static void main(String[] args) {
// Using the provided 2D array
int[][] intMatrix = {
{1, 1, 1, 1, 1},
{2, 4, 6, 8, 0},
{9, 8, 7, 6, 5}
};
// Replace the number 4 in the 2D array with the number 0
intMatrix[1][1] = 0;
// Declare and initialize a new empty 2x2 integer 2D array called
subMatrix
int[][] subMatrix = new int[2][2];
// Using 4 lines of code, multiply each of the elements in the 2x2 top
left corner of intMatrix by 5 and store the results in the subMatrix you created.
Afterwards, uncomment the provided print statement below.
subMatrix[0][0] = intMatrix[0][0] * 5;
subMatrix[0][1] = intMatrix[0][1] * 5;
subMatrix[1][0] = intMatrix[1][0] * 5;
subMatrix[1][1] = intMatrix[1][1] * 5;
System.out.println(Arrays.deepToString(intMatrix));
System.out.println(Arrays.deepToString(subMatrix));
}
}
Result:
[[1, 1, 1, 1, 1], [2, 0, 6, 8, 0], [9, 8, 7, 6, 5]]
[[5, 5], [10, 0]]
=====================nested loop=========================
public class NestedLoops {
public static void main(String[] args) {
int[] seatsDayOne = {850007, 841141, 150017, 622393, 178505, 952093,
492450, 790218, 515994, 926666, 476090, 709827, 908660, 718422, 641067, 624652,
429205, 394328, 802772, 468793, 901979, 504963, 733939, 706557, 724430, 663772,
577480, 886333, 323197, 283056, 378922, 628641, 494605, 606387, 179993, 755472,
253608, 975198, 328457, 885712, 411958, 418586, 254970, 299345, 632115, 915208,
661570, 328375, 538422, 321303};
int[] seatsDayTwo = {740912, 209431, 310346, 316462, 915797, 850440,
803140, 459194, 293277, 302424, 790507, 711980, 639916, 707446, 940339, 613076,
524157, 189604, 595934, 509691, 234133, 787575, 674602, 944308, 710345, 889699,
622393, 151931, 964325, 944568, 357684, 933857, 541190, 935076, 468848, 449446,
278951, 885503, 539124, 278723, 998622, 846182, 394328, 914002, 803795, 851135,
828760, 504936, 504322, 648644};
int matchCounter = 0;
// Fix the outer loop header to iterate through the first array of
seats
for(int i = 0; i < seatsDayOne.length; i++) {
// Fix the inner loop header to iterate through the second array
of seats
for(int j = 0; j < seatsDayTwo.length; j++) {
// Replace 1==2 with conditional logic to check if an
element in the first array matches an element in the second array
if(seatsDayOne[i]==seatsDayTwo[j]) {
matchCounter++;
System.out.println("Contestant: " + seatsDayOne[i] +
", Seat Day One: " + i + ", Seat Day Two: " + j);
break;
}
}
}
System.out.println("The total number of contestants reserving seats on
both days was: " + matchCounter);
}
}
Result:
Contestant: 622393, Seat Day One: 3, Seat Day Two: 26
Contestant: 394328, Seat Day One: 17, Seat Day Two: 42
The total number of contestants reserving seats on both days was: 2
===========Traversing 2D Arrays: Introduction===============
public class Introduction {
public static void main(String[] args) {
//Given the provided 2d array
int[][] intMatrix = {
{ 4, 6, 8, 10, 12, 14, 16},
{18, 20, 22, 24, 26, 28, 30},
{32, 34, 36, 38, 40, 42, 44},
{46, 48, 50, 52, 54, 56, 58},
{60, 62, 64, 66, 68, 70, 79}
};
// Store the number of subarrays of intMatrix into a variable called
'numSubArrays'
int numSubArrays = intMatrix.length;
System.out.println(numSubArrays);
// Store the length of the subarrays using the first subarray in
intMatrix. Store it in a variable called subArrayLength.
int subArrayLength = intMatrix[0].length;
System.out.println(subArrayLength);
// Store the number of columns in intMatrix into a variable called
'columns'
int columns = subArrayLength;
int rows = numSubArrays;
// Store the number of rows in intMatrix into a variable called 'rows'
// Replace the outer and inner for loop headers to iterate through the
entire 2D array. Use the iterators `i` for the outer loop and `j` for the inner
loop.
int sum = 0;
for(int i=0; i<rows; i++) {
for(int j = 0; j < columns; j++) {
// Insert a line of code to increase the variable `sum` by
each accessed element
sum += intMatrix[i][j];
}
}
System.out.println(sum);
}
}
Result:
5
7
1337
===========================Traversing 2D Arrays: Practice with
Loops============================
public class LoopPractice {
public static void main(String[] args) {
String[][] wordData = {{"study", "consider", "examine", "learn"},
{"ponder", "read", "think", "cogitate"}};
//Use nested enhanced for loops to calculate the total number of
characters in the wordData 2D array and print the result to the console. (Get the
string .length() of each element)
int characterCount = 0;
for (String[] wordRow : wordData) {
for (String word: wordRow) {
characterCount += word.length();
}
}
System.out.println(characterCount);
//Using nested while loops, iterate through all of the elements in the
2D array and print them to the console using the format: word [row][column]. The
formatted print statement has been provided.
int i = 0, j = 0;
while (i < wordData.length) {
j = 0;
while (j < wordData[i].length) {
System.out.println(wordData[i][j] + ": [" + i + "]" + "[" + j + "]");
j++;
}
i++;
}
}
}
Result
study: [0][0]
consider: [0][1]
examine: [0][2]
learn: [0][3]
ponder: [1][0]
read: [1][1]
think: [1][2]
cogitate: [1][3]
============