Lab 3
Lab 3
Lab 3
1. Write the change in memory after each line is executed in the following code:
From the previous output, what does the following statement means? “String is immutable
while StringBuffer is mutable.”
2. Write the change in memory after each line is executed in the following code:
a)
b)
What is the difference between the two blocks? Write a code to initialize index 2 in each
array.
1
3. Write a Java program that takes from the user the length of an array and creates it, and then
ask the user to enter a second number and then initialize the array with the multiples of that
number. For example, if the second number was 3, the initialization of the array will be 3,
6, 9, 12, 15 … and so on.
4. Write a Java method that takes an array as an input and an integer called searchNumber.
The purpose of that method is to return the number of occurrence of the searchNumber in
the array.
5. Create a 2D array of any dimensions, initialize it, and calculate the sum of each row and
column in separate arrays. For example, if the array’s dimensions are m × n, you will have
an array of size m to hold the sums of the rows and an array of size n to hold the sum of
columns. Try to print the length of the 2D array and discuss the output in terms of what
does that output represents and why only one number represents the length although it is a
2D array?
6. Consider having a Class called Person, write the change in memory after each line is
executed in the following code:
Also, after the execution of each line write how many Person objects are there in memory.
What s1, s2, and s3 are called?
7. Define Class Rectangle that has public member variables length and width, and
calculatePerimeter, calculateArea as methods.
8. In Question 7, if length and width are set to be private, what other changes has to be done?
(Write the code) Why? In addition, what is the advantage of making them private?
9. Using the Rectangle Class with all its updates, write code in the main to test each method
in the Class.
2
10.Write the change in memory after each line of code is executed (Assume that Class
Rectangle has a method called print that prints its dimensions):
Are there any errors in the code? If yes, what are those errors? What is the reason behind
them? What changes that have to be done to handle them?