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
LVL 7
gudii9Asked:
Who is Participating?
 
Jim CakalicSenior Developer/ArchitectCommented:
Q: 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.lang is being used.
A: I suppose one could make that argument. It was a design choice and I don't know what criteria the Java designers used when making that decision. You could argue that the classes in java.util are one possible implementation of those concepts. The two largest groups of classes within java.util are collections and date/time facilities. There are alternate implementations for both these concepts. For collections see http://java.dzone.com/articles/java-collections-%E2%80%93-are-there. One framework that I'm seeing increasing used is guava (google collections). An alternate date/time facility was implemented previously as JodaTime and as of Java 7 found it's way into the JDK as a replacement for the maligned Date and Calendar classes (a much needed replacement IMO). Because java.util uses some pretty obvious good names for things (List, Set, Tree, Map, Iterator, Date, Calendar ...), an alternate framework could readily use the same names. In this case, if you wanted to use that alternate framework, you would find that the automatic importing of java.util by the compiler had "polluted" the namespace forcing you to fully-qualify all your alternate references (e.g., org.guru.better.collections.List everywhere you referenced the alternate List interface.) The classes in java.lang are fundamental to the language itself (java.lang.Object) or used heavily by the compiler (java.lang.String, java.lang.StringBuilder).

Q: If i want only Stack is it better to import java.util.Stack or java.util.*?
A: Importing just java.util.Stack is preferred.

Q: Is there is any performance implication kind of issue if we use  like import java.util.*;
A: No. Absolutely no runtime performance issues. Import statements are purely for the compiler, not the runtime interpreter.
http://www.javaperformancetuning.com/news/qotm031.shtml

Q: what are ClassLoaders. I am not very familiar with classLoaders. please advise.
A: If you google java classloaders you'll get a lot of hits. Here's one from O'Reilly that looks pretty good:
http://www.onjava.com/pub/a/onjava/2005/01/26/classloading.html

Regards,
Jim
0
 
gudii9Author Commented:
i wonder why charlie showed as below
top personcharlie
0
 
gudii9Author Commented:
is Stack is a keyword. i cannot use as class name looks like
0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

 
ozoCommented:
"charlie" was the last item pushed onto the stack, so it was the one on top.
0
 
ozoCommented:
Not a keyword, but you already defined it here:
import java.util.Stack;
0
 
gudii9Author Commented:
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
0
 
ozoCommented:
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.
0
 
Jim CakalicSenior Developer/ArchitectCommented:
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
0
 
gudii9Author Commented:
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
0
 
Jim CakalicSenior Developer/ArchitectCommented:
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.
0
 
Jim CakalicSenior Developer/ArchitectCommented:
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
0
 
gudii9Author Commented:
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
0
 
Jim CakalicSenior Developer/ArchitectCommented:
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
0
 
gudii9Author Commented:
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
0
 
gudii9Author Commented:
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
0
 
Jim CakalicSenior Developer/ArchitectCommented:
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
0
 
gudii9Author Commented:
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
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.