• Google+
  • Twitter
  • YouTube
  • RSS
  • Facebook

Latest Java and Programming Tutorials

C++ for Beginners: If/Else

coffeenews
The If/Else statement lets you choose between two alternative actions in your program, which happens……..

C++ for Beginners: The “If” Statement
C++ for Beginners: Char and Bool
What’s New in Java 8: Lambda Expressions
C++ for Beginners: Floating Point Variable Types – Double and Float

You can now access ALL my premium courses for just $19 a month, cancellable anytime; no minimum period. Click here!

Java Spring Framework Tutorial

The Java Spring Framework Tutorial

My latest premium tutorial is an extensive introduction to the popular Spring Framework, including web programming with Spring MVC. $29.
My Kindle book about online teaching and my many attempts to free myself from office work … How to Make a Great Living Teaching Online

Java for Complete Beginners

Java for Complete Beginners

Completely free if you sign up via this link. Over 175,000 people have already joined this course on Udemy.com! Now available right here too. This course teaches you how to program in Java from scratch.
You can find lots more courses here

Want a Course but Can’t Afford to Pay?

If you want access to one of my paid courses but can’t afford to pay, email me at john@caveofprogramming.com with a brief email explaining your situation, and I’ll consider giving you free access.

Donate

If you feel like sending me some cash … well, thanks! You can do so right here:

Get a Job as a Software Developer

If you’re looking to get a job in software, my free Java for Complete Beginners is all you need, at the minimum. If you master the contents of this course and you’re prepared to travel and apply for lots of stuff, while there are no guarantees, you’ve got a good shot at getting a job as a programmer. This course includes advice about getting a job.

If you want to improve your chances by learning an advanced Java specialisation, my Servlets and JSPs (and JSTL) course gives you very marketable skills. You’ll need to separately study HTML and CSS a bit (not as hard as Java!) and preferably some SQL too.

Alternatively, you could Learn Android Programming or try Mastering Java Swing; Swing is widely taught in universities, but there are less jobs around for it than for web-based stuff (see Jobserve).

Finally, The Java Spring Tutorial gives you some very hot skills, but it’s advisable to learn about Servlets and JSPs first, unless you like being dropped in at the deep end.

My other free courses, Java Multi-threading and Java Design Patterns and Architecture, will certainly improve your chances in a job interview, and you can take them in whatever order you like.

{ 481 comments }

Leave a Comment

  • zhanyou xu July 21, 2014, 4:19 am

    I love your JAVA collections of framework. they are excellent for me. thanks

    Reply
  • Marius Claassen July 17, 2014, 11:24 am

    John
    Thanks for the Lambda tutorial. You may recall I made a suggestion on 9 June. And in your response you said you would look into it.

    As always, your simple, clear explanations are easy to follow.
    Be blessed

    Reply
    • John July 17, 2014, 12:01 pm

      Yes, that’s why I made it! Thanks for the suggestion. Looks like being one of my more popular videos. I’m also transcribing it to form the basis of an article.

      Reply
  • Florin July 16, 2014, 10:21 am

    awesome videos so far :D your a good instructor :)

    Reply
  • Mukhtar July 15, 2014, 3:00 pm

    hi,
    i need your help…
    i want to use external class in javafx.
    i want to show a graph( my graph class is in the same package)

    example:
    public class XYZ extends Application{
    private String x;
    Graph graph;
    graph = ….the graph from external class..

    @Override
    public void start(Stage stage) throws Exception {
    System.out.println(x); //x ist here NULL
    System.out.println(graph); //graph is here NULL

    }

    //getter und setter für x
    }

    x is filled in main class
    thank you

    Reply
    • John July 15, 2014, 7:06 pm

      Hello, not sure I understand … can’t you just use “new”? Or maybe you need a singleton?

      Reply
  • Muhammad July 14, 2014, 2:55 am

    Hi,
    I’m trying to make an intro that runs before the main app so that i’m trying to make the IDE wait 4 seconds before it runs the main app that the intro ends, i used wait() method and Thread.sleep() method as well but when i run it just opens a frame shows me my eclipse IDE
    [IMG]http://i57.tinypic.com/fa32gk.jpg[/IMG]

    Note : The intro is animated. And When i ignore Frame and run intro it runs fine
    Thanks.. :)

    Reply
    • John July 14, 2014, 8:34 am

      You need to run the intro on a separate thread so that Swing can get in there and update the frame before you show the next thing. Use SwingWorker. I have a similar example in my Swing course that shows a dialog. You’ll also need a Timer to close the intro and show the main window. It might even be possible to skip the SwingWorker and just use the Timer, I’m not sure. But either way, you need to show the intro using a method that returns immediately, so that the Swing dispatch thread can run in the background and update stuff after the intro is shown.

      Reply
  • Mohammed vasaiwala July 13, 2014, 5:51 pm

    Hi John,
    My name is Mohammed, John i want to write a program using for loop but the output should be in single line
    eg. for for(int i =0;i<5;i++)
    {
    System.out.println("*");
    }
    output (which i want): *****
    output (whuch i get): *
    *
    *
    *
    *

    Reply
    • John July 13, 2014, 6:42 pm

      Use print instead of println.

      Reply
  • Kc July 12, 2014, 3:51 pm

    Hi John,
    I started Java from zero, watched a couple of YouTube vids prior to joining Udemy. Almost done with the beginners course, my goal is to be a professional programmer.
    At this point, I know I have a long way to go but it appears that there are several things to learn after one acquires java basic knowledge.
    What are your recommendations once one completes the basic Java concept? I’m not looking for an easy way out but the best way to accomplish this.

    Regards
    Kc

    Reply
    • John July 12, 2014, 4:33 pm

      Hello Kc, it depends what your goal is. You can get a job just with knowing core Java. Understanding databases, e.g. MySQL is very helpful since probably most programs use some kind of database. Knowing multithreading is good too. Beyond that, universities usually seem to teach Swing programming, but Java web stuff (servlets, JSPs and the Spring framework, or Struts) is more in demand in the job market (see jobserve.com).

      Reply
      • Kc July 15, 2014, 2:02 pm

        Thanks John, you’ve been of great help plus thanks for a prompt response.
        I think I’ll go for Servlets, my question is, will I be required to learn multithreading? on the same breath, must I to learn MySQL?
        I appreciate your extra mile in responding to our many questions.

        rgds

        Reply
        • John July 15, 2014, 7:07 pm

          Hi Kc, you don’t need multithreading for servlet stuff, at least not usually. You’ll want to learn MySQL or another database. I go through the stuff you need in the course, for the course, so you can always just type that out and fill in your knowledge later. You might need to google some stuff if it’s unclear from my explanation.

          Reply
  • Mohammed vasaiwala July 9, 2014, 11:23 am

    Hi John,
    I’m refering your Java for begineers tutorials and its going quite well. Can you Please tell some books to refer for java as you mentioned in your tutorials that even you have learned from books.

    Reply
    • John July 9, 2014, 12:12 pm

      Hello Mohammed, I rarely use IT books myself, but people tell me Headfirst Java is good.

      Reply
      • Prashant July 12, 2014, 1:13 am

        head first is good book for begineers futher for standard refrences you can refer The complete reference java by Herbert Schildt

        Reply
  • Mani July 9, 2014, 4:06 am

    Hi John,
    I just wanna thank you for your great tutorials. I am a sophomore computer science student, and I need to tell you that you are a great teacher. whatever you are doing here is highly appreciable.
    I’ve learnt very good skills and knowledge especially in Java by watching your tutorials, and I am still improving them.
    So, thank you sir and have a happy life!

    Reply
  • Karen Guffey July 6, 2014, 8:54 pm

    Hi John,

    I’m about 1/4 of the way through your Java for Beginners tutorial, & from time to time you mention posting some info here. (I’m doing it through Udemy.) Do you mean the same video, or is there a place here where I can look at notes rather than a video? Thank you.

    Karen

    Reply
    • John July 7, 2014, 9:26 am

      Hi Karen, there are some articles on Java in the articles section of this site, although not nearly as many as videos!

      Reply
  • Abdullrahim Rahimi July 6, 2014, 5:23 pm

    Hello John,
    I am currently going through your “Java for complete beginners” course and was wondering if you could point me in the right direction regarding the goal I would like to reach with using Java.
    My main purpose of trying to learn Java is because I’m looking to use Java to send and receive messages in the financial market through the use of “FIX API Protocol”.
    I understand that this might sound new to you but I would highly appreciate it if you could maybe take a look at “FIX API protocol” via google and let me know which courses I should take in order to be able to use the protocol with Java.

    Kindest Regards,

    Reply
    • John July 6, 2014, 5:32 pm

      Hello Abdullrahim, I’ve looked at this before a little bit. You’ll need core Java, plus you might find multithreading useful, I’m not sure. If you want to have a user interface, you’ll probably want to learn Swing. Or you could just control everything from the command line.

      Reply
  • Mark July 5, 2014, 9:13 am

    Hi John,

    What course progression do you suggest with the following courses? I am signed up for some of these on udemy, and just wanted your opinion.

    Java for Complete Beginners
    Java Swing (GUI) Programming: From Beginner to Expert
    Java Multi-threading
    Java Design Patterns and Architecture
    Servlets and JSPs (and JSTL)
    The Java Spring Tutorial

    Thanks

    Reply
    • John July 5, 2014, 11:14 am

      Hi Mark, up to you really — there’s some advice on this page about this. Universities usually teach Swing after core Java. Servlets and JSPs is more basic than Spring. The rest you can mix up how you want.

      Reply
  • sanjay y.m July 4, 2014, 2:10 pm

    Hi John,

    I watched all of your tutorials, in YouTube(43 Videos) and it is really awesome, it covers all the basic concepts of java and now i found java easier. Sir can i get PDF of 43 programs if you don’t mind.

    Regards,
    SANJAY Y.M

    Reply
    • John July 4, 2014, 2:18 pm

      Hi Sanjay, I don’t have any PDFs. Do you want source code? It’s downloadable from the courses pages of my website.
      John

      Reply
    • Sanjay Y.M July 5, 2014, 1:40 pm

      Thank You John for your kind response. I will download source from your website ,thank you very much….

      Reply
  • Kevin July 3, 2014, 1:43 pm

    Hi John,

    I was wondering, would it be fine for me to download the videos that I have paid for and show them (but not distribute to them) to coworkers?

    Reply
    • John July 3, 2014, 2:05 pm

      Hi Kevin, if you don’t distribute them, I’m OK with that. Thanks for asking!

      Reply
  • Kc July 3, 2014, 8:27 am

    Thanks John, yo such a cam Teacher..

    Reply
  • George July 2, 2014, 6:24 pm

    How can i compare elements of 2 dimension array with the elements of an arraylist of which each index have got more than one value, my aim is to compare elements of array with those of each index of an array list ( as the elements of 2D array are of equal length with the elements of each index of the arraylist)

    Reply
    • John July 3, 2014, 12:48 pm

      You can use a nested for loop to step through both.

      Reply
  • Marcelo July 2, 2014, 5:38 pm

    Hi…
    i’m trying to create a SWING App, however i can’t clear the Text Fields as i click the OK button. Any tips??
    Thank you (from Brazil)

    Reply
    • John July 3, 2014, 12:47 pm

      Should be possible — just do setText(“”);

      Reply
  • Abhi July 2, 2014, 6:54 am

    Hi John, just want to know that did you have created any application or program that have followed MVC with multi-threading. Because I don’t see anything related to MVC with multi-threading in your JAVA or SWING videos and if you have not implemented then will you put up few small videos that implements MVC with multi-threading because following MVC with multi-threading is little tricky for example: using GUI Swing design layout taking Data out from Multiple Database using multi-threading with MVC and showing on swing component like JTable.

    Reply
    • John July 2, 2014, 7:29 am

      Hi Abhi, there is an element of multithreading in the Swing example that I go through in my Swing course. You can use SwingWorker to handle it all quite elegantly, together with ArrayBlockingQueue to avoid having to synchronize stuff.

      Reply
  • Muhammad June 27, 2014, 9:52 pm

    Hi John, I have a question..
    Iam working in a project which has a database (created by mysql workbench) it works fine with eclipse and when i run the runnable jar on my pc, but when i try it on another computer it doesn’t load from database, is there a way to make an offline database which can be packaged in the runnable jar ?

    Reply
    • John June 27, 2014, 10:49 pm

      You can package the SQLite database with your app, but then it’s only good for one user. If you want a shared database, you have to make sure that the URL where the jar connects to the database is accessible from any computers that the app runs on.

      Reply
  • Shashi Shekhar June 22, 2014, 7:28 pm

    Hi John,

    I am working on leaderboard application. It shows the sales agent with their rank and picture on the webpage. Also on the top of the page it shows top three sales agent. Is it possible to export the same webpage to a pdf with data and images?
    we can create a pdf by using iText plugins in java. But how to convert a dynamic webpage to pdf. I mean whatever user is seeing on the webpage. I am not able to find the solution. Please suggest me.

    Thanks
    Shashi

    Reply
    • John June 22, 2014, 7:34 pm

      Unless you can find some product that can do it, it might not be possible except as a screenshot. You can’t convert embedded flash to PDF, for example. All you can do is make a screenshot.

      Reply
  • shubham June 20, 2014, 8:14 am

    I’m lovin it, videos are awesome than I thought.thanks for tutorials.

    Reply
  • Alex Meilan June 17, 2014, 2:17 pm

    Hi,

    I am trying to access the program examples created by John on the Java tutorials. Are there any PDF versions of the program examples?

    Reply
    • John June 17, 2014, 8:00 pm

      No PDFs, but the source code is available, either by looking at the pages in the “videos” section of this site or by going to the last lectures in the Udemy courses.

      Reply
  • johngerard June 15, 2014, 6:33 pm

    The best course I have come across in learning Java for beginners, the pace is perfect and John delivers in a calm manner that is clear, concise and in an engaging manner.

    Reply
  • james June 15, 2014, 11:41 am

    Java for Complete Beginners.
    This course is really great. Explained at a level that is showing the core idea behind each topic. trying to get the certification in JAVA in a few months time and I think this course is going to get me on course for that…. THANK YOU!!

    Reply
  • Nithin June 12, 2014, 5:34 am

    Thanks John
    I wanted to learn java for automating using Selenium your course is more than Awesome , now I am feeling I need to Switch from Automation testing to java development , great course

    Reply
  • Chris June 10, 2014, 7:06 pm

    Hey John, I just wanted to thank you for all the great videos you post! I am currently doing your introduction to Java course and find it the best ever! I tried learning programming at least 3 other times with coursera, udacity and codeacademy but nothing ever stuck with me. It was like they are trying to teach the subject but just not in the right way. Once I started your Java course I have been addicted to programming! Your course helped me find in my life what I enjoy doing the most. I have already started writing my own programs with the knowledge you have taught me and I look forward to learning more every day. I have completed half of your class in 2 weeks and I never thought it would be so easy. Again thank you for the free classes and taking the time out of your day to help us with them!

    Reply
    • John June 10, 2014, 11:15 pm

      Really great to hear! I used to know a Chris Swain, but probably a different one …

      Reply
  • Ansul June 10, 2014, 6:58 pm

    Hi John,
    My name is Ansul, I am a tester, I have started learning java from your beginners tutorial.

    I have a quick question, I want to learn selenium. So, how much java I should know.

    Regards
    Ansul

    Reply
    • John June 10, 2014, 11:16 pm

      Maybe only the basics … depends exactly what you want to do though.

      Reply
      • Nithin June 12, 2014, 5:36 am

        @Ansul If you take java for beginners completely -its basically Core java you will become selenium superstar

        Reply
        • Ansul June 12, 2014, 12:50 pm

          Thanks Nithinl;

          Thanks John;

          Reply
  • Muhammad June 10, 2014, 5:57 pm

    Hi John! Thanks for your fast replies
    Iam stucked in the database tutorials xD I wrote the code just like you did but when i try it I get in the console :

    Running Database Test!!
    com.mysql.jdbc.JDBC4Connection@11644e1
    com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
    at com.mysql.jdbc.Util.getInstance(Util.java:384)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1013)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918)
    at com.mysql.jdbc.ConnectionImpl.throwConnectionClosedException(ConnectionImpl.java:1321)
    at com.mysql.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:1313)
    at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4532)
    at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4497)
    at model.Database.saveTodb(Database.java:54)
    at TestDatabase.main(TestDatabase.java:23)

    Reply
    • John June 10, 2014, 11:18 pm

      Sounds like the connection has been closed or not opened. But try asking in the Udemy forum, because probably other people will reply there too.

      Reply
  • Marius Claassen June 9, 2014, 7:13 am

    John
    I am learning Java and came across your beginner tutorials. Have almost worked through this entire set. You explain the concepts and practical work really well. Thank you.

    I read somewhere that Lambdas make it easy to pass methods. Do you have any plans to do a tutorial on lambdas?

    Reply
    • John June 9, 2014, 8:18 am

      I really should. I’ll look into it!

      Reply
  • Nitin June 4, 2014, 11:21 pm

    John:

    In each your vides, you are indicating that the coding is on http://www.caveofprogramming.com/. However, i try to find out the codes, I found some of the codes on this web site.

    I will appreciate if you email me link where all the codes are stored that will be great help.

    Thanks and Appreciate for Your Hard Work

    Reply
    • John June 4, 2014, 11:38 pm

      It’s embedded in the pages in the YouTube videos section, for all my free videos.

      Reply
  • Muhammad June 4, 2014, 7:57 am

    Hey John, Thanks for the tutorials, but i have some questions
    First, is there a source code for java swing course ?
    Second, in java swing course tutorial no. 38 did you create the table in mysql workbench or there is a way to connect our project table with the workbench ?
    Thanks ^_^

    Reply
    • John June 4, 2014, 8:02 am

      Hi Muhammad, the course code is attached to the final couple of lectures in the course. Yes, I created the tables in MySQL Workbench. You could also do it using SQL, but the Workbench lets you create a database diagram from which you can then automatically generate SQL. Then you put appropriate SQL in your project to query or update your tables.

      Reply
  • Jimmy June 3, 2014, 3:24 pm

    Hi John, I see you’ve posted some tutorials on JavaFX, where can I see them from the beginning?

    Thankyou, Jimmy

    Reply
    • John June 3, 2014, 3:38 pm

      Check the YouTube videos section.

      Reply
  • Steven Heynderickx May 29, 2014, 6:59 pm

    Hi john,

    I am enjoing your tutorials a lot! Congrats! I even bought the swing tutorial.
    I mostly listen to them using my iPad and the udemy platform…
    I went to your website to view the source code but I could not find it.
    All the links go to udemy, and on that page I find nothing.
    I am looking for the multithreading source code

    thanks for your tutorials and your input on this

    Steven

    Reply
    • John May 29, 2014, 8:26 pm

      Thanks Steven! It’s embedded in the pages here: http://www.caveofprogramming.com/youtube/#26

      Reply
      • Iulian June 2, 2014, 10:55 pm

        I have the same problem using the iPad. The code won’t download in Udemy. Anyway your answer solved the problem, but maybe it would me more comfortable to have the code in Udemy app.

        Reply
  • mark May 28, 2014, 4:50 pm

    Pls I want to learn database how and were do I start

    Reply
    • John May 28, 2014, 10:06 pm

      Download MySQL and Google for some MySQL tutorials.

      Reply
  • VInay May 27, 2014, 9:49 am

    Hey John,

    i am taking your free as well as paid courses.
    Is there any way i can download all videos in one go rather going to every tutorial and then manually downloading it.
    Cause course on spring is almost like 150+ tutorials and offline save is not working on my ipad.

    Reply
  • Alex May 27, 2014, 9:34 am

    Hi John,

    what application did you use for Mac recording of screen and sound?
    thanks

    Reply
    • John May 27, 2014, 10:50 am

      Screenflick. I’m not sure it’s the best though. Every so often I have to discard a video because it’s got loads of strange distortion. Not sure if it’s Screenflick or something else, but it only happens with Screenflick.

      Reply
  • Sud May 22, 2014, 4:48 am

    Hi.
    I learnt Java from here and it was wonderful.
    I’m looking at embedded C now, but I can’t seem to find anything as good as this. Could you recommend anything?

    Reply
    • John May 22, 2014, 11:02 am

      Thanks! I don’t know any embedded C tutorials. I’ve started making C++ tutorials if you’re interested though … will post them here but at the moment there are 3 on my YouTube channel

      Reply
  • shiva May 18, 2014, 9:56 am

    I couldn’t find source code for Java Multithreading. Can you show me the location!

    Reply
    • John May 18, 2014, 10:40 am

      Embedded in the pages in the YouTube video section.

      Reply
  • Abhijit May 17, 2014, 7:05 am

    Hey John!!!! I’m currently following ur course on java programming for beginners nd I’m loving it!!!!
    I just wanted to ask u if u didn’t mind uploading some tutorials on how to create games using java!!!!
    Thank you!!!!

    Reply
    • Steven Reedy May 25, 2014, 5:58 am

      I started off on Cave of Programming to learn basic Java. I have searched the web and this is the best website for doing that. Once you understand the basics of the language, check out theChernoProject on youtube. Also, Killer Game Programming in Java is a great book or ebook to look into.

      Reply
  • Nick Shepley May 16, 2014, 9:52 am

    Hi there John, I’ve just read and enjoyed your ebook and wanted to say thanks for the great ideas you’ve passed on. I’ve had a site that’s developed from a hobby into a something with quite a large audience, my podcast just got its 4,000th subscriber this week and it’s growing at 100 a week, which is crazy considering the ad hoc and bumbling way I tend to go about things. Anyway, reading about your story was very inspiring and I’m going to be recording my first online course some time this summer.

    All the best,

    Nick

    Reply
    • John May 16, 2014, 7:24 pm

      Cheers Nick. This site looks great!!! I’ll have to have a listen to your podcast. I love this stuff.

      Reply
  • Damo May 15, 2014, 10:14 pm

    Hi john. We have spoke before. So hi. Anyway I want to know more about java programming bit one thing is annoying me about it and that’s using the command line on windows to interact with java classes and how benificial it is. I have looked at the oracle examination questions and a lot refer to this process and perhaps a brief couple of videos on this would be great. If you can assist with this as a beginner exercise then great. Thanks a lot damian. Ps I you need any help with anything let me know.

    Reply
  • Kien May 9, 2014, 8:31 am

    Hi John,

    I’m following your course: Java for complete beginners. When I ran your code for Linked Lists (Section 3), I got the time taken for type ArrayList around 15ms, and LinkedList around 70ms. But when I change the code a little bit – increase the size of the loop 10 times:

    private static void doTiming(String type, List list) {

    for (int i = 0; i < 1E6; i++) {
    list.add(i);
    }

    long start = System.currentTimeMillis();

    for (int i = 0; i < 1E6; i++) {
    list.add(i);
    }

    long end = System.currentTimeMillis();

    System.out.println("Run time " + (end – start) + " for type " + type);
    }

    then the run times are:

    Run time 219 for type ArrayList
    Run time 31 for type LinkedList

    Could you please explain the why the results could be such different?

    Thanks.

    Reply
    • John May 9, 2014, 8:37 am

      I’m not sure, but with an ArrayList, everytime you double the size of the list, it has to copy the internal array to a whole new array. Whereas with LinkedList, you’re just adding to the end. That might have something to do with it. I realised after making these videos that I was mistaken about one stupid thing. LinkedList is only faster for inserting items into the middle or start of the list if you use an iterator. If you use an index, it has to iterate through the whole list up to that point of insertion to find where to insert the new object, which makes it useless. Bad mistake on my part :) Aside from this, it’s probably not worth reading too much into the exact run times … LinkedLists are only faster in this specific situation; using an iterator to insert an object at a location other than the end.

      Reply
  • Russell May 9, 2014, 5:47 am

    John,

    I love the content and presentation provided in your Java For Complete Beginners course. Was wondering if you had the time to explain why I am getting two more Machine objects (total of 4) generated than expected when I execute the following code:

    package tutorials;
    public class Machine {
    private static int ID = 0;
    private int machineID;
    public Machine() {
    ID++;
    this.machineID = ID;
    System.out.println(“Generation of Machine ” +
    this.machineID + ” object”);
    }
    public int getMachineID() {
    return machineID;
    }
    public void setMachineID(int machineID) {
    this.machineID = machineID;
    }
    public String toString() {
    return “I am Machine ” + this.machineID;
    }
    }

    package tutorials;
    import java.io.Serializable;
    public class Camera extends Machine implements Serializable{
    private static final long serialVersionUID = 1L;
    private static int ID = 0;
    private int cameraID;
    public Camera() {
    ID++;
    this.cameraID = ID;
    System.out.println(“Generation of Camera ” +
    this.cameraID + ” object”);
    }
    public String toString() {
    return “I am Camera ” + this.cameraID;
    }
    }

    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;

    public class SerializationApplication {

    public static void main(String[] args) {
    Camera camera1 = new Camera();
    Camera camera2 = new Camera();
    String fileName = “serialized.bin”;

    try(FileOutputStream fileOutputStream = new
    FileOutputStream(fileName)) {
    ObjectOutputStream objectOutputStream = new
    ObjectOutputStream(fileOutputStream);
    objectOutputStream.writeObject(camera1);
    objectOutputStream.writeObject(camera2);
    objectOutputStream.close();

    FileInputStream fileInputStream = new
    FileInputStream(fileName);
    ObjectInputStream objectInputStream = new
    ObjectInputStream(fileInputStream);
    Camera readCamera1 =
    (Camera)objectInputStream.readObject();
    Camera readCamera2 =
    (Camera)objectInputStream.readObject();
    objectInputStream.close();
    System.out.println(readCamera1);
    System.out.println(readCamera2);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    }
    }
    }

    The console output during execution shows the following:

    Generation of Machine 1 object
    Generation of Camera 1 object
    Generation of Machine 2 object
    Generation of Camera 2 object
    Generation of Machine 3 object
    Generation of Machine 4 object
    I am Camera 1
    I am Camera 2

    Reply
    • John May 9, 2014, 7:05 am

      Hello Russel, I had to look this one up … apparently when you deserialize an object, the default constructor of the first class in the hierarchy that does not implement serializable is run. So you have two parent constructor runs when you create the Camera objects, then two runs when you deserialize them. Static fields are not serialized.

      Reply
  • vinodh May 5, 2014, 7:54 am

    John,
    I am highly benefited by your courses.
    I am a java developer for more than a decade.
    Do you have plans to do course on web services.
    I want to learn it from you.
    regards
    vinodh

    Reply
  • Paul May 4, 2014, 5:07 pm

    I have to say John your tutorials are incredible they have really helped me at university get to grips with the Java language, so much so my student loan has come through and I am going straight over to Udemy.com to buy some of your courses! top work mate!
    Many many thanks.
    Paul

    Reply
  • Aaron May 2, 2014, 2:23 am

    Hey John, I just started your course “Java for complete beginners” I want to start by saying thank you and that I have already learned a lot. Although I am only on tutorial 4 I am having some difficulties with loops. I started off creating a loop and worked my way to having a value loop where it is <10 – but, I am stuck on the loops, the text "hello" is still in a continuous loop where I set the value to be <10 where value = value + 1; but it just keeps looping. Here is what I have:

    public class Appliaction {
    public static void main(String[] args) {

    int value = 0;

    while(value < 10)
    {
    System.out.println("hello " + value);

    value = value + 1;
    }
    }
    }

    I hope you have the time to reply, I do not want to move forward until I get this resolved. Thanks again and I hope to hear from you.

    Aaron

    Reply
    • John May 2, 2014, 8:21 am

      Hi Aaron, there is nothing wrong with this code! I suspect you are running the wrong project by mistake. Try right-clicking the project and going to run as Java application.

      Reply
      • Josh June 4, 2014, 5:27 pm

        Hey John, I’m 16, I’ve been trying to self teach myself java for about a year now, I’m currently watching your beginners tutorial, and I realize how much of the small things I have been missing, you explain this really well, it’s easy to understand. You make great tutorials dude

        Reply