Total Pageviews

Sunday, September 30, 2012

DIFFERENCE BETWEEN next() AND nextLine()

This post eradicates the confusion between next() and nextLine() and gives you a clear idea of how they work.

next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...

next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

COMMON PROBLEMS WITH next() :

Consider the example,



import java.util.Scanner;

public class temp
{
    public static void main(String arg[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("enter string for c");
        String c=sc.next();
        System.out.println("c is "+c);
        System.out.println("enter string for d");
        String d=sc.next();
        System.out.println("d is "+d);
    }
}


OUTPUT:                             HOW IT WORKS!

enter string for c                     
abc def                                  abc |def      //cursor stays after c
c is abc
enter string for d
d is  def                                 abc def|     //cursor stays after f


Look at the output keenly. When the input for c is given as abc def, it will not read the entire input abc def. next() reads only abc and places the cursor after the alphabet c. Now, when value for d is got using next(), it will not get new value. Rather, it takes the value after the current cursor position(since the cursor is after c, def is assigned to d and the cursor stays after f).

Now, when 
 String c=sc.next() in the above program is replaced as 
 String c=sc.nextLine(), the output will be

OUTPUT:                           HOW IT WORKS!

enter string for c
ABC DEF                             ABC DEF
c is ABC DEF                       |       //cursor moves to next line
enter string for d
GHI                                       ABC DEF
d is GHI                                 GHI|    //cursor stays after I

Since nextLine() is used for reading input for c, the entire line is read and hence ABC DEF is stored in c and the cursor is placed in the next line. Now when d is read using next() or nextLine(), the cursor will be in the next line and hence the input for d is read and is placed in d (here d gets the input GHI).

So whenever next() is used, make sure nextLine() used to place the cursor in the next line. Hence the above program is also written as, 
String c=sc.next();
sc.nextLine();
String d=sc.next();

Thanks for reading my blog... :-) Comment about my blog. Stay tuned for my next post.... 


INTERFACE

CAN A CLASS IMPLEMENT 2 INTERFACES HAVING COMMON METHOD NAME??? 

We know that a class can extend only one class(since multiple inheritance is not supported) and implement any number of interfaces. Consider a situation where a class implements 2 interfaces and both the interface have one method in common. 

Consider an eg:


interface inter1
{
    void print();
}
interface inter2
{
    void print();
    void increment();
}
public class psvm implements inter1,inter2
{
    int test=10;
    
    @Override        //OPTIONAL
    public void print()
    {
        System.out.println("hai in print()");
    }
    
    public void increment()
    {
        System.out.println(++test);
    }

    void other_methods()
     {
         //Method Body
      }
    public static void main(String args[])
    {
        System.out.println("hai");
        psvm object=new psvm();
        object.print();
        object.increment();
    }
}

this is possible... the implementing class will have the method common for two interfaces which will satisfy the requirements of both the interfaces(requirements in the sense, if an interface is implemented by a class, then the class must use all the methods given in the interface). Hence it doesn't matter what type of reference variable is used to call the common method. 

To make my statement sooo elementary, let me tell you like this. You promise your friend Thomas that you'll wear red shirt tomorrow. You also promise your friend Jack that you'll wear red shirt. Is it necessary to put two red shirts??? !!!! :-D One red shirt will satisfy the promise made to your friends. The same is applied here.

And note that void print() is prefixed with the keyword public. This is needed to distinguish the print() method from the other normal methods (eg: void other_methods() ) of the class. The keyword public indicates the compiler that the function print() has some declaration before its use (here it indicates that print() is in the interface). Hence public void print() is used rather than mere void print().

Also it is not necessary that all the methods in the interface must be used once a class implements an interface. It may not use some of the methods specified in the interface. In such case, the class name must be prefixed with the keyword abstract.

For eg.
Suppose if we develop a class named xxx which implements inter2 and if class xxx uses only the print() method, then it must be written as
abstract class xxx implements inter2
rather than
class xxx implements inter2This kind of implementation of interface is often called as partial implementations.

And finally, since interface does not contain definition of the methods, an interface can't implement another interface but it can extend other interfaces. It can extend multiple interfaces too.
Eg:
interface A
{
          method1();
          method2();
}
interface B
{
          method3();
}
interface C extends A,B
{
           method4();
}

This is the speciality of an interface, since classes can't extend more than one class but interface can extend one or more interfaces... ;-)

Thanks for reading my blog :-) positive comments are invited. Stay tuned for my next blog... ;-)

Saturday, September 22, 2012

CAN TWO CLASSES HAVE A FUNCTION WITH SAME SIGNATURE WITHOUT INTERFACE?

Consider the program...


class A
{
    void print()
    {
        System.out.println("hai in class A");
    }
}

class B
{
    void print()
    {
        System.out.println("hai in class B");
    }
}

public class y_interface
{
     public static void main(String arg[])
     {
         A obj=new A();
         obj.print();
         B obj1=new B();
         obj1.print();
         
     }
}

Here class A and class B have a function void print() with same signature. The above program runs without any error. Its output is

OUTPUT:
hai in class A
hai in class B

The main intention of this blog is that, there may be confusion like it is not possible to have two classes having function with same signature without interface. The main goal of introducing interface concept in Java is to provide support for multiple inheritance and for polymorphism(i.e. ability to perform same operation on a variety of objects). This blog clears this particular doubt.

Thanks for reading :-) Comment about the blog. Queries are highly welcomed. Stay tuned for my next blog ;-)

Thursday, September 13, 2012


IS IT POSSIBLE TO EXTEND THE CLASS WHICH HAS MAIN FUNCTION???

Yes, it is possible to extend the class which has main function. When i tried it using notepad and command prompt, i got the expected output. In NetBeans, i got a message...
The file has more main classes.
and it asked me to chose the main class from the list. When i choose the super class which has main(), i got the correct output. Also the output is correct when i choose the subclass. But i think it is stupidous to extend a class having main(). I didn't find any answer in Google for this question and i think this kind of inheritance has no real application. The program which i tried is...

public class psvm_class 
{
    int a=5;
   
     public static void main(String args[])
    {
        System.out.println("hai in main()");                                          
        demo obj=new demo();                                   
        obj.display();                               
    }
}
class demo extends psvm_class
{
    void display()
    {
        System.out.println("hai in demo class");
        System.out.println("value of a is "+a);
    }
}

OUTPUT:

hai in main()
hai in demo class
value of a is 5

The above program has two main() functions in it, one which is in psvm_class. Since class demo inherits from psvm_class, it also has one copy of main() !!!!! But still the program runs without any error!!!!!

Discussions and ideas about this peculiar case are invited... Post your ideas and comments about this blog. Sometimes i may be wrong. Your ideas might help me in correcting this blog. Feel free to spot it out. Thanks for reading this blog... ;-) Stay tuned for my next blog...

Wednesday, September 05, 2012


CAN I HAVE THE CLASS CONTAINING MAIN FUNCTION ANYWHERE IN THE PROGRAM?

It is not mandatory that a class which has main() must be at last. It can be anywhere. The program given below is an example...

EG:


public class psvm_class 
{
    static void print()
    {
        System.out.println("hai in print()");
    }
    public static void main(String args[])
    {
        System.out.println("hai in main()");
        print();                     //STATIC MEMBER OF SAME CLASS
        //display();                       THIS WILL THROW AN ERROR
        demo.display();         //STATIC MEMBER OF DIFFERENT CLASS
         System.out.println("a is "+demo.a);
    }
}

class demo
{
    static int a=0;
    static void display()
    {
        System.out.println("hai in demo class");
    }
}



OUTPUT
hai in main()
hai in print()
hai in demo class
a is 0


CAN I CALL STATIC MEMBERS JUST BY ITS NAME IF IT IS NOT PRESENT IN CURRENT CLASS???

It is well known that static members doesn't need any object for accessing it. If static members are present in the class from where it is called, then we can simply use its name for accessing it. But if it is in different class, we can't simply use its name. In this case, it is necessary to use the class name to specify that the static member which we are calling is in the class mentioned while calling. In the above example class demo has a static data member 'a' and static method display(). When they are accessed in main() without class name, an error is thrown like...


Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: display at extend_psvm_class.main(extend_psvm_class.java:12)


Hence the correct way of accessing is 
demo.a
demo.display()

But the static members of the class psvm_class can be called just by their name as
print()


A question may arise like why class name is used for accessing static members in different classes. This is because it is possible to have another class with static display() say...


class demo1
{
    static void display()
    {
        System.out.println("hai in demo1");
    }
}

Now in this case, if we simply use 
display()
then compiler doesn't know which display() method to call. To avoid this ambiguity, whenever static members of different classes are accessed, they are done by their corresponding class name.




Monday, September 03, 2012


CAN WE CALL A METHOD IN A CLASS WITHOUT AN OBJECT FROM MAIN FUNCTION WHICH IS DEFINED IN THE SAME CLASS???

Consider a class, say, class A, with one attribute and one method. main() is also inside the class A. Most of us may think since main() is in class A, we can access data members and methods without using an object. But this is not the case. You require an object to access the class members. 

Eg:


public class psvm
{
    int test=10;
    
    void display()
    {
        System.out.println("hai in display()");
    }
    
    public static void main(String args[])
    {
        System.out.println("hai");
        display();         //THIS WILL THROW AN ERROR!
    }
}

For the above program, you will get an error like...
non-static method display() cannot be referenced from a static context

But if the display method is declared static as
static void display()
then there will not be any error because static members does not require an object for invocation.

Also note keenly that the above program does not have import section but still the above program runs without any error. The reason is that the default package is 
java.lang.*

The reason why this package is made default is, coding a java program becomes useless without much functionality in java.lang because it is in this package, the basic data types like byte, string, int, thread etc are present. Hence this package is made as default.