Posts tagged ‘Java Programming’
Programming Java Tutorial – input / output
We also have some excellent Beginners Programming Java tutorials that use high quality narrated videos and practical working files to teach the fundamentals of programming in Java Beginners Java Tutorial CD
Java Tutorial – Input / Output
The code below is based on Java 1.6 – some syntax may differ for previous versions.
Receiving and sending data to and from an external source is something that you will likely have to do regularly as your programs develop. Java provides a number of classes and libraries to facilitate this process. In this tutorial we will concentrate on reading from and writing to external text files.
To send and receive data in Java, we use output and input ‘streams’. There are various resources within the Java language to interface with input and output streams in your programs, many of them suited to different types of programming tasks. This Java Tutorial will demonstrate a few of the more likely options for use within basic applications.
Java – Reading from a file
Create a new Java project in your IDE and add the following import statements at the top of your main class:
//input/ output imports import java.io.*; import java.util.*;
These imports contain the classes that we will use for our I/O operations: the first of these classes will be FileReader and Scanner. In the first example, we will read the text from a text file into our program one line at a time. Enter the following code in your main method:
//try block in case of IO exceptions try { //create filereader, passing filename String filename = "sometext.txt"; FileReader fr = new FileReader(filename); //pass filereader to scanner Scanner scan = new Scanner(fr); //loop through the file content while(scan.hasNextLine())//check that there is more { System.out.println(scan.nextLine()); } //close the input stream scan.close(); fr.close(); } //an exception has been thrown catch(IOException ioe) { //output the details System.out.println(ioe); ioe.printStackTrace(); }
The code has to be included in try/catch blocks because, when your program relies on external input, there is always a risk of unforeseen error, such as problems with the external file. Placing your code within the try block allows your program to continue functioning when these problems occur, and provides you with the ability to decide what should happen if the I/O processing goes wrong. This is the function of the catch block, so you should place here whatever you want the program to do on encountering such an error, as this is where the code will jump to when that happens.
Before compiling your program, you will need to create the file for reading. Open a text editor (such as notepad/ notepad++) and enter the following:
Outside of a book A dog is a man's best friend Inside of a dog It's too dark to read
Save your file with the name ‘sometext.txt’ in the same directory within your workspace as the new project; for example, on Windows, if the project is called AProject and your workspace directory is C:\Workspace save the file in the C:\Workspace\AProject directory. If you look at the first line of code in the try block, you’ll see that the filename given is a relative URL, i.e. it does not have a drive listed as part of it; you can also use the class with an absolute URL if you need to.
NB: If you’re using Eclipse you can find out your workspace location by choosing Project > Properties.
Now compile and run the program, you should see the contents of the file written a line at a time to the output console. What’s happening here is that the program is opening an input stream (according to the filename given) with the FileReader. The Scanner then processes the data from the stream, and can do this in a variety of ways, reading a line, a number or a byte at a time. Although our program merely outputs the data read in, once it’s in your program you can do whatever you need to with it, for example by assigning it to variables.
To demonstrate the purpose of the try and catch blocks, change the filename in the code so that it doesn’t match the actual file (e.g. String filename = “bla.txt”;) and run your program again. You’ll see the effect of the exception being thrown in your output console – this is because the program couldn’t find the file specified. (Remember to change the filename back afterwards.)
Using the Scanner, as above, makes text processing easier if you’re reading chunks of the text, however you can use the FileReader itself to read the file in a character at a time if this suits your needs. Processing data through the FileReader in this way is a little more complex, as the contents of the file are in the form of individual characters, including the newlines and end of file:
//create FileReader FileReader fRead = new FileReader(filename); //keep track of whether end of file reached boolean end = false; //loop through file characters while(!end) { //read the next character (as an int) int ch = fRead.read(); //-1 represents the end of file if(ch==-1) end=true; else { //write the character out char chr = (char)ch; System.out.print(chr); } } //close the stream fRead.close();
Run the program, it should have the same effect as the previous code.
Writing to a file in Java
The process for writing to files is similar, again, try and catch blocks are required and this time an output stream is opened. However, if your program cannot find the file specified to write to in the relevant directory, it will create it. If the file does exist the below methods will replace its contents. The first method writes to an output file using the FileWriter class, which can write a specified section of a string (in this case it should write ‘defg’); enter the following in your try block:
//write out using FileWriter FileWriter fw = new FileWriter("output1.txt"); //write specified section of string fw.write("abcdefghijkl", 3, 4); fw.close();
Check your workspace project directory to see if the output1.txt has been created and written to.
The next example uses the PrintWriter class to write to the file; demonstrating two approaches to inserting newlines:
//write out using PrintWriter PrintWriter pw = new PrintWriter("output2.txt"); //using println to insert newline at end pw.println("Some text I'd like to write to a file"); pw.println("And some more"); //use print - insert newline explicitly (\r\n) pw.print("Yet more I'd like to write to a file\r\n" + "And more again."); pw.close();
Again, check the appropriate directory for the output2.txt file; it should contain 4 lines of text.
Your programs will likely involve a range of different approaches to Input/Output depending on their particular requirements, so it is worth spending a little time familiarising yourself with the various options that Java provides.
Java Tutorial – Sorting and Searching Data
We also have some excellent Beginners Programming Java tutorials that use high quality narrated videos and practical working files to teach the fundamentals of programming in Java Beginners Java Tutorial CD
Java Tutorial – Sorting, Searching and Recursion
Once you start to use data structures in Java, you will inevitably encounter situations in which you need to sort or search through them. For the purposes of this beginners Java tutorial, we will use arrays to illustrate some basic sorting, searching and recursive algorithms.
An algorithm is a procedure, a series of steps that you define to solve a particular problem. In the examples below, our algorithms will be expressed in the Java code that we use in our programs.
Recursion
Some of the techniques we will be using rely on recursive processes, so let’s explore these first. A recursive method in your program is basically one that calls itself, i.e. within the method body, there will be a call to the method itself. Using recursive methods effectively can take a bit of practice, as your program can easily get caught in a loop, so you need to think the procedure in any such method through carefully.
To demonstrate a recursive function in action, let’s create a trivial example. Create a new Java project and enter the following in your main class, after the main method:
//recursive method public static int doSomething(int someNumber) { //check the value of the input parameter if(someNumber<=0) return someNumber; else { //decrement and call the method again someNumber--; System.out.println(someNumber); return(doSomething(someNumber)); } }
Now call the new method within your main method:
int result = doSomething(10); System.out.println("done: " + result);
All the program does is count down from the passed int value to zero. Experiment by changing the value of the int parameter passed to the method and observe what effect it has on the output printed to the console. The method manages to avoid getting stuck in a loop (caused by calling itself repeatedly) by having the conditional ‘if’ statement.
This simple recursive method has much the same effect as a loop, but, as you’ll see, recursion can be particularly useful when you have a complex problem that is best solved in stages, each stage taking you a step closer to the solution by simplifying it. A necessary ingredient for recursive methods then is that you specify explicitly how the method should behave with the simplest input, and then with each iteration, you work towards this simplest case. In the example above, the simplest case is when the int parameter is less than or equal to zero.
Try not to worry if this seems an odd practice at first, once you start using sorting methods the recursive approach will become clearer.
Sorting
The main reason for keeping a collection of data in sorted order is that it is far easier to find items within the data and therefore maintain it effectively. Keeping the data in sorted order does, however, involve a certain amount of processing, particularly when adding or deleting items.
When we say, for example, that an array is in sorted order, we mean that the items within the array are arranged according to some understood ordering system. Sometimes this is intuitive, for example if the array contains numbers, sorted order will naturally comprise numbers stored according to ascending (or sometimes descending) numerical value. Similarly, if the array contains String values, sorted order will generally mean alphabetical order.
However, there are cases when sorted order will be less clear – imagine you have created your own class declaration for use within your program, and you wish to store objects of your class in the array. You will have to decide then what constitutes sorted order for these objects. In order to do this you have to think about comparing two objects of the same class. When you compare two objects of the class, it must be that case that either one is ‘greater’ than the other, or they are ‘equal’. This is how your objects will be ordered, and to provide this in your own classes they will need to implement the Comparable interface, which means that your objects provide a compareTo method. Within this method you will need to decide how to measure the objects of your class against one another, for example, you might decide to use the value of some variable in the class.
Note: be careful when using the ‘equals’ method on your objects also, as the default equals method inherited from the Class Object, actually tests the object references, i.e. it tests to see whether the two variable names are pointing to the same object. If you plan to use the equals method, you would be best to provide your own implementation of the method, overriding the default for this reason.
For the purposes of this Java tutorial, we will stick to simple types in order to illustrate the algorithms required.
Selection Sort
Selection sort works by continually finding the next smallest item in the collection and placing it at the front. Create a new program and enter the following code in your main method to create an array with some arbitrary data in it:
//array with unsorted int data int [] myData = {3, 1, 9, 5, 7};
Now we will use selection sort to arrange the items in the array in ascending numerical order. The selection sort technique is as follows:
- Within the section of data that is yet to be sorted (initially the whole structure), find the smallest item
- Place this item at the first position (of the unsorted section), swapping it with any element that’s already there
- The unsorted section now contains one less item (the item just deemed smallest and therefore moved)
- Continue placing the smallest unsorted item in first position until all of the data has been sorted
Enter the following code after declaring the array and compile your program, observing its output:
//loop through the array for(int pos=0; pos<myData.length-1; pos++) { /* find and keep track of the smallest * element's position * -start at pos and look through the rest * (pos is at the start of the unsorted section) */ int minIndex = pos; //loop through the unsorted section for(int next=pos+1; next<myData.length; next++) { if(myData[minIndex]>myData[next]) minIndex=next; } //swap the item if necessary if(minIndex!=pos) { //keep track of the value currently at pos int temp = myData[pos]; //copy the new smallest value into pos myData[pos] = myData[minIndex]; //copy the swapped value into minIndex myData[minIndex] = temp; } //print the array for demonstration for(int p : myData) { System.out.print(p); } System.out.println(); }
When you look at the program output, try to work through which items are being swapped with one another at each stage – experiment by changing the int values (or their order) in the array.
Merge Sort
A more efficient approach to sorting the contents of an array is Merge Sort, which uses a recursive algorithm. This rests on the idea that merging two already sorted arrays is a simpler problem than sorting all of the data in one unsorted array. The algorithm therefore sorts an unsorted array by continually dividing it into two parts and sorting each part, merging the results into a final sorted array.
Add the following method to your program (after the main method):
/* mergeSort method sorts the data in a section of * the array passed * -parameters are the array containing the data to * be sorted, a temporary array for use with the * processing, and integers representing the start * and end positions of what data is to be sorted * within the array */ public static void mergeSort(int[] dataArray, int[] tempArray, int start, int end) { //array has been sorted if(start==end) return; //work towards sorted array by breaking the problem down else { //divide the data into two int center = (start+end)/2; //call the method on the first half mergeSort(dataArray, tempArray, start, center); //second half mergeSort(dataArray, tempArray, center+1, end); //merge the two halves into one sorted half int firstIndex = start; int secondIndex = center+1; int thirdIndex = start; //loop through both halves while(thirdIndex<=end) { /* work through both halves * inserting smallest item into * the temp array each time */ if(secondIndex>end || (firstIndex<=center && dataArray[firstIndex]<=dataArray[secondIndex])) { tempArray[thirdIndex]=dataArray[firstIndex]; thirdIndex++; firstIndex++; } else { tempArray[thirdIndex]=dataArray[secondIndex]; thirdIndex++; secondIndex++; } } //copy the temp contents into the main array for(int i=start; i<=end; i++) dataArray[i]=tempArray[i]; } }
Each time the method reaches the point of merging two halves, each half has already been sorted, since the mergeSort method has been first called on them, and on their subsections before they come to be merged, and so on. The method therefore solves the problem by repeatedly simplifying it and solving the simpler problems in turn. Now call the new method from your main method:
//array to sort int[] someData = {4, 3, 7, 6, 2, 8, 5, 9, 1}; //extra helper array int[] extraArray = new int[someData.length]; //call the mergesort method on the whole array mergeSort(someData, extraArray, 0, someData.length-1); //print the sorted array for testing for(int pr : someData) { System.out.print(pr); }
Again, experiment by changing the values in the input array and observing the program output.
It can be difficult to get into the ‘recursive’ way of thinking and certainly requires practice, but once you do you will tend to find that you identify problems that could benefit from a recursive solution fairly quickly. It can help when writing a recursive method if you start from the simplest case, then take care of the steps that work towards it each time the method executes (rather than starting from the most complex input, which is the first one to be executed, and can therefore seem an intuitive starting point).
Searching
You will often face the task of finding a particular element in a data structure for one reason or another. If your array data is unsorted, the only way to do this is to look through each of the elements in turn. This is known as linear search – enter the following code in your main method:
//collection of arbitrary strings String[] myStrings = {"potato", "carrot", "turnip", "onion", "leek", "courgette", "aubergine"}; //find the index of 'leek' int foundIndex=-1; //loop through the array for(int veg=0; veg //binary search method public static int binarySearch(String[] theData, String wanted) { //-1 means item not found int foundIndex=-1; //keep track of both ends of searchable area int top = theData.length-1; int bottom = 0; //loop through, dividing searchable area each time while(bottom<=top) { //look at middle element int middle = (top+bottom)/2; //compare middle element to item searched for int comp = theData[middle].compareTo(wanted); //middle is item searched for if(comp==0) return middle; /* if middle element is greater, * wanted element must be in lower half * and vice-versa, so we reduce the * searchable area accordingly */ else if(comp>0) //middle is greater top=middle-1; else //middle is lesser bottom=middle+1; } //finished searching return foundIndex; }
Now call the method within your main method:
//array of sorted strings String[] sortedStrings = {"aubergine", "carrot", "courgette", "leek", "onion", "potato", "turnip"}; //call the method - returns -1 if item not found int searchResult = binarySearch(sortedStrings, "potato"); System.out.println("found at index: "+searchResult);
Experiment with the code by searching for different elements in the array – you can also check how many iterations of the loop are required each time by including a System.out.print statement within the while loop in your binarySearch method. It is generally a good practice to include such ‘trace statements’ in your code, to check exactly what is happening at any stage in the program; it can be particularly helpful when debugging larger programs.
Although many of Java’s built-in datatypes provide sorting and searching methods, it can help with the efficiency of your own programs to think about the algorithms involved. Also, when you come to define your own data types, you may need to implement such methods yourself. There are numerous approaches to sorting and searching in Java, the examples above being only an introduction.
Beginners Java Tutorial – Inheritance
We also have some excellent Beginners Programming Java tutorials that use high quality narrated videos and practical working files to teach the fundamentals of programming in Java Beginners Java Training Videos – Programming
Beginners Java Tutorial – Introducing Inheritance
Programming can inevitably be a time-consuming and laborious process; for this reason programmers always look for ways to improve efficiency, such as the re-use of existing code. The structure of the Java language facilitates the practice of re-using code in a number of ways. One of these is Inheritance, which can have a profound effect on the way that you design your projects as a whole.
The basic principle in Inheritance is that you can create a Class that re-uses the code in an already existing Class by extending (inheriting from) it. The new Class inherits all of the features of the original Class, and is free to either add additional features or alter the features it has inherited, such as the way in which a method is implemented.
When a Class inherits from another Class, it is said to ‘extend’ it. The original Class is referred to as the Superclass, the inheriting Class being the Subclass. All Classes in the Java language ultimately extend the Class Object, although you do not state this explicitly in your Class declarations. This is why any Class that you create will naturally provide the methods outlined in the Object Class, such as toString(), even when you didn’t declare those methods in your Class declaration.
Let’s create a simple example – in your IDE create a new Java project and Main Class (leave the main method empty for now). Create a second Class called MySuperClass and enter the following code:
/**A Superclass .. */ public class MySuperClass { //instance variables /**an int */ private int someInt; /**a String */ private String someString; /** * Constructor function * @param intValue * @param stringValue */ public MySuperClass(int intValue, String stringValue) { someInt=intValue; someString=stringValue; } /** * Method outputs an arbitrary string */ public void aGreatMethod() { System.out.println("This really is a great method"); } }
Now create another Class called MySubClass and enter the following:
/** * MySubClass inherits from MySuperClass * and provides one additional method * * - This class will provide methods and * variables present in the SuperClass * although they are not declared here */ public class MySubClass extends MySuperClass { /** * Constructor function conforms to the * superclass constructor * @param subIntValue * @param subStringValue */ public MySubClass(int subIntValue, String subStringValue) { /* call the superclass constructor * which expects an int and a string */ super(subIntValue, subStringValue); } /** * Additional method provided in MySubClass */ public void anotherMethod() { System.out.println("This method is pretty good"); } }
Now, return to your Main class and enter the following as your main method:
public static void main(String[] args) { //create an instance of the subclass MySubClass mySub = new MySubClass(99, "blah"); //call the subclass' own method mySub.anotherMethod(); //call the inherited method mySub.aGreatMethod(); }
When you run the program you should see the following written to standard output:
This method is pretty good This really is a great method
As you can see from the above code, all you need to do to extend a Class is to use the syntax ‘extends’ in your Class declaration and ‘super()’ in your constructor method to call the constructor for the Superclass. As well as extending your own classes (as above) you can extend Classes that already exist, either within the language itself or within any external libraries that you happen to be using.
One common reason for using inheritance is to provide Classes that ‘specialise’ in some way. For example, you might have a program in which you want to represent the different sets of users of an application. These users might have some things in common but some differences – instead of having several distinct Classes in which you use sections of similar code, you could create a Superclass (e.g. User) and have several Subclasses inheriting from it. Your Superclass would provide all of the characteristics that the users have in common, while each Subclass can focus on what distinguishes it from the others.
Additional guidelines for using Inheritance:
- Each Subclass can only have one Superclass, although a Superclass can have many Subclasses.
- You can provide an alternative implementation for any method that you inherit from a Superclass by ‘overriding’ it – to do this you simply provide the method within your Class declaration and, providing the method signature is the same (same method name, parameter types/ number, and return type), your implementation will be the one that is called on objects of your Class.
Advanced Java topics relating to this Java tutorial are Polymorphism, Interfaces and Abstract Classes.
Java Tutorial – Organizing your Code
Java Tutorial – Organising Java Projects
As your programs grow in size and complexity, organisation and documentation will become more important. Applications developed in Java must be well-constructed and documented in order to function within the Object Oriented design model. Under this model, applications comprise a set of components interacting with one another – for this to be possible, the elements within must be clearly defined and explained. Even when you develop your own smaller projects, you will find that spending a little time and thought on these choices will save you a lot of headaches in the long run.
There are a series of simple measures that can contribute to a well-organised project, for example, the simple act of using plenty of whitespace and indentation in your code instantly makes it more readable, while this sounds boring and very uneventful .
Dividing up Requirements
It can be tempting, when starting a project, to sit down and immediately produce code, but resisting this urge can make life a lot easier. Once you have a set of requirements for your application, it can be extremely helpful to work out a ‘high-level’ plan before you start to write any code. For example: split the requirements into related sections, then use these to decide what your packages and classes will be. Even if you find that your implementation causes you to alter this initial plan, it provides a much more coherent starting point.
There are various modelling tools that can help this process, such as UML (Unified Modelling Language) – however, even if you decide not to choose such a formal approach, the simple act of splitting the requirements into groups can help you to visualise how you are going to solve the problems at hand.
Java Naming Conventions
It is well worth spending a few moments during coding to decide on appropriate names for variables, methods, classes and packages. In addition to the fact that this makes your work much more amenable to being used in other applications, it also makes your own development process easier. When you look back at a piece of code that you wrote some time before but have forgotten the details of, meaningful variable and method names will help you to understand it far quicker than if you have to read and process each line of code in your head! Although it may seem cumbersome at times, using whole words in your names can make your code much more readable.
For the same reason, observing the standard naming conventions for the language is always a good idea. In Java, this includes the following:
- variables should start lowercase, with uppercase letters indicating words within, e.g. myNumber, costPerPortion.
- method names should indicate (normally using verbs) what the method does, e.g. getCost, displayNames.
- methods used to get and set values should use the conventions getValue (e.g. getCost) and setValue (e.g. setCost) respectively.
Comments and Documents
Regardless of whether you are working on your own or as part of a team, the inclusion of informative comments in your code will always help the development along. The Java language features a variety of different types of comment:
Single line comments are used for short pieces of information throughout your code:
//print each name in the array for(int i=0; i
Multiline comments are used for more lengthy explanations, particularly if your code features a complex algorithm:
/* This algorithm does the following: -first it does this -then it does this -and so on */ for(int i=0; i
Javadoc
Java has its own system of documentation that is effectively built-in to the language. You can use Javadoc to automatically generate html documentation for your projects, and all you need to do is include Javadoc comments in your code:
/** Method calculates total cost from individual cost ... more explanation ... @param someNumber -int value representing individual cost @return totalCost -int value representing total cost */ public int getTotalCost(int someNumber) { //method code calculations.. return totalCost; }
Javadoc generates html based on such comments, which contain special tags such as @param and @return – if you include these the Javadoc will display this information in a standardised way. You should include Javadoc comments immediately before Class declarations, instance variable declarations, methods and constructors. The Java API is an example of Javadoc that you can view.
Beginners Java Programming Tutorial – Datatypes
We also have some excellent Beginners Programming Java tutorials that use high quality narrated videos and practical working files to teach the fundamentals of programming in Java Beginners Java Tutorial Videos – Programming
Java – Datatypes and Variables
Beginners Java Tutorial on Datatypes and Variables, ideal for the novice who is just starting to learn programming in JAVA
In order to program effectively in Java, you need to understand a little about the different datatypes in the language. A variable in Java can essentially be one of two things: a primitive type or an Object reference. To create efficient programs, you need to think about which types to use, as this will have a direct effect on performance.
The Java language is ‘strongly typed’, which means that when you declare a variable, you have to specify the type:
int myNum = 1; String myString = "hello"; Object myObject = new Object();
The advantage to this is that you have a degree of control over the underlying implementation (and therefore efficiency) of your projects. To make informed choices about datatypes, let’s look at the ways in which they are represented in memory.
Primitives
The Primitive types in Java are int, char, boolean, byte, double, float, long and short. Primitive type variables can be given a value when you declare them, and the values are stored in stack memory:
int myNum = 1; //in this case the value 1 is stored on the stack
In contrast, reference types are stored in heap memory, with only the Object reference on the stack (more on this below). You don’t need to understand the details of how your variables are stored in the computer’s hardware to program efficiently, as there are simple practices that will minimise the amount of memory that you use. In general, primitive types use less memory than Objects.
When it comes to choosing between primitive types, you should also try to minimise memory usage, e.g. for integer arithmetic: an int uses up less memory than a long; for floating point: a float uses less than a double – naturally there is a trade-off involved in this choice, since the larger types offer a greater range of possible values.
Note: The primitive types also have associated Wrapper classes (e.g. Integer). As well as storing the value (of e.g. an int), variables of these types can have methods called on them. However, being of the reference type, they occupy space in heap memory, and as such you should avoid using them unless you have specific reasons for using their associated methods.
Reference Types
When you create an Object, the JVM allocates a section of heap memory for it, with the Object reference stored on the stack. In this example:
Object myObject = new Object();
your myObject variable is essentially a pointer to a location in memory. The data etc contained within your Object is stored at this location. Given that this happens every time you create an Object, you can imagine that the amount of memory used up by your programs will quickly accumulate. However, there are more simple measures you can take to minimise this.
Garbage Collection
The JVM uses ‘garbage collection’ to free up areas of memory that are no longer being used. A location used by an Object in your program will be considered a candidate for garbage collection, if there are no longer any Object references pointing to it. For this reason, you need to think about where you declare variables, and for how much of the processing they need to remain available.
For example, if you consider the following trivial example:
//print the string backwards if it's at least 10 chars String myString = "blahdeblahdeblah"; String backString = ""; if(myString.length()>=10) { for(int i=myString.length()-1; i>=0; i--) { backString += myString.charAt(i); } System.out.println(backString); }
Providing you don’t need the backString variable further down in your program, it is better to declare it inside the ‘if’ statement:
//print the string backwards if it's at least 10 chars String myString = "blahdeblahdeblah"; if(myString.length()>=10) { String backString = ""; for(int i=myString.length()-1; i>=0; i--) { backString += myString.charAt(i); } System.out.println(backString); }
The backString variable is now ‘local’ to the conditional ‘if’ statement; once that statement has finished executing, the variable is no longer needed and is therefore garbage. In the first example, the variable had greater ‘scope’, and remained available longer than necessary, using up memory. You can also use this principle of ‘localising’ variables with the primitive types.
Note: The syntax for some reference types such as String and Array can be confusing at first – although these look the same as primitive types in that you can assign a value to them as you declare them (rather than using the keyword ‘new’, as with most other classes), they are Objects and occupy memory as such.
Beginners Java Tutorial – Objects and Classes
We also have some excellent Beginners Programming Java tutorials that use high quality narrated videos and practical working files to teach the fundamentals of programming in Java Beginners Java Tutorial Videos – Programming
Java Tutorial – Objects and Classes
This Java tutorial assumes some very basic Java knowledge, e.g. method syntax.
Objects are the key to building robust and efficient Java applications. When developing a large or complex system, developers begin the design process by dividing up the various project requirements into application components. These are ultimately represented by Objects within the application, and are implemented in code by Class declarations. While it might be difficult to perceive the advantages to this technique while you’re learning (and working on small projects), if you adopt the right practices at this stage, you will develop the skills required for professional Java development.
Creating Objects
In your Java IDE, create a new Project called MyFirstObject, with Main Class MyFirstObject (if you’re using Netbeans myfirstobject.MyFirstObject with myfirstobject as the package name). Inside your MyFirstObject Class enter the following:
//class declaration public class MyFirstObject { //main method public static void main(String[] args) { //code here will be executed when the program is run } }
Using Objects is a way of dividing up responsibility for the different parts of an application. You can do this in a variety of ways: for example, you can carry out some of your program’s tasks within separate methods, calling these from the main part of your code. Using Objects is similar to this, but each Object requires a Class declaration, which you create in a separate .java file.
The Objects that you may have already used, such as those representing Java datatypes String, Array etc also have their own Class declarations – these are built into the Java language itself, and although you can’t see the code, you can see an overview as part of the Java API (Application Programming Interface). The Objects that you define yourself will function in the same way – let’s create a simple example.
In your project, create a new Class called MyHelper, entering the following:
//class declaration public class MyHelper { //instance variable private int helperNum; //constructor method public MyHelper() { helperNum=1; } //public method public int getNumber() { return helperNum; } }
The above code is a simple Class declaration specifying the properties that any Object of the MyHelper Class will have – next we will create an ‘instance’ of the MyHelper Class within our Main Class, but first let’s look at the Class declaration.
Instance Variables
Instance variables represent any data that should be stored in every instance of your Object, meaning that every time you create a MyHelper Object it will contain a helperNum integer variable. Instance variables should always be private, so that their value cannot be changed except within the Class declaration itself – more on this later.
Constructor method
You can see that the constructor method looks the same as any other method, except that it doesn’t have a return type specified – this is because the constructor method is called when an Object of the Class is created (using the keyword ‘new’), and what it returns is – an Object of the Class. The constructor method should always have the same name as the Class. Within the constructor method, you carry out ‘initialisation’, meaning that you assign a value to your instance variables – when the constructor method has executed, none of your instance variables should be left without a value, as this can make your program unpredictable.
Public Method
The declaration contains one public method, ‘getNumber’, which can be called on any Object of the Class. Although the example may seem trivial, it is common to have methods which either set or return the value of an instance variable.
The reason for such methods relates to your instance variables being private. The basic principle underlying Object Oriented development is that your Objects have a ‘well-defined’ interface – this means that all access to the data contained within a Class should be through its methods. If the instance variables were public, external code would be free to change their values directly, which can be dangerous, since external code may not be aware of the implementation details for the Class. If you restrict all access to your instance variables, to the public methods in a Class, you can carry out any checks etc there to ensure that your data is not assigned invalid values.
Using your Class
Now go back to your Main Class and enter the following inside your main method:
//code here will be executed when the program is run //create a MyHelper object MyHelper mh = new MyHelper(); //call a method on it, assign the result to a variable int num = mh.getNumber(); //write the variable out for testing System.out.println(num);
Compile and run your program and you should see the number 1 written to standard output. You create an Object of your Class, and call methods on it, in exactly the same way as any other Object. From your main method, you can call any methods on the MyHelper Object that are declared as public inside the Class.
A Class may also have private methods that are for use within the Class only. For example, one of your public Class methods may involve complex or repetitive processing that you decide to separate out into its own method, calling this from the public method – in this case the separate method should be declared as private, as this method relates to the implementation of the Class itself, which external code should not have access to.
Object principles
If you’re new to Object Oriented development in general, it can help to think in terms of ‘black boxes’. One of the principles that makes Java suited to developing large projects, is the idea that any application developed in Java can in turn be used by anyone else as a component in another application. Many open source projects use Java, with people sharing resources that they have developed in the language.
For this approach to be feasible, it must not be necessary for someone using a component to have to understand all of the implementation details within it. So long as there is a ‘well-defined’ interface, you should be able to make use of external Java libraries and resources while knowing nothing about what goes on inside them – in the same way that you can use a String or Array without having to understand how it is implemented in the underlying code. In this approach, you can think of Objects as ‘black boxes’ – code external to the Class should be able to make use of it without having to be aware of the inner code. When you develop your own Objects, you should adopt the same principle – even if you’re developing an application single-handed, this approach makes for programs that are faster to build and easier to debug.
More on Classes
As a final note, you should be aware that you can have more than one constructor method in a Class, each one taking different parameters. In this case whichever method is called is dictated by what parameters are passed when an Object of the Class is created. To demonstrate, add a second constructor to your Class, beneath the existing one:
//class declaration public class MyHelper { //instance variable private int helperNum; //constructor method public MyHelper() { helperNum=1; } //second constructor - takes a parameter public MyHelper(int value) { helperNum=value; } //public method public int getNumber() { return helperNum; } }
Now add the following in your main method, after the existing code:
//create an object passing int parameter MyHelper mh2 = new MyHelper(2); int num2 = mh2.getNumber(); System.out.println(num2);
When you run your program, this time it should output 1 and then 2 for the new Object. Whichever constructor matches the type and number of parameters passed is the one that’s called during Object creation.
When using Objects in your programs, you should try to decide what the various Classes will be at the outset, by dividing up the different requirements that your project has, and assigning responsibility for these to your set of Objects.
Beginners Java Tutorial – Programming Part 1
We also have some excellent Beginners Programming Java tutorials that use high quality narrated videos and practical working files to teach the fundamentals of programming in Java Beginners Java Tutorial Videos
Beginners Java Tutorial – Part 1
The Java language is currently one of the most widely used programming platforms, and can be used to build both desktop and Web applications. Java is used to develop with the Object Oriented technique, in which applications are characterised as a set of interacting ‘objects’, the objects being modules of code. This Java tutorial assumes no prior knowledge and aims to teach the basic fundamentals of Java Programming.
To start programming with Java, you will need:
- The Java Runtime Environment (JRE) installed on your computer.
- A Java IDE (Integrated Development Environment) such as Eclipse or Netbeans.
Using an IDE will make your Java projects straightforward to manage and develop, and is therefore strongly recommended.
Java compilation
When you write code in a programming language, the compiler for the language generally translates your code into machine code for a particular system. This is code that can be run directly by the hardware of a computer with a specific operating system, architecture etc. The situation is slightly different with Java. When you create and compile your Java code, the end result is code that runs on the Java Virtual Machine, not code that runs directly on any actual machine. When the application is actually run, the JVM translates it into machine code for the specific computer it’s running on.
The process is as follows: when you write Java programs, your code is contained in .java files; when you compile and run these programs, .class files are generated – these contain bytecode, which runs on the JVM. The JVM code is then translated into machine code for the host machine. This means that when you create your Java applications, your compiled code can run on any operating system with Java installed, as it’s only translated into machine code when it’s actually run – this is one of the main advantages to using Java.
It isn’t necessary that you understand these concepts to get started with Java so don’t worry too much if it all seems confusing at this stage – it’ll begin to make more sense as you start to write programs.
Your first program
Once you’ve chosen and installed an IDE for Java, you’ll need to familiarise yourself with its interface; you may also need to perform setup tasks such as choosing a workspace location – see the instructions for your particular IDE. Within your chosen IDE, you’ll need to create a new project each time you want to start a new Java program. Each project will contain at least one package, with the package(s) containing your source .java files.
Different IDEs provide different levels of assistance, for example, when you create a new project/ class in Eclipse or Netbeans, the environment automatically creates a default package for your code.
Each .java file in the project will generally represent a ‘class’ in your application, grouping together related code. Each of these ‘class declarations’ provides a blueprint for a type of Object in your application. Again, the notion of Object will become clearer as your Java skills progress.
Every project will contain at least one class: the ‘Main’ class. When your Java application is compiled and run, the first code that is executed is the code inside the ‘main method’ – this code will be inside your Main class. Create a new Project in your IDE and name it MyFirstJava. If you’re using Netbeans choose Create Main class, entering myfirstjava.MyFirstJava as the name. If you’re using Eclipse create a new class inside your project and name it MyFirstJava. Select your MyFirstJava class and enter the following code (your IDE may have filled some of it in for you):
//class declaration public class MyFirstJava { //main method public static void main(String[] args) { //code to be executed at runtime System.out.println("Well Hello There"); } }
Note: If you’ve programmed with scripting languages before, you can think of methods as functions.
If you compile and run the program you should see the phrase written to the standard output console (this should be visible within your IDE interface). All that the code does is write a message out, as this is all that’s contained within the main method.
You really don’t need to understand all of what’s going on here, in fact it’s easier when you’re starting out to just treat it as a formula that works; you’ll understand the details later. Each time you create a new Java program just follow this pattern and enter your code within the main method to start with, and the rest will soon follow. Next Java tutorial – Objects and Classes .