Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / NewStats: 3,207,640 members, 7,999,808 topics. Date: Monday, 11 November 2024 at 01:49 PM |
Nairaland Forum / Mimohmi's Profile / Mimohmi's Posts
(1) (2) (3) (4) (5) (6) (of 6 pages)
Programming / Re: Learning Java Without Tears by mimohmi(m): 11:17pm On Aug 22, 2006 |
No big deal, you can just use this as an additional resource. |
Programming / Re: Learning Java Without Tears by mimohmi(m): 11:36pm On Aug 19, 2006 |
Final note on variables. Remember from the last note, I listed the various data types and played with numerical data types by getting the minimium and maximum values, we also talked about char for single letters. So let me just run through different way of declaring variables in Java. Numeric Variables: We can define numeric types using number system like decimal(default), Octal and Hexadecimal. Let just quickly show that. //The program demonstrates how to declare and use Java Data type public class VariablePlay2 { public static void main(String [] args){ //Using decimal int decimal = 1000; //using octal. add 0 as prefix int octal = 01000; //using hexadecimal. add 0x as prefix, values are not case sensitive int hexa = 0XADC; //show that hexadecimal values are not case sensitive int hexa2 = 0xadc; //Here, just want to print out the values, notice "" and +, just saying append one value to the // end of the other, without it, we will just get the sum of the numbers System.out.println("decimal value is "+decimal + " "+", octal value is "+ octal + " "+", hexa value is " + hexa + " "+", hexa2 value is "+ hexa2); } } Result: decimal value is 1000 , octal value is 512 , hexa value is 2780 , hexa2 value is 2780 So we can see that it is easy to use other number systems in Java, just follow the rules. Let's look at other rules. Character: To define a character in java, simple use char data type. Note you can assign only single letters and numbers within the rquired range as demostrated earlier. It must be placed within a single quote.Also, you can assign unicode values to a char variable but must begin with \u as prefix. Let me do some demo. //The program demostrates how to declare and use char Data type public class VariablePlay3 { public static void main(String [] args){ //declare variable of char char singleLetter = 'z'; //using Unicode values char Unicode = '\u004E'; //unicode value for letter E //using decimal char decimal = 234; //using hexadecimal char hexa = 0x892; //Here, just want to print out the values, notice "" and +, just saying append one value to the // end of the other, without it, we will just get the sum of the numbers System.out.println("Single Letter value is "+singleLetter + " "+", Unicode value is "+ unicode + " "+", decimal value is " + decimal + " "+", hexa value is "+ hexa); } } Result: Single Letter value is z , Unicode value is N , decimal value is O , hexa value is ? Let's look at floating numbers, by default all floating numbers are double, just the way all integers are treated as int. So, to specify a double variable a letter D or d is used as a postfix while for float letter F or f is used to indicate that the variable is of type float. The following demo will show how. //The program demonstrates how to declare and use Java Data type public class VariablePlay4{ public static void main(String [] args){ //declare variable of float float balance = 1000.90f; //try removing the f, compiler scretches possible loss of precision //you will be trying to put a squize an elephant in to an ant hole. //declare a variable of double double pay = 30003000.455; // notice here, no d or D is specified, compiler allows it // because double is the default type for floating point numbers //using postfix d for double double change = 456.234d; // the compiler will just thank you for specifically tell her what to do. // sorry, it a compiler he or she ? //using postfix f float fare = 38989.858f; //compiler will always force you to append f to your float declaration. //Here, just want to print out the values, notice "" and +, just saying append one value to the // end of the other, without it, we will just get the sum of the numbers System.out.println("balance value is "+balance + " "+", pay value is "+ pay + " "+", change value is " + change + " "+", fare value is "+ fare); } } Result: balance value is 1000.9 , pay value is 3.0003000455E7 , change value is 456.234 , fare value is 38989.86 So, on a final lap, let's look at other issues on data type. Remember i said int is the default value for none floating point numbers, but we have a long data type, so how do we declare it. It's simple, just append a letter L or l to it as a postfix. Also note that Java is very sensitive with data types, once you declare a variable as a specific data type, the compiler ensures it is used within that data type context except for few occassions, which i am going to demostrate.Before the demo let's look at a case study. Assuming you declare a variable of type byte and assign say 100 to it, if withing the program you added it to another number of any data type, the compiler automatically promotes the result to type int. So the gist is this, when you add two numbers of any type, you get an int as a result. So, how do get the required type back, we have to explicitely tell the compiler, hey i want my answer to be of this type by casting. If you have never heard of the word casting, not too much about it, it a process of telling the compiler that you know what you are doing and ready to help responsible for any loss of precision. //The program demostrates how to cast Java Data type public class VariablePlay5{ public static void main(String [] args){ //declare variable of byte byte number1 = 1; //declare a variable of short byte number2 = 50; /**declare a variable to hold the sum this line will not pass the compiler because the result will automatically promoted to int which is bigger than a byte */ //byte sum = number1 + number2; /*To correct the line above, we have to explicitly cast it. will this line make it pass the compiler ? The answer is no, we are only casting number1 and not the result. */ //byte sum = (byte) number1 + number2; // OK, will this one make pass the compiler, let watch and see. byte sum = (byte)(number1 + number2); //Here, because we are just outputting the result and not assigning it to any variable //it works. Here I have do some tricks to add my number1 and number2 within the println method System.out.print("The value of sum of number1 and number2 is " System.out.println(number1 + number2); //ok, let's output our wahala sum System.out.println("The value of sum after casting is = "+ sum); } } Result: The value of sum of number1 and number2 is 51 The value of sum after casting is = 51 So, when do we need to cast data types ? of course, when assigning larger data types to smaller types. From small to large is done for us by the compiler. Let's look at the other types. We might have some cases, where we want make a logical decision if certain conditions are true or false. Ok, let see such in the next code. //The program demonstrates how to declare and use Java Data type public class VariablePlay6{ public static void main(String [] args){ //Declare a long data type and set the value to 10000 //appending L is not mandatory but it is always good to do so. // Some could easily tell from looking at your code long number = 10000L; //Declare an int data type and set the value to 1000 int number2 = 1000; /*Declare a boolean data type and set the value to false. Try changing the value to true and run it again to see the result */ Remember, it can only have a value of true or false boolean isGreater = false; if (isGreater) { int add = (int)(number + number2); System.out.println("The sum is = " +add); } int sub = (int)(number - number2); System.out.println("The value of sub after test is = "+ sub); System.out.println("The test failed "+ isGreater); } } Result : The value of sub after test is = 9000 The test failed false Some people might have been worried as how do I declare a variable to hold say names and other things that hasn't been covered. OK, i will just demostrate that now. In Java, there is a class called String. String is handled in a very flexible way in Java. They are not among the primitive data types, but object types or what is called reference variables. They also treated specially, we find ourselves making alot of use of this type as i am going to demostrate in the next demo. Sorry before the demo, string variables are declared by puting the variable value within a double quote. //The program demostrates how use String in Java public class VariablePlay7{ public static void main(String [] args){ //Creating a String Reference variable by instantiating the String Class // and passing the value to it construstor String firstName = new String("Musa" //creating s a string by just initializing it with a value String surname = "Muhammad"; //create an int to hold say age int age = 50; // create an int to a number int number = 12; //notice the + sign. It is used to join string objects //ie add more string together. System.out.println(firstName + surname); //let add space between firstname and surname System.out.println(firstName + " " + surname); //let add age to number System.out.println(age + number); //let's print all the variables //watch this output closely //Everything was just appended to each other, if the first argument to the print method is a string //everything will just be treated as string System.out.println(firstName + surname + age + number); //Let print a nice looking output System.out.println(firstName + " "+surname + " "+ "is "+age + " years old and his lucky number is "+ number); } } Result: MusaMohammed Musa Muhammad 62 MusaMohammed5012 Musa Muhammad is 50 years old and his lucky number is 12 Using String could be very tricky in java, because you will need to understand how they are created and manipulated. For example , if we create String objects say to represent Dog and Cat. If we add the two, a third string will be created to hold the value while the original strings are still hanging in memory and holding their references.But when you change the reference, the value still exit in memory and we can not access them due to lack of reference,that's why we have to be very careful when using string because one might end up creating alot unreferenced string object which will just be occupying a chunk of memory. |
Programming / Re: Looking For People Interested In Exploring JavaEE 5 And EJB 3.0 by mimohmi(m): 1:28am On Aug 18, 2006 |
Hi sbucareer, Sorry for the break. I have been out for a while now. To your question. Personally, and from other sources, when developing a Java EE application, there are more things to be considered when it comes to persistant. With the facade pattern the business logic is often place in both the session and entity beans. Come to look at it, it is often advisable to put all business related logic that has to do with persistant entity in entity bean class, why ? It enable us to take the advantage of the container services like transaction and co. If we are going to use a CMP (Most times) we need to expose it's local interface to the session bean. Next is what type of session bean, come to think of it, since it is a banking app, there is the need to maintain a conversational state as per client as this can easily be propergated across multiple method call, thus making security and transaction handling easy. So, what the facade class will normally do is just to handle the app workflow. Like call the stateful session bean methods , the session bean calls the entity bean to supply the required data. Making a decision whether to expose local or remote interface of the bean require a lot of trade off like, location, parameter call ie either call by value or by reference, network and scalability. I will go for all local interfaces for both bean and let the facade handle the work flow. So all the client will ever call is my facade class. Hope it help. I will send you a book on design patterns for EJB. |
Programming / Re: Learning Java Without Tears by mimohmi(m): 11:51pm On Aug 17, 2006 |
So let take more look at variable. In Java we have basically two types of variable reference ie Object Reference (ie a reference to a class object) and Primitive reference, which we look at yesterday. Hope, thing are not getting bored. Let's also talk about a typical class structure.I will show it now. class ClassName { // Every class must have a name and defined using the class keyword // The can also have other modifier like public etc that shows // how we intend to expose our class to other applications or classes // either wihin our project or the outside world. // Naming Rules // 1.Must start with a letter, underscore( _ ) or dollar sign ( $ ). // 2.Can only use number after the first Letter. // 3 Must not be Java Keywords, keywords are used by the compiler so // the are special words. // classes can contain class variable datatype variableName; // if you don't want the default values for class variables, you specified a you // own default value. // Remember, they can either be primitive or object reference variables. datatype variableName = initialisationValue; // classes can have multiple constructors, this a place to initialiase class // variables public ClassName() { // Constructor are just special methods // Ther are used to create object instances // Naming rule --> must be same name with the class name and can have diff // access modifier // This is called default constructor because they don't take any argument // If we don't specify ANY constructor, the compiler will alway be kind to // inject one for you. // let me just show how a class with multiple constructor look like. public ClassName(int anumber){ // this one takes a number an argument // to invoke it you must pass an int to it eg ClassName cname = new // ClassName(0); will explain this later } // The next thing in a class are methods modifier returnType methodName(dataType argument) { return returnType; // Arguments reurned must be same with the // returnType dataType; } public int addTwoNumber(int number1, number2){ // Methods contains actions you want to perform on the variables // Here we want to add two numbers number1 and number2 // Naming convection same as class // Must have return type - must return a result // Like here, we are returning an integer (int) return number1 + number2; } // Every Executable Java Class must have a main method // Notice the the structure, any attempt to change it, the code will compile but // will not run // because the JVM, looks for this method to run your application. public static void main(String [] args){ // It must take an arrray of String as argument, must be public, static and void // return type // Here we can start our program // Instantiante the class (create an object of the class) ClassName cname = new ClassName(); // the new keyword is used to create a new object of a class // Here we created an instance of a class using the default // constructor ClassName dname = new Classname(20); // Create another object of ClassName, Using // the ClassName(int) constructor // we can now call our methods cname.mehodName(); cname.addtwoNumber(20,30); // using dname instance dname.mehodName(); dname.addtwoNumber(20,30); } // end of main method }// end the class defination So, this is a complete description of a class structure. In all of our lives as programmers. this is all we are ever going to be writing. The difference now is understanding the logic and putting it into this structure, infact this is a class template. I hope to finish the variable trail by next post, so that we can move to methods. |
Programming / Re: Learning Java Without Tears by mimohmi(m): 11:41pm On Aug 17, 2006 |
Sorry just want to cover up for the lost time, so here is my solution to the home work I will be looking forward to other solution. Yours might just be better than mine. // Solution to the home work // if you haven't tried it, please do //Notice no public in class decreation // more on that later class MinMax { /** *Am not going to declare any class (Instance variable) *because they all aready have values. *Take a look at the API, Notice *each of these primitive types have a class *and some static field. Static fields are Class *variables that it shared among mulitiple class instances. * I will demostrate that in the next code **/ //static byte byteMin = Byte.MIN_VALUE; public static void main(String []args){ /** *So just going to output the minimiun and maximium *values of all the primitive data types. *Notice I just use the class dot the value fields. * static fields for you **/ System.out.println("Minimium value of byte is "+ Byte.MIN_VALUE); System.out.println("Maximinm value of byte is "+ Byte.MAX_VALUE); System.out.println("Minimium value of short is "+ Short.MIN_VALUE); System.out.println("Minimium value of short is "+ Short.MAX_VALUE); System.out.println("Minimium value of int is "+ Integer.MIN_VALUE); System.out.println("Maximinm value of int is "+ Integer.MAX_VALUE); System.out.println("Minimium value of long is "+ Long.MIN_VALUE); System.out.println("Maximinm value of long is "+ Long.MAX_VALUE); System.out.println("Minimium value of double is "+ Double.MIN_VALUE); System.out.println("Maximinm value of double is "+ Double.MAX_VALUE); System.out.println("Minimium value of float is "+ Float.MIN_VALUE); System.out.println("Maximinm value of float is "+ Float.MAX_VALUE); //Here we need to do some extra work to get the min and max value System.out.println("Minimium value of char is "+ Character.MIN_VALUE); // prints blank System.out.println("Maximinm value of char is "+ Character.MAX_VALUE); // prints ? System.out.println(); System.out.println("About to do the tricks of getting the minimium and maximium values of char" /** * To print the minimiun and maximium values of char can be quite tricky *Remember char is just init under the hood. *We got the value ----> Character.MIN_VALUE *Passed the value to the Character.valueOf(Character.MIN_VALUE) *Change th result to interger (int)Character.valueOf(Character.MIN_VALUE) **/ System.out.println("Minimium value of char is "+ (int)Character.valueOf(Character.MIN_VALUE)); System.out.println("Maximium value of char is "+ (int)Character.valueOf(Character.MAX_VALUE)); } } Result Minimium value of byte is -128 Maximinm value of byte is 127 Minimium value of short is -32768 Minimium value of short is 32767 Minimium value of int is -2147483648 Maximinm value of int is 2147483647 Minimium value of long is -9223372036854775808 Maximinm value of long is 9223372036854775807 Minimium value of double is 4.9E-324 Maximinm value of double is 1.7976931348623157E308 Minimium value of float is 1.4E-45 Maximinm value of float is 3.4028235E38 Minimium value of char is Maximinm value of char is ? About to do the tricks of getting the minimium and maximium values of char Minimium value of char is 0 Maximium value of char is 65535 |
Programming / Re: Learning Java Without Tears by mimohmi(m): 2:27am On Aug 17, 2006 |
Hi, i think i need to get this classpath of a thing clear for windows users with this post. Ok, right click on my computer and click properties from the drop down menu items. I have tried to number the steps. I used my own computer path, yours might be different, all the same it must point to the Java SE location on your computer. I hope this will help.
|
Programming / Re: Learning Java Without Tears by mimohmi(m): 12:56am On Aug 17, 2006 |
Hello to all. First my apology to all for the long break, but thanks to skima, who gave me a call that my fans are growing. So I promised him to continue. While out. i have been laying my hands on new features of Java. From IDEs to some fantastic libraries. So today i am going to look at a fundamental aspect of programming VARIABLES. Everything we ever do in any programming hangs around data. Variables are just place holders , say we want to represent say name of employee, we must first declare a variable to hold that name, from there we are free to manipulate it in any way within the same program or from other programs. Like any other programming language, Java has it's owm ways of handling the different type of data. What is very important to us, is knowing the types and how they are being handled as this will enable us to chose the right type of variables to represent our data. Let me quickly list the data types we have in Java. 1. Byte (byte) -----> 8 bits Range --------> -128 to 127 2. Short (short) ------>16 bits --------> -32768 to 32767 3. Integer (int) -------->32 bits --------> -2147483648 to 2147483647 4. Long (long) ---------->64 bits --------> -9223372036854775808 to 9223372036854775808 5. Double (double) ------->32 bits -------> this is floating points (Home work, find float min and max values) 6. Float (float) ------->64 bits -------> do same for this 7. Boolean (boolean) ----> represent True or False 8. Character (char) -----> used to represent single characters. (basically int under the hood) --> range 0 to 65535. These are the basic data types we have in Java, they are called PRIMITIVE Data type and each have it's own range as shown above and default values as we will see later. Why must we know the range ? Please post your answers here. Ok, let's play with these data types. // This application is to show the default values of Java primitive data types public class VariablePlay { /** By coding standard, variable names must start with small letter. You must also know that the name of primitive data types are keywords in Java, as such you can use them to to declare your own variable, method or class names. **/ // Here am just going to declare them, without initialisation // the compiler will do that for me. // The law say you can do this only for class variable // more on that later // things on the left are the data types and right the variable names byte myByte; short myShort; int myInteger; long myLong; double myDouble; float myFloat; char character; //Here let's add a char and initialise it char initChar = 100; boolean myBoolean; /** Let me just add a constructor, but if I don't add, the compiler will do it for \ me. If you don't declare one, the compiler adds a default constructor for you. more on that later.Note same name with the class name and no return type **/ public VariablePlay() { //Let output something here to show when this constructor is called System.out.println("I am VariablePlay Constructor , never mind" } //This our main method, entry method for our program public static void main(String []args){ // Am just going to instantiate my class(make an object of the class and call it vp) VariablePlay vp = new VariablePlay(); //use the object created ie vp to print out the default values System.out.println("Default Value For byte = " + vp.myByte); System.out.println("Default Value For short = " + vp.myShort); System.out.println("Default Value For Interger = " + vp.myInteger); System.out.println("Default Value For long = " + vp.myLong); System.out.println("Default Value For double = " + vp.myDouble); System.out.println("Default Value For float = " + vp.myFloat); System.out.println("Default Value For char = " + vp.character); System.out.println("Default Value For char = " + vp.initChar); System.out.println("Default Value For boolean = " + vp.myBoolean); } } Result : I am VariablePlay Constructor , never mind Default Value For byte = 0 Default Value For short = 0 Default Value For Interger = 0 Default Value For long = 0 Default Value For double = 0.0 Default Value For float = 0.0 Default Value For char = Default Value For char = d Default Value For boolean = false Note: 1. the first four have default values of 0. All of these are basically int 2. The two output for char has nothing and d. char is unsigned (Can only be positive number) 3. boolean has false, used to test conditions 4. Float and double represent floating point number ie decimal 5. All numeric data type are signed in Java(ie can hold positive or negative values) except char. For the Home work, take a look at the Java API Specification, each of these data type have a class use them to get the maximium and minimium values of each. Just try, no matter you answer post it. |
Programming / Re: Java Resource CD For Nairaland by mimohmi(m): 2:17am On Apr 24, 2006 |
Hi Immortalme, Just a fleek of time. I was in Benin for the easter with my laptop. Never mind please give me a call, so that we can fix how to get the CDs across to you. Hope to hear from you soonest. My regards to your Oba. |
Programming / Re: Java Resource CD For Nairaland by mimohmi(m): 11:14pm On Apr 10, 2006 |
Please feel free to call me. So that we fix a meeting place and time. That simple. |
Autos / Make Cool Money From Car Hiring Services by mimohmi(m): 12:02am On Apr 10, 2006 |
Just started a car hiring business, does anybody know of companies that hire cars ? You get a cut on each car hired by your contacts. The cars are brand new Peugeot 206 and 307. If interested please call 01 8972759. Commision is negotiable. |
Programming / Re: Java Resource CD For Nairaland by mimohmi(m): 11:24pm On Apr 09, 2006 |
Hey Skima, you making me feel like a small don, never thanks for your comments what are friends for ? Well just to take the stress of sbucareer, guys, please feel free to call me. I am in Lagos. All you need to do is get 3 blank CDs, give me a call and we will fix a meeting place and exchange idea and the resource CDs are yours. |
Programming / Re: Java Resource CD For Nairaland by mimohmi(m): 11:28pm On Apr 06, 2006 |
Ok, if you are in lagos please call me on 018972759. The first set of CDs will be ready by mid week. The Contents, 1. Java SE 5.0 and 6.0. 2. Tomcat 5.xx 3. Sun Application Server 8.0 and 9.0. 4. JBoss 5. NetBeans 5.5 Preview + tutorial 6. Sun Java Studio Creator 2 + tutorial 7. EJB 2.0 and 3.0 specifications 8. Java 5.0 Specification 9. MasteringEJB3rdEd 10. J2EE 1.3 and 1.4 RI 11. EJB Design Patterns. 12. SCBCD CX310 090 Exam Study Kit Java Business Component Developer Certification for EJB 2005 13. JavaEE_ataGlance_v1.4 14. J2EE Architect Handbook 15. Jakarta Struts Live 16. Servlets and JavaServer Pages 17. EJB developers guide 18. BasicJava1 19. jdk-6-beta-doc 20. jwstutorial20 21. Clear cape server and many more. Hope, they will be helpful. So expecting calls from mid week from mid day. For those outside lagos, still call. Anything is possible. |
Programming / Java Resource CD For Nairaland by mimohmi(m): 12:54am On Apr 05, 2006 |
I am presently running a java training thread on this site. I discovered that most people have the problems of getting java materials including the development kits and other java IDE. So, i have decided to compile a CD containing all the resources for FREE. For the mode of distribution, please contact the site administrator. As I can only afford a few copies for now. If you are interested just indicate on this thread. e- books included |
Programming / Re: Learning Java Without Tears by mimohmi(m): 3:57am On Mar 31, 2006 |
Am really sorry for the network break. For some of the questions asked, promise to post reply by weekend. Why the break ? Noticed most people are having problems, getting the Java SE. So, am compiling a java resource cd for anyone interested. The collection include best selling books in java and related technologies such as Java Studio, JBose,Apache tomcat, Sun Java Application server 8.0 and 9.0 to mention a few. Am bases in lagos, so if you are in lagos, just indicate so that i will know how many copies to make available. ALL THESE FOR FREE. |
Programming / Re: Web Development Using Java by mimohmi(m): 2:00am On Mar 31, 2006 |
Hey sub, Out of the blue again. I am working on a project(personal), the aim is to develop a java web app that can be plug into say any site to carry out survey. The first page should be populated with a database supplied data and should consist of questions and answers. eg Q1 Rate my services A1 Excellent Very Good Good Poor (Radio buttons) So I created a survey database(mysql) Tables SurveyQuestions id (pk) name question SurveyResult id(fk) surveyOptions valueCount in my jsp as shown below; <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%-- The taglib directive below imports the JSTL library. If you uncomment it, you must also add the JSTL library to the project. The Add Library, action on Libraries node in Projects view can be used to add the JSTL 1.1 library. --%> <%-- <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> --%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %> <%@ page isELIgnored="false" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>JSP Page</h1> <!-- This sql code returns to two row with multiple columns. ---> <sql:query var="quest" dataSource="jdbc/SurveyDBF"> SELECT surveyquestion.question,surveyResult.surveyoption from surveyquestion, surveyResult where surveyquestion.id and surveyResult.id </sql:query> <!-- Now, want to loop through the result of the sql code to display a pair of question and line and got hook. Help --> <table border=0> </tr> <tr> <td> <c:forEach var="row" items="${quest.rows}"> <input name="nono" type ="radio"/><c:out value="${row.Surveyoption}" /> </c:forEach> </td></tr> </table> </body> </html> |
Programming / Re: Web Development Using Java by mimohmi(m): 12:14am On Mar 22, 2006 |
Finally downloaded the Sun Studio, pretty cool. Make developing web client easier. Please can you give me links to JSF tutorials. Thanks |
Programming / Re: Learning Java Without Tears by mimohmi(m): 11:39pm On Mar 18, 2006 |
Hi All, Let's take a look at our last two examples. Starting with the first. From line 1 - 12 : these are all bunch of comments. Some text editors like TextPad are able to identify comments. As you can see it appear in GREEN colour. Line 14 : This is called package statements. It allow developers to arrange the source codes in directories. The name must match a path to the specify directory. Most time the root directory for java application is the classes directory, so you don't add it to the package statement. If used in a code, it MUST be the first executable line, no other things are allowed before it except comments. Line 16 - 21: These are Java Documentation statements. Used by javadoc tool to generate Documentation that describe the purpose,classes,methods and variables defined in an application. But here, we are just describing the version and author. Line 23 : This is the beginning of our class definition, from where object of this class will be created for future use. Line 32 - 36 : Shows a method definition. But the define here is a very special method in Java. All java executable application must define it as it is is(public static void main(String[] args)). This method is what the JVM uses to execute your application. eg when we say java MyFirstApp The JVM first look for the main method, accept the class name of the application as an arguments. Usually as String array (more on this later).If everything is fine, it start running your logic. So next let's look at the second code, will just explain the difference. 1. The static import statement(this is the name Sun called it), was introduced with 5.0. It allow you to import static classes. It just a way of saving typing time. Once a static class is imported, you can call it's method without specifying the fully qualified name. But, there is danger hanging here. Assuming you have two methods with the same name but belonging to different static classes, you have no option than to use there fully qualified name, else naming conflict(error). 2. the printf() : This was also added to version 5.0. Provide a very flexible way of formating the output from your application. More on this later. Let's look at the documentaion, you will notice that a method named , MyFirstApp() MyFirstApp2() This are special methods in java, the are called CONSTRUCTORS, this is what is what allow you to create the object of the class. It must have the same name as the class name, it can not return anything even void (more on this later) but can take arguments, usually what you will use to initialise the object. All java class must have a construcutor, if you don't specify any, the compiler will just be kind enough to add one for you (default). But if you do, then it must follow the rule stated above. Also not that, if you do specify, the compiler won't bother to create any for you. 3. Still looking at the documentation, you will see Methods inherited from class java.lang.Object This shows that your class extends Methods java.lang.Object, All classes in java extends this class,thus automatically inherite all it's methed. note that java does not support multiple inheritance like C 0r C++. So, the next step is to download the java documentation API (Application Programming Interface). http://java.sun.com/j2se/1.5.0/download.jsp It contains all the classes definitions. Most of the times, this is what you are going to be using in developing your applications. Next post, we will be looking at the composition of a java class and get ready for some hands-on. |
Programming / Re: Learning Java Without Tears by mimohmi(m): 11:59pm On Mar 12, 2006 |
Remember promised to keep my notes short. As we progress, i will be introducing some of the new 5.0 features. Same application but in 5.0 way. The code is show below, follow the same procedure for compilation and running the application. To generate the documentation, use a wild card (*) for java. (go key in the the code, it's shown below and come back) Javadoc command: C:\projects\nairaland>javadoc -d C:\projects\nairaland\docs -keywords -author -version src\*.java check the documentation to see the result. Please try and run these examples, so that by next post, we will be speaking the same language. Java
|
Programming / Re: Learning Java Without Tears by mimohmi(m): 11:16pm On Mar 12, 2006 |
In the last tutorial, we looked at how to install and configure our Java environment on both windos and Linux systems. We also looked at how to setup the java development environment as required in real world production. So, today, we are going to use a simple program to illustrate the fundamentals of java. When you write a java program, what happen after that.What role those the compiler play, what is a Java Virtual Machine and what does it do and how does it read your applications.So, we kick off with the program as shown below. Please note the file name and the class MUST the SAME. And must be saved with a java file extension ie MyFirstApp.java as shown at the bottom of this post. Ok, pause, look at at the example. Now think of development environment. We need to create a folder, the name should be the same with our project name. This is not required but recommended. So our file structure should be like this. C:\projects\nairaland C:\projects\nairaland\src - put MyFirstApp.java here C:\projects\nairaland\classes - put nothing here, we will tell the javac (compiler) to put thing here for use C:\projects\nairaland\docs - nothing here, we will beg javadoc to help us too Now we are done. Remember the rules, no IDE and Never compile from the editor. If you do i will know but won't tell how. So, open the dos prompt.Go to our nairaland project folder. C:\projects\nairaland - we all should be here, am right,if you are not here, please better be "so thing is about to happen" Let's compile the Application. Do this. C:\projects\nairaland>javac -d classes src\MyFirstApp.java C:\projects\nairaland> - if everything is ok, we are back here. First thing just happend. Check the classes folder and what happened there. Please let me know. If you missed the first please don't pass here, until you are sure you saw what happened. If you are here, let's see another thing happening. So do this. C:\projects\nairaland>javadoc -d C:\projects\nairaland\docs -keywords -author -v ersion src\MyFirstApp.java You will see all this stuffs, don't panic, it just doing what we ask it to do. Creating destination directory: "C:\projects\nairaland\docs\" Loading source file C:\projects\nairaland\src\MyFirstApp.java, Constructing Javadoc information, Standard Doclet version 1.6.0-rc Building tree for all the packages and classes, Generating C:\projects\nairaland\docs\com/nairaland/\MyFirstApp.html, Generating C:\projects\nairaland\docs\com/nairaland/\package-frame.html, Generating C:\projects\nairaland\docs\com/nairaland/\package-summary.html, Generating C:\projects\nairaland\docs\com/nairaland/\package-tree.html, Generating C:\projects\nairaland\docs\constant-values.html, Building index for all the packages and classes, Generating C:\projects\nairaland\docs\overview-tree.html, Generating C:\projects\nairaland\docs\index-all.html, Generating C:\projects\nairaland\docs\deprecated-list.html, Building index for all classes, Generating C:\projects\nairaland\docs\allclasses-frame.html, Generating C:\projects\nairaland\docs\allclasses-noframe.html, Generating C:\projects\nairaland\docs\index.html, Generating C:\projects\nairaland\docs\help-doc.html, Generating C:\projects\nairaland\docs\stylesheet.css, C:\projects\nairaland> - so we are back here again. Now go to docs folder. C:\projects\nairaland\docs whao where did the resources,com folders and the html file come from. Lession 2, let me know. Finally to run MyFirstApp. Go here (dos prompt) C:\projects\nairaland type this command C:\projects\nairaland>java -classpath classes com/nairaland/MyFirstApp Learning Java Programming Without Tears at Nairaland.com - So this is the result of application C:\projects\nairaland> Take a look at the code,documentation and all the commands (dos), figure out our they relate. Please do this before my next post. Remember, promised to be slow. So many things and so many guestions a guess. Q and A next. Stunts Corner. For people with --- never mind let's try somethings. 1. Delete the docs and classes folders. Don't worry just do it. 2. Run the javac command again. ie C:\projects\nairaland>javac -d classes src\MyFirstApp.java C:\projects\nairaland>javadoc -d C:\projects\nairaland\docs -keywords -author -version src\MyFirstApp.java As you can see you can actually use the java command tools to auto generate and package our codes. Next, i want us to look at the documentation, compare the contents with our source code (MyFirstApp.java).
|
Programming / Re: Looking For People Interested In Exploring JavaEE 5 And EJB 3.0 by mimohmi(m): 2:44am On Mar 12, 2006 |
Seun, there is alot of changes between j2EE and JavaEE. The power of J2SE 5.0 was brought to bear on JavaEE 5.0. Look at the introduction of annotations, beans implementing the business interface( component interface) and much more. If you are interested, i am still working out the sharing formula. Thinking of setting up an e-mail add where anybody could either upload or download exchanged materials from. Or can you give us such access through this site. Hoping to hear from you. |
Career / Re: Passed Sun Certified Business Component Exams - 91% by mimohmi(m): 2:33am On Mar 12, 2006 |
As requested by subcareer, i want to share my experience with nairaland members. When i decided to go for the exams, i had no experience on business component. But it's all about challenges. Took about 6 weeks to learn and prepare for the exams. Bought 2 books, one for the certification and the other for hands on practice. The books were quite ok. Spent about an average of 15 hrs/day of reading for 3 weeks. Got another book from a pal at javeranch, was quite ok. The exam was quite interesting, the questions required detail understanding of EJB. For me i hate cramming, so i had to depend on my understanding of the exams objectives. it works, but some how it just didn't click. All the same, i think understanding is better than cramming. For the cost. I bought HeadFirst EJB for 5k and paid 30k for the exams, making 35k. paid for 9k for 2 months internet connection. Making a total of how much. There is always a price for everything like no TV, Radio and friends for this period. It's was quite difficult, that's the price we pay to study things we aren't familiar with. The questions were very tricky but all the same it's either you now it or fail it. If there are people going for the exam, just post it here, promise to help you sort it out. For more details keep an eye on this thread. Wishing you all a lovely sunday. But before i go, i would like to say a big thank you to subcareer, for advicing me to go for it, brother, a big hug. To seun, thanks for bringing us all together, by setting up this site and to all nigerlanders who one like viper, i say nagode for the encouragement. If anybody is interested in Sun cert exams, I am your man. sai anjuma |
Career / Passed Sun Certified Business Component Exams - 91% by mimohmi(m): 2:09am On Mar 12, 2006 |
As requested by sbucareer, i want to share my experience with Nairaland members. When i decided to go for the exams, i had no experience on business component. But it's all about challenges. Took about 6 weeks to learn and prepare for the exams. Bought 2 books, one for the certification and the other for hands on practice. |
Programming / Looking For People Interested In Exploring JavaEE 5 And EJB 3.0 by mimohmi(m): 5:31am On Mar 11, 2006 |
Hello, is there anybody interested in exploring the new JavaEE 5 and Sun Application Server 9.0(Beta). It's going to like everybody doing same thing and sharing ideas, solutions and materials. I bet you apart from few write up by few people and the various specifications from Sun, there isn't a book on it that i know. Bet it's going to be fun. |
Programming / Re: Programming - What About Newbies Like Me? by mimohmi(m): 5:20am On Mar 11, 2006 |
da808cutie, Bluej is a very simple IDE. Getting used to it shouldn't be diffcult, in fact that's what i use on my linux box. It has tutorial to get you started fast. Can you just post what exactly is the problem you are having with it. I am watching Have a lovely and error free weekend. |
Programming / Re: Java Has Failed! by mimohmi(m): 3:24am On Mar 10, 2006 |
sbucareer, am working on new features of 5.0. Hope to make the post after my exams. The Generic stuff is to checked if a parameter or an object passes IS-A test at compile time rather that at runtime, by specifying a type element as a parameter in the class definition. To force a generic method, pass the type parameter as an argument. So doing, the rest is for the compiler to ensure that only objects that passed IS-A test is allowed as parameter to the constructor or methods. As of 5.0, Collection classes were made generic. eg To declare a generic class public class Bus<E>{ List lagos = new ArrayList<E>(); // ArrayList to hold on bus objects, lagos can only contain objects that IS-A Bus public void addMolue(E molue) { // can only pass IS-A bus arguments lagos.add(molue); // can only add IS-A Bus to lagos } To implement inheritance with generic classes, follow the normal java rules. eg public class Vehicle<E extends Bus>{} // Vehicle can only contain IS-A Bus objects More on it next week. Have a lovely weekend. Tomorrow is my D-Day. |
Programming / Re: Learning Java Without Tears by mimohmi(m): 1:16am On Mar 10, 2006 |
IDE these days are not as simple to use as you think. Personally, i started using IDE late last year. Imagine setting up your class files to support import statements in your codes. Also, think about classpath issue to mention a few. For a beginner, that's just going to be too much. Another point is that when does he start learning to know the in and out of the compiler, like passing command line arguments, another hill for him. I think the use of IDE should be to enhance productivity, is like putting a fresh pastor in the pulpit, without giving him a bible. Even if he know where the verses are, do you expect him to cram the contents. No way brother. In fact, it is difficult to run away from command prompt as a java programmer. Like i read in one of the threads, somebody got a java file (jar) and wasn't able to run it, and his conclusion was java was difficult. To do that is quite simple. I will putthe command here for others, who are following. To run a java jar file use this command. java -jar NameOfFile.jar --------- use the file name or complete file path |
Programming / Re: Learning Java Without Tears by mimohmi(m): 12:11am On Mar 10, 2006 |
Seun, i usually don't advice beginners to use IDE for some obvious reasons. Using the jdk tools allow learners to focus on the language, rather than having to learn how to use an IDE. IDEs don't have specification as such anybody is free to develop it which ever way he or she likes. IDEs do always add IDE specific codes to your source codes, so with no standard, how do explain these codes to a student. |
Programming / Re: Java Has Failed! by mimohmi(m): 2:00am On Mar 09, 2006 |
Ok africanboy, if speed seem to be a minus for java. Let's do a speed test. After installing the J2SE 5.0 (jdk), we are not testing the 6.0 version(Beta) mind you. ok CD to C:\Program Files\Java\jdk1.6.0\demo\jfc\Java2D. In this folder you will see a file named Java2Demo.jar. It's a demo program, won't tell you the content until you have done the speed test. run the file with this command. To run just follow this steps. 1. go to dos prompt. 2. CD C:\Program Files\Java\jdk1.6.0\demo\jfc\Java2D 3. type this line to run it. java -Dsun.java2d.opengl=true -jar Java2D.jar 4. then a second command. java -jar Java2Demo.jar Then for codings look at these short examples. Old ways --- 1.4 ArrayList<Integer> list = new ArrayList<Integer>(); for (Iterator i = list.iterator(); i.hasNext() { Integer value=(Integer)i.next(); } New ways --- 5.0 ArrayList<Integer> list = new ArrayList<Integer>(); for (Integer i : list) { , } Expecting you comments. |
Programming / Re: Learning Java Without Tears by mimohmi(m): 12:32am On Mar 09, 2006 |
This is for Linux and Unix related system users. Here, am going to demonstrate how to install and configure java on a Linux box, Stand easy and look this way (Drill Instructors - NYSC Camp). For the development environment ,it's the same with the window's version except in instead of \ use /. Download whatever version (J2SE) you need (either the bin or rpm). For me i prefer the binary (bin) version. With it i can have multiple version of J2SE on my box, and with just a command i can switch between versions. But not possible with windows, this is Linux world. I recommend install J2SE (j2sdk) in your \usr\local directory, so that you can make it available to all users of the Linux box, that means you have to login as the root user. So copy the whatever J2SE version you downloaded to the /usr/local directory. 1. Open a terminal and CD to /usr/local 2. Make sure you have copied the J2SE file (ie downloaded bin file) to this location 3. Change the bin file permission chmod 755 <j2se file name>.bin 4. Execute the bin file. ./<j2se file name>.bin The installation process kicks off. Follow the instruction on the screen, and you might try saying no to the agreement. but if you say yes, remember Ukwa (Agreement na Agreement o). All after the agreement and inflation of files. Check the /usr/local you should find a folder name <j2se name> or it might have the old name ie j2sdk<version>. 5. Assume all is OK till now. Back to the terminal, create a system link to a jdk folder. If you don't understand just type in this command. ln -s /usr/local/<new j2sdk file name> /usr/local/jdk After you run the command, check /usr/local directory, you should see a folder with a green arrow pointing up and named jdk. this is the link we will use to set our classpart, so that if we have multiple version of J2SE, we simple issue same command in 5. we just change the j2dsk file name to our required version. 6. The final stage, we need to add the tools to our classpath, OK don't worry, it isn't difficult. Follow me, I be old soldier mind you. OK quick march. 7. Open the /etc/profile file using any text editor, some many available on Linux box. For me i use either kedit or gedit. so do this. Still on the terminal. gedit /etc/profile 8. Add this lines to the file, export PATH=$PATH:/usr/local/jdk/bin:/user/local/jdk/lib/tools.jar:/usr/local/jdk/jre/lib/rt.jar:./ export JAVA_HOME=/usr/local/jdk 9. Save the file and exit. 10. Back to the terminal, type this command source /etc/profile This is to reload the new changes made in the profile file. And finally type javac at the terminal and will see an output like the windows output. So Linux boys can now be part of the train. Please refer to to my conclusion on on the last post. After this stage, nothing like windows or Linux version. This is JAVA platform independent. . |
Programming / Learning Java Without Tears by mimohmi(m): 11:57pm On Mar 08, 2006 |
NOTE: Please i do not expect everybody to read this on-line, you can copy the pages to a storage device and take time to go through it or you can also print it out. Welcome to this thread. Having seen some threads in this forum, I'm happy that so many people in Nigeria are interested in learning Java. So I have decided to run a couple of threads as my contribution to developing a strong Java Community in Nigeria. So, if u are among the lucky ones that have decided to get started with learning Java, never mind, i am here to just get you started. Learning Java could be fun and frustrating, depending on the angle you look at it from.But I'm promising you that I am going to take it real slow and down to earth. I am also going to go about it from the professional way i.e after finishing, if we ever finish, you should be strong enough to add little effort and start hitting certification level. So let's get the ball rolling with the requirements. 1. To learn Java, of course you need a Java Development Tool (jdk) now called J2SE (Java 2 Standard Edition) from 5.0 version (Code named Tiger). There is a lot of improvement in the new edition, in fact there is a new version (Code named Mustang) already out but still at a beta (development) stage, the final version should be out soonest. But be rest assured that it is backward compatible. But Version 5.0 is recommended. It can be downloaded, which ever version you need from this link. http://java.sun.com/j2se/1.5.0/download.jsp It is recommended to use Sun Download Manager (SDM) to download the J2SE else you are going to have a frustrating time downloading it. The SDM can be downloaded from this link and it's easy to use. Read the read me file after installing it to get cracking. http://www.sun.com/download/ 2. Next, you are going to need a java aware text editor, i will recommend TextPad, there is a free evaluation version you can use. I do not recommend using Integrated Development Environment (IDE) for now. They do shield you from the real details of the language, and more so, they will always add some IDE specific codes to your application, this might confuse you. Also debugging your application could be difficult, if you don't know how errors are handled in java. TextPad can be downloaded from this link. http://www.textpad.com/download/ 3. Now that we have all the needed software requirements, installing the J2SE easy for windows but for Linux you have to do some tweeking to get it and running.For Linux users, if you are unable to install it, please feel free to post your problems, promise to sort it with you. Next thing is to configure our system and development environment. You need to add java to your system classpath. If you don't know what is classpath, never mind, i will explain. It's just a way of telling the system where to look for executable commands. Like if u type "dir" in your DOS prompt, the system list the content of a directory, because DOS commands are added to the classpath by default. So let's set the classpath. a. Right click My Computer icon on the desktop. b. Select properties. c. On the System Properties dialog box, select Advanced tab. d. Click on the Environment Variables button at the bottom. e. On the System Variables box, select Path under Variables, click Edit button. f. An Edit System Variable dialog box will show. g. In the Variable Value text Field, move your cursor to the beginning and add the path to your J2SE bin folder. eg C:\Program Files\Java\jdk1.5.0\bin,. click all the OK to take you back to Environmental Variables dialog box. Here, we are just going to add another simple System Variable, it for tools that depend on java to run. so Click the New button, A new System Variable dialog box appears. Just fill as stated below. Variable Name: JAVA_HOME Variable Value: C:\Program Files\Java\jdk1.5.0 - don't add the bin folder after this you can click all the OKs. Be warned, not to remove anything from the path when editing, if u do, your system might become unstable. So be careful. So, we are through with that. O boy no give up ooh. To test if everything went kool, click start, run, type cmd and hit enter. Na just to open Dos prompt o. Type javac hit enter, you should get a message like this. Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\Omo>javac Usage: javac <options> <source files> where possible options include: -g Generate all debugging info -g:none Generate no debugging info -g:{lines,vars,source} Generate only some debugging info -nowarn Generate no warnings -verbose Output messages about what the compiler is doing <more lines here> If you get this message all de kampe. If you don't get this message, no yawa, some systems might require a restart, so do it, if yawa still gas, ma boy, sorry you have to go all over the process again. It's never been easy, getting it right the first time. 4. Na wa o. I bet you, this is going to be the longest part, we will ever get. It's nice we learn to get it right from the beginning. Don't worry, this is the last paragraph for today. Setting our development environment. Java has a recommended file standard structure you should follow, for now we will be doing it ourselves.But in real production where you have hundreds of sources and class files, you will be using tools like Ant to arrange your file structures. I will just list the structure. a. Create a project directory that will contain all our projects folder. C:\project b. Create a sub directory, let's call it lecture1 (initial small letter), the name of our current project. C:\project\lecture1 c. Create a sub folder for lecture1, name it src - it must be named src, source codes (what you write) goes into this folder. C:\project\lecture1\src d. Create another sub folder for lecture1, name it classes - must also be named classes and your class files(compiled code) sit here. C:\project\lecture1\classes So now we are ready to start the party, but before we go, let's look at area where most beginners encounter problems.Take note. 1. Java is highly type checked. Mean the javac (compiler) will make sure you follow the rules. No short cuts. a and A are not the same. lagos and Lagos not same, so Lagos must be Lagos throughout your code. 2. White space are ignored. That is spaces between statements except for few exception like in classes,methods and variables declaration. (if you don't understand, don't panic, we go jump am pass). 3. Class declaration must start with { and end with }. 4. Method declaration must have () immediately after it's name and like classes must start and end with {}. 5. Every statement must terminiate with ; Though there are more, but these are what i feel are the most common, So my boy, me i dey check out. Take your time to digest it and make effort to get the required tool, because by next class we will write our first program and explain some concept in java using a simple program. Wish you all the best. To all, including the gurus and alike, please your criticism,observation,contribution and recommendations are welcome. Recommended free training site. Highly rated. www.javaranch.com Recommended Text book HeadFirst Java 5.0 (Second Edition) by Kathy Sierra and Bert Bates. HeadFirst Java (First Edition - covers version 1.4) by Same authors Recommended books for Certifications. Sun Certified Java Programmer Sun Certified Java Programmer 1.4 Exam Guide by Kathy Sierra and Bert Bates. Note: The 5.0 version seems not to as good as the 1.4 version Sun Certified Java Associate no books yet. It's a new exam for entry level. Sun Certified Web Component Developer 1.4. HeadFirst Servlet and JSP ( rated best in the category) - lots of hands on practice - simulation of real development paractice Sun Certified Business Component Developer 1.3. SCBCD EXAM STUDY KIT by Paul Sanghera (free pdf version available on-line) EJB Specification 2.0 from Sun. HeadFirst EJB by Kathy Sierra and Bert Bates (Very good teaching approach but some error, corrections available on-line). Mastering Enterprise JavaBeans 3rd Edition by Ed Roman and co (free pdf version available on-line) Recommended Bookshop in Lagos. Ebuy (Prices are ok, extra 1k or 1.5k above on-line prices). Delivering within 2 to 3 weeks. Call Seun 01-4751491 or Dolapo 08029494655 |
Programming / Re: Java Programming For Dummies by mimohmi(m): 11:19pm On Mar 08, 2006 |
Congratulations !! you have just succeeded in running you first java application. Look at the first line of the output window (DOS). Hello Word is your output from line 3. ie System.out.println("Hello World" . |
Programming / Re: Java Programming For Dummies by mimohmi(m): 1:55am On Mar 08, 2006 |
Good you are using TextPad. To run your HelloWorld application, Click Tools --------> Run Java Application or just simply press Ctrl+2 on your keyboard Hope it helps. |
(1) (2) (3) (4) (5) (6) (of 6 pages)
(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. 196 |