Avatar of gudii9
gudii9
Flag for United States of America asked on

stack example

hi,
import java.util.Stack;


public class Stacks {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
Stack person= new Stack();
person.push("adam");
person.push("brian");
person.push("charlie");
System.out.println("top person"+person.peek());

	}

}

Open in new window


i was trying above example.
Does java.util.* needs to be imported all the time?

Does not jdk 7 or 8 bundled and come with util package. which packages come by default with jdk.

please advise
Java EEJavaProgramming Languages-Other

Avatar of undefined
Last Comment
Jim Cakalic

8/22/2022 - Mon
gudii9

ASKER
i wonder why charlie showed as below
top personcharlie
gudii9

ASKER
is Stack is a keyword. i cannot use as class name looks like
SOLUTION
ozo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
ozo

Not a keyword, but you already defined it here:
import java.util.Stack;
Your help has saved me hundreds of hours of internet surfing.
fblack61
gudii9

ASKER
ok

Does java.util.* needs to be imported all the time?

Does not jdk 7 or 8 bundled and come with util package. which packages come by default with jdk.

please advise
ozo

Only the methods you use need to be imported.
Since the package is bundled by default, you can import it without first having to install it separately from the jdk.
Jim Cakalic

Hi.

All Java classes are arranged in packages which group related classes and interfaces together into a common "namespace". Every class or interface has a simple name from its definition and a fully-qualified name that includes the package in which it was declared using the package directive. So Object is really java.lang.Object and String is really java.lang.String. The java.lang package contains classes that are fundamental to the Java language, many (perhaps all) are used directly by the compiler. For this reason, the java.lang package is implicitly imported by the compiler so you can simply refer to String and not have to type java.lang.String everywhere you want to reference that class.

A class in a package can refer to any other class in the same package by its simple name. Classes in packages other than the same package and java.lang, regardless of their source -- provided with the jdk/jre, third part libraries, part of your application, must either be explicitly imported or be referenced by their fully-qualified name.

So the answer to your question, "Does java.util.* need to be imported" is technically No because you could choose to refer to all classes from that package with the fully-qualified name.  For example:

java.util.Stack stack = new java.util.Stack();

Open in new window


Because this gets ugly and verbose very quickly, the import statement is provided to allow you to tell the compiler how to resolve the fully-qualified names of classes in your source. When the compiler encounters a simple class name, it uses knowledge of the package directive and import statements to determine what class you really mean by the simple name. So you could choose to import java.util.Stack and then anywhere you refer to the type you simply say Stack because the compiler understands what you mean by virtue of the import. Or you could import java.util.* to define how to resolve all the classes and interfaces in that package. So while not technically required, it is good practice to use import statements to specify the fully-qualified names of classes on which your code is depending because it leads to more readable code and the imports serve to document your dependencies.

Package directives and import statements are syntatical elements -- they do not tell the JVM where to find the compiled bytecode of a class at runtime. ClassLoaders do this based on classpath definitions which specify jars , folders, etc. where dependent classes might be found.

Best regards,
Jim Cakalic
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
gudii9

ASKER
Package directives and import statements are syntatical elements -- they do not tell the JVM where to find the compiled bytecode of a class at runtime. ClassLoaders do this based on classpath definitions which specify jars , folders, etc. where dependent classes might be found.

i think i did not get this. can you please elaborate.


java.util.Stack stack = new java.util.Stack();

Open in new window


instead of avoiding pain of writing like above everytime if we import then we can write like below right

Stack stack = new java.util.Stack();

But we may end up many imports right even if we write simple program. What are most common imports we need to take into consideration.

Is eclipse Java Build Path Add External JARS and ADD JARS etc similar concepts to this idea. please advise
Jim Cakalic

You are correct. It is possible even with a reasonably simple class to have many imports. Eclipse has an "organize imports" feature that will analyze your code and automatically add (if possible) the imports required and organize (sort) them based on configuration rules you provide. CTRL-SHIFT-O (control shift oh) will do that.

Imports should be kept explicit if possible - individual classes and interfaces or specific constants and methods in the case of import static. This can get unsightly and/or unwieldy at some point. So typically at the point where you are importing some number of classes from the same package you'll change to the wildcard import. I think the Eclipse default might be 10. So say in addition to Stack you were going to import and use in the same class List, ArrayList, Set, HashSet, Map, TreeMap, Collection, Collections and a few others all from java.util. Using organize imports, when the list of imports reaches the prescribed number the individual imports will be removed and a wildcard java.util.* import will be added to indicate that everything in the java.util package should be added to the namespace.  The Java Build Path, Jar dependencies, maven dependencies, etc. are used to determine which classes are present in the project and could be candidate imports.

None of this has any runtime overhead. As yet these are all just textual elements to help the compiler. You  could reference just java.util.Stack in your code but import java.util.* and there is no difference in the size of the .class file created by the compiler or the footprint of the JVM when it runs the application. Speaking of which, it is the JVM that ultimately determines how to resolve class dependencies using the CLASSPATH specified folders and jars. So you might, for example, compile your application using the Java 1.5 compiler but run it using the Java 1,8 jvm. This is no problem so long as runtime resolved classes (in the case of java.util from rt.jar) have all the necessary methods with correct signature and scope as those of the compile time classes.
Jim Cakalic

By and large, you don't want to just always include some set of imports deemed commonly useful. Imports help other developers understand the larger context of your class so they should be specific to the dependencies of the actual code in the class. You might use SimpleDateFormat at lot. But it would be bad practice to always have an import for java.text.SimpleDateFormat or worse java.text.*. Reading just the imports, I would get the wrong idea about the dependencies (and possible behaviors) of your class. Some coding standards, like those from Google, do not allow wildcard imports at all (https://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s3.3-import-statements).

Jim
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
gudii9

ASKER
and organize (sort) them based on configuration rules you provide.


please elabirate on how to provide above configuration. i do not remember providing it.


specific constants and methods in the case of import static.


what is static import



I think the Eclipse default might be 10.


where to see it in eclipse and how to change it. I did not understand what it means.



The Java Build Path, Jar dependencies, maven dependencies, etc. are used to determine which classes are present in the project and could be candidate imports.


Any good link or book or tutorial or resource on this. This is most commonly used in projects but i do not have whole lot of idea on this.




it is the JVM that ultimately determines how to resolve class dependencies using the CLASSPATH specified folders and jars.



what are CLASSPATH specified folders and jars. and how JVM determines and resolve the dependencies.





compile your application using the Java 1.5 compiler but run it using the Java 1,8 jvm. This is no problem so long as runtime resolved classes (in the case of java.util from rt.jar) have all the necessary methods with correct signature and scope as those of the compile time classes.


How to ensure methods have correct sinature and scope as those of compile time classes in case of different compiler, jvm versions. How to change compiler and jvm versions in eclipse to test this.  Does eclipse have all these built in compiler , jvm versions within it or do i need to physically download it to my laptop and set advanced variable to JAVA and PATH and JAVA_HOME etc. Please advise
Jim Cakalic

Jim: and organize (sort) them based on configuration rules you provide.
Author: please elaborate on how to provide above configuration. i do not remember providing it.
Reply: In eclipse, click on the Window->Preferences menu item.In the text box on the top left of the dialog type organize imports and hit ENTER or click thru the tree to Java->Code Style->Organize Imports. This dialog is where you set the configuration for how eclipse reponds when you use the organize imports feature.

Jim: specific constants and methods in the case of import static.
Author: what is static import?
Reply: Static import is a construct introduced in Java 5 that allows unqualified access to static members without inheriting from the type containing the static members. For example, to reference the constant java.lang.Math.PI without fully-qualifying the package and class or even specifying the owning classname, your program can import it, either individually
      import static java.lang.Math.PI;
or en masse (all constant and static methods of the Math class):
      import static java.lang.Math.*;

Jim: I think the Eclipse default might be 10.
Author: where to see it in eclipse and how to change it. I did not understand what it means.
Repy: This is in the Organize Imports configuration as discussed in the first question.

Jim: The Java Build Path, Jar dependencies, maven dependencies, etc. are used to determine which classes are present in the project and could be candidate imports.
Author: Any good link or book or tutorial or resource on this. This is most commonly used in projects but i do not have whole lot of idea on this.
Reply: Here are two. For more google either eclipse build path or eclipse build path maven
http://www.informit.com/articles/article.aspx?p=367962 
http://ted-gao.blogspot.com/2011/09/using-maven-to-manage-library.html?_sm_au_=iVVTqvdVnTPWnDPV

Jim: it is the JVM that ultimately determines how to resolve class dependencies using the CLASSPATH specified folders and jars.
Author: what are CLASSPATH specified folders and jars. and how JVM determines and resolve the dependencies.
Reply: http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html

Jim: compile your application using the Java 1.5 compiler but run it using the Java 1,8 jvm. This is no problem so long as runtime resolved classes (in the case of java.util from rt.jar) have all the necessary methods with correct signature and scope as those of the compile time classes.
Author: How to ensure methods have correct sinature and scope as those of compile time classes in case of different compiler, jvm versions. How to change compiler and jvm versions in eclipse to test this.  Does eclipse have all these built in compiler , jvm versions within it or do i need to physically download it to my laptop and set advanced variable to JAVA and PATH and JAVA_HOME etc. Please advise.
Reply: At runtime you'll get an IncompatibleClassChangeError. For configuration of compiler and runtime in Eclipse see
http://blog.ajduke.in/2013/04/28/setting-up-new-java-compiler-and-runtime-in-eclipse-ide/

Regards,
Jim
gudii9

ASKER
Jim: and organize (sort) them based on configuration rules you provide.
Author: please elaborate on how to provide above configuration. i do not remember providing it.
Reply: In eclipse, click on the Window->Preferences menu item.In the text box on the top left of the dialog type organize imports and hit ENTER or click thru the tree to Java->Code Style->Organize Imports. This dialog is where you set the configuration for how eclipse reponds when you use the organize imports feature.

i tried as attached. i was not sure how to go next from there to set the configuration.

i have sample code as below in eclipse

public class TestHashMap {
	public static void main(String[] args) {
		HashMap hashMap = new HashMap();
		Dog d1 = new Dog("red");
		Dog d2 = new Dog("black");
		Dog d3 = new Dog("white");
		Dog d4 = new Dog("white");
		
		hashMap.put(d1, 10);
		hashMap.put(d2, 15);
		hashMap.put(d3, 5);
		hashMap.put(d4, 20);

		//print size
		System.out.println(hashMap.size());
		
		//loop HashMap
		for (Entry entry : hashMap) {
			System.out.println(entry.getKey().toString() + " - " + entry.getValue());
		}
	}
}

Open in new window


i clicked cntl+shift+o but it did not import
import java.util.HashMap;
automatically. please advise
OrganizeImp.jpg
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
gudii9

ASKER
Jim: I think the Eclipse default might be 10.
Author: where to see it in eclipse and how to change it. I did not understand what it means.
Repy: This is in the Organize Imports configuration as discussed in the first question.

i see 99 is that is the eclipse default ?(actually i am using RSA

IBM Rational® Software Architect for WebSphere Software

Version: 8.0.4
Jim Cakalic

Did not import HashMap using ctrl-shift-O

Not sure why. I created a new Java project in eclipse and in the project created the class TestHashMap into which I copied the code you posted. When I hit ctrl-shift-o Eclipse add the imports java.util.HashMap and java.util.Map.Entry asking about which Entry I wanted because there were two: Map.Entry and KeyStore.Entry.

I see 99 as the default for replacing individual imports with wildcard.

That would appear to be correct. Don't know if I was remembering an older version of eclipse or perhaps a custom setting for a client project on which I worked.

Regards,
Jim
gudii9

ASKER
The java.lang package contains classes that are fundamental to the Java language, many (perhaps all) are used directly by the compiler. For this reason, the java.lang package is implicitly imported by the compiler so you can simply refer to String and not have to type java.lang.String everywhere you want to reference that class.




why not java.util implicitly imported by java which also seems to me fundamental to java language.

I wonder why we cannot use all classes in java.util directly. I feel java designers should have handled java.util and other common packages similar to how java.;ang is being used.

Please advise




r you could import java.util.* to define how to resolve all the classes and interfaces in that package. So while not technically required, it is good practice to use import statements to specify the fully-qualified names of classes on which your code is depending because it leads to more readable code and the imports serve to document your dependencies.



if i want only Stack is it better to import like below

import java.util.Stack;
or import like below better
import java.util.*;


is there is any performance implication kind of issue if we use  like import java.util.*;






Package directives and import statements are syntatical elements -- they do not tell the JVM where to find the compiled bytecode of a class at runtime. ClassLoaders do this based on classpath definitions which specify jars , folders, etc. where dependent classes might be found



what are ClassLoaders. I am not very familiar with classLoaders. please advise
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ASKER CERTIFIED SOLUTION
Jim Cakalic

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.