Java Puzzles | Interview JAVA Puzzlers


1. Dangerous Comment

What will be the output?

public class InterviewBubble {

 public static void main(String[] args) {
  // my favorite website is
  http: //www.interviewbubble.com
   System.out.println("hello world");
 }
}

Answer:

$javac InterviewBubble.java
$java  InterviewBubble


hello world

It does compile correctly.  Basically, a colon in Java means a label for a GOTO statement.  So basically, http: is defining a label called "http".  The //www.quora.com after the label is just a standard Java comment.  It is just a coincidence that a standard URL is really just a Java label and then a comment.

2. Dirty Number Add

What will be the output?

public class InterviewBubble {
    public static void main(String[] args) {
        System.out.println(01234 + 43210);
        }
}

Answer:

$javac InterviewBubble.java
$java  InterviewBubble

43878

Good puzzle. Due leading zero on 01234 compiler will it as an octal number so first compiler will convert it as a decimal 

01234->668(decimal) ===>668+43210=43878.


3.  Bad String
What will be the output?

package com.interviewbubble;  
  
class String{}  

  public class Demo {     
    public static void main(String[] args) {         
      System.out.println("Challenge Success!!!");     
    } 
  } 

Answer:

$javac com/interviewbubble/Demo.java
$java com/interviewbubble/Demo

Error: Main method not found in class com.twisters.Demo, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application


If you create your own String class, then the main method will not be found.

public static void main(String args[]){
}

Here the main method's signature will be invalid as it will try to access the String class created by you. Do not use the same name to create classes, instead use something like

public class MyString{
}.

This should work for you. Thanks.

or Just change in main method by

public static void main(java.lang.String[] args)

Due to own own String class implementation in the file, it refers this String class instead of the standard java package String class.
     


Comments