Learning Java Without Tears

Welcome. Please Login, Register, Or Activate! 
type your username and password to login
Date: November 22, 2009, 04:33 AM
430671 members and 297822 Topics
Latest Member: Jadman
Nairaland [Nigerian Forum] Home Help Search Who is currently online? Login Register
Nairaland Forum  |  Technology  |  Programming  |  Learning Java Without Tears
Pages: (1) (2) Go Down Send this topic Notify of replies
Author Topic: Learning Java Without Tears  (Read 5075 views)
mimoh_mi (m)
Re: Learning Java Without Tears
« #32 on: August 19, 2006, 11:36 PM »

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.
ojochonu
Re: Learning Java Without Tears
« #33 on: August 21, 2006, 10:38 PM »

am yet 2 start learning at niit
mimoh_mi (m)
Re: Learning Java Without Tears
« #34 on: August 22, 2006, 11:17 PM »

No big deal, you can just use this as an additional resource.
adewaleafolabi (m)
Re: Learning Java Without Tears
« #35 on: September 17, 2006, 09:51 PM »

abeg u guys help me after downloading the java version 1.5.8 and editing the control panel thing my command prompt refuses to open it shows another program is currently using this file help me plz am so frustrated
whats left is C:\Program Files\Salford Software\FTN95;C:\Program Files\Salford Software\FTN95;
hayprof (m)
Re: Learning Java Without Tears
« #36 on: September 17, 2006, 10:21 PM »

I want one of those cds too!
mimoh_mi (m)
Re: Learning Java Without Tears
« #37 on: September 17, 2006, 11:56 PM »

@afolabbi

Please don't be frustrated, we all go through this when we are getting into something new, but I will tell you that
you are doing well, because we tend to learn more from our mistakes. Go through this process, http://www.nairaland.com/nigeria/topic-8060.0.html#msg569210 if it doesn't work, please just post
you classpath, so that I can see where things went gaga, hoping to hear from you.

@heyprof, if you don't mind give me a call on 018972759, so that time to meet. Pls get 3 blank cds.
Thanks
gbengaijot (m)
Re: Learning Java Without Tears
« #38 on: September 18, 2006, 12:04 AM »

isnt it just easier to download jDK 5.0 and then install it, as well as install Blue J. It automatically configures it path to the java development kit.

Isnt tat right Mimohmi?
mimoh_mi (m)
Re: Learning Java Without Tears
« #39 on: September 18, 2006, 01:03 AM »

@gbengaijot

For jre, yes, that is the Java Runtime Environment, but for the jdk, that is the development Environment,
 NO,  you have to manually add it to you classpath. Hope I have answer you question, have a nice day
gbengaijot (m)
Re: Learning Java Without Tears
« #40 on: September 18, 2006, 08:24 AM »

Mmmmmmm, i am really sorry if i got you wrong. I am doing my second Year (in Uni) first module on OOP using java, and we had the software on CD. My course tutor only asked me us to install, the JDK, and then the JDK5.0 and then the Blue J IDE.
Does that mean that the CD has been configured to notify the path itself?.

Please advise me ooo. coz i am gonna be a regular student on this thread and i want to learn all i can in JAva above my course mate.
adewaleafolabi (m)
Re: Learning Java Without Tears
« #41 on: September 18, 2006, 10:51 AM »

thanks this is my CLASSPATH "i\QTJava.zip"


this is wat remains of PathC:\Program Files\Salford Software\FTN95;C:\Program Files\Salford Software\FTN95;C:\Program Files\Java\jdk1.5.0\bin,.%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;C:\Microsoft SQL Server\80\Tools\Binn\

not wen i type cmd in the run dialog box it says another program is currently using this file, also others like telnet isn't recognised by windows anymore then isqlw, windows says it can't find the file but its there
mimoh_mi (m)
Re: Learning Java Without Tears
« #42 on: September 19, 2006, 12:48 AM »

@gbengaijot

Ok, this is the point, by the fact that your classpath was added to Blue J, doesn't mean it is
in your system classpath, the reason you were ask to install the Java SE first was to enable the Blue J to
integrate the java tools into it's own environment. Try going to your command prompt and type javac
or any of the tools in your Java SE bin folder. Won't tell you the result, or just try install some tool
like Tomcat, they screech and ask for JAVA_HOME, try and post your result.


@adewaleafolabi


From your classpath, i can't really figure out what the QTJava.zip is all about, but what I think you should do is set your 
 JAVA_HOME = C:\Program Files\Java\jdk1.6.0
then add  %JAVA_HOME%\bin to the end of your classpath, open a new Dos prompt and type javac and you should see a message like this

C:\Documents and Settings\Owner>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
 , ,
, ,

Your final classpath should be like this.
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;C:\Program Files\ATI Technologies\ATI Control Pane;%JAVA_HOME%\bin
Hope it helps, if it doesn't let me know.

mimoh_mi (m)
Re: Learning Java Without Tears
« #43 on: September 19, 2006, 02:56 AM »

@chistiana
Sorry for not checking some of the past post, ok, just feel free to let me where you got
lost, it is a learning thread, I did promised from my first post to carry everybody along.
Infact, if there are points that are not clear, anybody should just feel free to ask for
further clarification. So, expecting your post.
sedan (m)
Re: Learning Java Without Tears
« #44 on: September 23, 2006, 02:21 AM »

hi everyone. pls how can I can get in touch wit sir mimoh for the cds. thanx
Bossman (m)
Re: Learning Java Without Tears
« #45 on: September 23, 2006, 08:24 AM »

Can't you just send him an email via his profile?

Quote from: sedan on September 23, 2006, 02:21 AM
hi everyone. please how can I can get in touch wit sir mimoh for the cds. thanx
CHUKWUTEM (m)
Re: Learning Java Without Tears
« #46 on: September 23, 2006, 01:19 PM »

Mimoh_mi
I need d CDs but I'm presently@Abuja.I REALLY APPRECIATE ALL YOUR EFFORTS.I downloaded all  d tutorials to my fone.
mimoh_mi (m)
Re: Learning Java Without Tears
« #47 on: September 24, 2006, 11:44 PM »

@ sedan


Am in Lagos,  had problems with my old laptop, so lost all I had on it. All hope is not lost,
got another laptop for two months now. Still got all those stuff and more. So all you have to
do is give me a call on 01-8972759, and get some blank cds, and copy all you can.
For people outside Lagos, still give me a call, so that we make adequate plans to
get it across, wish all Java Fun week ahead.
sedan (m)
Re: Learning Java Without Tears
« #48 on: September 25, 2006, 02:14 AM »

oh! im so grateful, i'll call u soonest. thanx.
sedan (m)
Re: Learning Java Without Tears
« #49 on: March 05, 2007, 09:49 AM »

hey there, I was looking thru dis thread and Im really finding it interestin but the challenge is, I click on your link (sbucareer) to download the platform. it was sucessful but when it got to modifying the classpath, I did it & went to command prompt, javac.
It came out wit an error message, in short, I want to start compiling bt its not going
Bossman (m)
Re: Learning Java Without Tears
« #50 on: March 05, 2007, 12:25 PM »

From your post, I am thinking it can't find javac. Make sure you path is pointed to where javac is located. You can either set your path to it or try to compile from that location. It should be in the bin folder of your JDK installation.

Unless you are actually getting compile erroers. In which case you have to figure that out.
IronFist (m)
Re: Learning Java Without Tears
« #51 on: March 05, 2007, 06:28 PM »

Hi, if there is anyone in Abuja who is interested in getting Java materials (SDK and ebooks), u can give me a shout on 0805-931-7632.
azpunpin
Re: Learning Java Without Tears
« #52 on: August 18, 2008, 10:40 PM »

Hi,
  I am really interested in learning Java @ all cost, I read through this Post and it is encouraging.
1UP to You Poster,

Please, kindly continue the Tutorial.

Thanx
 .NET C#/VB.NET Project in the Pipeline for Programmers who may be interested  Formatting A SIM Card  Differences Between High & Low Level Languages?  Page 2
Pages: (1) (2) Go Up Send Topic to Friend by E-mail Reply 


Sections: Autos/Cars (2) Jobs/Vacancies (2) (3) Career Talk Education General(2) Politics Romance Computers Phones Travel
Sports Fashion Health Religion Celebrities TV/Movies (2) Music/Radio (2) Books Webmasters Programming

Links: Page1 Page2 Page3 Page4 Page5 Page6 Page7 Page8 Page9 Page10

Nairaland is owned by Oluwaseun Osewa. See also: Nairalist Classified Ads
Nairaland Forum | Powered by SMF 1.0.12.
© 2001-2005, Lewis Media. All Rights Reserved.