{"id":76118,"date":"2020-02-05T09:57:28","date_gmt":"2020-02-05T04:27:28","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=76118"},"modified":"2020-02-05T09:57:28","modified_gmt":"2020-02-05T04:27:28","slug":"data-types-in-java","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/","title":{"rendered":"Data Types in Java Programming with Implementation Examples"},"content":{"rendered":"<p>The data-types are the most important basis of any programming language. It is the most important concept for every beginner. The data type is essential to represent the type, nature and set of operations for the value which it stores.<\/p>\n<p>Java data types are the most basic and initial thing you should know before moving towards other concepts of Java. These are very useful in every aspect of Java, either to create a simple program or to develop any application or software.<\/p>\n<p>In this tutorial, we will discuss everything that is essential for learning data types in Java. And, I bet after completing this article, you will not face any difficulty in the topic.<\/p>\n<p>Before starting with Java data types, let&#8217;s first learn about data types in general.<\/p>\n<h3>What is a Data Type in Java?<\/h3>\n<p>In computer science, a data type is an attribute of data that tells the compiler or interpreter how the programmer aims to use the data.<\/p>\n<p>A data type restricts the values that expression, such as a variable or a function, might take. It defines how the values of that data type are stored in memory and what operations can be performed on the data.<\/p>\n<p>Data types incorporate storage categories like integers, floating-point values, strings, characters, etc.<\/p>\n<p><em>For example, if a variable is of \u201cint\u201d data type, then it can hold only integer values.<\/em><\/p>\n<p>Before moving towards the Java Data types, you must know the types of languages.<\/p>\n<p>There are majorly two types of languages:<\/p>\n<p>The first is <strong>statically typed language<\/strong> in which the data type of each variable has to be defined during the compile time. That is, we have to declare the type of the variable before we can use it.<\/p>\n<p>Once we declare a variable of a specific data type, then we cannot change its data type again. However, they can be converted to other types by using explicit type casting in Java, except boolean. Some statically typed languages are <strong>C, C++, C#, Java, <\/strong>and<strong> Scala<\/strong>.<\/p>\n<p><em>For example, if we write <strong>int num = 5<\/strong>;<\/em><\/p>\n<p>Then it means the variable num is of integer type and holds a numerical value and its type will always be the same.<\/p>\n<p>The other is <strong>dynamically typed language<\/strong>. In this type of language, the data types can change with respect to time and the variables are checked during run-time.<\/p>\n<p>Some dynamically typed languages are <strong>Ruby, Python, Erlang, Perl, VB,<\/strong> and <strong>PHP<\/strong>.<\/p>\n<h3>Java Data Types<\/h3>\n<p>Java is a statically typed language. The base of any programming language is its <strong>data types<\/strong> and operators. Java comes with a rich set of both data types and operators, which makes it suitable for any type of programming.<\/p>\n<p>There are two categories of data types in Java:<\/p>\n<ol>\n<li>Primitive Data Types<\/li>\n<li>Non-Primitive DataTypes<\/li>\n<\/ol>\n<h4>1. Primitive Data Types in Java<\/h4>\n<p>As the name suggests, the programming language pre-defines the primitive data types. Primitive types are the most basic data types available in Java. There are 8 primitive data types in Java: <strong>byte, char, short, int, long, float, double<\/strong> and <strong>boolean<\/strong>.<\/p>\n<p>These data types act as the basic building blocks of data manipulation in Java. Primitive data types have a constraint that they can hold data of the same type and have a fixed size. Primitive data types are also called intrinsic data types. We can also perform operations on primitive data types.<\/p>\n<p>All other types of data are derived from primitive data types.<\/p>\n<p>Below diagram shows the complete chart of primitive data types &#8211;<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/primitive-data-types-in-java.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-76162\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/primitive-data-types-in-java.jpg\" alt=\"primitive data types in java\" width=\"792\" height=\"360\" \/><\/a><\/p>\n<p>Here is the classification of primitive data types in Java:<\/p>\n<h5>1.1 Java Characters<\/h5>\n<p>A character is used to store a \u2018single\u2019 character. A single quote must surround a character. The valid Character type is <strong>char<\/strong>. In Java, a character is not an 8-bit quantity but here character is represented by a 16-bit Unicode.<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<p>char myChar = \u2019A\u2019 ;<\/p>\n<p><strong>Size:<\/strong><\/p>\n<p>2 bytes(16 bits)<\/p>\n<p><strong>Values:<\/strong><\/p>\n<p>A single character representing a digit, letter, or symbol.<\/p>\n<p><strong>Default Value:<\/strong><\/p>\n<p>&#8216;\\u0000\u2019 (0)<\/p>\n<p><strong>Range:<\/strong><\/p>\n<p>&#8216;\\u0000&#8217; (0) to &#8216;\\uffff&#8217; (65535)<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class CharDataType\n{\n  public static void main(String args[])\n  {\n    char marks,grade;\n    marks = '8';\n    grade = 'B';\n    System.out.println(\"Marks: \"+marks);\n    System.out.println(\"Grade: \"+grade);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">\n<p>Marks: 8<br \/>\nGrade: B<\/p>\n<\/div>\n<p>We can also perform arithmetic operations on it since it is an unsigned 16-bit type. <strong>For example<\/strong>, consider the following program:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">\/\/ char can be handled like integers\npublic class CharClass\n{\n  public static void main(String args[])\n  {\n    char myChar1 = 'A';\n    char myChar2 = 'B';\n\n    System.out.println(\"myChar1: \" +myChar1);\n    System.out.println(\"myChar2: \" +myChar2);\n    myChar2++; \/\/ valid increment operation\n    System.out.println(\"The Incremented value of myChar2: \" +myChar2);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">\n<p>myChar1: A<br \/>\nmyChar2: B<br \/>\nThe incremented value of myChar2: C<\/p>\n<\/div>\n<h5>1.2 Java Integers<\/h5>\n<p>Integer type stores whole numbers that may be positive or negative and should not contain any decimal places. Valid Integer types are &#8211; <strong>byte, short, int, <\/strong>and<strong> long<\/strong>. What type will be taken depends on the value or range of the variable.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/valid-integer-type-storage-in-java.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-76164\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/valid-integer-type-storage-in-java.jpg\" alt=\"valid integer type storage in java - java data types\" width=\"504\" height=\"302\" \/><\/a><\/p>\n<p><strong>1.2.1 byte\u00a0<\/strong><\/p>\n<p>The byte data type is mostly used in the large arrays which need memory savings. It saves memory as it is 4 times smaller than an int (integer). Sometimes, it can also be used in place of the &#8220;int&#8221; data type, when the value is very small.<\/p>\n<p>The byte data type is an 8-bit signed 2\u2019s complement integers.<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<p>byte myByte1 = -100 ;<br \/>\nbyte myByte2 = 25 ;<\/p>\n<p><strong>Size:<\/strong><\/p>\n<p>1 byte(8 bits)<\/p>\n<p><strong>Values:<\/strong><\/p>\n<p>Positive or negative whole numbers.<\/p>\n<p><strong>Default Value:<\/strong><\/p>\n<p>0<\/p>\n<p><strong>Range:<\/strong><\/p>\n<p>-128 to 127<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class ByteDataType\n{\n  public static void main(String args[])\n  {\n    byte myByte1,myByte2;\n    myByte1 = 127;\n    myByte2 = -48;\n    System.out.println(\"Byte 1: \" +myByte1);\n    System.out.println(\"Byte 2: \" +myByte2);\n    myByte1++; \/\/ Looping back within the range\n    System.out.println(\"Incremented Value of myByte1: \" +myByte1);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">\n<p>Byte 1: 127<br \/>\nByte 2: -48<br \/>\nIncremented Value of myByte1: -128<\/p>\n<\/div>\n<p><strong>1.2.2 short<\/strong><\/p>\n<p>Similar to the byte data type, a short data type is also used to save memory in large arrays. The short data type is a 16-bit signed 2\u2019s complement integer. It is half of an int (integer).<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<p>short myShort = 6000 ;<\/p>\n<p><strong>Size:<\/strong><\/p>\n<p>2 bytes (16 bits)<\/p>\n<p><strong>Values:<\/strong><\/p>\n<p>Positive or negative whole numbers.<\/p>\n<p><strong>Default Value:<\/strong><\/p>\n<p>0<\/p>\n<p><strong>Range:<\/strong><\/p>\n<p>-32768 to 32767<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class ShortDataType\n{\n  public static void main(String args[])\n  {\n    short myShort = 6000;\n    System.out.println(\"myShort: \" + myShort);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">\n<p>myShort: 6000<\/p>\n<\/div>\n<p><strong>1.2.3. int<\/strong><\/p>\n<p>Generally, we prefer to use int data type for integral values unless if there is no issue with memory. The int data type is a 32-bit signed 2&#8217;s complement integer.<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<p>int myNum = 700000 ;<\/p>\n<p><strong>Size:<\/strong><\/p>\n<p>4 bytes (32 bits)<\/p>\n<p><strong>Values:<\/strong><\/p>\n<p>Positive or negative whole numbers.<\/p>\n<p><strong>Default Value:<\/strong><\/p>\n<p>0<\/p>\n<p><strong>Range:<\/strong><\/p>\n<p>&#8211; 2,147,483,648 (-231) to 2,147,483,647 (231 -1)<\/p>\n<p><strong>Note:<\/strong> In Java Standard Edition (SE) 8 version and later, we can use the int data type to represent an unsigned <em>32-bit integer<\/em>, which has value in the range [0, 232-1]. We Use the <em>Integer<\/em> class to use the unsigned int data type of integer.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class IntDataType\n{\n  public static void main(String args[])\n  {\n    int myNum1, myNum2, result;\n    myNum1 = -7000;\n    myNum2 = 90000;\n    result = myNum1 + myNum2;\n    System.out.println(\"Number 1: \" +myNum1);\n    System.out.println(\"Number 2: \" +myNum2);\n    System.out.println(\"Number 1 + Number 2: \" +result);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">\n<p>Number 1: -7000<br \/>\nNumber 2: 90000<br \/>\nNumber 1 + Number 2: 83000<\/p>\n<\/div>\n<p><strong>1.2.4. long\u00a0<\/strong><\/p>\n<p>The long data type is a 64-bit signed 2&#8217;s complement integers. It is used when int data type cannot hold a value. It is 2 times larger than int(integer). We must use <strong>L<\/strong> at the end of the value.<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<p>long myLong = 11000000000L ;<\/p>\n<p><strong>Size:<\/strong><\/p>\n<p>8 bytes (64 bits)<\/p>\n<p><strong>Values:<\/strong><\/p>\n<p>Positive or negative whole numbers.<\/p>\n<p><strong>Default Value:<\/strong><\/p>\n<p>0<\/p>\n<p><strong>Range:<\/strong><\/p>\n<p>-9,223,372,036,854,775,808(-263) to 9,223,372,036,854,775,807(263 -1)<\/p>\n<p><strong>Note:<\/strong> In Java Standard Edition (SE) 8 version and later, we can use the long data type to represent an unsigned <em>64-bit long<\/em>, which has value in the range [0, 264-1]. We use the <em>Long<\/em> class to use the unsigned long data type.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class LongDataType\n{\n  public static void main(String args[])\n  {\n    long myLong1, myLong2, result;\n    myLong1 = 100000000L;\n    myLong2 = 200L;\n    result = myLong1 * myLong2;\n    System.out.println(\"Number 1: \" +myLong1);\n    System.out.println(\"Number 2: \" +myLong2);\n    System.out.println(\"Number 1 * Number 2: \" +result);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">\n<p>Number 1: 100000000<br \/>\nNumber 2: 200<br \/>\nNumber 1 * Number 2: 20000000000<\/p>\n<\/div>\n<h5>1.3 Java Floating-Point Types<\/h5>\n<p>These are the types that store the floating-point values or real numbers, which have floating decimal places.<strong> For example,<\/strong> it can store fractional numbers like 5.5, 100.78, 2090.985, etc. Valid floating-point types are <strong>float<\/strong> and <strong>double<\/strong>.<\/p>\n<p>We will discuss both of them in detail.<\/p>\n<p><strong>1.3.1. float<\/strong><\/p>\n<p>The float data type is a single-precision 32-bit floating-point, based on the IEEE 754 format (single-precision floating-point numbers). We use a float instead of double to store values in a large array of floating-point numbers so as to save memory.<\/p>\n<p>Remember, we should always end the float type value with <strong>f or F<\/strong>, otherwise, the compiler considers it as a double value.<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<p>float myFloat = 256.8f ;<\/p>\n<p><strong>Size:<\/strong><\/p>\n<p>4 bytes (32 bits)<\/p>\n<p><strong>Values:<\/strong><\/p>\n<p>Real numbers up to 7 decimal digits.<\/p>\n<p><strong>Default Value:<\/strong><\/p>\n<p>0.0f<\/p>\n<p><strong>Range:<\/strong><\/p>\n<p>1.40239846 x 10-45 to 3.40282347 x 1038<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class FloatDataType\n{\n \t\tpublic static void main(String args[])\n \t\t{\n \t\t \t\tfloat myFloat1,myFloat2,result;\n \t\t \t\tmyFloat1=1000.666f;\n \t\t \t\tmyFloat2=110.77f;\n \t\t \t\tresult=myFloat1-myFloat2;\n \t\t \t\tSystem.out.println(\"Number1: \"+myFloat1);\n \t\t \t\tSystem.out.println(\"Number2: \"+myFloat2);\n \t\t \t\tSystem.out.println(\"Number1-Number2: \"+result);\n \t\t}\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">\n<p>Number1: 1000.666<br \/>\nNumber2: 110.77<br \/>\nNumber1-Number2: 889.896<\/p>\n<\/div>\n<p><strong>1.3.2. double<\/strong><\/p>\n<p>Generally, we prefer to use the float data type for decimal values unless if there is no issue with memory. As it has a precision up to 15 decimals, it is safe to use double for large calculations. We can <em>optionally<\/em> use the suffix <strong>d<\/strong> or <strong>D<\/strong> to end the floating type value.<\/p>\n<p>That is, both 19.67 and 19.67d are the same. The double data type is a double-precision 64-bit floating-point, based on the IEEE 754 format (double-precision floating-point numbers).<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<p>double myDouble = 256.7879837 ;<\/p>\n<p><strong>Size:<\/strong><\/p>\n<p>8 bytes (64 bits)<\/p>\n<p><strong>Values:<\/strong><\/p>\n<p>Real numbers up to 15 decimal digits.<\/p>\n<p><strong>Default Value:<\/strong><\/p>\n<p>0.0<\/p>\n<p><strong>Range:<\/strong><\/p>\n<p>4.9406564584124654 x 10-324 to 1.7976931348623157 x 10308<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class DoubleDataType\n{\n    public static void main(String args[])\n    {\n        double myDouble1, myDouble2, result;\n        myDouble1 = 48976.8987;\n        myDouble2 = 29513.7812d;\n        result = myDouble1 + myDouble2;\n        System.out.println(\"Number 1: \" +myDouble1);\n        System.out.println(\"Number 2: \" +myDouble2);\n        System.out.println(\"Number 1 + Number 2: \" +result);\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">\n<p>Number 1: 48976.8987<br \/>\nNumber 2: 29513.7812<br \/>\nNumber 1 + Number 2: 78490.6799<\/p>\n<\/div>\n<h5>1.4 Boolean Types<\/h5>\n<p>A boolean data type is a 2-valued data type that is declared with the <strong>boolean<\/strong> keyword. It is capable of storing only two possible values i.e., <strong>true<\/strong> and <strong>false<\/strong>.<\/p>\n<p>This data type is used for flag generations, to check the true or false conditions. Boolean data type stores only 1-bit information and size is not precisely defined.<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<p>boolean myBool = false ;<\/p>\n<p><strong>Size:<\/strong><\/p>\n<p>Machine-dependent<\/p>\n<p><strong>Values:<\/strong><\/p>\n<p>true, false<\/p>\n<p><strong>Default Value:<\/strong><\/p>\n<p>false<\/p>\n<p><strong>Range:<\/strong><\/p>\n<p>true or false<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class BooleanDataType\n{\n  public static void main(String args[])\n  {\n    boolean myBool = true;\n    if(myBool == true)\n      System.out.println(\"I am using a Boolean data type\");\n      System.out.println(myBool);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">\n<p>I am using a Boolean data type<br \/>\ntrue<\/p>\n<\/div>\n<h4>2. Non-Primitive Data Types in Java<\/h4>\n<p>The term non-primitive data type means that these types contain \u201ca memory address of the variable\u201d.<\/p>\n<p>In contrast to primitive data types, which are defined by Java, non-primitive data types are not defined or created by Java but they are created by the programmers.<\/p>\n<p>They are also called<strong> Reference data types<\/strong> because they cannot store the value of a variable directly in memory.Non-primitive data types do not store the value itself but they store a reference or address (memory location) of that value.<\/p>\n<p>They can call methods to perform a particular function. They can also be null.<\/p>\n<p><strong>For example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">long modelNumber = 62548723468;<\/pre>\n<p>Instead of storing the value of modelNumber directly, reference data types in Java will store the address of this variable. So reference data type will store 1003 rather than the actual value. The below diagram explains how the value is stored in a memory area.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/storage-value-in-memory-area.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-76165\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/storage-value-in-memory-area.jpg\" alt=\"storage value in memory area - java data types\" width=\"717\" height=\"369\" \/><\/a><\/p>\n<p>There are many non-primitive data types in Java.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/non-primitive-data-types-in-java.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-76166\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/non-primitive-data-types-in-java.jpg\" alt=\"non-primitive data types in java\" width=\"500\" height=\"468\" \/><\/a><\/p>\n<p>Let us now understand these.<\/p>\n<h5>2.1. Java Strings<\/h5>\n<p>The String data type is used to store a sequence or array of characters (text). But in Java, a string is an <strong>object<\/strong> that represents an array or sequence of characters. The<em> java.lang.String<\/em> is the class is used for creating a string object.<\/p>\n<p>String literals should be enclosed within double-quotes. The difference between a character array and a string is that in the string a special character \u2018\\0\u2019 is present.<\/p>\n<p><strong>Basic Syntax for declaring a string in Java:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">String &lt;String_variable_name&gt; = \u201c&lt;sequence_Of_Strings&gt;\u201d ;<\/pre>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">String myString = \u201cHello World\u201d ;<\/pre>\n<p><strong>Ways to create a string object:<\/strong><\/p>\n<p>There are 2 ways of creating a String object:<\/p>\n<ul>\n<li><em>By using a string literal:<\/em> Java String literal can be created just by using double-quotes. <strong>For <\/strong><\/li>\n<\/ul>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">String myLine = \u201cWelcome to TechVidvan Java Tutorial\u201d;<\/pre>\n<ul>\n<li><em>By using a \u201cnew\u201d keyword:<\/em> Java String can also be created by using a new keyword. <strong>For example:<\/strong><\/li>\n<\/ul>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">String myLine = new String(\u201cWelcome to TechVidvan Java Tutorial\u201d);<\/pre>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class stringTutorial\n{\n  public static void main(String args[])\n  {\n    String string1 = \"Hello World\";\n    \/\/ declaring string using string literals\n    String string2 = new String(\"This is TechVidvan Java Tutorial \");\n    \/\/declaring string using new operator\n    System.out.println(string1);\n    System.out.println(string2);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">\n<p>Hello World<br \/>\nThis is TechVidvan Java Tutorial<\/p>\n<\/div>\n<h5>2.2. Java Arrays<\/h5>\n<p>An Array in Java is a single object which can store multiple values of the same data type. Arrays are homogeneous data structures that store one or more values of a specific data type and provide indexes to access them. A particular element in an array can be accessed by its index.<\/p>\n<p>The below diagram shows the illustration of arrays.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/working-of-java-arrays.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-76167\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/working-of-java-arrays.jpg\" alt=\"working of java arrays - java data types\" width=\"866\" height=\"384\" \/><\/a><\/p>\n<p>A two-step process of creating an array:<\/p>\n<p>Creating an array involves two steps which are:<\/p>\n<ol>\n<li>Array Declaration<\/li>\n<li>Array Initialization<\/li>\n<\/ol>\n<p><strong>Array Declaration<\/strong><\/p>\n<p>This is the first step in which we declare an array variable of the desired data type.<\/p>\n<p>The valid <strong>syntax<\/strong> for array declaration can be:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">data-type array_name [ ];\ndata-type [ ] array_name;<\/pre>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">int daysInMonth [ ];\nchar [ ] lettersInSentence;\ndouble salaryOfEmployees [ ];\nString progLanguages[ ];<\/pre>\n<p><strong>Array Initialization<\/strong><\/p>\n<p>In the second step, we allocate the memory to the array with the help of a <strong>new<\/strong> operator and assign the memory to the array variable. So, let us see how can we declare arrays in different ways.<\/p>\n<p>The valid <strong>syntax<\/strong> for array initialization can be:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">array_name = new data-type [size of array];\narray_name = new data-type {elements of array using commas};<\/pre>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">daysInMonth = new int [100];\nlettersInSentence = new char[5];\nsalaryOfEmployees = new double[ ] {10000, 50000, 30000, 25000, 40000};\nprogLanguages = { \u201cC\u201d, \u201cJava\u201d, \u201cRuby\u201d, \u201cPython\u201d, \u201cPHP\u201d };<\/pre>\n<p>Combining two steps, we can create an array as follows:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">data-type array_name [ ] = new data-type [size of array];\ndata-type [ ] array_name = new data-type [size of array];\ndata-type array_name [ ] = new data-type {elements of array using commas};<\/pre>\n<p><strong>Note:<\/strong> If the elements of an array are not given then Java stores the value of each element with 0.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class arrayTutorial\n{\n  public static void main(String args[])\n  {\n    int [ ] marksOfStudents = new int[ ] {65, 90, 78, 60, 84 };\n    System.out.println(\"Marks of first student: \" +marksOfStudents[0]);\n    System.out.println(\"Marks of second student: \" +marksOfStudents[1]);\n    System.out.println(\"Marks of third student: \" +marksOfStudents[2]);\n    System.out.println(\"Marks of fourth student: \" +marksOfStudents[3]);\n    System.out.println(\"Marks of fifth student: \" +marksOfStudents[4]);\n\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">\n<p>Marks of first student: 65<br \/>\nMarks of second student: 90<br \/>\nMarks of third student: 78<br \/>\nMarks of fourth student: 60<br \/>\nMarks of fifth student: 84<\/p>\n<\/div>\n<h5>2.3. Java Classes<\/h5>\n<p>A class is a collection of objects of the same type. It is a user-defined blueprint or prototype which defines the behavior or state of objects. Class and objects are the basic elements of Object-Oriented Programming that represent the real-world entities.<\/p>\n<p>A class consists of a set of properties (fields or variables) or methods\/operations to define the behavior of an object. We create a class using a <strong>class<\/strong> keyword.<\/p>\n<p>A class can be declared using the following components in the order-<\/p>\n<p><strong>1. Access modifiers:<\/strong> Access modifiers define the access privileges of a class. A class can be public or it has default access.<\/p>\n<p><strong>2. Class name:<\/strong> The name of a class should represent a noun and must start with a capital letter. These are the best practices to be kept in mind while declaring any class.<\/p>\n<p><strong>3. Body:<\/strong> The class body contains properties and methods. The body is always enclosed by curly braces { }.<\/p>\n<p><strong>Syntax of writing a class:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">AccessModifier class class_name\n{\nClass body - variables and methods();\n}<\/pre>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">  public class MyClass\n  {\n    int x = 5;\n    void display()\n    {\n    \/\/ methodBody;\n  }\n}<\/pre>\n<h5>2.4. Java Objects<\/h5>\n<p>It is a basic unit of Object-Oriented Programming which represents the real-world entities. An object is an instance of a class. It defines the state and behavior of real-life entities.<\/p>\n<ul>\n<li><strong>State:<\/strong> It represents the attributes and properties of an object.<\/li>\n<li><strong>Behavior:<\/strong> Methods define the behavior of an object. It also reflects the communication of one object with the other objects.<\/li>\n<li><strong>Identity:<\/strong> It gives a unique name to an object which allows one object to interact with other objects.<\/li>\n<\/ul>\n<p><strong>For example,<\/strong> An object \u2018Dog\u2019 has states like name, breed, color, size, age, and functions like bark, eat, run, sit.<\/p>\n<p><strong>Syntax of creating an object of a class:<\/strong><\/p>\n<p>To create an object of a class, specify the class name, followed by the object name, by using the new keyword-<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">class_name object_Name = new class_name();<\/pre>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">MyClass object1 = new MyClass();<\/pre>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class Student\n{\n  int marks = 76;\n  public static void main(String[] args)\n  {\n    Student student1 = new Student();\n    \/\/ creating object of the class by using new operator\n    System.out.println(\"Marks of student: \" +student1.marks);\n    Accessing the property \u201cmarks\u201d of the class with the help of an object.\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">\n<p>Marks of student: 76<\/p>\n<\/div>\n<h5>2.5. Java Interfaces<\/h5>\n<p>An interface is another reference type in Java.<\/p>\n<p>It is similar to a class. It can also have methods and variables, but the methods are declared implicitly as \u201cpublic\u201d and \u201cabstract\u201d in interfaces. However, since Java 9, we can include private methods in an interface.<\/p>\n<p>The abstract methods have only a method signature but they can not have a method body. An interface behaves like a blueprint of a class, which specifies \u201cwhat a class has to do and not how it will do\u201d.<\/p>\n<p>In the real-world, one user defines an interface, but different user provides its implementation. Moreover, it is finally used by some other user.<\/p>\n<p><strong>Syntax of writing interfaces:<\/strong><\/p>\n<p>To declare an interface, we just write the keyword \u201cinterface\u201d followed by the interface name:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">interface interface_name<\/pre>\n<p>To use an interface in a class, we have to append the keyword <strong>&#8220;implements&#8221;<\/strong> after the class name followed by the interface name.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">class class_name implements interface_name<\/pre>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">interface Serializable\n  {\n    \/\/ Abstract methods\n  }\nclass MyClass implements Serializable\n  {\n    \/\/class body\n  }<\/pre>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">\/\/creating an interface\ninterface Runnable\n{\n  public void run(); \/\/an abstract method\n}\n \/\/ implementing the interface\npublic class Person implements Runnable\n{ \tpublic void run()\n  {\n    System.out.println(\"This person can run\");\n  }\n\n  public static void main(String args[])\n  {\n    Person person1 = new Person();\n    person1.run();\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">\n<p>This person can run<\/p>\n<\/div>\n<p>An Interface is all about capabilities &#8211; like an interface is <strong>Runnable<\/strong>. Any class (class <strong>Person<\/strong> in this case) implementing Runnable must implement <strong>run()<\/strong>. So, an interface specifies a set of methods that the class has to implement.<\/p>\n<h3>Summary<\/h3>\n<p>By this tutorial, you understood the data types in Java and also its major classification of Primitive and Non-Primitive data types. We also discussed how to implement these data types in our Java programs and in real-world applications.<\/p>\n<p><em>Did we miss anything in Java data types article? Do share with us in the comments. TechVidvan will be glad to add it.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The data-types are the most important basis of any programming language. It is the most important concept for every beginner. The data type is essential to represent the type, nature and set of operations&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":76168,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[1588,1589,1590,1591,1592,1593,1594,1595],"class_list":["post-76118","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-array-declaration-in-java","tag-data-types-in-java","tag-java-array-initialization","tag-java-arrays","tag-java-classes","tag-java-interfaces","tag-java-objects","tag-java-strings"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Data Types in Java Programming with Implementation Examples - TechVidvan<\/title>\n<meta name=\"description\" content=\"Java Data Types - Learn about the primitive and non-primitve data types in Java with their use, syntax and implementation in Java program.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Data Types in Java Programming with Implementation Examples - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Java Data Types - Learn about the primitive and non-primitve data types in Java with their use, syntax and implementation in Java program.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-02-05T04:27:28+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/02\/data-types-in-java.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"16 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Data Types in Java Programming with Implementation Examples - TechVidvan","description":"Java Data Types - Learn about the primitive and non-primitve data types in Java with their use, syntax and implementation in Java program.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/","og_locale":"en_US","og_type":"article","og_title":"Data Types in Java Programming with Implementation Examples - TechVidvan","og_description":"Java Data Types - Learn about the primitive and non-primitve data types in Java with their use, syntax and implementation in Java program.","og_url":"https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-02-05T04:27:28+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/02\/data-types-in-java.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"16 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Data Types in Java Programming with Implementation Examples","datePublished":"2020-02-05T04:27:28+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/"},"wordCount":2481,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/02\/data-types-in-java.jpg","keywords":["array declaration in java","Data types in Java","java array initialization","java arrays","java classes","java interfaces","java objects","java strings"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/","url":"https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/","name":"Data Types in Java Programming with Implementation Examples - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/02\/data-types-in-java.jpg","datePublished":"2020-02-05T04:27:28+00:00","description":"Java Data Types - Learn about the primitive and non-primitve data types in Java with their use, syntax and implementation in Java program.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/02\/data-types-in-java.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/02\/data-types-in-java.jpg","width":802,"height":420,"caption":"java data types"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Data Types in Java Programming with Implementation Examples"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/76118","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=76118"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/76118\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/76168"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=76118"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=76118"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=76118"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}