Data types in java refer to type of data that can be stored in variable. As Java is strongly typed language, you need to define datatype of variable to use it and you can not assign incompatible datatype otherwise the compiler will give you an error.
1
2
3
|
int d="Hello"
|
The compiler will give you an error with this message – “Type mismatch: cannot convert from String to int”.
There are two types of data types in java.
There are two types of data types in java.
- Primitive data types
- Referenced data types.
Primitive data types:
Primitive data types are those datatypes which are defined by java language itself.
There are 8 primitive data types in java.
Data Type | Default Value | Default size |
---|---|---|
boolean | false | 1 bit |
char | ‘\u0000’ | 2 byte |
byte | 0 | 1 byte |
short | 0 | 2 byte |
int | 0 | 4 byte |
long | 0L | 8 byte |
float | 0.0f | 4 byte |
double | 0.0d | 8 byte |
Let’s see some example about data types:
Adding two integers:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package org.arpit.java2blog;
public class DataTypesDemo {
public static void main(String[] args) {
int a=10;
int b=20;
int c=a+b;
System.out.println(c);
}
}
|
When you run above program, you will get below output:
30
Assigning int to double(Widening):
Here we will assign int to double. As double takes more memory than int. This is widening operation.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package org.arpit.java2blog;
public class DataTypesDemo {
public static void main(String[] args) {
int a=30;
double b=a;
System.out.println(a);
System.out.println(b);
}
}
|
When you run above program, you will get below output:
30
30.0
30.0
Assigning double to int(Narrowing or typecasting):
Here we will assign double to int. As double takes more memory than int. This is Narrowing operation.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package org.arpit.java2blog;
public class DataTypesDemo {
public static void main(String[] args) {
double a=30.0;
int b=(int) a;
System.out.println(a);
System.out.println(b);
}
}
|
When you run above program, you will get below output:
30.0
30
30
Assinging int to byte(Overflow condition):
When you assing int to byte and value of int is larger than size of byte then it is a case of overflow.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package org.arpit.java2blog;
public class DataTypesDemo {
public static void main(String[] args) {
int a=200;
byte b=(byte) a;
System.out.println(a);
System.out.println(b);
}
}
|
When you run above program, you will get below output:
200
-56
-56
Reference data types:
Reference data types are those data types which are provided as class by Java API or by class that you create.
String is example of Reference data types provided by java.
String is example of Reference data types provided by java.
That’s all about data types in java.
0 Comments
If you have any doubts,please let me know