Stats: 3,183,639 members, 7,921,387 topics. Date: Thursday, 15 August 2024 at 01:08 AM |
Nairaland Forum / Science/Technology / Programming / Java Tutorial For Beginners (24027 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) 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(;, 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:
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:
One more thing before we conclude: [b]break, continue and labels[\b] A breakexits the loop it is contained in. A continueskips 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
In the snippet above, the condition for the loop is truetherefore 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 breakkeyword. 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:
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:
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:
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:
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
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 Scannerclass 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 Scannerclass'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:
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:
|
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:
- 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.
- for all the years From the statement we can deduce that we will use a for loop for this.
- for all the semesters Note that this is within the years for loop
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
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 switchstatement.
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 yearsfor loop
- CGPA = Total TGP / Total TNU - Display the CGPA to the user
Combining the code together we have:
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. ![]() |
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:
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...catchblock as follows:
Now, looking at our code we can see at this point, we need some exception handling:
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...catchblock 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:
If we now replace the previous line with our function we get a better more robust program:
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.
This is the full code:
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:
For instance, a course class can be declared as follows:
|
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).
Using Objects Objects are used with the '.' notation. That is if we have an object mth101Object. We can do the following:
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){ 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.
We can therefore create Course objects as follows:
|
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:
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.
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: creditLoadis 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: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: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: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:
Now, to initialize an array is a bit different. We use the new keyword and square brackets as follows:
For example, to create an array of Courses that will contain 10 courses:
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 ![]() 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; With this info, we can write out the design of our program:
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:
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:
We edit the Semester constructor as follows:
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:
We edit the setter for credit load as follows:
|
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: 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:. 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: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: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 |
My New Excel Dashboard / What Programming Language Is Used In Creating Viruses? / Where Is The Best Place To Learn Programming Or Artificial Intelligence?
(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. 188 |