Learning Java/Programming tips

When to use methods
The ideal method only handles one function, and is named appropriately. Using methods increases readability of your code and makes it easier to expand or change your software. You can also call your methods from separate places, reducing the total number of lines of code. Methods are also used to retrieve data from an object and store data in objects. These methods are called getters and setters. Example:

Methods are allowed to call other methods, but only if they have a different functions. Try using common sense when deciding whether use methods or not. There are multiple analysis tools to see if you are using methods right and efficiently. You should avoid having methods with a lot of lines of code, it often (but not always) indicates that the method can be broken up in smaller methods.

About Arrays
Arrays should be used for variables that have something to do with each other. Basically, arrays are a sets of variables, and arrays are a variable themselves. Here are some examples which declare arrays. Simply declaring an array in this way does not allocate space for the elements of the array. Declaring the array with a list of elements will allocate the space for the elements and also assign their values. To create an array one must use the new operator and specify the length of the array. Each array has an int member called length. It is simply how many items are in the array. You need to initialize each part of the array. To "access" the members of the array: Note: Do NOT use arrays when the members have nothing to do with each other. This causes code errors!

Code formatting
Code formatting is necessary to understand your code more easily. For example, the following is very hard to understand because it is not properly formatted: In much better format: Notice that the code is easier to understand. Every single new block that has { and } should have whitespace preceding it. Example:

To further improve the readability of your code, you should insert one empty line between methods: A good alternative is: You should make a new line after every statement/declaration. If a statement is too long, you can break it down.

Some Integrated Development Environments like Netbeans IDE have an auto-formatting function built in.

Good Comments
Good comments can help make your code look neat. They should tell what you are doing overall, not what you are doing on each line. For example, you can comment an if statement if it is complex, but not every statement has to be commented:

An example of bad commenting would be:

Quick way to convert numbers to strings
There will be a lot of times you need a String and you're working with numbers. This is one of the faster ways to convert numbers to String, but it's not very neat.

Getting numbers from strings
When you need to extract numbers from a string you can use the Wrapper classes to parse them into the number you need.