Home > Java certifications > Java – Console

Java – Console

To get sensitive user input without echoing it to the console/terminal, the Java SDK has introduced the java.io.Console class. The Console class is quite unique in the way it handles its data. It uses the native encoding of the system instead of the using the JVM’s default encoding.

The Console class provides methods to access the console/terminal, if any is associated with the JVM.

Using the Console class:
So how do you use the Console class ? Its pretty simple really. First get a reference to the Console class from the System class

Console con = System.console();

It is not always possible to get a reference to the console. Some scenarios prevent the developer from gaining access to the console. This method may return null in these cases. For example a batch process running on a server will not expect user input and usually does have a console. Your code must be capable of handling such situations.

Consider that you have a program that requires the user to secretly type in his/her password.

Entering sensitive data through the console:

Console con = System.console();
String user = con.readLine("Username: ");
char[] password = con.readPassword("Password: ");

If you were to run this code using the eclipse IDE it would not work (At least in eclipse 3.2).
This is because eclipse does not handle this code properly as yet. Run this code from the command prompt for now. Here is the output of the program


java com.Tests.Cert
Username: hello

Even though the output does not show a password being typed in, the user has typed it in on the console. The console’s feature allows the user to type in the password without it being echoed to the screen.

The line of code con.readLine(“Username: “); reads data from the console normally and stores it into a string. It also echoes whatever the user types onto the screen (you can see “hello” on the output). The line of code con.readPassword(“Password: “); prompts the user for a password but does not echo the contents of the password to the screen. This allows the user to enter his/her password safely using the Console class. To format the output to the screen the following code can be used.

Formatting data:

Console con = System.console();
String user = con.readLine("Welcome %s. Please login \nUsername:","Guest");
char[] password = con.readPassword("What is your password %s:",user);
System.out.println("User: " + user );
System.out.println("Password: " + new String (password) );


java com.Tests.Cert
Welcome Guest. Please login
Username: hello
What is your password hello:
User: hello
Password: bla

Notice that although the password is not visible in the console screen, the program was able to retrieve it. Also the line of code con.readPassword(“What is your password %s: “,user); will format the output such that the username is present when asking for the password. %s represents the String that was passed to the method. Now let’s take a look at using the format() method.

Formatting output only:

Console con = System.console();
con.format("Welcome %s \n", "Mr bond");
String user = con.readLine("Username: ");
char[] password = con.readPassword("What is your password %s:",user);
System.out.println("User: " + user );
System.out.println("Password: " + new String (password) );


Welcome Mr bond
Username: 007
What is your password 007:
User: 007
Password: goldeneye

In this case the formatting that was present in the readLine() method has been transferred to the format() method. Console also has a printf() method that works similar to the format() method. This method however has been made available only for convenience. Finally you can make use of the reader and writer classes to read and write to the Console.

Reader and Writer:
Note: This code throws IOException since we need read/write access to the console

char buffer[]= new char[1024];
Console con = System.console();
Reader reader = con.reader();
int numRead = reader.read(buffer); // #1
System.out.println(new String (buffer).substring(0, numRead) );
Writer writer = con.writer(); // #2


reader -- #a. Input provided by a user
reader -- #b. Written by System.out
reader -- #c. Written by console writer

The #a reader is the input that was provided to the program. The program reads this data using the Reader class. It reads the data into a character buffer in line #1 and prints the data to the console . At line #2 the console’s writer is obtained by the program and the contents of the character buffer are sent to the console output again (this time using System.out). Be wary however, when you use the Reader and Writer classes. They throw the IOException and since this is a checked Exception it must be handled. The code above throws this exception from a method (not shown) and thus need not handle it.

Back to home

Categories: Java certifications Tags: , ,
  1. Monu
    August 20th, 2009 at 04:05 | #1


    First of all, thanks for this post.

    BTW, you can also mention the fact that since readPassword returns a char array and not a string(like readLine) the password will not be pooled and hence it is considered a safer method than readLine().

  2. August 20th, 2009 at 04:16 | #2

    You are welcome.

    I am not sure if readLine() sends Strings to a pool, and even if it did, it is not necessarily any safer. I am not aware of a scenario where an outsider would be allowed to read java’s internal String pool.

    Thanks for sharing your thoughts

  3. Monu
    August 20th, 2009 at 12:12 | #3

    You are right, the string returned by readLine() might not go to the constant string pool. However, it remains in heap.

    There is a little security note in the description of the Console class that reads:

    If an application needs to read a password or other secure data, it should use readPassword() or readPassword(String, Object…) and manually zero the returned character array after processing to minimize the lifetime of sensitive data in memory.

    What I said was based on the above statement-perhaps too much thinking and assumptions.

  4. August 24th, 2009 at 15:37 | #4

    You are right. Strings are immutable and they remain in the heap until the garbage collector takes over. And when they are in the heap, they can be read by some profiling tools and heap analyzers.

    However this is a great post. Thanks for putting this up.

  5. August 24th, 2009 at 15:56 | #5


    ah ! a good point. You should still be able to sniff the heap data. I have to agree that getting rid of the reference as soon as possible is a good idea.

  6. September 6th, 2009 at 12:01 | #6

    It very good article which never came across before. Good job…

    Your blog is informative and good to spend :)

  7. Sonika
    October 30th, 2009 at 06:32 | #7

    Good post.
    This article helped me a lot to understand the facts of Console class and that too very easily.
    Thanks a lot!!!

  8. October 30th, 2009 at 07:53 | #8

    Thanks Yousuff.

    I am glad you found it useful. Thank you for leaving a comment

  9. Luciano
    November 11th, 2009 at 01:44 | #9

    Very Useful!

    I didn’t found any other reference instead of the Java API.


  10. November 11th, 2009 at 05:29 | #10

    I am glad you found it useful. Thank you for leaving your thoughts here

  11. Fort
    December 22nd, 2009 at 13:24 | #11

    Just in time before I take my certification exam. Good article/tutorial. Thanks!

  12. shruti
    February 21st, 2010 at 19:41 | #12

    thanks CertPal
    post is very useful
    good discussion
    thanks for the efforts

  13. Samuel
    April 19th, 2010 at 17:07 | #13

    Always useful info

  14. Paul
    May 1st, 2010 at 02:30 | #14

    Thanks for the info. Yet another scenario where heap is readable is JVM crash with core dump.Core dump will have whatever was in heap at the time.

  15. May 10th, 2012 at 08:53 | #15

    I like what you guys are up too Such smart work and reporting! Carry on the superb works guys I’ve incorporated you guys to my blogroll I think it will improve the value of my website

  16. July 9th, 2013 at 21:39 | #16

    La Sinonimia, i Sinonimi, i Contrari italiani

    La espressione sinonimo deriva dal Greco Antico (“synonymia” significava generalità in universale).
    Nell’ambito della semantica, il sinonimo indica due lessemi con la medesima accezione. Il sinonimo è l’opposto di avverso (detto altresì “antonimia”).

    Due sinonimi possono essere identificati ricorrendo al criterio
    della interscambiabilità, ciononostante quest’ultima non può giammai risultare assoluta.

    Invero la corrispondenza con il significato, il suo di lui singolare significante e la referenza paralinguistica restano unici verso ogni espressione.

    Per sinonimia si può cogliere altresì quella speciale forma retorica attraverso la quale si rappresenta il medesimo proposito impiegando parole con significato affine, vale a dire utilizzando o sinonimi, appunto, o anche la così detta metafora.

    In quest’ultima possibilità non si ottiene, tuttavia, una coerenza perfetta di senso, invece una corrispondenza; la mutazione stessa, accorgersi e seguire,
    sorvegliare e percepire, rende in misura maggiore facile l’impiego retorico della tecnica sinonimica.

    Molte importanti figure retoriche, come la iperbole, la circonlocuzione, l’enfasi delle ripetizioni, fanno reiteratamente appello alla sinonimia,
    in particolare nella climax anticlimax, dove fondamenti della ripetizione sono sovente sinonimi.

    Ulteriori particolari:

  17. April 24th, 2014 at 17:56 | #17

    Hello it’s me, I amm alsso vvisiting this website regularly, thiis website is really pleasaznt and tthe people are in fact sharing pleasant

  18. July 20th, 2014 at 03:50 | #18

    You’ve made some decent points there. I looked on thhe net forr more information about thee issue and found most iindividuals will go alongg with your views on this site.

  19. September 27th, 2014 at 00:44 | #19

    I was suggested this web site by my cousin. I’m not sure whether this post is written by him as nobody
    else know such detailed about my trouble. You’re amazing!


  20. October 13th, 2014 at 06:35 | #20

    Having read this I believed it was really informative.

    I appreciate you spending some time and effort to put this informative article together.
    I once again find myself spending a significant amount of time both reading and posting comments.

    But so what, it was still worthwhile!

  21. October 19th, 2014 at 03:54 | #21

    The luxury of Earth4Energy Manual is understandable as well as the convenience it could possibly offers are great. Individuals who have very fundamental skills may make use of the product to generate electricity from your own home using only Wind generators and Pv Panels. Earth4Energy offers fabulous strategies to effectively build as well as set up their very own energy generating processes for below what $ As soon as someone have setup their very own energy generating system using only the guide, there’re on the way to conserve anyplace between 70% to 100% on their own monthly Power Bills. When someone has produced far more power compared to what they could use, somebody can simply then just simply sell the excess energy back in their nearest energy/power company. Make moolah from an energy company, and send their situation the check! Now, thats a great idea!

  22. March 9th, 2015 at 19:28 | #22

    A fascinating discussion is worth comment. I do think
    that you should publish more about this subject
    matter, it might not be a taboo matter but generally people don’t discuss these subjects.
    To the next! Best wishes!!

  23. April 29th, 2015 at 12:09 | #23

    Just what I was searching for, regards for putting up.

  24. June 15th, 2015 at 12:31 | #24

    If you desire to increase your knowledge simply keep visiting this web site and be updated with the most recent news posted here.

  25. June 28th, 2015 at 04:14 | #25

    Every weekend i used to go to see this site, because i wish for enjoyment,
    since this this web page conations genuinely nice
    funny information too.

  26. July 14th, 2015 at 06:42 | #26

    Thank you, I’ve recently been looking for info approximately this subject for
    ages and yours is the greatest I’ve came upon till now.
    But, what about the bottom line? Are you sure about the supply?

  27. August 12th, 2015 at 08:02 | #27

    Hi my family member! I wish to say that this article is awesome, nice written and include approximately all significant infos. I would like to peer extra posts like this.

  28. August 16th, 2015 at 21:23 | #28

    obviously like your web-site but you have to check the spelling on quite a few of your posts. A number of them are rife with spelling problems and I find it very bothersome to tell the truth however I’ll definitely come back again.

  29. September 3rd, 2015 at 12:54 | #29

    Just want to say your article is as amazing. The clarity in your post is just great and i can assume you are an expert on this subject. Well with your permission allow me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please carry on the gratifying work.

  30. September 10th, 2015 at 15:46 | #30

    htc one m9+ kılıf

  31. September 11th, 2015 at 17:08 | #31

    That is really attention-grabbing, You are an excessively professional blogger.
    I have joined your feed and look ahead to in the hunt for extra of your great post.
    Also, I’ve shared your web site in my social networks

  32. September 17th, 2015 at 05:56 | #32

    While lots of Android apps are going free today, the
    best deals include:. Android is one of the biggest and most famous mobile platforms in all over the world that integrates thousands
    of mobile phone, tablets and many other devices.
    They should have a better understanding of the trends in Android application development.

  33. September 28th, 2015 at 12:04 | #33

    I got what you mean , thanks for putting up.Woh I am pleased to find this website through google. “Wisdom doesn’t necessarily come with age. Sometimes age just shows up by itself.” by Woodrow Wilson.

  34. October 1st, 2015 at 13:53 | #34

    It’s appropriate time to make a few plans for tthe longer term and it
    is time to be happy. I’ve learn this post and if I may just I desire to counsel you few fascinating things or tips.Perhaps you could write subsequent
    articles relating to this article. I wish to
    read more things approximately it!

  35. October 10th, 2015 at 11:15 | #35

    Thanks foor every other informative blog.

    Where else could I get that kind of info written in such a perfect approach?

    I have a undertaking that I am just now working on, and I have been at
    the glance out for such information.

  36. October 12th, 2015 at 15:08 | #36

    I know this website offers quality based articles or reviews
    and extra information, is there any other website which gives such information in quality?

  37. October 25th, 2015 at 12:23 | #37

    This paragraph is in fact a fastidious one it assists new net
    viewers, who are wishing for blogging.

  38. November 10th, 2015 at 10:02 | #38

    Great – I should certainly pronounce, impressed with your web site. I had no trouble navigating through all the tabs as well as related info ended up being truly easy to do to access. I recently found what I hoped for before you know it at all. Reasonably unusual. Is likely to appreciate it for those who add forums or something, web site theme . a tones way for your client to communicate. Excellent task.

  39. November 13th, 2015 at 08:57 | #39

    I genuinely enjoy studying on this internet site , it contains great blog posts. “Violence commands both literature and life, and violence is always crude and distorted.” by Ellen Glasgow.

  40. November 30th, 2015 at 12:24 | #40

    Merely wanna input on few general things, The website style is perfect, the written content is very great : D.

  1. February 25th, 2011 at 12:40 | #1