Category: Java

  • Comments

    Java Comments

    Java comments are text notes written in the code to provide an explanation about the source code. The comments can be used to explain the logic or for documentation purposes. The compiler does not compile the comments. In Java, comments are very similar to C and C++.

    In Java, there are three types of comments:

    • Single-line comments
    • Multiline comments
    • Documentation comments

    Let’s discuss each type of comment in detail.

    1. Single Line Comment

    The single-line comment is used to add a comment on only one line and can be written by using the two forward slashes (//). These comments are the most used commenting way.

    The single line comments are the most used commenting way to explain the purpose (or to add a text note) of the line.

    Syntax

    Consider the below syntax to write a single line comment in Java:

    // comment

    Example 1: Java Single Line Comment

    // if divisor is 0 throw an exceptionif(divisor ==0){thrownewIllegalArgumentException("divisor cannot be zero");}

    Example 2: Java Single Line Comment

    Following code shows the usage of single line comments in a simple program. We’ve added comments to code lines to explain their purpose.

    packagecom.tutorialspoint;publicclassMyFirstJavaProgram{publicstaticvoidmain(String[] args){MyFirstJavaProgram program =newMyFirstJavaProgram();double result = program.divide(100,10);System.out.println(result);}privatedoubledivide(int dividend,int divisor)throwsIllegalArgumentException{// if divisor is 0 throw an exceptionif(divisor ==0){thrownewIllegalArgumentException("divisor cannot be zero");}return(double) dividend / divisor;// returns the result of the division as double}}

    Output

    Compile and run MyFirstJavaProgram. This will produce the following result −

    10.0
    

    2. Multiline Comment

    The multiline (or, multiple-line) comments start with a forward slash followed by an asterisk (/*) and end with an asterisk followed by a forward slash (*/) and they are used to add comment on multiple lines.

    The multiline comments are very useful when we want to put a long comment spreading across multiple lines or to comment out the complete code.

    Syntax:

    Consider the below syntax to write multiline comment in Java:

    /*
    Comment (line 1)
    Comment (line 2)
    ...
    */

    Example 1: Java Multiline Comment

    /* This is an example 
    of 
    multi line comment. *//* if (dividend == 0) {
       throw new IllegalArgumentException("dividend cannot be zero");
    } */

    Example 2: Java Multiline Comment

    Following code shows the usage of multiple comments in a simple program. We’ve commented out extra code from a method using Multiline comments.

    packagecom.tutorialspoint;publicclassMyFirstJavaProgram{publicstaticvoidmain(String[] args){MyFirstJavaProgram program =newMyFirstJavaProgram();double result = program.divide(100,10);System.out.println(result);}privatedoubledivide(int dividend,int divisor)throwsIllegalArgumentException{if(divisor ==0){thrownewIllegalArgumentException("divisor cannot be zero");}/* if (dividend == 0) {
    
         throw new IllegalArgumentException("dividend cannot be zero");
      } */return(double) dividend / divisor;}}</code></pre>

    Output

    Compile and run MyFirstJavaProgram. This will produce the following result −

    10.0
    

    3. Documentation Comment

    The documentation comments are used for writing the documentation of the source code. The documentation comments start with a forward slash followed by the two asterisks (/**), end with an asterisk followed by a backward slash (*/), and all lines between the start and end must start with an asterisk (*).

    The documentation comments are understood by the Javadoc tool and can be used to create HTML-based documentation.

    Syntax

    Consider the below syntax to write documentation comment in Java:

    /**
    * line 1
    * line 2
    ...
    */

    Example 1: Java Documentation Comment

    /**
     * This is a documentation comment.
     * This is my first Java program.
     * This will print 'Hello World' as the output
     * This is an example of multi-line comments.
    */publicclassMyFirstJavaProgram{}

    The above commenting style is known as documentation comments. It is used by Javadoc tool while creating the documentation for the program code. We can give details of arguments, exception and return type as well using following annotation in documentation comments.

    /**
     * @param dividend
     * @param divisor
     * @return quotient
     * @throws IllegalArgumentException if divisor is zero
     */privatedoubledivide(int dividend,int divisor)throwsIllegalArgumentException{}

    Example 2: Java Documentation Comment

    Following code shows the usage of documentation comments in a simple program. We've defined a comments on the class declaration to give details of the class. In case of method, we're adding details of parameters, return value and exception raised in documentation block of the method comments section.

    packagecom.tutorialspoint;/**
     * This is a documentation comment. 
     * This is my first Java program.
     * This is an example of multi-line comments.
     * We're printing result of divison of two numbers in this program
     */publicclassMyFirstJavaProgram{publicstaticvoidmain(String[] args){MyFirstJavaProgram program =newMyFirstJavaProgram();double result = program.divide(100,10);System.out.println(result);}/**
    
    * @param dividend
    * @param divisor
    * @return quotient
    * @throws IllegalArgumentException if divisor is zero
    */privatedoubledivide(int dividend,int divisor)throwsIllegalArgumentException{if(divisor ==0){thrownewIllegalArgumentException("divisor cannot be zero");}return(double) dividend / divisor;}}</code></pre>

    Output

    Compile and run MyFirstJavaProgram. This will produce the following result −

    10.0
    
  • Basic Operators

    Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups −

    • Arithmetic Operators
    • Relational Operators
    • Bitwise Operators
    • Logical Operators
    • Assignment Operators
    • Misc Operators

    The Arithmetic Operators

    Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators −

    Assume integer variable A holds 10 and variable B holds 20, then −

    OperatorDescriptionExample
    + (Addition)Adds values on either side of the operator.A + B will give 30
    – (Subtraction)Subtracts right-hand operand from left-hand operand.A – B will give -10
    * (Multiplication)Multiplies values on either side of the operator.A * B will give 200
    / (Division)Divides left-hand operand by right-hand operand.B / A will give 2
    % (Modulus)Divides left-hand operand by right-hand operand and returns remainder.B % A will give 0
    ++ (Increment)Increases the value of operand by 1.B++ gives 21
    — (Decrement)Decreases the value of operand by 1.B– gives 19

    The Relational Operators

    There are following relational operators supported by Java language.

    Assume variable A holds 10 and variable B holds 20, then −

    OperatorDescriptionExample
    == (equal to)Checks if the values of two operands are equal or not, if yes then condition becomes true.(A == B) is not true.
    != (not equal to)Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.(A != B) is true.
    > (greater than)Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(A > B) is not true.
    < (less than)Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.(A < B) is true.
    >= (greater than or equal to)Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(A >= B) is not true.
    <= (less than or equal to)Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.(A <= B) is true.

    The Bitwise Operators

    Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.

    Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows −

    a =00111100
    b =00001101
    a&b =00001100
    a|b =00111101
    a^b =00110001~a  =11000011

    The following table lists the bitwise operators −

    Assume integer variable A holds 60 and variable B holds 13 then −

    OperatorDescriptionExample
    & (bitwise and)Binary AND Operator copies a bit to the result if it exists in both operands.(A & B) will give 12 which is 0000 1100
    | (bitwise or)Binary OR Operator copies a bit if it exists in either operand.(A | B) will give 61 which is 0011 1101
    ^ (bitwise XOR)Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) will give 49 which is 0011 0001
    ⁓ (bitwise compliment)Binary Ones Complement Operator is unary and has the effect of ‘flipping’ bits.(⁓A ) will give -61 which is 1100 0011 in 2’s complement form due to a signed binary number.
    << (left shift)Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.A << 2 will give 240 which is 1111 0000
    >> (right shift)Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.A >> 2 will give 15 which is 1111
    >>> (zero fill right shift)Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.A >>>2 will give 15 which is 0000 1111

    The Logical Operators

    The following table lists the logical operators −

    Assume Boolean variables A holds true and variable B holds false, then −

    OperatorDescriptionExample
    && (logical and)Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.(A && B) is false
    || (logical or)Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true.(A || B) is true
    ! (logical not)Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(A && B) is true

    The Assignment Operators

    Following are the assignment operators supported by Java language −

    OperatorDescriptionExample
    =Simple assignment operator. Assigns values from right side operands to left side operand.C = A + B will assign value of A + B into C
    +=Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand.C += A is equivalent to C = C + A
    -=Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand.C -= A is equivalent to C = C − A
    *=Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand.C *= A is equivalent to C = C * A
    /=Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand.C /= A is equivalent to C = C / A
    %=Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand.C %= A is equivalent to C = C % A
    <<=Left shift AND assignment operator.C <<= 2 is same as C = C << 2
    >>=Right shift AND assignment operator.C >>= 2 is same as C = C >> 2
    &=Bitwise AND assignment operator.C &= 2 is same as C = C & 2
    ^=bitwise exclusive OR and assignment operator.C ^= 2 is same as C = C ^ 2
    |=bitwise inclusive OR and assignment operator.C |= 2 is same as C = C | 2

    Miscellaneous Operators

    There are few other operators supported by Java Language.

    Conditional Operator ( ? : )

    Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be assigned to the variable. The operator is written as −

    variable x = (expression) ? value if true : value if false
    

    Following is an example −

    Example

    In this example, we’re creating two variables a and b and using ternary operator we’ve decided the values of b and printed it.

    publicclassTest{publicstaticvoidmain(String args[]){int a, b;
    
      a =10;
      b =(a ==1)?20:30;System.out.println("Value of b is : "+  b );
      b =(a ==10)?20:30;System.out.println("Value of b is : "+ b );}}</code></pre>

    Output

    Value of b is : 30
    Value of b is : 20
    

    instanceof Operator

    This operator is used only for object reference variables. The operator checks whether the object is of a particular type (class type or interface type). instanceof operator is written as −

    ( Object reference variable ) instanceof  (class/interface type)
    

    If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side, then the result will be true. Following is an example −

    Example

    In this example, we're creating a String variable name and then using instanceof operator we've checking the name is of String or not.

    publicclassTest{publicstaticvoidmain(String args[]){String name ="James";// following will return true since name is type of Stringboolean result = name instanceofString;System.out.println( result );}}

    Output

    true
    

    This operator will still return true, if the object being compared is the assignment compatible with the type on the right. Following is one more example −

    Example

    In this example, we're creating a variable a of class Vehicle and then using instanceof operator we've checking the name is of type Car or not.

    classVehicle{}publicclassCarextendsVehicle{publicstaticvoidmain(String args[]){Vehicle a =newCar();boolean result =  a instanceofCar;System.out.println( result );}}

    Output

    true
    

    Precedence of Java Operators

    Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −

    For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3 * 2 and then adds into 7.

    Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

    CategoryOperatorAssociativity
    Postfixexpression++ expression--Left to right
    Unary++expression --expression +expression -expression ⁓ !Right to left
    Multiplicative* / %Left to right
    Additive+ -Left to right
    Shift<< >> >>>Left to right
    Relational< > <= >= instanceofLeft to right
    Equality== !=Left to right
    Bitwise AND&Left to right
    Bitwise XOR^Left to right
    Bitwise OR|Left to right
    Logical AND&&Left to right
    Logical OR||Left to right
    Conditional?:Right to left
    Assignment= += -= *= /= %= ^= |= <<= >>= >>>=Right to left
  • Unicode System

    Unicode is an international character set that encompasses a vast range of characters, symbols, and scripts from many languages across the globe.

    Unicode System in Java

    Java programming language, being platform-independent, has built-in support for Unicode characters, allowing developers to create applications that can work seamlessly with diverse languages and scripts.

    Before Unicode, there were multiple standards to represent character encoding −

    • ASCII − for the United States.
    • ISO 8859-1 − for Western European Language.
    • KOI-8 − for Russian.
    • GB18030 and BIG-5 − for Chinese.

    So to support multinational application codes, some character was using single byte, some two. An even same code may represent a different character in one language and may represent other characters in another language.

    To overcome above shortcoming, the Unicode system was developed where each character is represented by 2 bytes. As Java was developed for multilingual languages it adopted the Unicode system. The lowest value is represented by \u0000 and the highest value is represented by \uFFFF.

    Approaches: Working with Unicode Characters & Values

    There are two approaches for working with Unicode characters in Java: Using Unicode Escape Sequences and Directly Storing Unicode Characters.

    The first approach involves representing Unicode characters using escape sequences and is useful when the characters cannot be directly typed or displayed in the Java code. The second approach involves directly storing Unicode characters in variables and is more convenient when the characters can be directly typed or displayed.

    The choice of approach depends on the specific requirements of the program. However, in general, Approach 2 is simpler and more convenient when the characters can be directly typed or displayed, while Approach 1 is necessary when they cannot.

    1. Using Unicode Escape Sequences

    One way to store Unicode characters in Java is by using Unicode escape sequences. An escape sequence is a series of characters that represent a special character. In Java, a Unicode escape sequence starts with the characters ‘\u’ followed by four hexadecimal digits that represent the Unicode code point of the desired character.

    Example: Use of Unicode Escape Sequences

    packagecom.tutorialspoint;publicclassUnicodeCharacterDemo{publicstaticvoid main (String[]args){//Unicode escape sequencechar unicodeChar ='\u0041';// point for 'A'System.out.println("Stored Unicode Character: "+ unicodeChar);}}

    Compile and run above program. This will produce the following result −

    Output

    Stored Unicode Character: A
    

    In the above code snippet, the Unicode escape sequence ‘\u0041’ represents the character ‘A.’ The escape sequence is assigned to the char variable unicodeChar, and the stored character is then printed to the console.

    2. Storing Unicode Values Directly

    Alternatively, you can directly store a Unicode character in a char variable by enclosing the character in single quotes. However, this approach may not be feasible for characters that cannot be typed directly using a keyboard or are not visible, such as control characters.

    Example 1: Assigning Unicode Character to Variable

    packagecom.tutorialspoint;publicclassUnicodeCharacterDemo{publicstaticvoidmain(String[] args){// Storing Unicode character directlychar unicodeChar ='A';// Directly storing the character 'A'System.out.println("Stored Unicode Character: "+ unicodeChar);}}

    Compile and run above program. This will produce the following result −

    Output

    Stored Unicode Character: A
    

    In this example, the character ‘A’ is directly enclosed in single quotes and assigned to the char variable unicodeChar. The stored character is then printed to the console.

    Example 2: Assigning Unicode Values to Variables

    packagecom.tutorialspoint;publicclassUnicodeCharacterDemo{publicstaticvoidmain(String[] args){// Storing Unicode characters using escape sequenceschar letterA ='\u0041';char letterSigma ='\u03A3';char copyrightSymbol ='\u00A9';// Storing Unicode characters directlychar letterZ ='Z';char letterOmega ='Ω';char registeredSymbol ='®';// Printing the stored Unicode charactersSystem.out.println("Stored Unicode Characters using Escape Sequences:");System.out.println("Letter A: "+ letterA);System.out.println("Greek Capital Letter Sigma: "+ letterSigma);System.out.println("Copyright Symbol: "+ copyrightSymbol);System.out.println("\nStored Unicode Characters Directly:");System.out.println("Letter Z: "+ letterZ);System.out.println("Greek Capital Letter Omega: "+ letterOmega);System.out.println("Registered Symbol: "+ registeredSymbol);}}

    Compile and run above program. This will produce the following result −

    Output

    Stored Unicode Characters using Escape Sequences:
    Letter A: A
    Greek Capital Letter Sigma: Σ
    Copyright Symbol: ©
    
    Stored Unicode Characters Directly:
    Letter Z: Z
    Greek Capital Letter Omega: Ω
    Registered Symbol: ®
    

    Example 3: Assigning Unicode Characters and Values to Variables

    This example demonstrates how to manipulate the stored Unicode characters. It calculates the difference between the capital letter ‘A’ and the small letter ‘a’ and uses that difference to calculate the capital letter ‘C.’ It then calculates the small letter ‘c’ by adding 32 to the Unicode code point of the capital letter ‘C.’ The manipulated Unicode characters are printed to the console.

    packagecom.tutorialspoint;publicclassUnicodeCharacterDemo{publicstaticvoidmain(String[] args){// Storing Unicode characters using escape sequenceschar letterA ='\u0041';char letterSmallA ='\u0061';// Storing Unicode characters directlychar letterB ='B';// Manipulating the stored Unicode charactersint difference = letterA - letterSmallA;char letterC =(char)(letterB + difference);char letterSmallC =(char)(letterC +32);// Printing the manipulated Unicode charactersSystem.out.println("Manipulated Unicode Characters:");System.out.println("Difference between A and a: "+ difference);System.out.println("Calculated Letter C: "+ letterC);System.out.println("Calculated Letter c: "+ letterSmallC);}}

    Compile and run above program. This will produce the following result −

    Output

    Manipulated Unicode Characters:
    Difference between A and a: -32
    Calculated Letter C: "
    Calculated Letter c: B
    
  • Type Casting

    Java Type Casting (Type Conversion)

    Type casting is a technique that is used either by the compiler or a programmer to convert one data type to another. For example, converting int to double, double to int, short to int, etc. Type typing is also known as Type conversion.

    There are two types of cast typing allowed in Java programming:

    • Widening type casting
    • Narrowing type casting

    Widening Type Casting

    Widening Type Casting is also known as implicit type casting in which a smaller type is converted into a larger type, it is done by the compiler automatically.

    Here is the hierarchy of widening type casting in Java:

    byte>short>char>int>long>float>double

    The compiler plays a role in the type conversion but not the programmers. It changes the type of the variables at the compile time. Also, type conversion occurs from the small data type to large data type only.

    Example 1: Widening Type Casting

    In the example below, we demonstrated that we can get an error when the compiler tries to convert a large data type to a small data type. Here, we created the num1 integer and num2 double variable. The sum of num1 and num2 will be double, and when we try to store it to the sum of the int type, the compiler gives an error.

    packagecom.tutorialspoint;publicclassTester{// Main driver methodpublicstaticvoidmain(String[] args){// Define int variablesint num1 =5004;double num2 =2.5;int sum = num1 + num2;// show outputSystem.out.println("The sum of "+ num1 +" and "+ num2 +" is "+ sum);}}

    Compile and run Tester. This will produce the following result −

    Output

    Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    	Type mismatch: cannot convert from double to int
    
    	at com.tutorialspoint.Tester.main(Tester.java:9)
    

    Example 2: Widening Type Casting

    In the example below, we created the num1 and num2 variables as same in the first example. We store the sum of both numbers in the sum variable of double type. In the output, we can observe the sum of double type.

    packagecom.tutorialspoint;publicclassTester{// Main driver methodpublicstaticvoidmain(String[] args){// Define int variablesint num1 =5004;double num2 =2.5;double sum = num1 + num2;// show outputSystem.out.println("The sum of "+ num1 +" and "+ num2 +" is "+ sum);}}

    Compile and run Tester. This will produce the following result −

    Output

    The sum of 5004 and 2.5 is 5006.5
    

    Narrowing Type Casting

    Narrowing type casting is also known as explicit type casting or explicit type conversion which is done by the programmer manually. In the narrowing type casting a larger type can be converted into a smaller type.

    When a programmer changes the variable type while writing the code. We can use the cast operator to change the type of the variable. For example, double to int or int to double.

    Syntax

    Below is the syntax for narrowing type casting i.e., to manually type conversion:

    double doubleNum =(double) num;

    The above code statement will convert the variable to double type.

    Example: Narrowing Type Casting

    In the example below, we define the num variable of integer type and initialize it with the value. Also, we define the doubleNum variable of double type and store the num variable’s value after converting it to the double.

    Next, We created the ‘convertedInt’ integer type variable and stored the double value after type casting to int. In the output, we can observe the value of the double and int variables.

    packagecom.tutorialspoint;publicclassTester{// Main driver methodpublicstaticvoidmain(String[] args){// Define int variableint num =5004;// Type casting int to doubledouble doubleNum =(double) num;// show outputSystem.out.println("The value of "+ num +" after converting to the double is "+ doubleNum);// Type casting double to intint convertedInt =(int) doubleNum;// show outputSystem.out.println("The value of "+ doubleNum +" after converting to the int again is "+ convertedInt);}}

    Compile and run Tester. This will produce the following result −

    Output

    The value of 5004 after converting to the double is 5004.0
    The value of 5004.0 after converting to the int again is 5004
    
  • Data Types

    Data types define the type and value range of the data for the different types of variables, constants, method parameters, returns type, etc. The data type tells the compiler about the type of data to be stored and the required memory. To store and manipulate different types of data, all variables must have specified data types.

    Java data types are categorized into two parts −

    • Primitive Data Types
    • Reference/Object Data Types

    Java Primitive Data Types

    Primitive data types are predefined by the language and named by a keyword. There are eight primitive data types supported by Java. Below is the list of the primitive data types:

    • byte
    • short
    • int
    • long
    • float
    • double
    • boolean

    Java byte Data Type

    • Byte data type is an 8-bit signed two’s complement integer
    • Minimum value is -128 (-2^7)
    • Maximum value is 127 (inclusive)(2^7 -1)
    • Default value is 0
    • Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an integer.
    • Example − byte a = 100, byte b = -50

    Java short Data Type

    • Short data type is a 16-bit signed two’s complement integer
    • Minimum value is -32,768 (-2^15)
    • Maximum value is 32,767 (inclusive) (2^15 -1)
    • Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an integer
    • Default value is 0.
    • Example − short s = 10000, short r = -20000

    Java int Data Type

    • Int data type is a 32-bit signed two’s complement integer.
    • Minimum value is – 2,147,483,648 (-2^31)
    • Maximum value is 2,147,483,647(inclusive) (2^31 -1)
    • Integer is generally used as the default data type for integral values unless there is a concern about memory.
    • The default value is 0
    • Example − int a = 100000, int b = -200000

    Java long Data Type

    • Long data type is a 64-bit signed two’s complement integer
    • Minimum value is -9,223,372,036,854,775,808(-2^63)
    • Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
    • This type is used when a wider range than int is needed
    • Default value is 0L
    • Example − long a = 100000L, long b = -200000L

    Java float Data Type

    • Float data type is a single-precision 32-bit IEEE 754 floating point
    • Float is mainly used to save memory in large arrays of floating point numbers
    • Default value is 0.0f
    • Float data type is never used for precise values such as currency
    • Example − float f1 = 234.5f

    Java double Data Type

    • double data type is a double-precision 64-bit IEEE 754 floating point
    • This data type is generally used as the default data type for decimal values, generally the default choice
    • Double data type should never be used for precise values such as currency
    • Default value is 0.0d
    • Example − double d1 = 123.4

    Java boolean Data Type

    • boolean data type represents one bit of information
    • There are only two possible values: true and false
    • This data type is used for simple flags that track true/false conditions
    • Default value is false
    • Example − boolean one = true

    Java char Data Type

    • char data type is a single 16-bit Unicode character
    • Minimum value is ‘\u0000’ (or 0)
    • Maximum value is ‘\uffff’ (or 65,535 inclusive)
    • Char data type is used to store any character
    • Example − char letterA = ‘A’

    Example: Demonstrating Different Primitive Data Types

    Following examples shows the usage of variour primitive data types we’ve discussed above. We’ve used add operations on numeric data types whereas boolean and char variables are printed as such.

    publicclassJavaTester{publicstaticvoidmain(String args[]){byte byteValue1 =2;byte byteValue2 =4;byte byteResult =(byte)(byteValue1 + byteValue2);System.out.println("Byte: "+ byteResult);short shortValue1 =2;short shortValue2 =4;short shortResult =(short)(shortValue1 + shortValue2);System.out.println("Short: "+ shortResult);int intValue1 =2;int intValue2 =4;int intResult = intValue1 + intValue2;System.out.println("Int: "+ intResult);long longValue1 =2L;long longValue2 =4L;long longResult = longValue1 + longValue2;System.out.println("Long: "+ longResult);float floatValue1 =2.0f;float floatValue2 =4.0f;float floatResult = floatValue1 + floatValue2;System.out.println("Float: "+ floatResult);double doubleValue1 =2.0;double doubleValue2 =4.0;double doubleResult = doubleValue1 + doubleValue2;System.out.println("Double: "+ doubleResult);boolean booleanValue =true;System.out.println("Boolean: "+ booleanValue);char charValue ='A';System.out.println("Char: "+ charValue);}}

    Output

    Byte: 6
    Short: 6
    Int: 6
    Long: 6
    Float: 6.0
    Double: 6.0
    Boolean: true
    Char: A
    

    Java Reference/Object Data Type

    The reference data types are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy, etc.

    Class objects and various types of array variables come under reference datatype. The default value of any reference variable is null. A reference variable can be used to refer to any object of the declared type or any compatible type.

    Example

    The following example demonstrates the reference (or, object) data types.

    // Creating an object of 'Animal' classAnimal animal =newAnimal("giraffe");// Creating an object of 'String' classString myString =newString("Hello, World!");
  • Variable Types

    What is a Java Variable?

    A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable’s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

    Variable Declaration and Initialization

    You must declare all variables before they can be used. Following is the basic form of a variable declaration −

    data type variable [= value][, variable [= value]...];

    Here data type is one of Java’s data types and variable is the name of the variable. To declare more than one variable of the specified type, you can use a comma-separated list.

    Example of Valid Variables Declarations and Initializations

    Following are valid examples of variable declaration and initialization in Java −

    int a, b, c;// Declares three ints, a, b, and c.int a =10, b =10;// Example of initializationbyteB=22;// initializes a byte type variable B.double pi =3.14159;// declares and assigns a value of PI.char a ='a';// the char variable a iis initialized with value 'a'

    Java Variables Types

    The following are the three types of Java variables:

    • Local variables
    • Instance variables
    • Class/Static variables

    1. Java 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.
    • Local variables are implemented at stack level internally.
    • 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 1: Variable’s local scope with initialization

    Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to only this method.

    publicclassTest{publicvoidpupAge(){int age =0;
    
      age = age +7;System.out.println("Puppy age is : "+ age);}publicstaticvoidmain(String args&#91;]){Test test =newTest();
      test.pupAge();}}</code></pre>

    Output

    Puppy age is: 7
    

    Example 2: Variable's local scope without initialization

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

    publicclassTest{publicvoidpupAge(){int age;
    
      age = age +7;System.out.println("Puppy age is : "+ age);}publicstaticvoidmain(String args&#91;]){Test test =newTest();
      test.pupAge();}}</code></pre>

    Output

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

    2. Java Instance Variables

    • Instance variables are declared in a class, but outside a method, constructor or any block.
    • When a space is allocated for an object in the heap, a slot for each instance variable value is created.
    • 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.
    • Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName.

    Example of Java Instance Variables

    importjava.io.*;publicclassEmployee{// this instance variable is visible for any child class.publicString name;// salary  variable is visible in Employee class only.privatedouble salary;// The name variable is assigned in the constructor.publicEmployee(String empName){
    
      name = empName;}// The salary variable is assigned a value.publicvoidsetSalary(double empSal){
      salary = empSal;}// This method prints the employee details.publicvoidprintEmp(){System.out.println("name  : "+ name );System.out.println("salary :"+ salary);}publicstaticvoidmain(String args&#91;]){Employee empOne =newEmployee("Ransika");
      empOne.setSalary(1000);
      empOne.printEmp();}}</code></pre>

    Output

    name  : Ransika
    salary :1000.0
    

    3. Java Class/Static Variables

    • Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
    • There would only be one copy of each class variable per class, regardless of how many objects are created from it.
    • 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.
    • Static variables can be accessed by calling with the class name ClassName.VariableName.
    • 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.

    Example of Java Class/Static Variables

    importjava.io.*;publicclassEmployee{// salary  variable is a private static variableprivatestaticdouble salary;// DEPARTMENT is a constantpublicstaticfinalStringDEPARTMENT="Development ";publicstaticvoidmain(String args[]){
    
      salary =1000;System.out.println(DEPARTMENT+"average salary:"+ salary);}}</code></pre>

    Output

    Development average salary:1000
    
  • Basic Syntax

    When we consider a Java program, it can be defined as a collection of objects that communicate via invoking each other’s methods. Let us now briefly look into what do class, object, methods, and instance variables mean.

    • Object − Objects have states and behaviors. Example: A dog has states – color, name, breed as well as behavior such as wagging their tail, barking, eating. An object is an instance of a class.
    • Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports.
    • Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
    • Instance Variables − Each object has its unique set of instance variables. An object’s state is created by the values assigned to these instance variables.

    First Java Program

    Let us look at a simple code that will print the words Hello World.

    Example

    publicclassMyFirstJavaProgram{/* This is my first java program.
    
    * This will print 'Hello World' as the output
    */publicstaticvoidmain(String&#91;]args){System.out.println("Hello World");// prints Hello World}}</code></pre>

    Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps −

    • Open notepad and add the code as above.
    • Save the file as: MyFirstJavaProgram.java.
    • Open a command prompt window and go to the directory where you saved the class. Assume it's C:\.
    • Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption : The path variable is set).
    • Now, type ' java MyFirstJavaProgram ' to run your program.
    • You will be able to see ' Hello World ' printed on the window.

    Output

    C:\> javac MyFirstJavaProgram.java
    C:\> java MyFirstJavaProgram 
    Hello World
    

    Basic Syntax

    About Java programs, it is very important to keep in mind the following points.

    • Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have different meaning in Java.
    • Class Names − For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.Example − class MyFirstJavaClass
    • Method Names − All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.Example − public void myMethodName()
    • Program File Name − Name of the program file should exactly match the class name.When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile).But please make a note that in case you do not have a public class present in the file then file name can be different than class name. It is also not mandatory to have a public class in the file.Example − Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'
    • public static void main(String args[]) − Java program processing starts from the main() method which is a mandatory part of every Java program.

    Java Identifiers

    All Java components require names. Names used for classes, variables, and methods are called identifiers.

    In Java, there are several points to remember about identifiers. They are as follows −

    • All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
    • After the first character, identifiers can have any combination of characters.
    • A key word cannot be used as an identifier.
    • Most importantly, identifiers are case sensitive.
    • Examples of legal identifiers: age, $salary, _value, __1_value.
    • Examples of illegal identifiers: 123abc, -salary.

    Java Modifiers

    Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers −

    • Access Modifiers − default, public , protected, private
    • Non-access Modifiers − final, abstract, strictfp

    We will be looking into more details about modifiers in the next section.

    Java Variables

    Following are the types of variables in Java −

    • Local Variables
    • Class Variables (Static Variables)
    • Instance Variables (Non-static Variables)

    Java Arrays

    Arrays are objects that store multiple variables of the same type. However, an array itself is an object on the heap. We will look into how to declare, construct, and initialize in the upcoming chapters.

    Java Enums

    Enums were introduced in Java 5.0. Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums.

    With the use of enums it is possible to reduce the number of bugs in your code.

    For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium, and large. This would make sure that it would not allow anyone to order any size other than small, medium, or large.

    Example

    classFreshJuice{enumFreshJuiceSize{SMALL,MEDIUM,LARGE}FreshJuiceSize size;}publicclassFreshJuiceTest{publicstaticvoidmain(String args[]){FreshJuice juice =newFreshJuice();
    
      juice.size =FreshJuice.FreshJuiceSize.MEDIUM;System.out.println("Size: "+ juice.size);}}</code></pre>

    Output

    The above example will produce the following result −

    Size: MEDIUM
    

    Note − Enums can be declared as their own or inside a class. Methods, variables, constructors can be defined inside enums as well.

    Java Keywords

    The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.

    Sr.NoReserved Words & Description
    1abstractAs per dictionary, abstraction is the quality of dealing with ideas rather than events.
    2assertassert keyword is used in Java to define assertion. An assertion is a statement in Java which ensures the correctness of any assumptions which have been done in the program.
    3booleanboolean datatype is one of the eight primitive datatype supported by Java. It provides means to create boolean type variables which can accept a boolean value as true or false.
    4breakThe break statement in Java programming language has the following two usages −When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.It can be used to terminate a case in the switch statement.
    5bytebyte datatype is one of the eight primitive datatype supported by Java. It provides means to create byte type variables which can accept a byte value.
    6casecase keyword is part of switch statement which allows a variable to be tested for equality against a list of values.
    7catchAn exception (or exceptional event) is a problem that arises during the execution of a program.
    8charchar datatype is one of the eight primitive datatype supported by Java.
    9classJava is an Object-Oriented Language. As a language that has the Object-Oriented feature.
    10constfinal keyword is used to define constant value or final methods/classes in Java.
    11continueThe continue keyword can be used in any of the loop control structures.
    12defaultdefault keyword is part of switch statement which allows a variable to be tested for equality against a list of values.
    13doA do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.
    14doubledouble datatype is one of the eight primitive datatype supported by Java.
    15ifAn if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
    16enumThe Java Enum class is the common base class of all Java language enumeration types.
    17extendsextends is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword.
    18finalfinal keyword is used to define constant value or final methods/classes in Java.
    19finallyfinally keyword is used to define a finally block. The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.
    20floatfloat datatype is one of the eight primitive datatype supported by Java. It provides means to create float type variables which can accept a float value.
    21forA for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times.
    22gotogoto statement is not supported by Java currrenly. It is kept as a reserved keyword for future. As an alternative, Java supports labels with break and continue statement.
    23ifAn if statement consists of a Boolean expression followed by one or more statements.
    24implementsGenerally, the implements keyword is used with classes to inherit the properties of an interface.
    25importimport keyboard is used in context of packages.
    26instanceofinstanceof keyword is an operator which is used only for object reference variables.
    27intint datatype is one of the eight primitive datatype supported by Java.
    28interfaceAn interface is a reference type in Java. It is similar to class. It is a collection of abstract methods.
    29longlong datatype is one of the eight primitive datatype supported by Java.
    30native
    31new
    32packagePackages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
    33privateMethods, variables, and constructors that are declared private can only be accessed within the declared class itself.
    34protectedThe protected access modifier cannot be applied to class and interfaces.
    35publicA class, method, constructor, interface, etc. declared public can be accessed from any other class.
    36return
    37shortBy assigning different data types to variables, you can store integers, decimals, or characters in these variables.
    38staticThe static keyword is used to create variables that will exist independently of any instances created for the class.
    39strictfp
    40superThe super keyword is similar to this keyword.
    41switchA switch statement allows a variable to be tested for equality against a list of values.
    42synchronized
    43thisthis keyword is a very important keyword to identify an object. Following are the usage of this keyword.
    44throwIf a method does not handle a checked exception, the method must declare it using the throws keyword.
    45transientSerialization is a concept using which we can write the state of an object into a byte stream so that we can transfer it over the network (using technologies like JPA and RMI).
    46tryA method catches an exception using a combination of the try and catch keywords.
    47void
    48volatile
    49whileA while loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true.

    Comments in Java

    Java supports single-line and multi-line comments very similar to C and C++. All characters available inside any comment are ignored by Java compiler.

    Example

    publicclassMyFirstJavaProgram{/* This is my first java program.
    
    * This will print 'Hello World' as the output
    * This is an example of multi-line comments.
    */publicstaticvoidmain(String&#91;]args){// This is an example of single line comment/* This is also an example of single line comment. */System.out.println("Hello World");}}</code></pre>

    Output

    Hello World
    

    Using Blank Lines

    A line containing only white space, possibly with a comment, is known as a blank line, and Java totally ignores it.

    Inheritance

    In Java, classes can be derived from classes. Basically, if you need to create a new class and here is already a class that has some of the code you require, then it is possible to derive your new class from the already existing code.

    This concept allows you to reuse the fields and methods of the existing class without having to rewrite the code in a new class. In this scenario, the existing class is called the superclass and the derived class is called the subclass.

    Interfaces

    In Java language, an interface can be defined as a contract between objects on how to communicate with each other. Interfaces play a vital role when it comes to the concept of inheritance.

    An interface defines the methods, a deriving class (subclass) should use. But the implementation of the methods is totally up to the subclass.

  • Environment Setup

    Set Up Your Java Development Environment

    If you want to set up your own environment for Java programming language, then this tutorial guides you through the whole process. Please follow the steps given below to set up your Java environment.

    Java SE is available for download for free. To download click here, please download a version compatible with your operating system.

    Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories.

    Setting Up the Environment Path for Windows 2000/XP

    Assuming you have installed Java in c:\Program Files\java\jdk directory. Below are the steps to set up the Java environment path for Windows 2000/XP:

    • Right-click on ‘My Computer’ and select ‘Properties’.
    • Click on the ‘Environment variables’ button under the ‘Advanced’ tab.
    • Now, edit the ‘Path’ variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\Windows\System32, then edit it the following way
      C:\Windows\System32;c:\Program Files\java\jdk\bin.

    Setting Up the Environment Path for Windows 95/98/ME

    Assuming you have installed Java in c:\Program Files\java\jdk directory. Below are the steps to set up the Java environment path for Windows 95/98/ME:

    • Edit the ‘C:\autoexec.bat’ file and add the following line at the end −
      SET PATH=%PATH%;C:\Program Files\java\jdk\bin

    Setting Up the Environment Path for Linux, UNIX, Solaris, FreeBSD

    Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.

    For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc −

    export PATH=/path/to/java:$PATH’

    Online Java Compiler

    We have set up the Java Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online.

    Try the following example using Run & Edit button available at the top right corner of the above sample code box −

    publicclassMyFirstJavaProgram{publicstaticvoidmain(String[]args){System.out.println("Hello World");}}

    For most of the examples given in this tutorial, you will find a Run & Edit option in our website code sections at the top right corner that will take you to the Online Java Compiler. So just make use of it and enjoy your learning.

    Popular Java Editors

    To write Java programs, you need a text editor. There are even more sophisticated IDEs available in the market. The most popular ones are briefly described below −

    • Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities.
    • Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html.
    • Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from www.eclipse.org.

    IDE or Integrated Development Environment, provides all common tools and facilities to aid in programming, such as source code editor, build tools and debuggers etc.

  • Hello World Program

    Printing “Hello World” on the output screen (console) is the first program in Java and other programming languages. This tutorial will teach you how you can write your first program (print “Hello World” program) in Java programming.

    Java program to print “Hello World”

    Java program to print “Hello World” is given below:

    publicclassMyFirstJavaProgram{/* This is my first java program.
    
    * This will print 'Hello World' as the output
    */publicstaticvoidmain(String&#91;]args){System.out.println("Hello World");// prints Hello World}}</code></pre>

    Steps to Write, Save, and Run Hello World Program

    Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps −

    • Open notepad and add the code as above.
    • Save the file as − "MyFirstJavaProgram.java".
    • Open a command prompt window and go to the directory where you saved the class. Assume it's C:\.
    • Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there is no error in your code, the command prompt will take you to the next line (Assumption − The path variable is set. Learn: Java Envionment Setup).
    • Now, type 'java MyFirstJavaProgram' to run your program.
    • You will be able to see "Hello World" printed on the screen.

    Output

    C:\> javac MyFirstJavaProgram.java
    C:\> java MyFirstJavaProgram
    Hello World
    

    Explanation of Hello World Program

    As we've successfully printed Hello World on the output screen. Let's understand the code line by line.

    1. Public Main Class

    publicclassMyFirstJavaProgram{

    This line is creating a new class MyFirstJavaProgram and being public, this class is to be defined in the same name file as MyFirstJavaProgram.java. This convention helps Java compiler to identify the name of public class to be created before reading the file content.

    2. Comment Section

    /* This is my first java program.
    * This will print 'Hello World' as the output
    */

    These lines being in /* */ block are not considered by Java compiler and are comments. A comment helps to understand program in a better way and makes code readable and understandable.

    3. Public Static Void Main

    publicstaticvoidmain(String[]args){

    This line represents the main method that JVM calls when this program is loaded into memory. This method is used to execute the program. Once this method is finished, program is finished in single threaded environment.

    4. Keywords Used

    Let's check the purpose of each keyword in this line.

    • public − defines the scope of the main method. Being public, this method can be called by external program like JVM.
    • static − defines the state of the main method. Being static, this method can be called by external program like JVM without first creating the object of the class.
    • void − defines the return type of the main method. Being void, this method is not returning any value.
    • main − name of the method
    • String []args − arguments passed on command line while executing the java command.

    5. System.out.println() Method

    System.out.println("Hello World");// prints Hello World

    System.out represents the primary console and its println() method is taking "Hello World" as input and it prints the same to the console output.

  • JDK vs JRE vs JVM

    All three JDK, JRE and JVM are interdependent. JDK is Java Development Kit primarily meant for Developers to develop Java based applications. JRE is Java Runtime Environment where Java program runs. JDK carries JRE as an integral part of it. JRE can be installed seperately as well on systems where no developement is to be done and we only need to run the Java based application or a java program is to be executed. The JVM is a specification, and can have different implementations, as long as they adhere to the specs. The specs can be found in the below link − https://docs.oracle.com. JRE is an implementation of the JVM.

    JDK

    JDK is an abbreviation for Java Development Kit which includes all the tools, executables, and binaries required to compile, debug, and execute a Java Program.JDK is platform dependent i.e. there are separate installers for Windows, Mac, and Unix systems. JDK includes both JVM and JRE and is entirely responsible for code execution. It is the version of JDK that represents a version of Java.

    JRE

    JRE is a Java Runtime Environment which is the implementation of JVM i.e. the specifications that are defined in JVM are implemented and create a corresponding environment for the execution of code. JRE comprises mainly Java binaries and other classes to execute the program like JVM which physically exists. Along with Java binaries JRE also consists of various technologies of deployment, user interfaces to interact with code executed, some base libraries for different functionalities, and language and util-based libraries.

    JVM

    JVM is the abbreviation for Java Virtual Machine which is a specification that provides a runtime environment in which Java byte code can be executed i.e. it is something that is abstract and its implementation is independent of choosing the algorithm and has been provided by Sun and other companies. It is JVM which is responsible for converting Byte code to machine-specific code. It can also run those programs which are written in other languages and compiled to Java bytecode. The JVM performs the mentioned tasks: Loads code, Verifies code, Executes code, and Provides runtime environment.

    Difference between JDK, JRE, and JVM

    Following are the important differences between JDK, JRE, and JVM −

    Sr. No.KeyJDKJREJVM
    1DefinitionJDK (Java Development Kit) is a software development kit to develop applications in Java. In addition to JRE, JDK also contains number of development tools (compilers, JavaDoc, Java Debugger etc.).JRE (Java Runtime Environment) is the implementation of JVM and is defined as a software package that provides Java class libraries, along with Java Virtual Machine (JVM), and other components to run applications written in Java programming.JVM (Java Virtual Machine) is an abstract machine that is platform-dependent and has three notions as a specification, a document that describes requirement of JVM implementation, implementation, a computer program that meets JVM requirements, and instance, an implementation that executes Java byte code provides a runtime environment for executing Java byte code.
    2Prime functionalityJDK is primarily used for code execution and has prime functionality of development.On other hand JRE is majorly responsible for creating environment for code execution.JVM on other hand specifies all the implementations and responsible to provide these implementations to JRE.
    3Platform IndependenceJDK is platform dependent i.e for different platforms different JDK required.Like of JDK JRE is also platform dependent.JVM is platform independent.
    4ToolsAs JDK is responsible for prime development so it contains tools for developing, debugging and monitoring java application.On other hand JRE does not contain tools such as compiler or debugger etc. Rather it contains class libraries and other supporting files that JVM requires to run the program.JVM does not include software development tools.
    5ImplementationJDK = Java Runtime Environment (JRE) + Development toolsJRE = Java Virtual Machine (JVM) + Libraries to run the applicationJVM = Only Runtime environment for executing the Java byte code.