In training materials from ElementK, I observed the use of System.in.read() to accept input from the keyboard. In my intro to Java class, I was taught to use the Scanner class in Java. What is the different between these two methods?
I’ll talk about the Scanner class although the Java API docs do a much better job of clarification. If you want to create a simple Java program where the user is prompted to enter words, characters or numbers, you need a class that allows you to do this. The Scanner class does not belong to the java.lang package to you need to import the Scanner class from java.util.Scanner using the import command at the top of your Java class.
I’m taking advantage of training materials offered through an alliance with my school and ElementK to bone up on Java. I am currently taking the Java Fundamentals course which is a nice follow-up to the Intro to Computer & Programming course I just completed. With a little Java under my belt, I know that comparing two Object variables using the == operator can lead to unwanted results. In Java, object variables only hold the address in memory where the object is stored. Backing up a bit, here’s the code for creating an object in Java:
Classname objVar = new Classname();
The new operator allocates memory for the object to be created, calls the Class constructor and returns a reference to that memory which is then assigned to objVar.
So, if you do a direct comparison of two object variables like this obj1 == obj2, you are really comparing the memory locations of the objects you want! Unless your specific intent is to check and see if an object is an alias of another, you should avoid direct comparisons if you’re really trying to compare the state of two objects.
Imagine my surprise to find this snippet of code in ElementK’s training files for testing equality:
In this case, my recommended change would be:
where the getName() method returns a String object which we can them compare using the built-in equals or equalsIgnoreCase methods to compare the values returned by getName().
I haven’t actually read them yet but with my upcoming free time, I’ll make some headway. So much to do! 🙂 Without making this post longer than it needs to be, here are the achievements I unlocked!
but there’s not “follow-up”