You are on page 1of 8

Data types are divided into two groups:

 Primitive data types -


includes byte, short, int, long, float, double, boolean and char
 Non-primitive data types - such as String, Arrays and Classes 

 A primitive data type specifies the size and type of variable values, and it
has no additional methods.
 There are eight primitive data types in Java:

Data Type Size Description

byte 1 byte Stores whole numbers from -128 to 127

short 2 bytes Stores whole numbers from -32,768 to 32,767

int 4 bytes Stores whole numbers from -2,147,483,648 to


2,147,483,647

long 8 bytes Stores whole numbers from


-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7


decimal digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15


decimal digits

boolean 1 bit Stores true or false values

char 2 bytes Stores a single character/letter or ASCII values


Numbers

Primitive number types are divided into two groups:

Integer types stores whole numbers, positive or negative (such as 123 or


-456), without decimals. Valid types are byte, short, int and long. Which type
you should use, depends on the numeric value.

Floating point types represents numbers with a fractional part, containing one


or more decimals. There are two types: float and double.

Non-primitive data types are called reference types because they refer to


objects.

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

 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).
 Non-primitive types can be used to call methods to perform certain
operations, while primitive types cannot.
 A primitive type has always a value, while non-primitive types can
be null.
 A primitive type starts with a lowercase letter, while non-primitive types
starts with an uppercase letter.
 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.

Variables naming convention in java

1) Variables naming cannot contain white spaces, for example: int number = 100;
is invalid because the variable name has space in it.
2) Variable name can begin with special characters such as $ and _
3) As per the java coding standards the variable name should begin with a lower
case letter, for example int number; For lengthy variables names that has more
than one words do it like this: int smallNumber; int bigNumber; (start the second
word with capital letter).
4) Variable names are case sensitive in Java.
Java Type Casting

Type casting is when you assign a value of one primitive data type to another
type.

In Java, there are two types of casting:

 Widening Casting (automatically) - converting a smaller type to a larger


type size
byte -> short -> char -> int -> long -> float -> double

 Narrowing Casting (manually) - converting a larger type to a smaller


size type
double -> float -> long -> int -> char -> short -> byte

Widening Casting

Widening casting is done automatically when passing a smaller size type to a


larger size type:

public class MyClass {

public static void main(String[] args) {

int myInt = 9;

double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9

System.out.println(myDouble); // Outputs 9.0

Narrowing Casting

Narrowing casting must be done manually by placing the type in parentheses in


front of the value:

public class MyClass {

public static void main(String[] args) {

double myDouble = 9.78;

int myInt = (int) myDouble; // Manual casting: double to int


System.out.println(myDouble); // Outputs 9.78

System.out.println(myInt); // Outputs 9

Java Strings

Strings are used for storing text.

A String variable contains a collection of characters surrounded by double


quotes:

String greeting = "Hello";

String Length

A String in Java is actually an object, which contain methods that can perform
certain operations on strings. For example, the length of a string can be found
with the length() method:

There are many string methods available, for


example toUpperCase() and toLowerCase():
The indexOf() method returns the index (the position) of the first
occurrence of a specified text in a string (including whitespace):

String txt = "Please locate where 'locate' occurs!";

System.out.println(txt.indexOf("locate")); // Outputs 7

Array

Java provides a data structure, the array, which stores a fixed-size sequential


collection of elements of the same type. An array is used to store a collection of data,
but it is often more useful to think of an array as a collection of variables of the same
type.
Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process
arrays using indexed variables.
To use an array in a program, you must declare a variable to reference the array, and
you must specify the type of array the variable can reference. Here is the syntax for
declaring an array variable −

Syntax
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

System.out.println(cars[0]);

// Outputs Volvo

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

System.out.println(cars.length);

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (int i = 0; i < cars.length; i++) {

System.out.println(cars[i]);

A multidimensional array is an array containing one or more arrays.

To create a two-dimensional array, add each array within its own set of curly
braces:

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

int x = myNumbers[1][2];

System.out.println(x); // Outputs 7

ublic class MyClass {

public static void main(String[] args) {

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

for (int i = 0; i < myNumbers.length; ++i) {

for(int j = 0; j < myNumbers[i].length; ++j) {

System.out.println(myNumbers[i][j]);

}
}

}
Types of Variables in Java
There are three types of variables in Java.
1) Local variable 2) Static (or class) variable 3) Instance variable

Static (or class) Variable


Static variables are also known as class variable because they are associated
with the class and common for all the instances of class. For example, If I create
three objects of a class and access this static variable, it would be common for
all, the changes made to the variable using one of the object would reflect when
you access it through other objects.

Example of static variable


public class StaticVarExample {
public static String myClassVar="class or static variable";

public static void main(String args[]){


StaticVarExample obj = new StaticVarExample();
StaticVarExample obj2 = new StaticVarExample();
StaticVarExample obj3 = new StaticVarExample();

//All three will display "class or static variable"


System.out.println(obj.myClassVar);
System.out.println(obj2.myClassVar);
System.out.println(obj3.myClassVar);

//changing the value of static variable using obj2


obj2.myClassVar = "Changed Text";

//All three will display "Changed Text"


System.out.println(obj.myClassVar);
System.out.println(obj2.myClassVar);
System.out.println(obj3.myClassVar);
}
}
Output:

class or static variable


class or static variable
class or static variable
Changed Text
Changed Text
Changed Text
As you can see all three statements displayed the same output irrespective of the
instance through which it is being accessed. That’s is why we can access the
static variables without using the objects like this:

System.out.println(myClassVar);
Do note that only static variables can be accessed like this. This doesn’t apply for
instance and local variables.
Instance variable
Each instance(objects) of class has its own copy of instance variable. Unlike
static variable, instance variables have their own separate copy of instance
variable. We have changed the instance variable value using object obj2 in the
following program and when we displayed the variable using all three objects,
only the obj2 value got changed, others remain unchanged. This shows that they
have their own copy of instance variable.

Example of Instance variable


public class InstanceVarExample {
String myInstanceVar="instance variable";

public static void main(String args[]){


InstanceVarExample obj = new InstanceVarExample();
InstanceVarExample obj2 = new InstanceVarExample();
InstanceVarExample obj3 = new InstanceVarExample();

System.out.println(obj.myInstanceVar);
System.out.println(obj2.myInstanceVar);
System.out.println(obj3.myInstanceVar);

obj2.myInstanceVar = "Changed Text";

System.out.println(obj.myInstanceVar);
System.out.println(obj2.myInstanceVar);
System.out.println(obj3.myInstanceVar);
}
}
Output:

instance variable
instance variable
instance variable
instance variable
Changed Text
instance variable

Local Variable
These variables are declared inside method of the class. Their scope is limited to
the method which means that You can’t change their values and access them
outside of the method.

In this example, I have declared the instance variable with the same name as
local variable, this is to demonstrate the scope of local variables.
Example of Local variable
public class VariableExample {
// instance variable
public String myVar="instance variable";

public void myMethod(){


// local variable
String myVar = "Inside Method";
System.out.println(myVar);
}
public static void main(String args[]){
// Creating object
VariableExample obj = new VariableExample();

/* We are calling the method, that changes the


* value of myVar. We are displaying myVar again after
* the method call, to demonstrate that the local
* variable scope is limited to the method itself.
*/
System.out.println("Calling Method");
obj.myMethod();
System.out.println(obj.myVar);
}
}
Output:

Calling Method

Inside Method

instance variable

If I hadn’t declared the instance variable and only declared the local variable
inside method then the statement System.out.println(obj.myVar); would have
thrown compilation error. As you cannot change and access local variables
outside the method.

You might also like