0% found this document useful (0 votes)
55 views

Chapter 2 Data Types in Java

There are two types of data types in Java: primitive and non-primitive. Primitive types include boolean, char, byte, short, int, long, float, and double. Non-primitive types include classes, interfaces, and arrays. Variables must be declared before use and specify a type. There are rules for valid identifiers in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

Chapter 2 Data Types in Java

There are two types of data types in Java: primitive and non-primitive. Primitive types include boolean, char, byte, short, int, long, float, and double. Non-primitive types include classes, interfaces, and arrays. Variables must be declared before use and specify a type. There are rules for valid identifiers in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Data Types in Java

Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:

Primitive data types: The primitive data types include Boolean, char, byte, short, int, long, float
and double.

Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language.

All variables must be declared before its use. That is why we need to declare variable's type and
name.

There are 8 types of primitive data types:

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

The Boolean data type is used to store only two possible values: true and false. This data type is
used for simple flags that track true/false conditions.

Example: boolean isJavaFun = true;

boolean isJavaHard = false;

System.out.println (isJavaFun); // Outputs true

System.out.println (isJavaHard); // Outputs false

Int Data Type

The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in
our tutorial, the int data type is the preferred data type when we create variables with a numeric
value. Its default value is 0.
Example: int myNum = 100000;

System.out.println (myNum);

Float Data Type

Float data type is used whenever we need a number with a decimal, such as 9.99 or 3.14515.

The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should
end the value with an "f":

Example: float myNum = 5.75f;

System.out.println (myNum);

Double Data Type

The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you
should end the value with a "d":

Example: double myNum = 19.99d;

System.out.println (myNum);

Char Data Type

The char data type is used to store a single character. The character must be surrounded by single
quotes, like 'A' or 'c':

Example: char myGrade = 'B';

System.out.println (myGrade);
Note:

The main difference between primitive and non-primitive data types are:

1. Primitive types are predefined (already defined) in Java. Non-primitive types are created
by the programmer and is not defined by Java (except for String).
2. Non-primitive types can be used to call methods to perform certain operations, while
primitive types cannot.
3. A primitive type has always a value, while non-primitive types can be null.
4. A primitive type starts with a lowercase letter, while non-primitive types starts with an
uppercase letter.
5. The size of a primitive type depends on the data type, while non-primitive types have all
the same size.
Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.

User Defined Datatypes

User defined datatypes are also called non-primitive data types because they are those types of
datatypes which are defined by users or programmers.

Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.

Java Class

A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

o Methods
o Constructors
o Nested class and interface
.. Java class having single class

Public class First{

……………………

Public static void main(String args[])

………………..

.. Java class having multiple class

Class Third{

…………….

Class second{

……………

Public class First{

Public static void main(String args[])

{
…………..

Variables in Java

A variable is a container which holds the value while the Java Program is executed. A variable is
assigned with a data type.

There are three types of variables in Java:

o local variable
o instance variable
o static variable

Local Variables

 Local variables are declared in methods, constructors, or blocks.

 Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor, or block.

 Access modifiers cannot be used for local variables.

 Local variables are visible only within the declared method, constructor, or block.

 There is no default value for local variables, so local variables should be declared and an
initial value should be assigned before the first use.

Example

Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to
only this method.
public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
test.pupAge();
}
}

This will produce the following result −

Output
Puppy age is: 7
Example

Following example uses age without initializing it, so it would give an error at the time of
compilation.

public class Test {


public void pupAge() {
int age;
age = age + 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
test.pupAge();
}
}

This will produce the following error while compiling it −

Output
Test.java:4:variable number might not have been initialized
age = age + 7;
^
1 error

Instance Variable

 Instance variables are declared in a class, but outside a method, constructor or any block.

 Instance variables are created when an object is created with the use of the keyword 'new'
and destroyed when the object is destroyed.

 Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present throughout
the class.

 Instance variables can be declared in class level before or after use.

 Access modifiers can be given for instance variables.

 The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private (access level). However,
visibility for subclasses can be given for these variables with the use of access modifiers.

 Instance variables have default values. For numbers, the default value is 0, for Booleans it
is false, and for object references it is null. Values can be assigned during the declaration
or within the constructor.
Example

public class InstVariable {

int sum; //sum is an instance variable

void f1()

int a=5,b=6;

sum = a+b;

System.out.println ("Add = "+ sum);

public static void main(String[] args) {

InstVariable i1 = new InstVariable();

i1.f1();

Static Variable

 Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.

 Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final, and static. Constant variables never
change from their initial value.

 Static variables are stored in the static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the program
stops.

 Visibility is similar to instance variables. However, most static variables are declared
public since they must be available for users of the class.

 Default values are same as instance variables. For numbers, the default value is 0; for
Booleans, it is false; and for object references, it is null. Values can be assigned during
the declaration or within the constructor. Additionally, values can be assigned in special
static initializer blocks.

 When declaring class variables as public static final, then variable names (constants) are
all in upper case. If the static variables are not public and final, the naming syntax is the
same as instance and local variables.

Examples

public class StaticClass {

static String sum = "Sum of a and b is";

public static void main(String[] args) {

int a = 5,b=4,c;

c=a+b;

System.out.println("sum = "+c);

}
Constants

A constant is a variable whose value cannot change once it has been assigned. Java doesn't have
built-in support for constants. A constant can make our program more easily read and
understood by others. To define a variable as a constant, we just need to add the keyword “final”
in front of the variable declaration.

Identifiers

Identifiers in Java are symbolic names used for identification. They can be a class name, variable
name, method name, package name, constant name, and more. However, In Java, There are some
reserved words that can not be used as an identifier.

Rules for Identifiers

o A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and underscore(_)
or a dollar sign ($). for example, @bca2ndsem is not a valid identifier because it contains
a special character which is @.
o There should not be any space in an identifier. For example, bca 2ndsem is an invalid
identifier.
o An identifier should not contain a number at the starting. For example, 123bca is an invalid
identifier.
o An identifier should be of length 4-15 letters only. However, there is no limit on its length.
But, it is good to follow the standard conventions.
o We can't use the Java reserved keywords as an identifier such as int, float, double, char,
etc. For example, int double is an invalid identifier in Java.
o An identifier should not be any query language keywords such as SELECT, FROM,
COUNT, DELETE, UPDATE etc.

Literals

Literal in Java is a synthetic representation of boolean, numeric, character, or string data. It is a


means of expressing particular values in the program, such as an integer variable named ‘’/count
is assigned an integer value in the following statement.

int count = 0;

A literal ‘0’ represents the value zero.


Thus, a constant value assigned to the variable can be referred to as literal.
Literals in Java can be classified into six types, as below:
1. Integral Literals
2. Floating-point Literals
3. Char Literals
4. String Literals
Example: String name = “BCA”;
5. Boolean Literals
Type conversion in Java

When you assign value of one data type to another, the two types might not be compatible with
each other. If the data types are compatible, then Java will perform the conversion automatically
known as Automatic Type Conversion and if not then they need to be casted or converted
explicitly. For example, assigning an int value to a long variable.

Widening or Automatic Type Conversion

Widening conversion takes place when two data types are automatically converted. This happens
when:

The two data types are compatible.

When we assign value of a smaller data type to a bigger data type.

For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.

Example:

class Test

public static void main(String[] args)

int i = 100;
// automatic type conversion

long l = i;

// automatic type conversion

float f = l;

System.out.println("Int value "+i);

System.out.println("Long value "+l);

System.out.println("Float value "+f);

Output:

Int value 100

Long value 100

Float value 100.0

Narrowing or Explicit Conversion

If we want to assign a value of larger data type to a smaller data type we perform explicit type
casting or narrowing.

This is useful for incompatible data types where automatic conversion cannot be done.

Here, target-type specifies the desired type to convert the specified value to.
char and number are not compatible with each other. Let’s see when we try to convert one into
other.

//Java program to illustrate incompatible data

// type for explicit type conversion

public class Test

public static void main(String[] argv)

char ch = 'c';

int num = 88;

ch = num;

Error:

7: error: incompatible types: possible lossy conversion from int to char

ch = num;

1 error

Explicit Type conversion

//Java program to illustrate explicit type conversion

class Test
{

public static void main(String[] args)

double d = 100.04;

//explicit type casting

long l = (long)d;

//explicit type casting

int i = (int)l;

System.out.println("Double value "+d);

System.out.println("Long value "+l);

System.out.println("Int value "+i);

Output:

Double value 100.04

Long value 100

Int value 100

You might also like