Import Statements with examples:
Let me explain import statement with an example
Example 1:
class Test
{
public static void main(String[]
agrs)
{
Arraylist
al=new Arraylist();
}
}
Compile time error cannot find symbol symbol: class
Arraylist Location: class Test
This issue can be resolved in two ways:
Sol1: Using fully qualified name like java.util.Arraylist
al=new java.util.Arraylist();
Sol2: Importing java.util.Arraylist like import
java.util.Arraylist; (this is the preferred solution)
Types of import:
- . Explicit class import
- Implicit class import
Explicit class import: example is import
java.util.Arraylist;
It is highly
recommended to use explicit class import because it increases the readability
of the code.
Implicit class import: example is import java.util.*;
It is not recommended as it reduces the readability of the
code.
Example of Implicit class import:
Example1:
import java.util.*;
import java.sql.*;
class Test
{
public
static void main(String[] args)
{
Date
d=new Date();
}
}
Compile time error “reference to Date is ambiguous”.
We are getting this ambiguity problem as Data is available in
both util and sql package. So it is recommended to use explicit class import
Example2:
import java.util.Date;
import java.sql.*;
class Test
{
public
static void main(String[] args)
{
Date
d=new Date();
}
}
Util package Date will be considered
While resolving class name compiler uses the following
precedence
1.
Explicit class import
2.
Classes present in present working directory
3.
Implicit class import
import com.thoughtworks.selenium.DefaultSelenium;
ReplyDeleteimport com.thoughtworks.selenium.rc;
public class demofb {
public static void main(String[] args) {
// TODO Auto-generated method stub
DefaultSelenium rc = new DefaultSelenium("localhost", 4444 , "firefox C:\\Program Files (x86)\\Mozilla Firefox", "https://www.facebook.com");
rc.start();
i have given an import statement like this and i am getting an error as
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at rcdemofb.demofb.main(demofb.java:7)
what is the problem and how could i resolve it.
The explanation of import statements is invaluable for every Java developer. It clarifies the significance of imports in organizing code and avoiding conflicts. Cybersecurity Predictions Future The examples and best practices make it easy.
ReplyDelete