This post originated from an RSS feed registered with Java Buzz
by instanceof java.
Original Post: Static import In java
Feed Title: Instance Of Java
Feed URL: http://feeds.feedburner.com/blogspot/TXghwE
Feed Description: Instance of Java. A place where you can learn java in simple way each and every topic covered with many points and sample programs.
If we want to reuse any predefined class or user defined class or interface or enum which is present in a package we need to import those entire packages or those classes so that we can use those classes present inside the package.
import packagename.ClassTest;
import packagename.*;
For example if we want to read some data from keyboard we can use scanner class present in util package.
import java.util.Scanner;
We can import everything inside a package by using .*
import java.util.*;
Without importing want to use that class then code seems to like this
package com.instanceofjava;
class A{
public static void main(String [] args){
int number;
java.util.Scanner in = new java.util.Scanner(System.in);
System.out.println("Enter a number to check even or odd");
number=in.nextInt();
}
}
if we use import no need to mention class name in declaration
package com.instanceofjava;
import java.util.Scanner;
class A{
public static void main(String [] args){
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number to check even or odd");
number=in.nextInt();
}
}
Static import:
Normal imports will import the all the classes so that we can use them. similarly static imports will import all static data so that can use without class name.
One of the advantage of using static imports is reducing keystrokes and re usability.
System.out.println() ; we can write as out.println() . But using eclipse short cut syso (ctrl+sapce) gives System.out.println() faster than static imports usage.
And there may be a chance of complexity in readability.
If we use class name before method like Math.sqrt() then can understand easily that method belongs to particular class . with static imports reduces readability.
One more disadvantage is naming conflicts.
If we use Integer.Max_value we cannot use Float.Max_value