Are java imports used professionally? - java

I'm currently self studying Java, and am not sure with this "import" thing. It adds classes(not sure), and has methods that would serve a different function relative on the type of class I declare from the "import"ed thing.
I'm curious if import is frequently used for work, or is this relative to the user if he/she would want to use import or not.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner ThisObject = new Scanner(System.in);
}
}

Java import is a compile time feature that allows you to omit the package name when programming. There is no byte-code import, the compiler will replace
Scanner ThisObject = new Scanner(System.in);
with
java.util.Scanner ThisObject = new java.util.Scanner(System.in);
As for how common it is, I would say extremely. However, there is another form of import called static import which allows you to bring static methods and fields from another class into your current namespace. static import is not very common. Finally, Java variable names start with a lower case letter (by convention).
import static java.lang.System.in;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner thisObject = new Scanner(in); // System.in through static import
}
}

Related

Using pre-defined class names in java

I'm fairly new to Java. I learnt that the names of predefined classes in java are not keywords and thus we can use those as identifiers.
I tried out the following code: (I know that that import is redundant)
import java.lang.*;
class Process{
public Process(){
System.out.println("Constructor of Process");
}
}
public class NewMain {
public static void main(String[] args) {
Process p = new Process();
}
}
and the out put was:
Constructor of Process
However, when I replaced import java.lang.*; with import java.lang.Process;, I got an error cause it tried to instantiate the predefined Process class. I had assumed that the program will check scope by scope and will thus execute the userdefined class constructor in both cases. How am I wrong?

How to correctly write the extends functionality instead of import statement? [duplicate]

This question already has answers here:
What's the difference between importing and extending a class?
(10 answers)
Closed 3 years ago.
Instead of import statement , I am using extends attribute for java.util.Scanner class.I am getting error with below code snippet.How to correct it?
class test extends java.util.Scanner {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value from keyboard:");
int ans = sc.nextInt();
System.out.println("The value entered through keyboard ::"+ans);
}
}
Short answer: you can't because java.util.Scanner is final and you cannot extend it.
But, you can using encapsulation as follow, in same package create a new class MyScanner:
import java.io.InputStream;
import java.util.Scanner;
public class MyScanner implements Iterator<String>, Closeable {
private Scanner scanner;
public MyScanner(InputStream in) {
this.scanner = new Scanner(in);
}
//Override classes you need
}
and use it in your class:
import java.io.InputStream;
import java.util.Scanner;
public class MyScanner {
private Scanner scanner;
public MyScanner(InputStream in) {
this.scanner = new Scanner(in);
}
public int nextInt() {
return scanner.nextInt();
}
}
Be aware that solution here is to declare two classes in same package
You can't extend the Scanner class since it's final.
Even if it was possible, extending Scanner doesn't allow you to eliminate the import statement when you refer to the Scanner class without the package name.
It makes no sense to extend Scanner for the given code. If you want to avoid the import statement, use the full class name:
class test
{
public static void main(String[] args)
{
java.util.Scanner sc = new java.util.Scanner(System.in);
System.out.println("Enter the value from keyboard:");
int ans = sc.nextInt();
System.out.println("The value entered through keyboard ::"+ans);
}
}
Scanner is a final class and can therefore not be extended.
If you want to use the scanner without importing it explicitely, you could try the following:
class Test
{
public static void main(String[] args)
{
java.util.Scanner sc = new java.util.Scanner(System.in); // Specify full class path over here
System.out.println("Enter the value from keyboard:");
int ans = sc.nextInt();
System.out.println("The value entered through keyboard ::"+ans);
}
}
Keep in mind the naming conventions: a class name should start with an uppercase letter.

Static import with same static variable names

I am doing a static import of members of class Long and Integer:
import static java.lang.Integer.MAX_VALUE;
import static java.lang.Long.MAX_VALUE;
Now if I am trying to use this variable MAX_VALUE and print it I will get an error:
import static java.lang.Integer.MAX_VALUE;
import static java.lang.Long.MAX_VALUE;
public class StaticImportDemo2 {
public static void main(String[] args) {
//Error :: The field MAX_VALUE is ambiguous
System.out.println("Print without static import Integer.MAX_VALUE "+MAX_VALUE);
}
}
This is fine. To remove the error i will have to remove one static import to resolve this ambiguity .
The main issue I am getting is, if I use wildcard * with Integer class
static import, the class gets compiled with no errors:
import static java.lang.System.out;
import static java.lang.Integer.*;
import static java.lang.Long.MAX_VALUE;
public class StaticImportDemo2 {
public static void main(String[] args) {
System.out.println("Print without static import Integer.MAX_VALUE " + MAX_VALUE);
}
}
The ambiguity must still exist. Why does this compile with no issues?
Why does this compile with no issues?
Because the Java Language Specification says that it does. See chapter 6 and 7, but particularly from 6.4.1:
A type-import-on-demand declaration never causes any other declaration to be shadowed.
A static-import-on-demand declaration never causes any other declaration to be shadowed.
And that’s probably because it’s very convenient to be able to wildcard-import entire packages, but sometimes you’ll have to resolve conflicts. It would suck (particularly in pre-IDE days) if the only alternative was to explicitly import every item. So specific (non-wildcard) imports were given precedence. That way, you just specify which you mean for the ambiguous items you want to use.

Scanner Object Error

I don't understand why I always get an error whenever I create a new object from the Scanner class.
I have JDK 1.8.0.25
import java.util.Scanner;
public static Scanner input = new Scanner (System.in);
public class NewClass {
public static void main(String args[]) {
System.out.print("Hello");
}
}
You can't define variable outside the class, so define your scanner within your class like:
public class NewClass {
public static Scanner input = new Scanner (System.in);
..
}
Static is a class variable and details about the variables are here
It seems to me you are trying to write java using a Text editor. My suggestion is to use an IDE (NetBeans is my favorite, but Eclipse is a very common choice) and to follow Oracle lessons on the site. As for your problem : curly braces denote the start and end of a class, fields are declared inside of a class, so they must go after the first open braces.
Also : try to avoid using the static and public modifiers in fields.
You can't just define a variable, even if it is a static variable in the middle of nowhere - it should be defined inside a class. E.g.:
import java.util.Scanner;
public class NewClass {
// Moved inside the class
public static Scanner input = new Scanner (System.in);
public static void main(String args[]) {
System.out.print("Hello");
}
}

questions on static import on java

import static java.lang.System.out;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class ShadowingByImporting
{
public static void main(String[] args)throws FileNotFoundException
{
out.println("Calling println() in java.lang.System.out");
PrintWriter pw=new PrintWriter("log.txt");
writeInfo(pw);
pw.flush();
pw.close();
}
public static void writeInfo(PrintWriter out)
{
out.println("Calling pritnln() in the parameter out");
System.out.println("Calling println() in java.lang.System.out Example");
}
}
The above program is given in Khalid Mugal's SCJP Guide,according to him by the principle of shadowing in static import the second println method in writeInfo. Method will execute twice, but when I run this following dissimilar output came.
Please somebody explain what's the actual concept.
Calling println() in java.lang.System.out
Calling println() in java.lang.System.out Example
This has nothing to do with static imports in general,
but rather with the fact that the parameter out of writeInfo is hiding the outer definition of out which in this case happens to be a static import.
This hiding is also possible when you have
public class ShadowingByImporting
{
PrintWriter out = ...;
public static void main(String[] args)throws FileNotFoundException
{
In function writeInfo, the out is a local variable, while System.out is fully-qualified, representing the standard output stream.
static import is generally used to import static public object into your scope, like System.out in this case. So you can use out directly without the fully qualified name ClassName.ObjectName, System.out in this case.

Categories

Resources