Showing posts with label java coding question. Show all posts
Showing posts with label java coding question. Show all posts

Tuesday, 4 August 2015

What is the output of following program?

  1. package com.javastepbystep;

  2. class A
  3. {
  4.  
  5.      static int method1(int i)
  6.     {
  7.          return method2(i *= 11);
  8.      }
  9.  
  10.       static int method2(int i)
  11.      {
  12.           return method3(i /= 11);
  13.       }
  14.  
  15.        static int method3(int i)
  16.       {
  17.            return method4(i -= 11);
  18.       }
  19.  
  20.       static int method4(int i)
  21.      {
  22.          return i += 11;
  23.      }
         
  24.      public static void main(String [] args)
  25.     {
  26.           System.out.println(method1(11));
  27.      }
  28.  
  29. }

Ans: 11

Sunday, 2 August 2015

What is the output of following program?

 public class B{
    
      B b= new B();
    
     public int show(){
          return (true ? null : 0);
     }
    
     public static void main(String[] args)  {
    
            B b= new B();
            b.show();
        }
    
    }

Output:
  1. Exception in thread "main" java.lang.StackOverflowError
  2. at com.instanceofjava.B.<init>(B.java:3)
  3. at com.instanceofjava.B.<init>(B.java:5)
  4. at com.instanceofjava.B.<init>(B.java:5) 

Explanation:

  • Whenever we create the object of any class constructor will be called first and memory allocated for all non-static variables
  • Here  B b= new B(); the variable is an object and assigned to a new object of the same class
  • B b= new B(); statement leads to recursive execution of constructor will create infinite objects so at the run time an exception will be raised
  • Exception in thread "main" java.lang.StackOverflowError
  • The common cause for a stack overflow exception is a bad recursive call. Typically this is caused when your recursive functions don't have the correct termination condition

Thursday, 30 July 2015

Difference between == and .equals()

They both differ very much in their significance. equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects! That means, the contents of the objects.

Whereas the '==' operator is expected to check the actual object instances are same or not.

For example, lets say, you have two String objects and they are being pointed by two different reference variables s1 and s2.


 s1 = new String("abc");
 s2 = new String("abc");

Now, if you use the "equals()" method to check for their equivalence as


 if(s1.equals(s2))
      System.out.println("s1.equals(s2) is TRUE");
 else
      System.out.println("s1.equals(s2) is FALSE");
You will get the output as TRUE as the 'equals()' method check for the content equivality.

Lets check the '==' operator.


if(s1==s2)
     System.out.printlln("s1==s2 is TRUE");
   else
     System.out.println("s1==s2 is FALSE");

Now you will get the FALSE as output because both s1 and s2 are pointing to two different objects even though both of them share the same string content.

It is because of 'new String()' everytime a new object is created.

Try running the program without 'new String' and just with


   String s1 = "abc";
   String s2 = "abc";

You will get TRUE for both the tests.

Saturday, 30 May 2015

Java Declaring Objects

You can declare object of class Box as follows:

Box box;

Normally we say that box is an object of type Box. This is correct in C++ but this is not fully correct in Java. Because box is simply a variable that can hold reference to an object of type Box.

This is like pointer to a structure in C/C++. The reference box will store garbage or null reference unless we assign reference of some object of class Box to it.

After the above declaration variable box will contain garbage or null reference as shown below:

This indicates that variable box is not pointing to any object.

If the variable box is defined in a method or block it will contain garbage, as local variables are not initialized by default. To make sure that it contains null unless some valid reference (conceptually same as pointer of C/C++) is assigned to it, you must declare and initialize the box as follows:

Box box = null;

If the above declaration of box is outside any method/block then it is an instance variable and there is no need not initialize it with null as an instance/reference variables are always initialized with null.

Java Access/Visibility Modifiers

Access/visibility modifiers control access to a class, interface, data member or method. There are four levels of visibility in Java:


  • public
  • protected
  • package
  • private

1. Access/Visibility Modifiers for Top-Level Classes.

Visibility of a top-level class can be either public or package.

public

The keyword public is the only modifier, which can be used with a top-level class. If a class is to 
be visible to all the classes irrespective of their package, then it must be declared as public by specifying the modifier public, which should appear before the keyword class.

package

There is no keyword package for visibility control. In the absence of any access/visibility modifier before the top-level class, its visibility is only within the package in which it is defined. The concept of package is somewhat similar to the concept of friend classes in C++.

2. Access/Visibility Modifiers for Data Members and Methods.

When used in the variable or method declarations, access/visibility modifiers control access to the variable or method i.e. they decide who can access the variables and methods. These modifiers are not applicable for local variables as their visibility/scope is anyhow limited to the method/block in which they are declared.

public

Any method or variable is always visible in the class in which it is declared. The instance methods of a class can access any other method (instance as well as static method) or variable (instance as well as static variable) declared in the class. Similarly a static method of a class can access any other static method or static variable declared in the same class. 

If a method or variable is to be visible to all the classes, then it must be declared as public by specifying the modifier public, which should appear before the data type. For example, main() method is always declared as public. The reason is that main() method is accessed by the code which is part of JVM i.e. it is outside the class in which main() method is declared. Similarly an instance or static variable can be declared public by specifying modifier public as shown below:

public float width;
public static float width;

A variable or method declared as public has the widest possible visibility. It can be accessed from any class.

private

If you want that a method or variable should not be visible outside the class in which it is declared then its access modifier should be private. We use this modifier to hide the variable or method so that it cannot be accessed from outside the class. 

A variable declared as private has the least possible visibility but it is the most commonly used modifier to encourage data encapsulation and data hiding.  

package 

There is no keyword package. In the absence of any access/visibility modifier before a data member or method, its visibility is only within the package in which it is defined.

protected

A variable declared as protected can be accessed from all the classes belonging to the same package as that of the class in which member is declared. This visibility is similar to the package scope. But in addition to this a protected member can be accessed from any child class irrespective of the package in which it is declared.

Example: A simple class Box is defined below.

1 class Box
2 {
3    double width;
4    double height;
5    double length;
6 }

Example: The class Box is redefined here to include one method volume().

1 class Box
2 {
3    double width;
4    double height;
5    double length;
6    void volume()
7    {
8        double vol = width * height * length;
9        System.out.println(vol);
10  }
11 }

Java defining a class

A Java class represents a user-defined data type. It acts like a template using which we can create multiple objects. The objects are like variables /instances of the data type represented by the class. To begin with you can think of a class as struct of C with the difference that a struct data type can have only data as members whereas the class can have data as well as methods as its members.

The general form of a class is

modifiers class <classname>
{
      <body of the class>
}

The body of the class can consist of data members as well as methods.
The general form is expanded below to show the fact that the class body can contain data members (variables) as well as methods.

modifiers class <classname>
{
modifiers type variable1;
modifiers type variable2;
.

.

modifiers type methodname1(parameter-list)
{
     <body of the method>
}

modifiers type methodname2(parameter-list)
{
     <body of the method>
}

.

.

}