22

I had my first programming exam recently...and well I pretty much flopped it. Did not do great at all. I have only myself to blame as outside of college time, I pretty much did nothing.

Now I have another coming up near summer time and I'm not allowing this to happen again. For a couple of weeks now I've been reading, reading and reading some more. I keep going over the older things I missed and the newer things we're doing. So, obviously I can notice a huge difference in my understanding of the language. However, that's about it. I can read the code and I now have an idea of what's going on in the code... but when it comes to me writing the code myself I'm just clueless. It's like I never know what approach to take and can never really fully comprehend the questions.

I have done a fair amount of reading (been doing around 5-6 hours for the past month or so) each day... But when opening my IDE I always feel doomed it's really demotivating. Especially because I have knowledge of nodes, lists, arraylists, interfaces ect ect but besides from reading them on a page that's about it. I can point out exactly everything that's going on in a program so annotating a presample code I find fine... but writing my own code is another story..

13
  • 8
    It helps to have a goal. If, for example, you wanted to make a game, you could download a framework or library and follow introductory tutorials. If something less complex, you can begin by searching for examples of these programs, deconstruct them and modify them to fit your needs or interests.
    – Kai Qing
    Commented Feb 27, 2014 at 0:39
  • 10
    Read less and program more. Find simple projects and do them. Don't worry about doing it perfectly, just get them to do what they are supposed to be doing. Then think about how you can do better.
    – Philipp
    Commented Feb 27, 2014 at 9:25
  • 1
    For a couple of weeks now I've been reading, reading and reading some more. - Reading is a start, actually coding is a lot better. Try writing a program in psuedocode on paper, then translate it to java. It's a bit easier if you already know what you have to do.
    – Andreas
    Commented Feb 27, 2014 at 9:47
  • 1
    possible duplicate of How can I really master a programming language?
    – gnat
    Commented Feb 27, 2014 at 17:16
  • 1
    I found this to be a very interesting article while trying to figure out how to code and teach others the basics of coding: The Camel has Two Humps. Some people just get it immediately, others never will - but most of us can learn. If you can read and understand code, you're off to a great start :)
    – brichins
    Commented Feb 27, 2014 at 19:06

9 Answers 9

45

You learn how to write programs by writing programs.

But you gotta start small, man.

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}  

From there, begin building...

public class HelloWorld {
    static String test = "This is a test";

    public static void main(String[] args) {
        System.out.println(test);
    }
}

and then...

public class HelloClass {
    String test;

    public void setTest(String str)
    {
        test = str;
    }  

    public String getTest()
    {
        return test;
    }
}

public class HelloWorld {
    HelloClass myHelloInstance;

    public static void main(String[] args) {
        myHelloInstance = new HelloClass();
        myHelloInstance.SetTest("Hello World.")
        String myResult = myHelloInstance.getTest();
        System.out.println(myResult);
    }
}  

... and so on. Once you understand the basics of how objects work, it will be much easier to write larger programs.

4
  • 9
    Your second example should fail to compile because you are accessing a non-static variable in a static context.
    – Brandon
    Commented Feb 27, 2014 at 11:55
  • 35
    @Brandon: then it's a debugging exercise nice and early.
    – Bryan B
    Commented Feb 27, 2014 at 14:37
  • This is how everyone learns to code, I guess, or should learn to code.
    – mrudult
    Commented Feb 27, 2014 at 18:01
  • 1
    Embrace your inner Nike and "just do it".
    – NotMe
    Commented Feb 27, 2014 at 21:41
15

Great question! It's important to realise that you have multiple learning curves to climb. Just so that you don't think that you are only learning a programming language. You are doing quite a bit more than that.

You are learning about ...

  1. The tools that you use to write code. Your development environment, the editor, the debugger, your compiler. There are manuals and help files for all these tools, check them out. The more you know the tools the easier it is to create code.
  2. The syntax of the programming language under study, from your post it sounds like you are putting a lot of focus here and you certainly need to.
  3. Solution Design Skills. How to put together a useful, maintainable piece of code. This is the muscle that you need to build up. Like other posters have pointed, you learn by doing.

I suspect that it's point three where you are struggling. You are learning how to say things in code (syntax) but really you are asking us what should I be saying in code. Is there a right way and a wrong way to do things?

I would suggest that you take on a challenge. Have a look at the following as an exercise.

http://en.wikipedia.org/wiki/Eight_queens_puzzle

Now this is a tough challenge. You have to place eight Queens on a chess board so that each of the Queens are safe from each other.

So as a learner this may be an over-reach, however you can look at this problem and use it to learn how to write code.

Here's a strategy to try out ...

  1. Restate the problem to be far simpler that the stated problem to be solved. Forget the eight queens. Focus on just one. Learn how to write the code to represent a chess board in memory, place a single queen on that board and then display it to the user on screen in just text.

  2. Once you have made a stab at Step 1. Place two queens on such that they are both safe.

  3. Finally, have a go at placing more than 2 queens on the board so that they are all safe.

The above steps are a twist on a design strategy called Step-wise Refinement. It's a little bit old-school in terms of design but it will take you from a blank screen to some interesting code in no time.

There are other design and implementation strategies: Test Driven Design, Object Oriented Design and Design Patterns to name a few.

In time you will add these strategies to the arsenal and use them as and when required. The more design strategies you study and practise the easier it will become.

May the source be with you.

2
  • How is OO Design different from Design Patterns? Or are you putting the two together? Commented Feb 27, 2014 at 8:53
  • 1
    Stepwise refinement and OO are not mutually exclusive either, but you probably know that. May the source be with you. +1
    – Gusdor
    Commented Feb 27, 2014 at 10:21
15

A Quick Foreword

Learn By Doing: Knowledge vs Know-How

There's a huge difference knowledge and know-how. It's a common mistake for new learners to think that because they can "understand" a program as they read it, they actually understand the reasoning for the program being written the way it is.

And the only way to get to that second part is to practice. Sit down, open a text editor, a command line, and get down to it.

Programming in the Small

It's likely (and expected) that at this stage your ability to comprehend how several complex software components interact with one another is limited. And it's actually a good thing, as it forces you to start from the basics. Don't jump the gun and move at the right pace: start with small exercises for small tasks.

To be honest I've never been convinced that starting to learn programming with Java is the way to go (I used to teach programming for a living in university, and still do occasionally private tuition). It is in itself too complex to get you started, and most Java books will appear quite daunting. Nevertheless, it surely can be done (at least for some areas of that global knowledge we expect from programmerS), as long as you restrict yourself to learning step by step.

Books

As you're set on Java, and if you need a decent Java book, I'd recommend:

  • Thinking in Java. It's OK, though now slightly outdated.
  • The Java Tutorial. It's not exactly the best learner's companion, but a great reference to keep at hand, as it covers all the basics and provides examples. The Learning the Java Language Trail should probably be on your reading list, though I'd think it can be daunting for complete beginners as it introduces concepts that may be hard to grasp at first.
  • Effective Java. It's not a great book for learning, but also an awesome reference you should have at hand for later. Not to read in one sitting, but in bite-sized chunks.

I'm only mentioning this as I don't know what you use in class. There's a tons of other books. Some are good. Some will cripple students for years.


Your Study Process

The Basic Workflow

From now on, I'd advise you to follow this 2-step process for all the exercises and code samples you've seen in class:

  1. read and study
    1. read the exercises
    2. make sure you understood them
  2. code
    1. close the book
    2. sit down in front of a computer with that code editor and command line
    3. attempt to rewrite the program by yourself

In case of Failure

If you fail and feel like you need to take a peek at the book, your failure is likely to be either:

  • (most likely) that you didn't actually understand the solution,
  • (less likely) that you've forgotten how a particular bit of the solution looks like: syntax, API use, ...

The first cause is likely to be what you face the most often. The second one is anecdotal. Both are addressed by recurrent practice.

Every time you fail at implementing one of these early examples, look at the book again, then close it again. Don't code while looking at the book. I'd even advise that you delete your entire solution and start over. The repetition is an annoying but important part of the learning process.

Do not take this lightly. Every time you feel the urge to tell yourself "yeah, ok, I know this" or "I'm 90% there, it's almost as good as done" and want to skip to another section, fight that urge back and start over. It's very difficult to have the honesty to admit to yourself that you didn't fully understand a concept.

Side note: I consider it a great disservice that most school programs now attempt to "kickstart" programming courses by dumbing things down too much and providing tooling that's too advanced for students: the goal is not to make your life miserable or for you too learn by heart things that later in your career will be automated by your tools and that you'll sometimes even barely remember. It's to teach you all the bits that float around.

In Case of Success: Go Beyond!

If you succeed at implementing your exercise, don't necessarily jump directly to the next one. Try to see what you can do to improve that one. Can you change the output that was requested? Add a small feature? An option? Try to, as you are now in that fun zone where you're passed the main difficulty, and these self-imposed tiny requirements are more likely to keep your spirits up a bit.

Don't go too far though: you don't go from printing the alphabet and reversing it to suddenly making it appear on a diagonal on the screen with a gradient of colors. Take small steps. Learning is a long and iterative process, and you need to approach problems with increasing levels of difficulty (for instance, see how I usually think of explaining recursion).


It's Just Learning - A Comparison

Your problem is actually not related to programming at all. It's the same problem thousands of people encounter when they try to learn maths.

If you give them a problem, they don't see how to work their way to the solution. However, if you write down the solution for them, most will understand it and think "darn, that was so simple!". Yet you'll give them a similar problem with different measures and hypotheses and they'll fail to solve it: they didn't understand the logic behind it, and they need practice to be able to do it themselves.

Note that this is a common problem with maths, but in my opinion you see it in tons of other fields where there's some logic required: learning solfege, language grammar, physics, etc... And it's not down to a "natural" ability to understand these things: it just comes down to practice (be it in that area, or in others that lead the individual to grasp concepts in this field more easily).

There's no reason you can't learn to write code. You just jave to keep trying until you reach that "ah AH!" / Eureka moment. Then move on to the next, harder, problem.


These may help as well (later):

0
6

I know this isn't the answer you're going to want to hear but: Write more code!

More specifically dissect the code that you do understand. It often helps me to "translate" it into regular English (as I'm a relative beginner).

Don't be afraid to brainstorm your idea for writing a piece of code first (ie "I want to declare a variable here, iterate through this segment etc"), and THEN look up piece by piece how to do these various segments.

Remember that coding is less like an exercise in memorization and like figuring out a way to construct something out of building blocks. Much like learning an actual foreign language, comprehension comes first, this is a good sign that you are well on your way.

Just have faith that the more you write and read code, the more it will make sense.

0
5

As others have said, this is a case where you must practice, practice, practice.

Write a bunch of small programs that solve one problem only

Sometimes, the hardest part is actually coming up with something worth programming. If you can, try to work in a topic that you think you're struggling with - like classes, inheritance, etc. Some ideas off the top of my head:

  • Generate 1000 random numbers and insert them into a collection(queue, list, etc). Sort the collection without using any provided methods that sort the collection for you.
  • List 10 people you know. First sort their names based on first names and display them. Then, sort their names based on their last names and display them. Then, try sorting them based on the pattern "last, first"(ie so Smith, Andrew would be before Smith, Jessica).
  • Find all prime numbers between 1 and 100.
  • (Inheritance) Make a Polygon class, and give it the function GetArea. Now, make the classes Triangle and Rectangle inherit from Polygon, and make sure they implement GetArea. Keep doing this for higher order polygons(pentagon, hexagon, etc).
  • Try picking things from the code golf stack exchange*

*The purpose of code golf is to do the provided task by using the least amount of characters, bytes or some other metric stated in the question. If you read some of the answers, you quickly appreciate the clever ways people solve these problems. Do not focus on solving the problem in the fewest bytes! The people who post to code golf are very experienced programmers. But, some of the questions offer easy tasks in and of themselves.

Some fun code golf examples:

  • Powers of 4. Don't worry about solving with a regex(it is quite difficult, as you can see by the answers). But, instead solve the question "Given a string s, is its length divisible by a power of 4?" You can do offshoots as well: Is a string's length divisible by 4? Is it divisible by 6? Is it prime(this is difficult for long strings, so try it if you get gutsy!)?
  • Substrings. Given a string s, output all possible substrings.
  • Word counting. This one may be tricky depending on how far you are in your programming studies. There are a few things that make it very easy(like associative collections), but if you don't know those things it can be difficult.
  • If the title sounds cryptic to you, just ignore the question. Like I said, code golf is for experienced programmers. Just focus on the simple problems, and try to come up with a simple answer.

Basic structure of solving a problem:

A lot of these give you a good idea of what a function should look like. Given X, do Y, and the result should be Z:

void foo()
{
    // Set up X here

    // Do Y here

    // Display Z here
}

For the purposes of learning the basics and becoming familiarized with a language, the above template is sufficient. A more object-oriented template would be:

Z foo(input X)
{
    Z result;
    // Do Y to X
    return result;
}

If it helps, write it down on paper as well. Talk yourself through the process of how you, as a human being, would solve this problem. Example: Given the numbers i, j, and k, display them in descending order. As a person, it's easy to solve. The hard part is translating your ideas into line-by-line instructions so a computer can solve it.

Try to come up with your own ideas as well. It can be tough, but even the simplest of programs might teach you something you didn't know. The whole point is to drill yourself with the basics, until they become second nature.

3

You won't get anywhere by just reading code; you need to be writing code. Just write code. Don't worry if the code you write is crap; everyone has written crap code. Some people make a living out of it. Nobody starts off writing good code and I'm of the opinion that while learning, it's almost necessary to write bad code because only then does the difference between good and bad code become truly apparent.

It's hard to appreciate the difference between good and bad code when reading two blocks of code that do the same thing, but when you've written a script and you get someone knowledgeable to review it and provide feedback the difference often becomes much more apparent because you can directly apply it to what you know.

Programming is not something you can learn by rote memorisation; it's not like your times tables or dates in history. Programming is a practical skill that requires constant practice to stay sharp. Learning programming without writing code is like learning to swim by reading a book.

1

Like others are saying, you just need to practice writing code. In order for that to be fulfilling, you need to challenge yourself with solving some kind of problem, whether it's printing predefined messages, making a simple interactive calculator or solving some specific task.

If you're short on inspiration, Project Euler has a plethora of math/programming exercises of increasing difficulty. They give you clear and challenging goals to accomplish, and should help you get more comfortable designing programs.

1

Just thought I'd chime in on this topic because it really hits close to home.

You just need to start coding. Don't get me wrong, reading is great but what really gives you that working coding knowledge is actually building something. I learnt more from a single summer placement than I did the previous year reading about it.

I should also add that you should't just start coding blindly. Make a project for yourself. You need some sort of direction to put yourself in so you know what you want to make. You'll be surprised to see how much you'll learn quickly. If you just open up an IDE and start making simple hello world examples, that demotivating feeling will creep up on you quickly. Find something with a little depth and before you know it you'll be expanding on it.

4
  • this does seem to add anything substantial over what was already posted in prior answers
    – gnat
    Commented Feb 27, 2014 at 14:54
  • @gnat I'm assuming you meant "Doesn't" and that's your opinion. I went through the exact same situation he's going though and I'm sharing what helped me. If you forgot the intro to his question here it is: "Could you guys give any tips..."
    – SeanWM
    Commented Feb 27, 2014 at 14:57
  • @SeanWM - Programmers is a bit different than what you may be used to with SO. If something is already answered well, re-iterating the same points in your own answer is not all that constructive. And that's regardless of if the OP is asking for tips or opinions. It just doesn't make for good Q&A. It's better to up vote the existing answer(s) and possibly leave a constructive comment indicating a facet that was missed.
    – user53019
    Commented Feb 27, 2014 at 15:52
  • +1, this answer does add something important into the mix. Thats the importance of having a real project to work on, not just examples and small test programs. Commented Feb 27, 2014 at 16:02
0

This question already has some really good answers, but there are a few thoughts I havent't seen yet.

Learning a programming language is much like learning a 'real' language: It's always much easier to read than to write, be it a single sentence, a scientific paper, or a book. When reading, much can be figured out just from the context, understanding the text or code as you read it. When you see a word you don't know, maybe you know another word with the same stem; when you see a method, the name of the method gives you a good idea of what it does. When writing, you have to remember not only the syntax, but also the actual words to use. And its the same for programming.

As others have said, you can't learn to write programs just from reading programs.

Start small. Look for a Java tutorial, and do all the units, one after another. And when you are confident enough, pick a small project to test your skills, maybe some simple game you know well that does not require too much GUI interaction. When you've decided, don't just open your Eclipse and stare at the 'blank page'. Create a storyboard. You don't have to draw elaborate UML diagrams, just think about how certain aspects of the program could be solved -- how the story or your argument unfolds, so to speak. And when writing the code, start with a rough draft. I usually write lots of comments, describing what the program should do, in what order, and then start filling in the actual program code.

Not the answer you're looking for? Browse other questions tagged or ask your own question.