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

Java Code Snippets with Solutions

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)
19 views4 pages

Java Code Snippets with Solutions

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

Java Code Snippets

1. What is wrong with the below code:

public class Main {

public static void main(String[] args) {

int[] numbers = {1, 2, 3, 4, 5};

[Link](numbers[5]);

Answer: [Link]: Index 5 out of


bounds for length 5

2. What will be the output of the following code:

public class Main{

public static void main(String []args){

for (int i = 0; i < 5; i++) {

if (i == 2)

continue;

[Link](i + " ");

Answer:

b) 0 1 3 4

3.

public class SwapNumbers {

public static void main(String[] args) {

int a = 10;

int b = 20;
[Link]("a is " + a + " and b is " + b);

a = a + b;

b = a - b;

a = a - b;

[Link]("After swapping, a is " + a + " and b is " + b);

Answer:

a is 10 and b is 20

After swapping, a is 20 and b is 10

4.

int age = 20;

String result = (age > 18) ? "Minor" : “Major";

[Link](result);

Answer: Minor

5. What is the output of the following program?

public class Main {

public static void main(String[] args) {

int x = 10;

int y = x++;

[Link](y);

Answer: 10
6.

class TestApp {

public static void main(String[] args) {

for (int index = 0; index>2; index++) {

[Link]("Welcome");

break;

Answer: <no output>

7.

class TestApp {

public static void main(String args[]) {

int bits;

bits = -3 >> 1;

[Link](bits);

bits = -3 << 1;

[Link](bits);

Answer:

-2

-6

[Link] is the output

[Link]("1"+new Integer(2) + 3);

Answer: 123
9.

class TestApp {

public static void main(String args[]) {

String str1 = "abc";

String str2 = new String("abc");

[Link](str1 == str2);

[Link]([Link](str2));

Answer: false true

10.

int x = 10;

[Link](--x + x++);

Answer: 18

Common questions

Powered by AI

The conditional (ternary) operator in Java offers a more concise syntax compared to traditional if-else statements. In the example, the expression (age > 18) ? "Minor" : "Major" assigns the result "Minor" or "Major" based on the boolean evaluation of age > 18. If using traditional if-else statements, this would require a more verbose syntax: if (age > 18) { result = "Minor"; } else { result = "Major"; }. The ternary operator achieves the same logic succinctly but can be less readable if overused in complex conditions .

In Java, the '==' operator compares references, checking if two String objects point to the same memory location, while the 'equals()' method compares the actual content or values of the Strings . In the given example, str1 == str2 returns false as 'str1' and 'str2' are different objects in memory, while str1.equals(str2) returns true because it checks for value equality, confirming the content is the same.

In the expression System.out.println(--x + x++);, the pre-decrement operator (--x) first decreases x by 1, from 10 to 9. Then, x is used in the addition due to the lower precedence of the post-increment operator (x++), which increments x after the current expression evaluation. The calculation is therefore 9 + 9, resulting in 18, but x is 10 after the operation . The careful ordering of operations impacts both the output value and the final state of x.

The usage of bitwise operators << (left shift) and >> (right shift) on negative integers in Java directly manipulates the binary representation of the integers. The operation -3 >> 1 results in -2, because the right shift maintains the sign bit on negative numbers, effectively performing arithmetic shift . Conversely, the operation -3 << 1 results in -6, as the left shift does not maintain the sign bit and only shifts all bits to the left, doubling the magnitude but keeping the number negative. Understanding these implications is critical for correctly manipulating bits in signed integer operations.

The 'SwapNumbers' example uses a series of arithmetic operations to swap values of two variables without a temporary variable by relying on the sum and difference properties: a = a + b; b = a - b; a = a - b. This method effectively reallocates the values such that 'a' and 'b' are swapped. It is efficient in terms of space since it does not require additional storage, but it is crucial to note that it can only be safely used when overflow is not a concern due to large integer values .

The logical error occurs because the loop's initialization, for (int index = 0; index>2; index++), sets a condition index > 2 that is false from the outset since index starts at 0. Thus, the loop body is never executed, including the 'break' statement . Consequently, "Welcome" is never printed, and no output occurs. The condition ensures the loop will never run.

Attempting to access an index outside the bounds of an array in Java results in a java.lang.ArrayIndexOutOfBoundsException error . This can be prevented by ensuring that any index accessed is within the range of 0 to the array length minus one. Additionally, implementing proper loop conditions and bounds checking can help avoid such errors.

The expression outputs '123' rather than a numerical sum due to Java's rules for String concatenation. When "1" plus a new Integer(2) is evaluated, the Integer object is implicitly converted to a String because the + operator, when one operand is a String, performs concatenation . The resultant "12" is then concatenated with 3, treated as a String, resulting in "123". This sequence illustrates the precedence of string concatenation over arithmetic addition when a String is involved in expressions.

In the given Java loop, the 'continue' keyword causes the loop to skip the current iteration when i equals 2 . This directly affects the flow by continuing with the next iteration at the loop increment step, thus preventing the code inside the loop after 'continue' from executing for that iteration. As a result, the number '2' is omitted from the output, producing "0 1 3 4" instead of "0 1 2 3 4".

In Java, the pre-increment operator (++x) increases the variable's value before it is evaluated in the expression, whereas the post-increment operator (x++) increases the value after the expression is evaluated. In the example where int y = x++; y is assigned the value of x before x is incremented, thus y gets the initial value of x, which is 10. This is crucial in expressions and assignments where the order of operations affects the program's logic and results .

You might also like