0% found this document useful (0 votes)
9 views4 pages

Java Programming Basics Lab Exercise

This document contains the answers to 7 questions about using predefined classes in Java. The questions cover topics like creating String and Random objects, using String and Random methods, and reading input using the Scanner class. For each question, the student provided the correct code segments or descriptions to demonstrate their understanding of working with these common predefined classes in Java.

Uploaded by

Ku H6
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views4 pages

Java Programming Basics Lab Exercise

This document contains the answers to 7 questions about using predefined classes in Java. The questions cover topics like creating String and Random objects, using String and Random methods, and reading input using the Scanner class. For each question, the student provided the correct code segments or descriptions to demonstrate their understanding of working with these common predefined classes in Java.

Uploaded by

Ku H6
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

STIA1123 Programming 2

Lab Exercise: Predefined Classes (Ku Hazwan bin Ku Izham) 289889

1. Write TWO (2) different ways to create an object from the String class.

Answer :
1- String name = new String(“Micheal”);
2- String name = “Micheal”;

2. What is the output for the following Java statements?


String phr = new String("Big,blue sky");
[Link]([Link]([Link](","),7));

Answer :
-,blu

3. Give your description on the output that will be produced by the execution of the following
statements.
Random rd = new Random();
[Link]([Link](41) + 10);

Answer :
The output will be the sum of random number from a range of 10 to 50.
4. Write Java code segment that use class Random to generate two random numbers that is
greater than or equal to 0, and less than 100 and store the values into local variable num1 and
num2. Then use class Math to determine and display the largest between both values.

Answer :

Output :

5. Determine the output of the following code segments:

String test = "abc";


test = test + test;
[Link](test);

Answer :
abcabc

Random random = new Random();


double d = [Link] ( 2.5 + [Link](1) );
[Link]("The value is ” + d);

Answer :
The value is 3.0 or 2.0
6. Class Scanner in Java is used to read input from the console. Answer all of the following
questions:

a) Write a Java statement to instantiate an object input of class Scanner.

 Answer :

Create object Scanner Input = new Scanner([Link]);

b) By using the object input, read two integer values and assigned to variable x and y.

Answer :

Int x = [Link]()

Int y = [Link]()

c) By using an appropriate method from class Math, display the value of X y.

Answer :

[Link]("Product of " + x + " and " + y + " is: " +

[Link](x, y));

7. Given below are the statements that declare and create two String objects

String text1 = "School of Computing";


String text2 = "College of Arts and Sciences";
String text3 = “UUM Sintok”;

a. Write a Java statement to display the total length of the text1, text2 and text3.

Answer :

[Link]("length of (" + text1 + ") : " + [Link]());

[Link]("length of (" + text2 + ") : " + [Link]());

[Link]("length of (" + text3 + ") : " + [Link]());


b. By using the variables of text1 and text2. Write a Java statement to display as output
“College of Arts and Computing”.
Answer :

Output :

Common questions

Powered by AI

The statement `System.out.println(rd.nextInt(41) + 10);` generates a random integer between 0 (inclusive) and 41 (exclusive), which results in any integer from 0 to 40. By adding 10 to the result of `rd.nextInt(41)`, the range of possible output values shifts to between 10 and 50 (inclusive). This illustrates how random number generation works in Java, particularly how ranges can be adjusted by adding a constant.

The method call `phr.substring(phr.indexOf(","),7)` operates on the string "Big,blue sky". The `indexOf(",")` returns the index position of the comma, which is 3. The `substring` method then extracts the characters from index 3 up to, but not including, index 7. Therefore, it returns the string ",-blu", which includes the comma and the characters following it up to index 6 . This demonstrates understanding of substring extraction and index manipulation in Java.

Using the Scanner class, such as `Scanner input = new Scanner(System.in);`, is beneficial for interactive applications, allowing flexible user input handling. However, for pre-determined values or tests, direct assignment, like `int x = 10; int y = 20;`, is more efficient as it avoids runtime input overhead. The choice depends on application needs: for small-scale or unit tests, direct assignment saves resources, while Scanner is essential for real-time data acquisition . This evaluation includes understanding trade-offs between user interaction and performance.

In Java, string concatenation using the `+` operator results in a new String object that combines the content of the operands. The code snippet `String test = "abc"; test = test + test; System.out.println(test);` first initializes `test` with "abc", then concatenates "abc" with itself, resulting in "abcabc" as the output, due to the `+` operation . This demonstrates basic string concatenation principles and dynamic reassignment.

To transform 'School of Computing' into 'College of Arts and Computing', one must substitute parts of the original string: `String transformed = "College of Arts and " + text1.substring(text1.indexOf("Computing")); System.out.println(transformed);` This creation dynamically combines the desired prefix with the suffix extracted from `text1`, demonstrating substring manipulation and concatenation . Ensures understanding of selective string replacement and concatenation.

There are two primary ways to create an object from the String class in Java: using a string literal and using the String constructor. Creating a string using a literal, such as `String name = "Michael";`, is simple and memory efficient as it uses the string pool. In contrast, using the constructor, like `String name = new String("Michael");`, creates a new String object in the heap, which might not take advantage of the string pool, consuming more memory . The pros of the first method include efficiency and simplicity, while the constructor approach allows for more explicit object creation but at the cost of increased memory usage.

To read integers using the Scanner class, instantiate a Scanner object attached to System.in, and use `nextInt()` to read values. For example: `Scanner input = new Scanner(System.in); int x = input.nextInt(); int y = input.nextInt();`. Then use Math methods to compute and display the product: `System.out.println(Math.multiplyExact(x, y));` This computes and prints the product of the two integers with precision and handles traditional input/output operations in Java .

The Java code segment `double d = Math.round(2.5 + random.nextInt(1));` will always produce either 2.0 or 3.0. Since `random.nextInt(1)` returns 0, the expression simplifies to `2.5 + 0`, resulting directly in rounding `2.5`. The method `Math.round()` rounds 2.5 to the nearest integer, which is 3.0. Therefore, this statement effectively illustrates the behavior of rounding towards the nearest integer . Understanding involves appreciation of rounding principles and zero-bound random generation.

To generate two random numbers and determine the larger, first instantiate the Random class, generate the numbers, and use the Math class for comparison. For example: `Random rd = new Random(); int num1 = rd.nextInt(100); int num2 = rd.nextInt(100); System.out.println(Math.max(num1, num2));` This code creates two random integers from 0 to 99 and uses `Math.max()` to print the larger of the two . This demonstrates the utilization of built-in Java classes for basic computational tasks.

To determine and display the total length of multiple strings, use the `length()` method on each String object. For example, `String text1 = "School of Computing";` and `System.out.println("Length: " + text1.length());` will output the length of `text1`. Applying this to multiple strings, like `text2` and `text3`, and summing their lengths gives a total length. Each string's length contributes to a comprehensive view of the memory footprint for string storage .

You might also like