Learn Java programming tutorial lesson 1 - First Program Learn Java programming tutorial lesson 2 - Variables and constants Learn Java programming tutorial lesson 3 - Decisions Learn Java programming tutorial lesson 4 - Loops Learn Java programming tutorial lesson 5 - Data input and type conversions Learn Java programming tutorial lesson 6 - Arrays Learn Java programming tutorial lesson 7 - Object-Oriented Programming(OOP) Learn Java programming tutorial lesson 8 - Inheritance
This creates a class called Hello. All class names must start with a capital letter. The main part of the program must go between curly brackets after the class declaration. The curly brackets are used to group together everything inside them.
public class Hello {
We must now create the main method which is the section that a program starts.
public class Hello { public static void main(String[] args) { } }
The word public means that it is accessible by any other classes. static means that it is unique. void is the return value but void means nothing which means there will be no return value. main is the name of the method. (String[] args) is used for command line parameters. Curly brackets are used again to group the contents of main together. You probably won't understand a few of the things that have just been said but you will know what they mean later on. For now it is enough just to remember how to write that line. You will see that the main method code has been moved over a few spaces from the left. This is called indentation and is used to make a program easier to read and understand. Here is how you print the words Hello World on the screen:
public class Hello { public static void main(String[] args) { System.out.println("Hello World"); } }
Make sure that you use a capital S in System because it is the name of a class. println is a method that prints the words that you put between the brackets after it on the screen. When you work with letters like in Hello World you must always put them between quotes. The semi-colon is used to show that it is the end of your line of code. You must put semi-colons after every line like this.
If you did everything right then you will see no errors messages and your program will be compiled. If you get errors then go through this lesson again and see where your mistake is.
Do not add .class on to the end of Hello. You will now see the following output on the screen: Hello World Congratulations! You have just made your first Java program.
Comments
Comments are written in a program to explain the code. Comments are ignored by the compiler and are only there for people. Comments must go between a /* and a */ or after //. Here is an example of how to comment the Hello World program:
/* This program prints the words Hello World on the screen */ public class Hello // The Hello class { public static void main(String[] args) // The main method { System.out.println("Hello World"); // Print Hello World } }
Variable types
There are 3 different types of data that can be stored in variables. The first type is the numeric type which stores numbers. There are 2 types of numeric variables which are integer and real. Integers are whole numbers such as 1,2,3,... Real numbers have a decimal point in them such as 1.89 or 0.12. Character variables store only 1 letter of the alphabet. You must always put the vlaue that is to be stored in a character variable inside single quotes. A string variable is like a chracter variable but it can store more than 1 character in it. You must use double quotes for a string instead of single quotes like with a character. Boolean variables can store 1 of 2 values which are True or False. Here is a table of the types of variables that can be used: Name byte short int long float double char String boolean Type Values Numeric - Integer -128 to 127 Numeric - Integer -32 768 to 32 767 Numeric - Integer -2 147 483 648 to 2 147 483 647 Numeric - Integer -9 223 372 036 854 775 808 to 9 223 372 036 854 775 807 Numeric - Real -3.4 * 1038 to 3.4 * 1038 Numeric - Real -1.7 * 10308 to 1.7 * 10308 Character All unicode characters Character All unicode characters Boolean True or False
Declaring variables
You can declare a variable either inside the class curly brackets or inside the main method's curly brackets. You declare a variable by first saying which type it must be and then saying what its name is. A variable name can only include any letter of the alphabet, numbers and underscores. Variable names can start with a $ but may not start with a number. Spaces are not allowed in variable names. You usually start a variable name with a lower case letter and every first letter of words that make up the name must be upper case. Here is an example of how you declare an integer variable called MyVariable in the main method:
public class Variables { public static void main(String[] args) { int myVariable; } }
If you want to declare more than 1 variable of the same type you must seperate the names with a comma.
public class Variables { public static void main(String[] args) { int myVariable, myOtherVariable; } }
Using variables
A = is used to store a value in a variable. You put the variable name on the left side and the value to store in the variable on the right side. Remember to use quotes when storing String values. You can also store a value in a variable when it is declared or later in the program.
public class Variables { public static void main(String[] args) { int myInteger; myInteger = 5; String myString = "Hello"; } }
Variables in calculations
The important thing about variables is that they can be used in calculations. When you perform a calculation you must store the result in a variable which can also be a variable that is used in the calculation.. Here is an example of how to add 2 numbers together and store the result in a variable:
public class Variables { public static void main(String[] args) { int answer; answer = 2 + 3; } }
Once you have stored a value in a variable you can use it in a calculation just like a number.
public class Variables { public static void main(String[] args) { int answer; int number = 2; answer = number + 3; } }
Here is a table of operators which can be used in calculations: Operator Operation + Addition Subtraction * Multiplication / Division % Remainder of division
Constants
Constants are variables with values that can't be changed. The value is assigned to a constant when it is declared. Constants are used to give names to certain values so that their meaning is more obvious. The meaning of the number 3.14 is not obvious but if it was given the name PI then you know immediatly what it means.Use the word final in front of a normal variable declaration to make it a constant.
public class Variables { public static void main(String[] args)
{ } }
If you change i to 4 and run this program again you will see that no message is printed.
Relational operators
You will see that a == has been used to test if the values are equal. It is important to know that a = is for setting a value and a == is for testing a value. The == is called a relational operator. Here is a table of the other relational operators that can be used: == != > >= < <= Equal to Not equal to Greater than Greater than or equal to Less than Less than or equal to
else
We know that if the condition is true then the code directly afer the if statement is run. You can run code for when the condition is false by using the else statement.
public class Decisions { public static void main(String[] args) { int i = 4; if (i == 5) System.out.println("i is equal to 5"); else System.out.println("i is not equal to 5"); } }
Grouping statements
If you want to run more than 1 line of code in an if statement then you must group them together with curly brackets.
public class Decisions { public static void main(String[] args) { int i = 4; if (i != 5) { System.out.println("i not is equal to 5"); System.out.println("i is equal to " + i); } } }
Nested if structures
You can put if statements inside other if statments which will make them nested if statements. It is sometimes more efficient to use nested if statements such as in the following example which finds out if a number is positive, negative or zero:
public class Decisions { public static void main(String[] args) { int i = 1; if (i > 0) System.out.println("Positive"); else if (i < 0) System.out.println("Negative"); else
} }
System.out.println("Zero");
For loop
The for loop goes from a number you give it to a second number you give it. It uses a loop counter variable to store the current loop number. Here is the format for a for loop:
for (set starting value; end condition; increment loop variable)
You first set the loop counter variable to the starting value. Next you set the end condition. While the condition is true the loop will keep running but when it is false then it will exit the loop. The last one is for setting the amount by which the loop variable must be increased by each time it repeats the loop. Here is how you would do the example of printing Hello 10 times using a for loop:
public class Loops { public static void main(String[] args) { int i; for (i = 1; i <=10; i++) System.out.println("Hello"); } }
} }
While loop
The while loop will repeat itself while a certain condition is true. The condition is only tested once every loop and not all the time while the loop is running. If you want to use a loop counter variable in a while loop then you must initialize it before you enter the loop and increment it inside the loop. Here is the Hello example using a while loop:
public class Loops { public static void main(String[] args) { int i = 1; while (i <= 10) { System.out.println("Hello"); i++; } } }
Do while loop
The do while loop is like the while loop except that the condition is tested at the bottom of the loop instead of the top.
public class Loops { public static void main(String[] args) { int i = 1; do { System.out.println("Hello"); i++; } while (i <= 10) } }
Learn Java programming tutorial lesson 5 - Data input and type conversions
Until now we have set the values of variables in the programs. Now we will learn how to get input from the user so that our programs are a bit more interesting and useful.
You will see that it says "throws Exception" at the end of the main method declaration. An exception is an error and "throws Exception" tells java to pass the error to the operating system for handling. Your program will not compile if you don't put this in.
Reading strings
The easiest way to read a string is to use the graphical input dialog. We must import the JOptionPane.showInputDialog method before we can use it. Then we can use the JOptionPane.showInputDialog method to read the string. We can print the entered string using the JOptionPane.showMessageDialog method. You must then put a System.exit(0) at the end of the program or else the program will not stop running.
import javax.swing.*; public class ReadString { public static void main(String[] args) { String s; s = JOptionPane.showInputDialog("Enter your name"); JOptionPane.showMessageDialog(null, "Your name is " + s); System.exit(0);
Type conversions
Once you have read a string you might want to convert it to another data type such as an integer. You have already seen in a previous example that you must use the type that you want to convert to between brackets in front of the variable to be converted. Here is an example of some conversions:
public class Convert { public static void main(String[] args) { int i; char c = 'a'; i = (int)c; i = 5; c = (char)i; } }
Strings are not variables but actually classes which is why we must use the Integer.parseInt() method to convert a string to an integer.
import javax.swing.*; public class ConvertString { public static void main(String[] args) { String s; int i; s = JOptionPane.showInputDialog("Enter a number"); i = Integer.parseInt(s); JOptionPane.showMessageDialog(null, "The number you entered is " + i); System.exit(0); } }
Declaring an array
Declaring an array is the same as declaring a normal variable except that you must put a set of square brackets after the variable type. Here is an example of how to declare an array of integers called a.
public class Array { public static void main(String[] args) { int[] a; } }
An array is more complex than a normal variable so we have to assign memory to the array when we declare it. When you assign memory to an array you also set its size. Here is an example of how to create an array that has 5 elements.
public class Array { public static void main(String[] args) { int[] a = new int[5]; } }
Instead of assigning memory to the array you can assign values to it instead. This is called initializing the array because it is giving the array initial values.
public class Array { public static void main(String[] args) { int[] a = {12, 23, 34, 45, 56}; } }
Using an array
You can access the values in an array using the number of the element you want to access between square brackets after the array's name. There is one important thing you must remember about arrays which is they always start at 0 and not 1. Here is an example of how to set the values for an array of 5 elements.
public class Array { public static void main(String[] args) { int[] a = new int[5]; a[0] = 12; a[1] = 23;
} }
A much more useful way of using an array is in a loop. Here is an example of how to use a loop to set all the values of an array to 0 which you will see is much easier than setting all the values to 0 seperately.
public class Array { public static void main(String[] args) { int[] a = new int[5]; for (int i = 0; i < 5; i++) a[i] = 0; } }
Sorting an array
Sometimes you will want to sort the elements of an array so that they go from the lowest value to the highest value or the other way around. To do this we must use the bubble sort. A bubble sort uses an outer loop to go from the last element of the array to the first and an inner loop which goes from the first to the last. Each value is compared inside the inner loop against the value in front of it in the array and if it is greater than that value then it is swapped. Here is an example.
public class Array { public static void main(String[] args) { int[] a = {3, 5, 1, 2, 4}; int i, j, temp; for (i = 4; i >= 0; i--) for (j = 0; j < i; j++) if (a[j] > a[j + 1]) { temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } }
2D arrays
So far we have been using 1-dimensional or 1D arrays. A 2D array can have values that go not only down but also across. Here are some pictures that will explain the difference between the 2 in a better way.
1D Array 01 12 23 34 45 2D Array 012 0123 1456 2789 All that you need to do to create and use a 2D array is use 2 square brackets instead of 1.
public class Array { public static void main(String[] args) { int[][] a = new int[3][3]; a[0][0] = 1; } }
Creating a class
You have already been creating classes in the programs you have written so far. To show you how they work we will need to create a separate class in a separate file. This class will be called Student.
public class Student { }
Now we will add 2 variables to the class which are the student's name and student number.
public class Student { String studentName; int studentNumber; }
Next we must add methods for getting and setting these variables.
public class Student { String studentName; int studentNumber; public void setStudentName(String s) { studentName = s; } public void setStudentNumber(int i) { studentNumber = i; } public String getStudentName() { return studentName; } public int getStudentNumber() { return studentNumber;
Instantiating an object
Now that we have finished writing the class we must create the main program that will instantiate the object. We will call the main program class TestClass. It should look just like how every other java program starts off.
public class TestClass { public static void main(String[] args) { } }
Now we will instantiate the object. To do this we declare a reference to the object called stu and set it equal to a newly created object in memory.
public class TestClass { public static void main(String[] args) { Student stu = new Student(); } }
Constructors
A constructor is a method that is run when an object is instantiated. Constructors are useful for initializing variables. The constructor is declared with only the name of the
class followed by brackets. Here is an example of the Student class that initializes both student name and student number.
public class Student { String studentName; int studentNumber; Student() { studentName = "No name"; studentNumber = 1; } public void setStudentName(String s) { studentName = s; } public void setStudentNumber(int i) { studentNumber = i; } public String getStudentName() { return studentName; } public int getStudentNumber() { return studentNumber; } }
You can also pass parameters to a constructor when you instantiate an object. All you need to do is add the parameters in the brackets after the constructor declaration just like a normal method.
public class Student { String studentName; int studentNumber; Student(String s, int i) { studentName = s; studentNumber = i; } public void setStudentName(String s) { studentName = s; }
public void setStudentNumber(int i) { studentNumber = i; } public String getStudentName() { return studentName; } public int getStudentNumber() { return studentNumber; } }
Now all you need to do is put the parameters in the brackets when you instantiate the object in the main program. public class TestClass { public static void main(String[] args) { Student stu = new Student("John Smith",12345); System.out.println("Student Name: " + stu.getStudentName()); System.out.println("Student Number: " + stu.getStudentNumber()); } }
Person class which has a variable for the person's name. There are also set and get methods for the name.
class Person { private String name; public void setName(String n) { name = n; } public String getName() { return name; }
Now we will create the Student class that has a variable for the student number and the get and set methods for student number. The extends keyword is used to inherit from the Person class in the following example.
class Student extends Person { private String stuNum; public void setStuNum(String sn) { stuNum = sn; } public String getStuNum() { return stuNum; }
Finally we have to create a program that will instantiate a Student object, set the name and student number and then print the values using the get methods.
public class TestInheritance { public static void main(String[] args) { Student stu = new Student(); stu.setName("John Smith"); stu.setStuNum("12345"); System.out.println("Student Name: " + stu.getName()); System.out.println("Student Number: " + stu.getStuNum()); } }
Abstract inheritance
Abstract classes are created only for the purpose of being inherited from. In fact you can't instantiate an object from an abstract class. You must put the abstract keyword in front of the class name declaration to create an abstract class. We can change the Person class above to show how it works.
abstract class Person { private String name; public void setName(String n) { name = n; } public String getName() { return name; }
Interfaces
Interfaces are like abstract classes because you can't instantiate them and they are only used for being inherited from. The difference is that interfaces are not allowed to have variables unless they are constants and methods are not allowed to have a body. The point of an interface is for you to override the methods that are declared in it. You must use the implements keyword instead of extends when using interfaces. Here is an example of the Person class as an interface and the Student class that uses the Person interface.
interface Person { public void setName(String n); public String getName(); } class Student implements Person { private String stuNum; private String name; public void setStuNum(String sn) { stuNum = sn; } public String getStuNum() { return stuNum; }
C# - A new and popular language that is based on C but has a lot more features and is much easier to use Pascal - A very popular learning language that is easier to use than C C++ - Based on C but includes advanced features. It is better to learn C before C+ + Java - Java is becoming a popular business and learning language. Doesn't teach you some important concepts that C/C++ does
If you are learning programming as a hobby then you should choose a programming language like Visual Basic because it is easy to use and you can start making useful programs straight away. Alternatives to Visual Basic:
Delphi - Delphi is a little bit more difficult than Visual Basic but teaches other important programming concepts Scripting Languages(Python, Perl) - Easier to program in than compiled languages but not always as useful
Comments
You will find that programming is difficult at first but becomes easier later. You should try not to quit if you think it is too difficult for you because most programmers once thought it was difficult but have no problems today. Learning how to program is very rewarding and is worth all the hard work. Good Luck!