Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Tutorial: Primitive Data Types

  1. #1
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    661
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Tutorial: Primitive Data Types




    Note: This tutorial is meant to be a little more compact that oracles tutorial, directed at beginners.


    In this tutorial I will be covering all the basics regarding primitive data types.
    I believe this topic is quite valuable when you’re writing your Java programs as each data type have their place at some time or another.

    In addition to the int primitive data type, which I’m sure many of you will have already encountered, there are 7 additional types:

    (In no specific order)

    1. float
    2. double
    3. byte
    4. short
    5. int
    6. long
    7. char
    8. boolean




    Now from here, primitives split into two sub-categories; you have the numeric types, and you have boolean.
    All 1-7 are classed as numeric types, and Boolean simply holds true of false.

    Now before I delve any deeper, some of you may have noticed that String isn’t among these data types, and that’s for a very good reason, as String comes under ‘Reference types’ and not ‘Primitive types’.
    We will not be going into the differences between the two, but I’d just thought I’d mention it to avoid any confusion.

    Some quick facts:
    • A variable’s data type determines the values it may contain, and the operations that may be performed on it.
    • Within Java, each data type is denoted by a reserved word.
    • Each type is allocated a fixed amount of Storage

    Now to begin;



    Byte (8 bits)

    A byte is a data type which ranges over integer values between -128 and 127. The attempt of assigning numbers out of that range will result in an error.


    Example:
    public static void main(String[] args) {
    		byte myByte;
     
    		System.out.println("Minimum: " + Byte.MIN_VALUE);
    		System.out.println("Maximum: " + Byte.MAX_VALUE);
     
    		myByte = 12; // valid
    		myByte = -3; // valid
    		myByte = 128; // INVALID
    	}


    Output:
     

    Minimum: -128
    Maximum: 127








    Short (16 bits)

    This data type may only contain whole numbers between -32,768 and 32,767. The attempt of assigning numbers out of that range will result in an error.


    Example:
    	public static void main(String[] args) {
    		short shorty;
     
    		System.out.println("Minimum: " + Short.MIN_VALUE);
    		System.out.println("Maximum: " + Short.MAX_VALUE);
     
    		shorty = 12; //valid
    		shorty = -500; //valid
    		shorty = 40000; //very much invalid.
     
    	}

    Output:
     

    Minimum: -32768
    Maximum: 32767



    Note how values are assigned in the form of 32767 and not 32,767.






    int (32 bits)

    An int is a data type which ranges over the integer values between -2147483648 and 2147483647.
    This data type is the most common data type many programmers use when dealing with numerical data.


    Example:
    public static void main(String[] args) {
    		int myInt;
     
    		System.out.println("Minimum: " + Integer.MIN_VALUE);
    		System.out.println("Maximum: " + Integer.MAX_VALUE);
     
    		myInt = 40000; // valid
    		myInt = -600000000; // valid
    		myInt = -2147483649; // INVALID
     
    	}

    Output:
     

    Minimum: -2147483648
    Maximum: 2147483647








    Long (64 bits)

    A long is a data type which can only have whole number values between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807.
    As you can see, that’s one lengthy range.


    Example:
    public static void main(String[] args) {
    		long soLong;
     
    		System.out.println("Minimum: " + Long.MIN_VALUE);
    		System.out.println("Maximum: " + Long.MAX_VALUE);
     
    		soLong = 40000; // valid
    		soLong = -600000000; // valid
    		soLong = -6000000000000000000; // INVALID
    		soLong = -6000000000000000000L; // Valid - 'L' @ the end.
    	}


    Now, notice how I’ve noted ‘soLong = -6000000000000000000;’ as invalid even though it’s within range.
    Well that’s because when dealing with long data types, you should be placing the letter ‘L’ after the number.
    Note that the use ‘L’ at the end is not case sensitive, so feel free to use the higher or lower case.


    Output:
     

    Minimum: -9223372036854775808
    Maximum: 9223372036854775807








    Float & Double (32 & 64 bits)

    Float and double and both types of floating point literals, which mean they don’t need to be whole numbers.

    Notes:
    Float
    • Single-precision floating-point numbers
    • Seven significant figures
    • Stored using 32 bits

    Double
    • Double-precision floating-point numbers
    • Fifteen significant figures
    • Stored using 64 bits


    Example:
    public static void main(String[] args) {
    		float myFloat;
    		double myDouble;
     
    		System.out.println("Amount of bits to represent a float:" + Float.SIZE);
    		System.out.println("Amount of bits to represent a double:" + Double.SIZE);
     
    		myFloat = 4;
    		myFloat = 12.1; //INVALID
    		myFloat = 12.1f; //valid
     
    		myDouble = 10; //valid
    		myDouble = 34.5; //valid
    		myDouble = 15.5D; //valid
    		myDouble = -1223222222222222222222222222222222222222222222222222222222.3; //valid
     
    	}


    When using floats, which are not whole, you should always end the assignment with a higher, or lower case ‘F’.
    When using double, the placement of ‘D’ at the end is only optional and not a requirement.


    Output:
     

    Amount of bits to represent a float:32
    Amount of bits to represent a double:64








    Char (16 bits)

    The char data type is used to store characters.
    Each character has its own unique internal code value, which you will see demonstrated in the example.

    Firstly take a look at the following image, and navigate your way to number 65 under decimal. You should notice that it relates to the character uppercase ‘A’.


    Hopefully you will be able to see what’s going on in this program now:


    	public static void main(String[] args) {
    		char myFirstChar;
    		myFirstChar = 65; // A
    		System.out.println(myFirstChar);
    		myFirstChar += 1; // increment by 1 - to 'B'
    		System.out.println(myFirstChar);
     
    		char mySecondChar = 'Z'; //valid
    		mySecondChar = 'ZA'; //INVALID
    		mySecondChar = "C"; //INVALID
     
    	}

    Output:
     

    A
    B




    Notice that the only valid methods of using a char is to:
    assign it a number, which represents a character from the ASCII table or
    to declare a single character within apostrophes. The use of quotation marks is not legal in this occasion.







    Boolean
    A boolean is a data type which can only have two values, true or false.
    Both true and false are case sensitive, and should always be the lowercase.
    This data type represents one bit of information, but its "size" isn't something that's precisely defined.

    Here’s an example of how to use the boolean data type, and situations where they can be useful:


    public static void main(String[] args) {
    		boolean falseBoolean = false;
    		boolean trueBoolean = true;
     
    		System.out.println("falseBoolean is: " + falseBoolean);
    		System.out.println("trueBoolean is: " + trueBoolean);
     
    		int x = 0;
    		while (trueBoolean) { //while true
    			x++; // increment by 1
    			System.out.println("X incremented to: " + x);
    			if (x == 5) {
    				trueBoolean = false;
    			}
    		}
    		System.out.println("END");
    	}


    Output:
     

    falseBoolean is: false
    trueBoolean is: true
    X incremented to: 1
    X incremented to: 2
    X incremented to: 3
    X incremented to: 4
    X incremented to: 5
    END









    Now that the basic details of each type has been covered, lets discuss their uses.

    byte vs short vs int vs long

    For most programs, the int data type should be sufficient for holding numerical data, so in most cases, the only time you need to stray away from int is when:
    A) Your values exceed the limit of an int, where you would use long.
    B) Your program has memory restraints, so to save memory, you would use, short or byte… depending on the range of the values you need to store.


    float vs double

    If you wish to store a decimal number to 5 significant figures, a float might be best here, but say
    you wish to store a decimal number up to 10 significant figures, you would use a double.
    Either way, for decimal values, double is the default choice for most programmers.

    Please note that although these data types support decimal values, they should not be used for currency due to the precision loss that may incur.
    When dealing with large amounts of currency, the best approach is to use BigDecimal.


    Boolean & Char

    As the boolean data type only stores true or false, Its uses are to act as flags in basic true or false conditions, such as loop conditions or logical conditions.

    The char data type can be used for quite a few things, but usually It calls for a certain occassion when they are actually required. Some of the most basic
    times to use this data type can be for the use of a Switch statement.



    Arithmetic operations

    For all the numeric types, all of the following arithmetic operations can be executed:
    • Multiplication ( * )
    • Division ( / )
    • Addition ( + )
    • Subtraction ( - )
    • Remainder ( % )


    These operators are commonly used while programming, so be sure to make the most of them.





    As this tutorial is mean't to be a brief, compact introduction to primitive data types, It obviously won't cover everything.
    I would still recommend you visit Oracle's official tutorial to find out more.
    Primitive Data Types




    All form of feedback, corrections will be appreciated, I'd make sure to correct / improve spelling or factual information.
    Thanks.
    Last edited by newbie; August 23rd, 2011 at 04:03 PM.
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  2. The Following 4 Users Say Thank You to newbie For This Useful Post:

    B33R4NG (July 5th, 2012), JavaPF (August 23rd, 2011), Json (August 22nd, 2011), Qcoderz (March 27th, 2012)


  3. #2
    Junior Member
    Join Date
    Aug 2011
    Location
    Jalgaon
    Posts
    1
    My Mood
    Amazed
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Tutorial: Primitive Data Types

    still it's great tutorial.

  4. #3
    Banned
    Join Date
    Feb 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Tutorial: Primitive Data Types

    Ok thanks to you.

  5. #4
    Junior Member B33R4NG's Avatar
    Join Date
    Jul 2012
    Posts
    3
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default

    Very "newbie" friendly. Thanks again for your hard work!

Similar Threads

  1. [SOLVED] Enum types, how does he know %s value?
    By beer-in-box in forum Java Theory & Questions
    Replies: 11
    Last Post: September 17th, 2011, 12:47 PM
  2. Enumerated Types
    By mushy in forum Object Oriented Programming
    Replies: 3
    Last Post: January 27th, 2011, 10:06 AM
  3. Replies: 4
    Last Post: September 5th, 2010, 10:29 AM
  4. Incompatible Types
    By Kimimaru in forum What's Wrong With My Code?
    Replies: 3
    Last Post: June 28th, 2010, 09:52 AM
  5. Fitting a large primitive into a small reference variable
    By Phobia in forum Java Theory & Questions
    Replies: 15
    Last Post: October 23rd, 2009, 03:10 PM