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

Java Code Snippets

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

Java Code Snippets

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
You are on page 1/ 4

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

System.out.println(numbers[5]);

Answer: java.lang.ArrayIndexOutOfBoundsException: 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;

System.out.print(i + " ");

Answer:

b) 0 1 3 4

3.

public class SwapNumbers {

public static void main(String[] args) {

int a = 10;

int b = 20;
System.out.println("a is " + a + " and b is " + b);

a = a + b;

b = a - b;

a = a - b;

System.out.println("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";

System.out.println(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++;

System.out.println(y);

Answer: 10
6.

class TestApp {

public static void main(String[] args) {

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

System.out.println("Welcome");

break;

Answer: <no output>

7.

class TestApp {

public static void main(String args[]) {

int bits;

bits = -3 >> 1;

System.out.println(bits);

bits = -3 << 1;

System.out.println(bits);

Answer:

-2

-6

8.what is the output

System.out.println("1"+new Integer(2) + 3);

Answer: 123
9.

class TestApp {

public static void main(String args[]) {

String str1 = "abc";

String str2 = new String("abc");

System.out.println(str1 == str2);

System.out.println(str1.equals(str2));

Answer: false true

10.

int x = 10;

System.out.println(--x + x++);

Answer: 18

You might also like