Posts tagged ‘Beginners Java Tutorial’

Java Tutorial – Connect to MySQL Database

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

.

Java Tutorial – Database Programming

This tutorial assumes knowledge of basic database concepts and MySQL.

In this Java tutorial you will learn how to connect to a MySQL database.

Connecting to a database will likely be a common task as your Java projects progress. In this JAVA tutorial, we will use the Java Database Connectivity API (Application Programming Interface) – JDBC to deliver our data.

The JDBC libraries provide the means to connect your programs to a database and perform any operations upon the data that you require. To start using JDBC you need:

  • the JDK (which you may already have installed)
  • a JBDC driver, which depends on the Database Management System you are using for your data.

Once you have installed a driver compatible with the DBMS for your data source, create a new Java project in your IDE. Enter the following import statement at the top of your Main Class:

	//import required for database operations
import java.sql.*;

Now enter your main method (this code is for MySQL databases, with notes where alterations are required for other systems):

public static void main(String[] args)
{
		//try block for sql exceptions
	try
	{
			//create driver - ALTER TO SUIT YOUR DRIVER/ DBMS
		Class.forName("com.mysql.jdbc.Driver").newInstance(); 
		
			//database connection code - ENTER YOUR DETAILS
		String username = "yourname";
		String password = "yourpwd";
		
			//URL - ALTER TO CONNECT TO YOUR DATABASE
		String dbURL = "jdbc:mysql://somedomain.com/database?user="
			+ username + "&password=" + password;
			
			//create the connection - ALTER FOR YOUR DBMS
		java.sql.Connection myConnection = 
			DriverManager.getConnection(dbURL);
			
			//create statement handle for executing queries
		Statement stat = myConnection.createStatement();
		
	}
	catch( Exception E ) 
	{ System.out.println( E.getMessage() );	}
}

If exception handling is as yet unfamiliar to you, the try and catch blocks provide your program with the ability to continue when unexpected input is received, for example when communicating with data sources. There is always a possibility of unforeseen error when your code relies on external input, in which case the code may ‘throw an exception’. You simply put the code that will potentially cause an exception to be thrown inside the try block, and the response to any exceptions inside the catch. If an input error (or in this case an sql error) occurs, the code will immediately jump to the catch block – all we do in this case is write the details of the error out to the console.

Your code is now ready to execute some queries on the data – to do so, enter code such as the following example at the end of (inside) the try block:

//query to select all of the data from a table
String selectQuery = "Select * from MyTable";
	//get the results
ResultSet results = stat.executeQuery(selectQuery);
	//output the results
while (results.next())
{
		//example - column is called 'firstname'
	System.out.println("first name: " + 
		results.getString("firstname"));
}

You can use the statement handle (the ‘stat’ variable in the code above) to execute other SQL statements on your data, such as updates and inserts. For updates, use the syntax:

//example update statement
String updateStatement = 
	"Update MyTable set SomeColumn=192 where OtherColumn=12";
	//int return indicates success or failure
int updateSuccess = stat.executeUpdate(updateStatement);
System.out.println("success? "+updateSuccess);

For inserts the syntax is the same:

//example insert statement
String insertStatement = 
	"Insert into MyTable (col1, col2, col3) 
	values (12, 'bla', 127)";
	//int return indicates success or failure
int insertSuccess = stat.executeUpdate(insertStatement);
System.out.println("success? "+insertSuccess);

You can also use the Result Set to get information about metadata:

	//get the metadata from a ResultSet
ResultSetMetaData mData = results.getMetaData();

The ResultSetMetaData object provides methods to ascertain details of the data such as table names within the database, column names within tables etc.

Once you’ve carried out whichever operations you need on your data, you should then close the connection:

results.close();
stat.close();
myConnection.close();

The JDBC API is widely used within Java applications due to the fact that it is standard and can be used for many relational database systems. While some of the details within the above code may need to be slightly altered for your chosen DBMS, the overall structure of your database connectivity code will remain the same.

January 7, 2009 at 6:06 pm Leave a comment

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.

December 11, 2008 at 2:04 pm Leave a comment

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.

December 8, 2008 at 9:07 pm 1 comment

Beginners Java Tutorial – Methods – Control Structures

Java – Methods and Control Structures

This Java tutorial is intended for people in the early stages of beginning Java programming.

When you compile and run a Java program, the JVM executes whatever is within the main method. These instructions are carried out sequentially unless dictated otherwise by the code itself, for example by using control structures, calling methods or creating Objects. This tutorial introduces basic control structures and method invocation in Java.

When you start programming in any language, it can seem intuitive to think of a program as a series of instructions that are executed in a linear fashion. However, when building applications, you will structure your code in a number of different ways.

For example, if your application allows user interaction, whatever code is executed will depend on what the user does at any point. Whenever your programs use external input, whether from user interaction or e.g. where content comes from a database, you need to tailor the behaviour of your code to suit the particular input that it receives.

Conditionals

Imagine you have an application in which a series of products are being displayed, the product details being pulled from a database. Your display will look messy if the product names are longer than 20 characters so you decide to display only the first 20, cropping the remaining letters off. In your IDE, create a new Java project and enter the following in your main method:

//main method
public static void main(String[] args)
{
		//product name - would have come from database
	String productName = "Deluxe Man-Size Tissues";
		//name as it will be displayed
	String displayName = "";
		//conditional statement
	if(productName.length()>20)
		displayName = productName.substring(0, 20);
	else
		displayName = productName;
		//test the result
	System.out.println(displayName);

}

In this trivial example, the product name is ‘hard-coded’ into the program but imagine that when you sit down to write the program, you have no idea what String value will be in that variable. Look at the conditional statement and think about what happens at runtime. If the variable name is indeed longer than 20 chars, only the code under the ‘if’ will execute, with the ‘else’ being ignored. If the name is 20 chars or less, only the ‘else’ executes, with the ‘if’ ignored. The statement within the ‘if’ brackets (‘productName.length()>20’) is a test which, when carried out, returns a true or false value – if true the instructions carry out the ‘if’, if false they jump to ‘else’. When you run the program, it should output “Deluxe Man-Size Tiss” – experiment by changing the productName variable.

Loops in Java

Another basic way to introduce a control structure to your code is by using loops. You will often find when programming that you need to carry out repetitive processing – you can reduce the amount of code that you actually need to write by using ‘while’ or ‘for’ loops.

Imagine you have an array of products whose names you want to display – enter and run the following code:

//product array
String[] products = {"Hats", "Shoes", "Ties"};
	//print each to standard output
for(int i=0; i

The code within this loop will execute as many times as there are elements in the array. What happens when the instructions reach the loop:

  • The first time the loop is carried out, the value 0 is assigned to the i variable.
  • The test i<products.length is carried out, returning a true or false value.
    • If the test returns true
      • the content of the loop (printing out the value at position i in the array) is carried out
      • i++ is executed (i is incremented to keep track of how many times the loop has executed)
      • the loop is then re-entered – the test carried out again to see if i is still less than the length of the array
    • If the test returns false, the loop is abandoned and whatever code lies after it is executed.

A while loop can be used to the same effect:

int j=0;
while(j

Methods

You will often find that you are carrying out the same processing in more than one place within your program, for example, imagine you have several arrays that you wish to display the contents of in the same way – you can define your own methods to do this. In your project, enter the following:

//class declaration
public class MyClass
{
		//main method
	public static void main(String[] args)
	{
			//product array
		String[] products = {"Hats", "Shoes", "Ties"};
			//call the method, passing it the product array
		int elems = printElements(products);
			//test the result
		System.out.println(elems + " printed");
	}

		//method prints the elements in a given array
	public static int printElements(String[] elements)
	{
		for(int e=0; e

When creating your own methods like this, you have to decide what the type and number of parameters are, what the return type is (int in this case, void if there is none), as well as the content and name of the method (try to make this meaningful but concise if possible).

You can then call the method passing it any other String array and it will perform the same action with it – try it by creating a second array with different length and content.

December 3, 2008 at 5:44 pm 1 comment

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.

Next Java Tutorial – Methods and Control Structures

December 3, 2008 at 4:54 pm 1 comment

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:

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 .

November 20, 2008 at 12:12 pm Leave a comment


Follow us on Twitter

Error: Twitter did not respond. Please wait a few minutes and refresh this page.