DATA TYPES IN JAVA
What if you have number of different kinds of balls (tennis,
cricket, golf, and synthetic) lying in front of you in a ground and you are
told to separate them and put them in 4 separate buckets? You will probably put
the same kind of balls in one bucket. Similarly, Datatypes are used to store
different types of data values in a variable. Java, being rich in datatypes is
classified into two types of datatypes. First, Primitive data type and second,
Non-primitive data types.
Primitive data types
These are the intrinsic datatypes , and are predefined in
Java libraries. There are total eight datatypes in java.
Integer types:
There are four types of integer datatypes namely, byte,
short, int & long, having different range and size(refer to the table,
below) . The use of datatype which acquires lesser size on disk and sufficient
to store the value is always recommended ,since using bigger sized datatypes
increases a lot of time to run the code.
Syntax:
byte num1=1;
short num2=2;
int num3= 3;
int num4= 4;
Floating Point Types:
Float and double are two types of similar datatypes in Java,
both representing floating point types values. But apart from having different sizes, float
values are single type precision and double values are double type precision,
in short ,double is more precise.
Note: while assigning a float value to the variable, the
value must be followed by the letter f;
Ex: float floatNumber =
1.71f;
Char Datatype:
Char datatype is used to store characters in a variable. It is
used to store a single character.
Note: while assigning a character value to the variable it
must be closed within single quotes. The char datatype type can store any
character including whole number and special characters.
Ex: char newChar = ‘c’;
Boolean Datatypes:
Boolean datatypes are used to check whether a particular
condition is true or not. It can store either of the two values, i.e., true or
false.
Syntax: boolean result= true;
or
boolean result =false;
Data type Size Minimum value Maximum value
byte |
One bytes |
-128 |
127 |
short |
Two bytes |
-32,768 |
32,767 |
int |
Four bytes |
-2,147,483,648 |
2,147,483,647 |
long |
Eight bytes |
-9,223,372,036,854,775,808 |
9,223,372,036,854,775,807 |
float |
Four bytes |
3.4e-038 |
1.7e+0.38 |
double |
Eight bytes |
3.4e-038 |
1.7e+308 |
char |
Two bytes |
- |
- |
boolean |
One bytes |
- |
- |
Non-primitive Datatypes in Java
·
Non-primitive datatypes are different from primitive
ones as they do not store actual value, instead they use the reference of the
actual values.
·
Primitive datatypes are predefined in Java, whereas Non-primitive ones are those
which are defined by the user(except for Strings).
·
There are 4 types of non primitive datatypes in java,
i.e., Strings, Arrays, Classes and interface.
STRINGS
Strings are one of the most important and commonly used
non-primitive datatype in Java. Strings are used to store series of characters
in a variable.
Two ways of creating a String variable in Java
i) By using ‘new’ keyword
String myStr = new String(“Hello”);
ii) By using just String literals
String myStr ="Hello";
The difference between
declaring the same in two different ways is quite prominent and is often asked
in interviews of some big techies. So let’s talk about it.
There are two areas in the memory location regarding Strings.
i) String Heap Area
ii) String Pool Area
Below is the image which explains the two memory locations
regarding the string.
String Pool Area:
When a String is created by just using the literals (ex:
String myStr= “Hello”;), the value of the string is stored in string pool area
and not in the string heap area. Also, if there are more than one strings (which
are also created by using literals only) , having the same value, then only one
value of all the common valued strings will be stored in the string pool area
and other strings will be using it. The images below will surely help in
elaborating the concept:
String Heap Area:
If a string is created using a ‘new’ keyword then its value
is stored in the string pool area as well as in the string heap area. But
again, if there is a same value of any other string already stored in the
string pool area, then that common value
will not be stored again. Also if the string is created using ‘new’ keyword
then( unlike string pool area) each time the value will be stored in the string
heap area irrespective of the fact that there is a same value of any other string
already stored in the string heap area or not.
String Indexing
Strings in java can range from tiny to huge, having said
that, we can access each and every member of a string using their respective
index. Index is nothing but the place of the elements in strings. The only thing
one has to keep in mind is that, indexes always start from 0, not 1 and the
same case applies for arrays which we will be looking forward to, next. We can
also access the index of any character using ‘stringName.indexOf(‘character’)’
in Java. Let’s understand about index
with the help of an example.
Ex:
String myString = "Coding Winds";
System.out.println(myString.indexOf('C'));
System.out.println(myString.indexOf('o'));
System.out.println(myString.indexOf('d'));
System.out.println(myString.indexOf('i'));
System.out.println(myString.indexOf('n'));
System.out.println(myString.indexOf('g'));
System.out.println(myString.indexOf(' '));
System.out.println(myString.indexOf('W'));
System.out.println(myString.indexOf('i'));
System.out.println(myString.indexOf('n'));
System.out.println(myString.indexOf('d'));
System.out.println(myString.indexOf('s'));
OUTPUT SCREEN :
Now if you will notice the output, you will see that the
index of any character which is occurring more than once in the string, is the
index of the position at which they occur for the first time.
So for this case we can also put the starting index in the
‘indexOf()’ method after the letter , separated by a comma. So the search for
the character will start from the mentioned index.
Ex:
String myString = "Coding Winds";
System.out.println(myString.indexOf('C'));
System.out.println(myString.indexOf('o'));
System.out.println(myString.indexOf('d'));
System.out.println(myString.indexOf('i'));
System.out.println(myString.indexOf('n'));
System.out.println(myString.indexOf('g'));
System.out.println(myString.indexOf(' '));
System.out.println(myString.indexOf('W'));
System.out.println(myString.indexOf('i',5));
System.out.println(myString.indexOf('n',5));
System.out.println(myString.indexOf('d',5));
System.out.println(myString.indexOf('s'));
OUTPUT SCREEN :
NOTE: The empty spaces (“ “) in Strings also have an index in Java.
ARRAYS
Arrays are collections of same kind of data values, stored in
a contiguous blocks of memory location, represented by a single variable. Arrays
are similar concept to strings, these
are the kind of non-primitive data types which are not predefined in Java. So
to understand it conceptually let’s jump right into the example.
Creating an Array
Array can be declared into two ways:
i) int marks[]=new int[5];
ii) int[] marks = new int[5];
note: here 5 tells us the length of an array & marks
is the variable representing the array of length 5.
Likewise Strings , Arrays follow the same rule for indexing
in java.
Initializing an Array
Arrays can be intialised in two ways:
i)
int marks[]={76,48,81,56,91};
ii)
int marks[]=new int[5];
marks[0]=76;
marks[1]=48;
marks[2]=81;
marks[3]=56;
marks[4]=91;
The above two arrays named ‘marks’ stores the collection of
marks of 5 students. Both the initialisations are same, the only difference is
that in first one we are initialising the whole array at once, and in the
second one we are initialising each and every index of the array one by one.
Also, like any other variable we can play with any of the
elements of the array or modify its value.
Ex:
int a=marks[2]+9;
System.out.print(a);
Output :
90
Taking user input in array
i)Taking the input for each index:
Taking the input of an array for each index can result in a
lengthy code, though the user can use this way for any array of small length
(such as 3).
Ex:
String cars[] = new String[3];
cars[1]=sc.nextInt();
cars[2]=sc.nextInt();
cars[3]=sc.nextInt();
Note: ‘sc.nextInt()’ is use to fetch integer-inputs from the user
during an output. We will talk about user inputs in details in the upcoming
blogs.
ii)Taking the input by using for loops:
Loops are used to do a certain task for a specified number of
times in a code, until a certain condition becomes false. We will talk about
loops in details in the next article. First of all let us understand how a ‘for
loop’ works in a program.
Syntax:
for(initialisation; condition; increment/decrement){
//CODE
}
So basically in a ‘for loop’ the set of statements or code
(within the brackets) is iterated specified number of times until the given
condition becomes false. Similarly for taking input in an array using a for
loop we will run the loop until the every index of the array gets a certain
value by the user. Let us have a look at a example.
String cars[] = new String[3];
for(int i=0; i<3; i++){
cars[i]=sc.nextInt();
}
In the above example, inside the for loop round brackets we
have an int variable assigned to zero, the second statement checks the condition
whether the value of the integer has reached the value of the length of the
array or not and the third statement increments the value of the integer ‘i’ ,
every time the loop starts. Note that the loop will always run up to n-1 times
where n is the length of that array, since the indexes of arrays start from 0.
Below is the elaborated explanation of how the loop will work and the user will
be allowed for the input until the last index place of the array .
for(int i=0; i<3; i++){
// cars[0]
= sc.nextInt();
// cars[1]= sc.nextInt();
System.out.println(cars[i]); // cars[2]= sc.nextInt();
// At i=3, loop will break
}
(since the loop is set to work until
i<3, this time the iteration will not work)
For displaying the loops to the output screen after the array
has collected the data by the user as inputs, one can use the ‘for loops’ one
again.
Ex:
for(int i=0; i<3; i++){
System.out.println(cars[i]);
}
Note: Instead of using ‘i<3’ the user can also use
‘i<cars.length’. ‘arrayName.length’ function allows the user to take
or store the length of any given array inside a variable.
Ex:
int n=cars.length;
Note: We will discuss more about loops in the upcoming articles.
CLASSES
Classes is one of the basic concepts of Java as OOPs which allows the user
to represent methods in it.
Classes are the set of blocks which can be considered as the prototype or
blueprint representing number of methods and their bodies, from which objects
can be created. Classes are everything in a Java program, as we begin our code
with a class. Additional classes can be added as per the requirement.
Public classes
Syntax:
public class Coding_Winds {
}
The keyword "public" is a modifier here tells that the class is
public and it is visible to and can be accessed by any other class in the
program, by the user. Also there can only be one public class in one
program, in java.
Static classes
Syntax:
static class Coding_Winds {
}
The keyword "static" is a modifier here, tells that the class is
a local class or inner class and these
are used as the nested classes within other classes in a program.
Note: We’ll talk more about in OOPs.
INTERFACES
An interface is a set of blocks which contains method reference (or
abstract) in it. It is quite similar to classes in java but unlike classes, it
contains only abstract methods or the method name and not the actual method. The
purpose of an interface is to hide certain information, and only make the
important information available (that is in the interface). Look for the
example below which tells us how to write an interface in java.
Ex:
interface Cars{
void Lamborghini();
void Porsche();
}
After writing the interface in the program, we can implement it by the
classes and write the actual bodies of the methods inside the classes. For
implementing the an interface we can simply use the keyword ‘implements’ after
the class name.
Ex:
interface Cars{
void Lamborghini();
void Porsche();
}
class Car implements Cars{
public void Lamborghini() {
System.out.println("A Lambo is probably the
dream car for everyone");
}
public void Porsche() {
System.out.println("Hey, Porsche is really fast dude");
}
}
public class Coding_Winds {
public static void main(String[] args) {
Car myCar = new Car();
myCar.Lamborghini();
myCar.Porsche();
}
}
On Running the above code, we will receive the following output :
A Lambo is probably the dream car for everyone Hey, Porsche is really fast dude Multiple Classes Java gives us the comfort of implementing multiple interfaces in a classes,
which is not the case with classes (we’ll talk about extending a class and
super classes in OOPS). Just after the
first interface name (after the keyword ‘interfaces’, we can put the name of
the second interface after a comma. The example below with elaborate the
implementation of multiple interfaces in a class. interface Cars{ void Lamborghini(); void Porsche(); } interface LuxuryCars{ void RollsRoyace(); void Maybach(); } class Car implements Cars, LuxuryCars{ public void Lamborghini() { System.out.println("A Lambo is probably the
dream car for everyone"); } public void Porsche() { System.out.println("Hey, Porsche is really fast dude"); } public void Maybach() { System.out.println("Maybach is a really
comfortable car"); } public void RollsRoyace() { System.out.println("RollsRoyace is a luxurious.
You can't ask more"); } }
public class Coding_Winds {
public static void main(String[] args) { Car myCar = new Car(); myCar.Lamborghini(); myCar.Porsche(); myCar.Maybach(); myCar.RollsRoyace(); } } OUTPUT : A Lambo
is probably the dream car for everyone Hey,
Porsche is really fast dude Maybach
is a really comfortable car
RollsRoyace has everything
in luxury. You can't ask more By default interface attributes
are public, static and final.
Note: Unlike classes you cannot
create an object out of an interface and it cannot contain a constructor
either. |
Hope you are clear on this topic do read our more articles on JAVA LANGUAGE.
If you still have any doubt on this topic then do come to us via email "sophomoretechs@gmail.com" or via Instagram "@coding.winds".
This article is SUBMITTED By : Pranjal Rai
Do subscribe to our daily blog update by clicking here.
Thank You!
No comments:
Post a Comment