Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,151,558 members, 7,812,790 topics. Date: Monday, 29 April 2024 at 07:23 PM

Java Tutorial For Beginners - Programming (2) - Nairaland

Nairaland Forum / Science/Technology / Programming / Java Tutorial For Beginners (23686 Views)

C++ Tutorial For Beginners... Part 1... / For Beginners: Learn How To Create A Simple Android Native App / Programming Challenge For Beginners N20000 (2) (3) (4)

(1) (2) (3) (4) (5) (Reply) (Go Down)

Re: Java Tutorial For Beginners by nnasino(m): 12:15pm On Nov 22, 2014
Let's take a deeper look into the for loop.
for(initialization; condition; iteration)
statement;

Note that all/any of initialization, condition or iteration can be left empty but make sure the semi colons are left. For example, you can have a for loop like this
for(;wink
, this is simply an infinite loop. Now let us take the components one by one:
Initialization: As we said earlier to initialize a variable is to give it a value. This part of the for loop is used to set the value of a variable. You can set the value of multiple variables here. You can also declare variables here. Most of the time you will declare a single variable called the loop control variable. The loop control variable is the variable used to control the execution of the for loop. It is usually part of the condition and part of the iteration. Example:

for(int i =0; i < 4; i++)

In the above code, the loop control variable is i. It is initialized to the value 0. You can also see that it is part of the condition (i < 4) for ending the loop. It is also part of the iteration as it is incremented at each point.
Remember that you can declare more than one variable in the initialization part. For example, in this snippet
for(int i = 0; i < object.size(); i++)
, if the size of object is lets say 2000, this means that object.size() will be called 2000 times. This is a waste of processing power since object.size() remains the same throughout the execution of the for loop. We can store the size of object in the initialization and refer to the variable instead of calling the function all the time.
for(int i =0, size = object.size(); i < size; i++)
. This save us processing power at the expense of creating a variable (memory). This shows that there will always be a tradeoff between processing speed(power) and memory. So we should be able to weigh the benefits and choose when using extra memory will be advantageous to our processing.

Condition
This is checked at each iteration to know whether the loop continues. It the condition evaluates to true, the loop proceeds, but if it is false then the loop exits. Note that any expression that evaluates to true or false can be used here. examples:

for(int i = 0, j =12; i < j; i++).....
for(int height = 100; height > 20; height--)
for(int i = 0, j=23; (i < 10) && (23 > 4); i++)....


Iteration
This part is simply to insert code that you want to execute at the end of each iteration. For example increment the loop control variable i++ or basically anything else. But it is advisable and good coding practice to only put code which affects the loop control variable here.
examples:

for(int i = 1, j =4; i < 5; i++, j--)



One more thing before we conclude:
[b]break, continue and labels[\b]
A
break
exits the loop it is contained in. A
continue
skips all the code ahead and moves to the beginning of the loop and labels are used to specify which loop to apply these constructs on.
e.g

while(true){
statements;
statements;
if(someThing)
break;
}

In the snippet above, the condition for the loop is
true
therefore it is an infinite loop. Sometimes infinite loops are necessary so we
need a way to break out of the loop. This is where we use the
break
keyword. In the snippet above, the loop runs until someThing evaluates to true.

For continue, it is used to skip all code and return to the beginning of the loop. example:

while(i < 5){
statement;
statement2;
if(someThing)
continue;
statement3;
statement4;
statement5;
}

In the above snippet, if someThing evaluates to true, statement 3, 4 and 5 are skipped and execution continues at the beginning of the loop that is i <5 is checked.


labels: labels are useful in loops are nested. A loop is said to be nested if it is located inside another loop. For example:

for(int i = 0; i < 5; i++)
for(int j = 0; j < 5; j++)
break;

In the above code snippet, the inner for loop is broken out of. But say we wanted to break out of the outer for loop? this is where labels come in. We can give loops labels, which will then be used together with the break and continue statements. To break out of the outer loop in the above code snippet, we write as follows:

loop1: for(int i =0; i < 5; i++)
for(int j =0; j < 5; j++)
break loop1;



Well, that's all for loops, and we are done with part one of the tutorial. We now have all we need to solve most problems that can come up. We will now start solving problems to strengthen our knowledge.

This is the fun part, and I will like for it to be interactive.
Re: Java Tutorial For Beginners by nnasino(m): 2:28pm On Nov 22, 2014
Methods
Methods are used to group a set of statements performing one task. When you write code which you notice keeps repeating itself then you might need to create a method/function to handle that task. Functions can take values called parameters which it will use in its computation. An example of a function is a function that checks if a number is a prime number or not. Functions/methods can return an answer or not. When a function does not return any value it is of type void. Defining a function:

type nameOfMethod(parameter list){
body of method;
return avalue; //if type is not void
}

If you are not returning any value then type should be
void
. If you are returning a value then type should be the type of the value you want to return (int, float, double, String etc). Also, if you are returning a value then you must have the return keyword in the body of the method. The parameter list, is a comma separated list of the parameters to be passed to the function. The parameters must have the type and the name by which they will be accessed.
An example

int sum(int a, int b){
//This function sums two numbers
return a + b; //using the two parameters passed to it.
}

The above function takes, two

Getting user input from the user:
We haven't discussed classes or objects so far but we will need to use them in our exercises so i'll give crash course on both. A class is simply a framework for creating objects. It contains variables and functions within it which represent properties and behaviours of the objects it will be used to create respectively. For example, a vehicle class is a framework for creating vehicles. It's properties can include speed, colour, size, etc while it's behaviours include move(), stop(), changeOil() etc. So with a single class definition we can create numerous objects each having their own properties. The good thing about objects is that we can use them without knowing how they are implemented. A car can be driven without knowing what engine is in it or how it was built. Objects can also be nested within one another. A steering wheel is a fully developed object with its own components. But it is contained in the vehicle object. The vehicle doesn't need to know anything about how the steering wheel was built/created all it needs to know are what it can be used for and how to use it.
We will delve into objects later on but for now we need to use one in our program ( we will be using it regularly).

The
Scanner
class is a built-in java class for reading input. It can read from files, standard input (user) and other streams. To use these functions we need to create an object of the Scanner class.
In java this is done by:
Scanner scannerObject;

We have declared the scanner class, but before we can use it we need to initialize it.
New Concept:
Constructor
: A constructor is a function that is used to initialize a newly created object. We'll stop there for now and continue. Just note that the constructor of a class is a function with the same name as the class. Now the
Scanner
class's constructor takes one parameter which represents where the input comes from. In our case, the input comes from Standard input (keyboard), so the parameter is
System.in
.
So to declare and initialize the Scanner object we have:

Scanner scan = new Scanner(System.in);

This creates an object for us. We also need to import the Scanner class. We do this by putting
import java.util.Scanner;
at the top of the file. For now ignore all these, we will still treat objects and classes later on. But for now just copy this code into your file.
Note: If you use netbeans, set up your key map with the eclipse settings so you can follow with the shortcut keys i will be using to do this, click Tools menu > options, then click the keymap tab and change the netbeans to eclipse, click apply and then ok.

Netbeans will be very helpful when working with objects. Now you have set up your key map. You can use the following:
Type Sca and press Ctrl+space, this will bring up a list of all classes matching the what you've typed select the one you require and press enter, in this our case the one in java.util. Doing this will automatically import the class for us.
Also, we can type Scanner and declare and initialize the object without importing. The IDE will definitely complain, at this point press Ctrl+shift+O, this imports all missing classes.
As we move on, i'll be introducing more function keys for making our work easy.

Now to our challenges:
Challenge 1:
Write a program which displays the number of prime numbers from zero to a number. Number should be provided by the user.
We break the problem into components:
- Get number from the user.
- check if each number is a prime number. if they are increment the count.
- Display the count to the user.

To get input from the user we use the Scanner class
-We will be checking many numbers therefore we will need a loop
-We will be checking if a number is prime so we will create a function to check

The program therefore goes:



class Primes{
static boolean isPrime(int number){ //isPrime is declared as static, so we can use it within main (main is also static)
if(number == 2)
return true;
for(int i = 2; i < number; i++){
if(number % i == 0) //If the number can be divided by any other number apart from 1 and itself
return false; //Then it is not prime
}
return true; //If not it is prime
}
public static void main(String[] args){ //type psvm and press tab, netbeans will complete this for you
int number = 0; //Variable for holding the maximum number
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the maximum number" ); //type sout and press tab
number = scan.nextInt();
int count = 0; //The number of primes found
for(int i = 2; i <= number; i++){
if(isPrime(i))
count++;
}
System.out.println("The number of primes between 1 and " + number + " is " + count);
}
}
Re: Java Tutorial For Beginners by nnasino(m): 1:10pm On Nov 27, 2014
Wow, good day everyone it's been awhile been pretty busy with work.

Today, we'll take on a common problem which will help us revise all we have learnt so far and introduce a few new constructs.
We will create a program that will calculate the CGPA of a student. It's a pretty simple program but it helps reinforce all we have learnt so far.
First of all, calculating cgpa involves the following:


- get the number of years to calculate
- for all the years
- for all the semesters
get the number of courses offered
for all the courses
- get the title/code of the course
- get the credit load/unit of the course
- get the letter grade obtained
calculate Total number of units and total grade point of the semester
- add all TNUs of all semesters (Total number of units)
- add all TGPs of all semesters (Total grade point)
- CGPA = Total TGP / Total TNU
- Display the CGPA to the user


We now have the algorithm let's now take each part one at a time:
But first let us declare variables we will be needing:

int TNU = 0; // Total number of units
int TGP = 0; //Total grade point
double TTGP = 0.0; //Total of the TNUs
double TTNU = 0.0; //Total of the TGPs
int numOfCourses =0; //the number of courses for a semester
String title = null; //title of a course
int creditLoad = 0; //Credit load of a course
char gradeLetter = 'F'; //Grade letter of a course
double CGPA = 0.0; //Cumulative grade point average

- get the number of years to calculate
To get any input from the user we need the scanner class so initialize it first before reading the number of years.


//Declare variable for holding the number of years
int numOfYears = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Welcome, enter the number of years: "wink;
numOfYears = Integer.parseInt(scan.nextLine());
System.out.println();



- for all the years


From the statement we can deduce that we will use a for loop for this.

for(int years = 1; years <= numOfYears; years++){


}


- for all the semesters
Note that this is within the years for loop

//There are usually two semesters each year
for(int semester = 1; semester <= 2; semester++){


}

get the number of courses offered
for all the courses
- get the title/code of the course
- get the credit load/unit of the course
- get the letter grade obtained
-calculate Total number of units and total grade point of the semester

This is nested in the semesters for loop


//get the number of courses offered for the semester
numOfCourses = Integer.parseInt(scan.nextLine());
//For all courses
for(int course = 0; course < numOfCourses; course++){
//get the title/code of the course
System.out.print("Please enter the title/code of the course: "wink;
title = scan.nextLine();
//get the credit load/unit of the course
System.out.printf("Please enter the credit load of %s: ", title);
creditLoad =Integer.parseInt(scan.nextLine());
//get the letter grade obtained
System.out.printf("Please enter the grade letter of %s: ", title);
gradeLetter = scan.nextLine().charAt(0)
//calculate Total number of units and total grade point of the semester
//Convert the grade letter to a point A - 5, B -4 etc
//Add the grade point of this course to the total grade point of this semester
TGP += creditLoad * gradeValue(gradeLetter);
//Add the credit load of this course to the total number of units of this semester
TNU += creditLoad;
}

We can see that we used the function gradeValue(gradeLetter) and therefore we have to define it.
The function takes the letter grade entered and returns the equivalent value. A is 5, B is 4, C is 3,
D is 2, E is 1 and F is 0. We can achieve this using a
switch
statement.


static int gradeValue(char letter){
static int gradeValue(char letter) {
switch (letter) {
case 'a':
case 'A':
return 5;
case 'b':
case 'B':
return 4;
case 'c':
case 'C':
return 3;
case 'd':
case 'D':
return 2;
case 'e':
case 'E':
return 1;
default:
return 0;
}
}

You can see we have done something different here. You can have more than one case run the same piece of code. Above, if the enters a small a or a capital A it returns 5. Also, we didn't use breaks in the switch because return exits the loop so no need for breaking.
Put this above the main (public static void main()) method.


- add all TNUs of all semesters (Total number of units)
- add all TGPs of all semesters (Total grade point)

This is done within the
years
for loop

TTNU += TNU;
TNU = 0;
TTGP += TGP;
TGP = 0;



- CGPA = Total TGP / Total TNU
- Display the CGPA to the user



CGPA = TTGP / TTNU;
System.out.printf("Your CGPA is: %.3f%n", CGPA);


Combining the code together we have:


/*This is a good place to write information about your program. Including the use, your name, the date and the version.
* A commandline application for calculating CGPA. No exception handling.
*/
package learn;

import java.util.Scanner;

/**
*
* @author nnasino
*/
public class GPA {

static int gradeValue(char letter) {
switch (letter) {
case 'a':
case 'A':
return 5;
case 'b':
case 'B':
return 4;
case 'c':
case 'C':
return 3;
case 'd':
case 'D':
return 2;
case 'e':
case 'E':
return 1;
default:
return 0;
}
}

public static void main(String[] args) {
int TNU = 0; // Total number of units
int TGP = 0; //Total grade point
double TTGP = 0.0; //Total of the TNUs
double TTNU = 0.0; //Total of the TGPs
int numOfCourses = 0; //the number of courses for a semester
String title = null; //title of a course
int creditLoad = 0; //Credit load of a course
char gradeLetter = 'F'; //Grade letter of a course
double CGPA = 0.0; //Cumulative grade point average

int numOfYears = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Welcome, enter the number of years: " );
numOfYears = Integer.parseInt(scan.nextLine());
System.out.println();
for (int years = 1; years <= numOfYears; years++) {
//There are usually two semesters each year
for (int semester = 1; semester <= 2; semester++) {
//get the number of courses offered for the semester
System.out.printf("Please enter the number of courses for Semester %d: ", semester ) ;
numOfCourses = Integer.parseInt(scan.nextLine() ) ;
//For all courses
for (int course = 0; course < numOfCourses; course++) {
//get the title/code of the course
System.out.print("Please enter the title/code of the course: " ) ;
title = scan.nextLine();
//get the credit load/unit of the course
System.out.printf("Please enter the credit load of %s: ", title) ;
creditLoad = Integer.parseInt(scan.nextLine()) ;
//get the letter grade obtained
System.out.printf("Please enter the grade letter of %s: ", title ) ;
gradeLetter = scan.nextLine().charAt(0 ) ;
//calculate Total number of units and total grade point of the semester
//Convert the grade letter to a point A - 5, B -4 etc
//Add the grade point of this course to the total grade point of this semester
TGP += creditLoad * gradeValue(gradeLetter ) ;
//Add the credit load of this course to the total number of units of this semester
TNU += creditLoad;
}
}
TTNU += TNU;
TNU = 0;
TTGP += TGP;
TGP = 0;
}
CGPA = TTGP / TTNU;
System.out.printf("Your CGPA is: %.3f%n", CGPA ) ;
}
}


Type this into a file named GPA.java and compile and run. We will build on this file while introducing new concepts in later lessons.
Well, have a nice day everyone and happy coding. smiley
Re: Java Tutorial For Beginners by nnasino(m): 5:53pm On Nov 28, 2014
Hi, everyone. I'm back for today's lesson. Today we will add some improvements to the GPA program of yesterday while introducing some new concepts.

Looking at our program closely we can easily see that there are problems with it. There isn't any reasonable error handling. The smallest of errors from the user can cause the program to crash or to behave wrongly. For example, if in place of credit load, the user enters a letter or a word, the program crashes with an error. Also, if one enters a number or a letter that isn't between A and F, then the program just treats it as zero. So today, we will be correcting all those issues and thus improving our program.

We will be looking at error handling today. Also called Exception Handling. Exception handling is simply a way of handling an error thus stopping it from crashing the application. In java, when an error occurs, an exception is thrown, if it is not handled, then it crashes the program.
Handling an exception is referred to as catching it. So in java when an exception occurs, we can either handle it or 'rethrow' to another part of the application. This part can also either handle or rethrow it again. This can go on till the last part where if it is not handled it causes the program to crash.

There are a few constructs/keywords used in exception handling. They include:

try
catch
throw
throws
finally


I won't explain them in words, rather i will use them in our program. Basically, to catch an exception, we put the piece of code that can throw such an exception within a
try...catch
block as follows:

try{
code that can potentially throw an exception
}catch(ExceptionName exceptionVariableName){
Exception handling code: //this code is called if an exception of type ExceptionName is thrown
}catch([i]AnotherExceptionName[i] exceptionVariableName2){
Notice that you can catch more than one exception :w
}finally{
any code in the finally block is executed regardless of whether an exception occurs or not
}


Now, looking at our code we can see at this point, we need some exception handling:

for(int course = 0; course < numOfCourses; course++){
//get the title/code of the course
System.out.print("Please enter the title/code of the course: "wink;
title = scan.nextLine();
//get the credit load/unit of the course
System.out.printf("Please enter the credit load of %s: ", title);
creditLoad =Integer.parseInt(scan.nextLine());
//get the letter grade obtained
System.out.printf("Please enter the grade letter of %s: ", title);
gradeLetter = scan.nextLine().charAt(0)
//calculate Total number of units and total grade point of the semester
//Convert the grade letter to a point A - 5, B -4 etc
//Add the grade point of this course to the total grade point of this semester
TGP += creditLoad * gradeValue(gradeLetter);
//Add the credit load of this course to the total number of units of this semester
TNU += creditLoad;
}

The bolded line can potentially throw an exception. You can verify this by inputting a letter instead of a number when asked for credit load. We can put this in a
try...catch
block but then what would we put as the exception handling code? and how can recover back to where the code stopped?. We can achieve this by putting this code into its own function/method. So we create a function called readCreditLoad() which we can call that will handle its exception handling independently and will only return after a valid credit load has been inputted.

So here is the function:

static int getCreditLoad(Scanner scan, String courseTitle){ //The function takes the scanner object and the course title as it's parameters
int result = 0; //The result to be returned
while(true){ //Keep asking for the credit load
try{ //Put the code in a try block to catch any exception that is thrown
System.out.printf("Please enter the credit load of %s: ", courseTitle); //Formatted print: this will be explained later on
result = Integer.parseInt(scan.nextLine());
//If the program reaches here then that means there was no error
//Let us now make sure that the user doesn't give us a ridiculous value. Credit load shouldn't be more than 25 at most
if(result > 25){
//the value is too large
throw new NumberFormatException("Credit load is too large"wink; //this throws our own exception, which will be handled also
}else if (result < 0){
//credit load cannot be negative
throw new NumberFormatException("Credit Load cannot be negative"wink;
}
}catch(NumberFormatException exc){
System.out.println("Error: " + exc.getMessage()); //Exceptions usually have information about themselves, including the errormessage
//exc.printStackTrace(); //This method is useful for debugging, it gives you a trace of all where and how the exceptions were generated
continue; //continue to the beginning of the loop
}
//if we get here then the program is fine and the credit load was read successfully so we leave the loop
break;
}
return result;
}


If we now replace the previous line with our function we get a better more robust program:


for(int course = 0; course < numOfCourses; course++){
//get the title/code of the course
System.out.print("Please enter the title/code of the course: "wink;
title = scan.nextLine();
//get the credit load/unit of the course
System.out.printf("Please enter the credit load of %s: ", title);
creditLoad = readCreditLoad(scan);
//get the letter grade obtained
System.out.printf("Please enter the grade letter of %s: ", title);
gradeLetter = scan.nextLine().charAt(0)
//calculate Total number of units and total grade point of the semester
//Convert the grade letter to a point A - 5, B -4 etc
//Add the grade point of this course to the total grade point of this semester
TGP += creditLoad * gradeValue(gradeLetter);
//Add the credit load of this course to the total number of units of this semester
TNU += creditLoad;
}


Now that the credit load part is corrected, let us correct the grade letter part. We will do this by modifying the getGradeValue() function. We will make it read the grade by itself and handle exceptions itself also.


static int gradeValue(Scanner scan, String courseTitle) {
char letter = 'f';
while (true) {
System.out.printf("Please enter the grade letter of %s: ", courseTitle);
letter = scan.nextLine().charAt(0); //Select the first character only
switch (letter) {
case 'a':
case 'A':
return 5;
case 'b':
case 'B':
return 4;
case 'c':
case 'C':
return 3;
case 'd':
case 'D':
return 2;
case 'e':
case 'E':
return 1;
case 'f':
case 'F':
return 0;
default:
System.out.println("Error: Please enter a grade letter from A to F"wink;
}
}
}


This is the full code:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package learn;

import java.util.Scanner;

/**
*
* @author chigozirim
*/
public class GPA {

static int gradeValue(Scanner scan, String courseTitle) {
char letter = 'f';
while (true) {
System.out.printf("Please enter the grade letter of %s: ", courseTitle);
letter = scan.nextLine().charAt(0); //Select the first character only
switch (letter) {
case 'a':
case 'A':
return 5;
case 'b':
case 'B':
return 4;
case 'c':
case 'C':
return 3;
case 'd':
case 'D':
return 2;
case 'e':
case 'E':
return 1;
case 'f':
case 'F':
return 0;
default:
System.out.println("Error: Please enter a grade letter from A to F"wink;
}
}
}

static int getCreditLoad(Scanner scan, String courseTitle) { //The function takes the scanner object and the course title as it's parameters
int result = 0; //The result to be returned
while (true) { //Keep asking for the credit load
try { //Put the code in a try block to catch any exception that is thrown
System.out.printf("Please enter the credit load of %s: ", courseTitle); //Formatted print: this will be explained later on
result = Integer.parseInt(scan.nextLine());
//If the program reaches here then that means there was no error
//Let us now make sure that the user doesn't give us a ridiculous value. Credit load shouldn't be more than 25 at most
if (result > 25) {
//the value is too large
throw new NumberFormatException("Credit load is too large"wink; //this throws our own exception, which will be handled also
} else if (result < 0) {
//credit load cannot be negative
throw new NumberFormatException("Credit Load cannot be negative"wink;
}
} catch (NumberFormatException exc) {
System.out.println("Error: " + exc.getMessage()); //Exceptions usually have information about themselves, including the errormessage
//exc.printStackTrace(); //This method is useful for debugging, it gives you a trace of all where and how the exceptions were generated
continue; //continue to the beginning of the loop
}
//if we get here then the program is fine and the credit load was read successfully so we leave the loop
break;
}
return result;
}


public static void main(String[] args) {
int TNU = 0; // Total number of units
int TGP = 0; //Total grade point
double TTGP = 0.0; //Total of the TNUs
double TTNU = 0.0; //Total of the TGPs
int numOfCourses = 0; //the number of courses for a semester
String title = null; //title of a course
int creditLoad = 0; //Credit load of a course
char gradeLetter = 'F'; //Grade letter of a course
double CGPA = 0.0; //Cumulative grade point average

int numOfYears = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Welcome, enter the number of years: "wink;
numOfYears = Integer.parseInt(scan.nextLine());
System.out.println();
for (int years = 1; years <= numOfYears; years++) {
//There are usually two semesters each year
for (int semester = 1; semester <= 2; semester++) {
//get the number of courses offered for the semester
System.out.printf("Please enter the number of courses for Semester %d: ", semester);
numOfCourses = Integer.parseInt(scan.nextLine());
//For all courses
for (int course = 0; course < numOfCourses; course++) {
//get the title/code of the course
System.out.print("Please enter the title/code of the course: "wink;
title = scan.nextLine();
//get the credit load/unit of the course
creditLoad = getCreditLoad(scan, title);
//calculate Total number of units and total grade point of the semester
//Convert the grade letter to a point A - 5, B -4 etc
//Add the grade point of this course to the total grade point of this semester
TGP += creditLoad * gradeValue(scan, title);
//Add the credit load of this course to the total number of units of this semester
TNU += creditLoad;
}
}
TTNU += TNU;
TNU = 0;
TTGP += TGP;
TGP = 0;
}
CGPA = TTGP / TTNU;
System.out.printf("Your CGPA is: %.3f%n", CGPA);
}

}


So, today we learnt about exceptions and how to use them to make our programs more robust. Try and practise this on your own. Are there any improvements that can be made?
Try and use exception handling when reading the number of courses and number of years.
Re: Java Tutorial For Beginners by nnasino(m): 11:04am On Dec 01, 2014
Hello, everyone,
Today i'll be introducing classes and objects.
I'll take this slowly so we can get the grasp of it. We will then use them to improve our GPA application.

Classes:
A class is simply a framework for creating objects. A class is a description of something. With this description that 'something' can then be created.
For example, in our above program, we can have a class named
course
. Classes describe objects. The description can include properties and behaviours.
Properties are simply variables that are embedded in the class. For example, a property of a course is the course title, it's credit load and probably the level it is for (300 level, 400 level etc). Behaviours are methods/functions embedded in the class. An example of a behaviour of a class is for instance setGradeLetter(). Now, we can simply set the grade letter for the course by setting the property but then a method is better because with a method we can check the letter that was inputted to see if it is between A to F. We could also set the score after setting the grade within the same function.

So, in a nutshell
- A class is a framework used to group related data which represent an entity together. This framework can then be used to create objects.
- An object can have properties and behaviours which are variables and methods respectively.

To define a class, we use the following syntax:

class ClassName{
int var1;
other variable declarations

int getVar1(){
}
other method declarations
}


For instance, a course class can be declared as follows:

class Course{
int creditLoad; //the number of units of this course
String courseTitle; // course title
int level; // the level for this course e.g MTH 101 is a 100 level course so level = 100;
char gradeLetter; //The grade obtained in the course
int score; //score = gradeValue(5 for A, 4 for B etc) * creditLoad

int setGrade(char grade){
//to be implemented
}

}
Re: Java Tutorial For Beginners by nnasino(m): 12:11pm On Dec 01, 2014
With the class defined, we can now create objects with it. Objects are like variables but they are a bit different. A variable is stores the data it holds whereas an object stores a reference to the data it holds. Don't bother yourself with this for now. To create an object, we create its reference ( a name that will point to it) and then initialize it with an object (the real data).


Course mth101Object; //create the reference
mth101Object = new Course(); //create the object and let the reference point to it



Using Objects
Objects are used with the '.' notation. That is if we have an object
mth101Object
. We can do the following:

mth101Object.creditLoad = 4; //four unit course
mth101Object.courseTitle = "MTH 101";

This way we can use an object just like a variable.

We will now introduce a few more new concepts.
Constructors
Access Specifiers
static
package

Constructors
A constructor is simply a special method that is called when an object is to be created. In the above example, we wrote
new Course()
. The Course() method is the constructor. But we didn't declare any method like that in our class. Java creates a default constructor if we don't define any constructor. Notice that the constructor used above doesn't take any arguments. This is not a must. Like any other method, a constructor can take any number or types of arguments. Now, we will improve our course class code by adding two constructors. The compiler chooses which compiler to call depending on the parameters passed to it. This is called method overloading and will be discussed later on.

Code for defining a constructor:
public NameOfClass(parameters){
//statements
//statements
}


Now, we will create two constructors for the class, one will take no parameters and the other will take 2 parameters, the course title and the credit load of the course.

class Course{
int creditLoad; //the number of units of this course
String courseTitle; // course title
int level; // the level for this course e.g MTH 101 is a 100 level course so level = 100;
char gradeLetter; //The grade obtained in the course
int score; //score = gradeValue(5 for A, 4 for B etc) * creditLoad

public Course(){
//Initialize the variables with default values.
level = 0;
gradeLetter = 'F';
creditLoad = 0;
courseTitle = null;
}
public Course(String courseTitle, int creditLoad){
//Initialize the variables provided
this.courseTitle = courseTitle; //Note the use of the this keyword. this is used to differentiate the courseTitle owned by the object and the one gotten from the function arguments
this.creditLoad = creditLoad;
//Initialize the other variables with default values
this.gradeLetter = 'F';
this.level = 0;
}

int setGrade(char grade){
//to be implemented
}
}



We can therefore create Course objects as follows:


Course course1 = new Course();
course1.courseTitle = "MTH 101";

Course course2 = new Course("MTH 101", 4);

Re: Java Tutorial For Beginners by Nobody: 12:13pm On Dec 01, 2014
I'm very sorry if this is not permitted.. How can I write a java program to compute fractions and display the result exactly( as fraction too) without turning it to decimal or rounding off/up.. Do I need to import any java package??
Re: Java Tutorial For Beginners by nnasino(m): 1:01pm On Dec 01, 2014
Access Specifiers
Access specifiers are used to specify which classes can access resources (variables/methods). There are four access specifiers in java.
public, private, protected and default

default
The specifier we have been using the default specifier (not writing anything before a variable/method). The default specifier means that only other classes from the same package can access the resource. Packages will be explained later on and the default access specifier will be revisited.

private/public
If a resource is specified as private it can only be accessed by members of the same class. If a resource/member is specified as public then it can be accessed by all classes.
In our class code:

class Course{
//It is standard code practice to make your instance variables (variables belonging to an object) private
//You can create getter and setter methods that will be used to get and set the value of the variable
private int creditLoad; //the number of units of this course
private String courseTitle; // course title
private int level; // the level for this course e.g MTH 101 is a 100 level course so level = 100;
private char gradeLetter; //The grade obtained in the course
private int score; //score = gradeValue(5 for A, 4 for B etc) * creditLoad

//example getter and setter methods
public int getCreditLoad(){
return creditLoad;
}
public void setCreditLoad(int creditLoad){
//this is a pro of using setters, you can check some constraints and the integrity of the data
if(creditLoad < 0)
throw new Exception("Credit load can not be negative"wink;
if(creditLoad > 20)
throw new Exception("Credit load can not be more than 20"wink;
this.creditLoad = creditLoad;
}

//Constructors are usually public because they are called from other classes
public Course(){

//Initialize the variables with default values.
level = 0;
gradeLetter = 'F';
creditLoad = 0;
courseTitle = null;
}
public Course(String courseTitle, int creditLoad){
//Initialize the variables provided
this.courseTitle = courseTitle; //Note the use of the this keyword. this is used to differentiate the courseTitle owned by the object and the one gotten from the function arguments
this.creditLoad = creditLoad;
//Initialize the other variables with default values
this.gradeLetter = 'F';
this.level = 0;
}

int setGrade(char grade){
//to be implemented
}
}


With the above code, then
mth101Object.creditLoad;
will fail, now we have to use the public method
mth101.object.getCreditLoad()
. We will discuss protected much later, but you can read it up if curious.


static
The static keyword is used to specify that a member belongs to a class and not an object. For example, in our above code, we have no static variable. This is because all the members we have defined all belong to objects. The course framework can not have a course title, only a tangible object (a real course) can have a course title and a course credit load. You can think of static members as members that each object doesn't have its own unique copy. A member that has a single copy for all objects created i.e a member that belongs to the class.

In the Course class, let us think and come up with a static variable. A variable that can belong to the Course class only. I've got it. We usually check the credit load that passed into the setCreditLoad method to see if it is greater than 20. We hard coded this value 20 into our code. This isn't good practice, instead we can create a variable MAXIMUM_CREDITLOAD. But this information is more to the framework (class) than to individual objects (it's the same value and storing it in each object will be a waste of space). So, we use the static keyword to attach it to the class and not to the objects that are created.

class Course{
//Only one copy of this variable will be created. it can be accessed using the classname. Course.MAXIMUM_CREDITlOAD
private static int MAXIMUM_CREDITLOAD = 20;
//It is standard code practice to make your instance variables (variables belonging to an object) private
//You can create getter and setter methods that will be used to get and set the value of the variable
private int creditLoad; //the number of units of this course
private String courseTitle; // course title
private int level; // the level for this course e.g MTH 101 is a 100 level course so level = 100;
private char gradeLetter; //The grade obtained in the course
private int score; //score = gradeValue(5 for A, 4 for B etc) * creditLoad

//example getter and setter methods
public int getCreditLoad(){
return creditLoad;
}
public void setCreditLoad(int creditLoad){
//this is a pro of using setters, you can check some constraints and the integrity of the data
if(creditLoad < 0)
throw new Exception("Credit load can not be negative"wink;
if(creditLoad > MAXIMUM_CREDITLOAD) //within the class, we don't need to put the class name
throw new Exception("Credit load can not be more than 20"wink;
this.creditLoad = creditLoad;
}

//Constructors are usually public because they are called from other classes
public Course(){

//Initialize the variables with default values.
level = 0;
gradeLetter = 'F';
creditLoad = 0;
courseTitle = null;
}
public Course(String courseTitle, int creditLoad){
//Initialize the variables provided
this.courseTitle = courseTitle; //Note the use of the this keyword. this is used to differentiate the courseTitle owned by the object and the one gotten from the function arguments
this.creditLoad = creditLoad;
//Initialize the other variables with default values
this.gradeLetter = 'F';
this.level = 0;
}

int setGrade(char grade){
//to be implemented
}
}


package
In java, a package is simply a way of grouping similar classes together. The package of a file specified on the first line of the file using the syntax
package nameOfPackage;
. All classes declared within that file will belong to that package. Packages are synonymous with folder names. An example of the usefulness of packages is when creating a desktop application. For instance, this our GPA program; say we want to create a GUI for it, we can put the GUI in a package named gui, and for our classes which form the core of the application we can put them in a package named core. If we don't specify a package name in a file, the classes in that file will be added to the default package.

Now, we understand packages we can now revisit the default access specifier: say we have project structured like this:
GPAgui
----core
--------Course
------------int creditLoad;
------------private String courseTitle;
--------Student
------------private int numberOfCourses;
------------public int studentName;
----gui
--------MainWindow
------------.....////.
------------../gui stuff////

From the above:
default:
creditLoad
is default therefore
members within course can access it, Student can also access it since they are both in the core package but MainWindow can not access it.
public: studentName is public therefore
MainWindow, Course and Student can access it
private: courseTitle
Only members of Course can access courseTitle


That's all for today, try and digest the message for today. Tomorrow, we will use the knowledge we have acquired to make our program better.
Cheers,
Re: Java Tutorial For Beginners by nnasino(m): 2:09pm On Dec 01, 2014
choose4me:
I'm very sorry if this is not permitted.. How can I write a java program to compute fractions and display the result exactly( as fraction too) without turning it to decimal or rounding off/up.. Do I need to import any java package??
It's alright as long as you learn.
You can achieve this using apache's fraction class. visit http://commons.apache.org/math/userguide/fraction.html.
Re: Java Tutorial For Beginners by Nobody: 5:03pm On Dec 01, 2014
keep up the good work bro.....

1 Like

Re: Java Tutorial For Beginners by talk2chichi: 4:05pm On Dec 03, 2014
Hello Lecturer, please am new in programming, I use java but I don't know if you also know how to use oracle 10g, I will really need your help in both. Thanks
Re: Java Tutorial For Beginners by nnasino(m): 9:38am On Dec 04, 2014
talk2chichi:
Hello Lecturer, please am new in programming, I use java but I don't know if you also know how to use oracle 10g, I will really need your help in both. Thanks
Well, i use oracle 11g but it's just basic stuff, no pl/sql.
Re: Java Tutorial For Beginners by Shuayb0(m): 1:55pm On Dec 06, 2014
You re doing a very good job man, keep up the good work.

1 Like

Re: Java Tutorial For Beginners by talk2chichi: 9:35pm On Dec 08, 2014
nnasino:

Well, i use oracle 11g but it's just basic stuff, no pl/sql.
ok thanks for your tutorials. May God Almighty continue to give you wisdom, knowledge and understanding. Amen

1 Like

Re: Java Tutorial For Beginners by nnasino(m): 2:39pm On Dec 09, 2014
Hi everyone, a good day to you all. Sorry i've been quite busy.
We will continue the tutorial today with more on objects and classes. We will improve on our program by using the concepts we have learned so properly. We learnt about classes and objects last time but today we will use them in our current program. I will also introduce the concept of an array today.

Looking at our program closely we will need about three classes to properly organize the program:
A Student class, a Semester and a Course class. The student class will contain information such as the name of the student the number of years the student wants to calculate, the CGPA of the student and the semesters of the student. The semester class will contain courses (yes, objects can contain other objects), the TNU (total number of units offered), TGP (total grade point) and the GPA of the semester. With these three classes we can restructure our program better.

But first, let us introduce the concept of the array. An array is simply a collection of variables. Yes, that simple it is simply a collection of variables. For example, in our program, each semester has a collection of courses. So we say each semester has an array of courses.
Note: there are many other ways of organizing collections of data but we use the array as it is simple and basic.

Array syntax:
to declare an array we write:

type[] arrayname;


Now, to initialize an array is a bit different. We use the new keyword and square brackets as follows:

arrayname = new int[size];


For example, to create an array of Courses that will contain 10 courses:

Course[] courseList = new Course[10];


After creating the array, we can access its elements by using the [] brackets. EAch element has an index. An array that is of size 10 has indices from 0 to 9. Counting in computers starts from zero so it will end at nine (Notice: nairaland pages start from zero wink). So to access the first element we use
courseList[0]
. To access the 10th character we use
courseList[9]
. If you try to access an element that doesn't exist for instance
courseList[10]
an exception will be thrown. Finally, to know the size of an array we can get that from the array as follows:
 arrayname.length;
courseList.length;


With this info, we can write out the design of our program:


Student
--nameOfStudent
--CGPA
--TTNU
--TTGP
--noOfYears
--Semesters[] -- array of semesters
Semester
--noOfCourses;
--TNU
--TGP
--GPA
--Courses[] --array of courses
Course
--courseCode
--creditLoad
--gradeLetter
--score


In this our project, we will be creating this app like a real life app using packages.
Open up your netbeans ide. Click new project and select java application:

Make sure create main class is ticked.

Name your project GPA app and finish. Create three classes Course.java, Semester.java and Student.java. While creating these classes set their package to
core
. Now, in each file, create the variables for each class. Remember to keep all of them private. Now, netbeans can help us with the getter and setter methods as well as constructors. Press the shortcut key alt-shift-s (or right click within the editor and click insert code), select getter and setter, then select all your variables and click generate. Do this for all the files. Press the shortcut key alt-shift-s and click constructor, then select the following for the classes as follows:

Course:
courseCode
creditLoad

Student:
nameOfStudent
noOfYears

Semester:
noOfCourses



After clicking the generate button, we will edit the constructors and some of the setters to our own taste.
We edit the Student constructor as follows:

public Student(String nameOfStudent, int noOfYears) {
this.nameOfStudent = nameOfStudent;
this.noOfYears = noOfYears;
//initialize the semester list
semesters = new Semester[noOfYears];

}


We edit the Semester constructor as follows:

public Semester(int noOfCourses) {
this.noOfCourses = noOfCourses;
courses = new Course[noOfCourses];
}


Now, create getters and setters for all the variables in the Course class.


For the getters and setters:
We edit the setter setGradeLetter(char gradeLetter) as follows:

public void setGradeLetter(char gradeLetter) throws Exception {
switch (gradeLetter) {
case 'a':
case 'A':
this.gradeLetter = 'A';
this.score = 5 * creditLoad;
case 'b':
case 'B':
this.gradeLetter = 'B';
this.score = 4 * creditLoad;
case 'c':
case 'C':
this.gradeLetter = 'C';
this.score = 3 * creditLoad;
case 'd':
case 'D':
this.gradeLetter = 'D';
this.score = 2 * creditLoad;
case 'e':
case 'E':
this.gradeLetter = 'E';
this.score = 1 * creditLoad;
case 'f':
case 'F':
this.gradeLetter = 'F';
this.score = 0;
default:
throw new Exception("Please enter a grade letter from A to F"wink;
}
}


We edit the setter for credit load as follows:

public void setCreditLoad(int creditLoad) throws Exception{
if (creditLoad <= 20 && creditLoad >= 0) {
this.creditLoad = creditLoad;
}
throw new Exception("Please enter credit load greater than 0 and less than 20"wink;
}
Re: Java Tutorial For Beginners by asalimpo(m): 11:35pm On Dec 09, 2014
Y not change d grade letters to a particular case to reduce checking for different cases in the switch statemnt.
Re: Java Tutorial For Beginners by nnasino(m): 1:10pm On Dec 10, 2014
asalimpo:
Y not change d grade letters to a particular case to reduce checking for different cases in the switch statemnt.

Like this right,
Character.toUpperCase(gradeLetter);

Yes, you're right but I haven't taught how to use the java standard library and i am still explaining classes and objects so i don't think we have learnt enough to use that at this point.
Re: Java Tutorial For Beginners by WINDSOW(m): 7:00pm On Dec 10, 2014
@OP,being a programmer working in a firm,Do u jst write open codes like tis or u relate the codes with GUI.
Eg:VB.net for instance,u relate the program codes with textbox,label,button,RadioButton etc

(2). What kind of task do programmers execute saying working in an IT firm.
Eg; like programs to ...

Pls help my curiosity
Re: Java Tutorial For Beginners by nnasino(m): 8:54am On Dec 11, 2014
WINDSOW:
@OP,being a programmer working in a firm,Do u jst write open codes like tis or u relate the codes with GUI.
Eg:VB.net for instance,u relate the program codes with textbox,label,button,RadioButton etc

(2). What kind of task do programmers execute saying working in an IT firm.
Eg; like programs to ...

Pls help my curiosity
. 1. Most of the time programs are related to a gui, either a native gui or web ui. In this tutorial, we will get to the gui part and make this a full application but you can't understand guis without understanding classes, objects, loops and the rest. 2. It depends on what your company does. Like for example we use the play framework(java and scala) to build enterprise web and mobile applications for financial institutions. We decided to make it a SaaS (software as a service) application. In conclusion, do not underestimate the relevance of command. Line applications. For anything, it is useful for logging and unit testing.
Re: Java Tutorial For Beginners by WINDSOW(m): 10:26am On Dec 11, 2014
nnasino:
. 1. Most of the time programs are related to a gui, either a native gui or web ui. In this tutorial, we will get to the gui part and make this a full application but you can't understand guis without understanding classes, objects, loops and the rest. 2. It depends on what your company does. Like for example we use the play framework(java and scala) to build enterprise web and mobile applications for financial institutions. We decided to make it a SaaS (software as a service) application. In conclusion, do not underestimate the relevance of command. Line applications. For anything, it is useful for logging and unit testing.
Thanks bro,@least I nw have a sense of direction.Thank U so much.Cheers!!!

1 Like

Re: Java Tutorial For Beginners by dejt4u(m): 9:50pm On Dec 13, 2014
Following
Re: Java Tutorial For Beginners by Misogynist2014(m): 9:59pm On Dec 13, 2014
Leaving a sentence behind to show that I was here.
Re: Java Tutorial For Beginners by haibe(m): 10:15pm On Dec 13, 2014
coincidentally am learning Java. Following thread

1 Like

Re: Java Tutorial For Beginners by Nobody: 10:25pm On Dec 13, 2014
Nice one mehn.

1 Like

Re: Java Tutorial For Beginners by Tex42(m): 10:27pm On Dec 13, 2014
will join in two months time when i buy my pc.


weldon op!

1 Like

Re: Java Tutorial For Beginners by DonaldGenes(m): 10:33pm On Dec 13, 2014
Op, drop your BBM pin

Fortunately, I am learning Java but have gone far.
I have Created some Program using NetBeans
Re: Java Tutorial For Beginners by god2good: 11:07pm On Dec 13, 2014
For people who doesn't ve computer but ve Android smart phone can download an apps called ”AIDE” from Google play to do it

1 Like

Re: Java Tutorial For Beginners by Dizney(m): 11:34pm On Dec 13, 2014
proud to be a nacossite
i rep FUTA

1 Like

Re: Java Tutorial For Beginners by franconian: 11:37pm On Dec 13, 2014
^^^The two guys above are weird!


@OP, following....
Re: Java Tutorial For Beginners by 2smart9ja: 8:13am On Dec 14, 2014
nnasino:
Hi, everyone. I was inspired by my friend and oga ezechinwa to start this thread. I will be teaching java to beginners in the house. I am not an expert but i think some knowledge can be shared.

Tools needed are jdk (java development kit), netbeans IDE and a good computer.

For jdk visit http://www.oracle.com/technetwork/java/javase/downloads/index.html
Note: please install jdk separately, do not download the jdk + netbeans bundle

For netbeans visit https://netbeans.org/downloads/


For a good computer, well visit computer village or jumia.com or if you already have one move on.

Once, you have these installed, launch netbeans. Create a new project by clicking File Menu > New Project. Set up the required information and click finish. Once you have a new project you can then run the file you are working on by using the shortcut Shift+f6.
You are now set and ready to take your first step as a java programmer.

I will encourage you to persevere, that programming is fun, stimulative to the brain, and is rewarding. The important thing is not how much or how fast you learn but how long you can keep your attention to it. With time, you will forget the beginning days.

Finally, before we start off, i will recommend that as a programmer you learn how to type. Yes, i mean it, learn how to type without looking at the keyboard. This will help you tremendously. Visit keybr.com for an online typing tool. If you can get yours hands on mavis beacon teaches typing that will also be fine and if you are from the linux world ktouch or klavaro will do.

Thanks, and welcome aboard to the tutorial.
Pls where can go to download the Mavis beacon cause I don't have money to always be online
Re: Java Tutorial For Beginners by haibe(m): 8:21am On Dec 14, 2014
I would recommend eclipse software also for we beginners

1 Like

(1) (2) (3) (4) (5) (Reply)

Programmers: At What Age Did You Start Programming? / I Want To Learn Computer Programming, What Language Should I Learn First? / Community Project(strictly Java)

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 204
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.