Showing posts with label Basic Interview Questions. Show all posts
Showing posts with label Basic Interview Questions. Show all posts

Saturday, 12 January 2019

Java Beginners Excercises Part - 2


BASIC JAVA

1) Correct the program below so that it can compile and run without any errors and prints the text “Hello World”:
public class MyFirstProgram { public void main(String args){ System.out.println("Hello World"); } }
public class MyFirstProgram {
   public static void main(String[] args){         
         System.out.println("Hello World");
   }
}

DATA TYPES AND CONSTANTS

1) Correct the variable initializations below:

public class DefineSomeVariables
{
    double amount = 100.50;
    long population = 9999999999;
}


public class DefineSomeVariables
{
     double amount = 100.50d;
     long earthPopulation = 9999999999l;
}

2) What is the difference between Variable and Constant?

Constants are basically variables whose value can't change. We use the keyword final to declare constants like below.

public final int DAYS = 7;

According to java convention, the Constant name should be in capital letters always.

OPERATORS

1) Provide the output of the below code:

public class SimpleOperations
{
    public static void main(String[] args)
    {
        double a = 10.5 % 2;
        double b = 3.5 * 2;
        float c = (float)6.8 / 2;
        System.out.println("a => " + a + " b => " + b + " => c " + c);
     }
}

a => 0.5 b => 7.0 => c 3.4

2) What is the data type conversion in Java? Fill in the missing values in the below code.

double x = 9.997;
int nx = (...) x;

When we assign a value of one data type to another, the two types might not be compatible with each other. If the data types are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion and if not then they need to be cast or converted explicitly.

double x = 9.997;
int nx = (int) x;

3) Fill in the blank below:

x += 4; is equivalent to ...

x += 4; is equivalent to x = x + 4;



4) After execution below statements what would be the value of variables m, n, a and b:

int m = 7;
int n = 7;

int a = 2 * ++m;
int b = 2 * n++;

a = 16, m = 8
B = 14, n = 8


5) Write down the result of the below expressions in the form of True and False:

int x = 10;
Int y = 20;

x < y
...


x > y
...


x <= y
...


x >= y
...


x == y
...


x != y
...



x < y = True

x > y = False

X <= y = True

x >= y = False

x == y = False

x != y = True





ENUMS

1) Why use Enums instead of Constants? Which is better?

// Constants for player types
public static final String ARCHER = "Archer";
public static final String WARRIOR = "Warrior";

// Constants for genders
public static final String MALE = "Male";
public static final String FEMALE = "Female";

then you end up not really knowing the type of your data - leading to potentially incorrect code:

String playerType = Constants.MALE; // This is wrong but Java will not complain

if you use enums, that would end up as:

// Compile-time error - incompatible types!
PlayerType playerType = Gender.MALE;

This is why Enums are better than Constants.

STRING

1) Write down the output of the below String comparisons:

public class StringComp
{
    public static void main(String[] args)
    {
        String a = "Rahul";
        String b = "Rahul";
        String c = new String("Rahul");
        System.out.println("Rahul".equals(a));
        System.out.println("Rahul" == a);
        System.out.println(a.equals(b));
        System.out.println(a==b);
        System.out.println(a.equals(c));
        System.out.println(a==c);
    }
}

System.out.println("Rahul".equals(a)); // True
System.out.println("Rahul" == a); // True
System.out.println(a.equals(b)); // True
System.out.println(a==b); // True
System.out.println(a.equals(c)); // True
System.out.println(a==c); // False

2) Write down the output of the below String class methods:

public class StringMethods
{
    public static void main(String[] args)
    {
       String str = "Java Fundamentals";
System.out.println(str.charAt(5));
System.out.println(str.startsWith("java"));
System.out.println(str.endsWith("tals"));
System.out.println(str.indexOf("men"));
System.out.println(str.lastIndexOf("a"));
System.out.println(str.replace("Fund", "Coll"));
System.out.println(str.substring(3));
System.out.println(str.substring(1, 5));
System.out.println(str.toLowerCase());
System.out.println(str.toUpperCase());

    }
}

System.out.println(str.charAt(5)); // F
System.out.println(str.startsWith("java")); // false
System.out.println(str.endsWith("tals")); // true
System.out.println(str.indexOf("men")); // 10
System.out.println(str.lastIndexOf("a")); // 14
System.out.println(str.replace("Fund", "Coll")); // Java Collamentals
System.out.println(str.substring(3)); // a Fundamentals
System.out.println(str.substring(1, 5)); // ava
System.out.println(str.toLowerCase()); // java fundamentals
System.out.println(str.toUpperCase()); // JAVA FUNDAMENTALS



3) Correct the below code if you see any mistakes?
String str;
// Some code here
if(str.length != 0 && str != null)
{
    //Do something here
}


String str;
// Some code here
if(str != null && str.length != 0)
{
     //Do something here
}

SCANNER / COMMAND LINE INPUT

1) Complete the below code which is used to take input from the command line:

public class CommandLineInput
{
    public static void main(String args[])
    {
        Scanner in = new Scanner(.....); // Code missing here
        System.out.print("What is your name? ");
        String name = …………………………….. // code missing here
        System.out.print("Your name is: "+name);

        //Get second input
        System.out.print("How old are you? ");
        int age = ……………………………………. // code missing here
        System.out.print("Your age is: "+age);
     }
}


public class CommandLineInput
{
     public static void main(String args[])
     {
          Scanner in = new Scanner(System.in);
          System.out.print("What is your name? ");
          String name = in.nextLine();
          System.out.print("Your name is: "+name);

           //Get second input
          System.out.print("How old are you? ");
          int age = in.nextInt();
          System.out.print("Your age is: "+age);

      }
}

BLOCK SCOPE

1) Fill in the blanks:

class Test
{
     private int x;
     public void setX(int x)
     {
          // set the x argument variable value in instance field x
………………………………………….
      }
}

class Test
{
       private int x;
       public void setX(int x)
       {
            // set the x argument variable value in instance field x
    This.x = x;
       }
}


2) Write the output of the below program:

public class Test
{
     static int x = 11;
     private int y = 33;
     public void method1(int x)
     {
         Test t = new Test();
          this.x = 22;
          y = 44;
          System.out.println("Test.x: " + Test.x);
          System.out.println("t.x: " + t.x);
          System.out.println("t.y: " + t.y);
          System.out.println("y: " + y);
      }
      public static void main(String args[])
      {
          Test t = new Test();
           t.method1(5);
       }
}

Test.x: 22
t.x: 22
t.y: 33
Y: 44

LOOPS

1) Can for and while loop be infinite? If yes, implement the code.

Yes, We can have infinite for and while loops.

while(true)
{
      //This code execution will be infinite
}

for(;;)
{
     //This code execution will be infinite
}

2) Correct the below code so that the below program print number 1 to 10:

int i = 0;
for(i<10;)
{
    System.out.println(i);
}

int i = 1;
for(;i<=10; i++)
{
     System.out.println(i);
}

ARRAY

1) What type of error is in the below code? Compile time or run time? Fix the error and rewrite that code block.

class ArrayExample
{
      public static void main (String[] args)
      {
           int[] arr = new int[2];
           arr[0] = 10;
           arr[1] = 20;

           for (int i = 0; i <= arr.length; i++)
                   System.out.println(arr[i]);
       }
}

It is a Runtime error. This program will throw ArrayIndexOutOfboundException.

We have to correct the loop condition like the below:

for (int i = 0; i < arr.length; i++)
     System.out.println(arr[i]);

2) Fill in the blanks so that only indexes of even number gets printed:

public void arrayExample()
{
    int[] a = new int[10];
    int length = a.length;
    for (int i = 0; i < a.length; i++)
        a[i] = i+10;

     //Print the array
    for (int i = 0; i < a.length; ...) // you have to change here in the code
        System.out.println(a[i]);
}

public void arrayExample()
{
     int[] a = new int[10];
     int length = a.length;
     for (int i = 0; i < a.length; i++)
        a[i] = i+10;

     // print the array
     for (int i = 0; i < a.length; i+=2) // you have to change here in the code
       System.out.println(a[i]);
}

3) What would be the output of the following program where we are copying an array.

class TestArrayCopyDemo {
      public static void main(String[] args) {
          char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
                                    'i', 'n', 'a', 't', 'e', 'd' };
          char[] copyTo = new char[7];
          System.arraycopy(copyFrom, 2, copyTo, 0, 7);
          System.out.println(String.valueOf(copyTo));
      }
}

caffeine


CLASSES AND OBJECTS

1) Identify the issues and fix those:

public class Employee
{
       String name;
int salary;

        void Employee(String name, int salary) // you can find a issue here
        {
             this.name = name;
             this.salary = salary;
         }

         private int calulateTax()
         {
             // you can find an issue here
             static int tax = 10; // This is the percent;
             return salary * 10 / 100;
         }

        public static void main(String[] args)
        {
              Employee e = new Employee("Rahul", 1000);
             System.out.println(e.calulateTax());
         }
}

public class Employee
{
       String name;
int salary;

       Employee(String name, int salary)
       {
            this.name = name;
            this.salary = salary;
        }

        private int calulateTax()
        {
             int tax = 10; // This is the percent;
             return salary * 10 / 100;
         }

         public static void main(String[] args)
         {
               Employee e = new Employee("Rahul", 1000);
               System.out.println(e.calulateTax());
          }
}

2) Fill in the blanks so that puppy’s age gets printed on the console

public class Puppy
{
     int puppyAge;

     public Puppy(String name)
     {
        System.out.println("Name chosen is :" + name );
     }

     public void setAge( int age )
     {
         puppyAge = age;
     }

     public int getAge()
     {
         System.out.println("Puppy's age is :" + puppyAge );
         return puppyAge;
     }

     public static void main(String []args)
     {
          Puppy myPuppy = new Puppy( "tommy" );
          myPuppy.setAge( 2 );

         /* Call another class method to get puppy's age, add code here */
…………………………………………………………...

     }
}

public class Puppy
{
     int puppyAge;

     public Puppy(String name)
     {
           System.out.println("Name chosen is :" + name );
     }

     public void setAge( int age )
     {
           puppyAge = age;
     }

     public int getAge()
     {
           System.out.println("Puppy's age is :" + puppyAge );
           return puppyAge;
      }

      public static void main(String []args)
      {
           Puppy myPuppy = new Puppy( "tommy" );
           myPuppy.setAge( 2 );

           /* Call another class method to get puppy's age, add code here */
           myPuppy.getAge( );

       }
}

STATIC METHODS

1) Correct the method declaration so that we can call that statically:

public class StaticMethodExample
{


public void getListofFriuts()
{
      // do something here
}

public static void main(String[] args)
{
      StaticMethodExample.getListofFriuts();
}
}

public class StaticMethodExample
{
public static void getListofFruits()
{
      // do something here
}

public static void main(String[] args)
{
      StaticMethodExample.getListofFruits();
}
}


2) What is wrong with the below code? I just want to call one constructor from another using this keyword

public Employee(double s)
{
       nextId++;
this("Employee #" + nextId, s);

}

this keyword statement should be the first line in the constructor like below:

public Employee(double s)
{
       this("Employee #" + nextId, s);
nextId++;

}
SPECIFIC CODE BLOCKS

1) What would be the output of the following code?

public class Employee
{
private static int nextId;
private int id;
private String name;
private double salary;

static {
   System.out.println(“This is the static block”);
}

// object initialization block
{
System.out.println(“This is the initialization block”);
id = nextId;
nextId++;
}

public Employee(String n, double s)
{
     System.out.println(“This is the two argument constructor”);
name = n;
salary = s;
}

public Employee()
{
      System.out.println(“This is the no argument constructor”);
name = "";
salary = 0;
}

public static void main(String[] args)
{
    Employee e = new Employee();
}
}

This is the static block
This is the initialization block
This is the no argument constructor

INHERITANCE

1) What is the benefit of inheritance? How can we call the parent class constructor from the child class?

The main benefit of inheritance is code reusability. We can call the parent class constructor using the super keyword.

2) What is the error in below code? Correct that.

class MountainBike extends Bicycle
{
     public int seatHeight;
     public MountainBike(int gear,int speed, int startHeight)
     {
         seatHeight = startHeight;
         super(gear, speed);
      }
      public void setHeight(int newValue)
      {
           seatHeight = newValue;
      }
}

public MountainBike(int gear,int speed, int startHeight)
{
      super(gear, speed);
      seatHeight = startHeight;
}

super keyword call can be used as first-line inside a constructor.

3) How can we make sure that no one can extend a particular class?

Using final keyword. If we add final keyword before the class name then that class can not be extended by any class.

public final class Utility
{

}

4) Modify the below code so that no one can override the below method in any child class.

public void noOneCanOverrideMe()
{

}

public final void noOneCanOverrideMe()
{

}