[Go to site: main page, start]

Java Programming Basics and Notes

0% found this document useful (0 votes)
70 views6 pages
Java is a compiled programming language where code written in .java files is transformed into byte code by a compiler before being executed by the Java Virtual Machine. A compiler translates…

Uploaded by

haribabu ocr
  • Java Methods and Constructors
  • Introduction to Java
  • Java Compiler and Operators
  • String Manipulation
  • Array Initialization
  • Handling Multidimensional Arrays
  • Practical Exercises with Arrays
  • Array Traversal Techniques

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";

[Link]([Link](person2));
// Prints false, since "Paul" is not "John"

[Link]([Link](person3));
// Prints true, since "Paul" is "Paul"

Concatnate
String username = "PrinceNelson";
[Link]("Your username is: " + username);
This code will print:

Your username is: PrinceNelson

int balance = 10000;


String message = "Your balance is: " + balance;
[Link](message);
This code will print:

Your balance is: 10000

public Store() {
[Link]("I am inside the constructor method.");
}

// main method is where we create instances!


public static void main(String[] args) {
[Link]("Start of the main method.");

// create the instance below


Store lemonadeStand = new Store();
// print the instance below
[Link](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[[Link]-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!

[Link](3 * intMatrix[1][2]);

====================Modifying Elements in a 2D Array=============


import [Link];
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;

[Link]([Link](intMatrix));
[Link]([Link](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 < [Link]; i++) {

// Fix the inner loop header to iterate through the second array
of seats
for(int j = 0; j < [Link]; 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++;
[Link]("Contestant: " + seatsDayOne[i] +
", Seat Day One: " + i + ", Seat Day Two: " + j);
break;
}
}
}
[Link]("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 = [Link];
[Link](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;
[Link](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];

}
}
[Link](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 += [Link]();
}
}

[Link](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 < [Link]) {


j = 0;
while (j < wordData[i].length) {
[Link](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]
============

Common questions

Powered by AI

Modifying elements within a 2D array can impact the array's structure or the logic of subsequent operations as it alters the dataset's integrity and potential relationships between elements. For example, replacing elements changes the data representation, which could affect calculations, searches, or other logical operations. In examples, adjusting numbers for specific conditions might change totals or conditional checks within algorithms. Ensuring the accuracy and logic of operations relies on maintaining appropriate modifications to produce valid and intended results .

2D arrays can be traversed using nested loops where the outer loop iterates over rows, and the inner loop iterates over columns. Operations can be performed on each element systematically during the traversal. In the source example, a full sum of the elements within a 2D integer matrix is computed by iterating through each element and aggregating its value into a sum variable. Such traversal allows for operations like summing, searching, or modifying elements systematically across the entire dataset .

2D arrays in Java can be initialized using different methods, such as declaring first and initializing later (e.g., float[][] floatTwoD; followed by floatTwoD = new float[4][10]) or declaring and initializing in a single step using initializer lists (e.g., int[][] dataChart = new int[15][8]). Another method is using initializer lists with predefined elements (e.g., char[][] ticTacToe = {{'X', 'O', 'O'}, {'O', 'X', ' '}, {'X', ' ', 'X'}}). These methods provide flexibility in preparing arrays for specific data structures, requirements, or data manipulations .

In Java, value equality refers to comparing the actual content or values of objects, typically using the .equals() method, whereas reference equality checks whether the reference variables point to the same memory location, using the == operator. Value equality is best used for comparing objects based on their logical equivalence, such as when comparing string contents. Reference equality is appropriate when determining if two references point to the same object instance, such as when managing object identities or caching. Selecting between these depends on whether the logical content or the memory identity is of interest in the context .

Nested loops facilitate operations on 2D arrays by allowing iteration through each element across all rows and columns. The outer loop typically iterates over rows, while the inner loop iterates over columns within each row. This structure is essential for accessing or modifying each element systematically. However, performance considerations include the time complexity, which is often O(n^2) for a matrix with n elements, potentially leading to performance degradation for very large arrays, thus requiring optimization strategies like parallel processing or algorithmic improvements .

Constructors in Java serve as special methods that are called when an instance of a class is created. They initialize objects and set the initial state of an object by assigning values to its fields. Constructors contribute to object instantiation by enabling the setup of necessary resources or initial values, which ensures that objects are ready for use immediately after their creation. The provided constructors in the 'Car' class example show how constructors can be overloaded to provide different initialization paths for objects depending on the arguments passed during instantiation .

To efficiently find matching elements in two arrays, nested loops can be utilized where the outer loop iterates through the elements of the first array and the inner loop iterates through the elements of the second array. This approach allows checking each element of the first array against every element of the second array. Conditional logic inside the inner loop can identify matches and perform actions such as counting or printing matched pairs, as shown in the Java example where a matchCounter keeps track of matches .

The transformation of Java code into bytecode significantly enhances Java's portability because bytecode is a platform-independent code that can be executed on any device equipped with a Java Virtual Machine (JVM). This JVM abstracts the underlying hardware and operating system, allowing the same Java program to run on different platforms without modification. Hence, Java's "write once, run anywhere" capability is largely attributed to bytecode .

The Java 'Car' class example demonstrates encapsulation by defining private instance variables such as color, mpg, and isElectric, which can only be accessed and modified through the class's methods, specifically constructors in this case. This abstraction allows the internal state of an object to be shielded from direct modification from outside the class, thereby ensuring controlled access and modification. Encapsulation enhances maintainability, scalability, and security in object-oriented programming by restricting unauthorized access and modification .

In Java, using .equals() instead of == when comparing objects is crucial because .equals() checks for value equality, meaning it compares the actual contents of the objects. On the other hand, == checks for reference equality, which means it determines if both objects point to the same memory location. This distinction is important to ensure the correct comparison of objects' data rather than their memory addresses .

JAVA
=====
Java is a compiled programming language, meaning the code we write in a .java file 
is transformed into byte code
System.out.println(lemonadeStand);
  }
}
Parameter:
public class Car {
  String color;
  int mpg;
  boolean isElectric;
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
492450, 790218, 515994, 926666, 476090, 709827, 908660, 718422, 641067, 624652, 
429205, 394328, 802772, 468793, 901979, 5049
System.out.println(subArrayLength);
// Store the number of columns in intMatrix into a variable called 
'columns'
int col
System.out.println(wordData[i][j] + ": [" + i + "]" + "[" + j + "]");
        j++;
      }
      i++;
    }
}
}
Resul

You might also like