Skip to main content

Data Types in Java

Session 1 - Data Types in Java

What is Data ?
 Most of you have shopped online and this is what a typical purchase looks like

  1.     You select a product which has a Price, Tax, Quantity
  2.     You pay using your Credit Card by entering Name, CC Number, Expiration Date, Billing    Address, Zipcode
Words above in Bold are data.


What is then Data Type ?
   Can we say Price, Tax, Quantity is of type Number because we can apply Arithmetic (+, -, /, *, %) Operations on them, i.e. we multiply Price Quantity and than add Tax.
Similarly Your Name, Address are text because it doesn't make sense to have Arithmetic Operation on them and in Java we call them String.



Supported Data Types in Java
  String   -  Text
  double  - Real Numbers i.e. 33.2, 20.0 etc
  int         - Non-Real Numbers i.e. 10, 30, 3453 etc



Typical Java Programs using the above Data Types

public class DataTypesDemo {
    public static void main(String[] args) {

        // define a Data Variable message of type String
        String message = "Hello World!";
        
        // print to console i.e. black screen
        System.out.println(message);
    }
}

        Code Snippet - 1

        // define a Data Variables of type int
        int x = 10;
        int y = 20;
        int z = x + y;
        // print to console i.e. black screen
        System.out.println(z);

        Code Snippet - 2
       // define a Data Variables of type int
        double x = 10.0;
        double y = 20.0;
        double z = x + y;
        // print to console i.e. black screen
        System.out.println(z);
  
Question for you.
  what type is Phone No. (i.e. int or String) ?
    Its String since you will never apply Arithmetic Operations on it.

Homework
There are few others Data Types which I missed that can be found in any book. 

Comments

Jon said…
I know this is an 'introduction', but Java Doubles are NOT real numbers! They are _approximations_ of Real numbers! Doubles/Floats should NEVER under any circumstance be used for prices! Watch the movie Office Space for an explanation... or try this code at home:

public static void testSomething() {
double maybeOne = .1 * 10;
System.out.println("Does .1 x 10 = 1 in floating point math?");
System.out.println(maybeOne == 1);
System.out.println("Actual Value:" + maybeOne);

maybeOne = .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1;
System.out.println("How about if we add .1 ten times?");
System.out.println(maybeOne == 1);
System.out.println("Actual Value:" + maybeOne);
}

Output:

Does .1 x 10 = 1 in floating point math?
true
Actual Value:1.0
How about if we add .1 ten times?
false
Actual Value:0.9999999999999999
Jon said…
Good post other than that small technical error!
Its also advisable to use BigDecimal instead of float and double if you are doing price calculation. also checking float value in loop or if condition could result in erroneous comparison .

Javin
An Example of using ArrayList in Java 1.5 with generics
Somnath Kayal said…
good blog & here also a good blog which describe the data types in java in a clear diagram, so people can easily read and understand.

Popular posts from this blog

Access multiple Databases in JPA

According to JPA specification we can define multiple "persistence-unit" elements (i.e. like below) in persistence.xml file and can easily refer them inside Dao layers as this. public class PolarDaoImpl {     @PersistenceContext(unitName="PolarPU")     protected EntityManager entityManager; -- } public class BearDaoImpl {     @PersistenceContext(unitName="BearPU")     protected EntityManager entityManager; -- } Checkout sample persistence.xml <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">     <!-- Database 1 -->     <persistence-unit name="PolarPU" transaction-type="RESOURCE_LOCAL">         <

JPA 2 new feature @ElementCollection explained

@ElementCollection is new annotation introduced in JPA 2.0, This will help us get rid of One-Many and Many-One shitty syntax. Example 1: Stores list of Strings in an Entity @Entity public class Users implements Serializable {     private static final long serialVersionUID = 1L;     @Id     @GeneratedValue(strategy = GenerationType.AUTO)     private Long id;     @ElementCollection     private List<String> certifications = new ArrayList <String> ();     public Long getId() {         return id;     }     public void setId(Long id) {         this.id = id;     }     public List <String> getCertifications() {         return certifications;     }     public void setCertifications(List <String> certifications) {         this.certifications = certifications;     } .. }         Users u = new Users();         u.getCertifications().add("Sun Certified Java Programmer");         em.persist(u); Generated Tables    Users    Co

Reuse JPA Entities as DTO

Note : Major design advantages of JPA Entities are they can detached and used across tiers and networks and later can by merged. Checkout this new way of querying entities in JPA 2.0 String ql = " SELECT new prepclass2.Employee (e.firstname, e.lastname) FROM Employee e "; List<Employee> dtos = em.createQuery(ql).getResultList(); The above query loads all Employee entities but with subset of data i.e. firstname, lastname. Employee entity looks like this. @Entity @Table(name="emp") public class Employee implements Serializable {     private static final long serialVersionUID = 1L;     @Id     @GeneratedValue(strategy = GenerationType.AUTO)     private Long id;     @Column     private String firstname;     @Column     private String lastname;     @Column     private String username;     @Column     private String street;     @Column     private String city;     @Column     private String state;     @Column     private String zipc