Computer Applications
Give the output of the following program segment and specify how many times the loop is executed.
String s = "JAVA";
for(i = 0; i < s.length(); i += 2)
System.out.println(s.substring(i));
Java
Java Iterative Stmts
12 Likes
Answer
JAVA
VA
The loop executes 2 times.
Working
- The string
xcontains the value"JAVA", which has a length of 4. - The
forloop initializesito 0 and increments it by 2 in each iteration (i = 0, 2). - In the first iteration, when
iis 0,x.substring(0)extracts the substring from index 0 to the end, which is"JAVA". This is printed. - In the second iteration, when
iis 2,x.substring(2)extracts the substring from index 2 to the end, which is"VA". This is printed. - When
ibecomes 4, the conditioni < x.length()(i.e.,4 < 4) becomes false, so the loop terminates. - Therefore, the loop executes exactly 2 times, printing the substrings
"JAVA"and"VA".
Answered By
5 Likes
Related Questions
Consider the following array and answer the questions given below:
int a[] = {12, 10, 8, 4, 6, 2, 3, 5, 7};
(a) What is the output of System.out.print(a[0] + a[5]);?
(b) What is the index (subscript) of the largest element of the array a[]?
(a) Write the Java statement to initialize the first 6 odd numbers in a 3 × 2 array.
(b) What is the result of x[0][1] + x[2][1] of the above array?
Define a class named CloudStorage with the following specifications:
Member Variables:
int acno – stores the user’s account number
int space – stores the amount of storage space in GB purchased by the user
double bill – stores the total price to be paid by the user
Member Methods:
void accept() – prompts the user to input their account number and storage space using Scanner class methods only.
void calculate() – calculates the bill total price based on the storage space purchased using the pricing table provided:Storage range Price per GB (Rs) First 15 GB 15 Next 15 GB 13 Above 30 GB 11 void display() – displays the account number, storage space and bill to be paid.
Write a main method to create an object of the class and invoke the methods of the class with respect to the object.
Define a class to accept values into a 4 × 4 integer array. Calculate and print the NORM of the array.
NORM is the square root of sum of squares of all elements.1 2 1 3 5 2 1 6 3 6 1 2 3 4 6 3Sum of squares of elements = 1 + 4 + 1 + 9 + 25 + 4 + 1 + 36 + 9 + 36 + 1 + 4 + 9 + 16 + 36 + 9 = 201
NORM = Square root of 201 = 14.177446878757825