Showing posts with label Java basics. Show all posts
Showing posts with label Java basics. Show all posts

Tuesday, 29 November 2016

Facts about Variable Length Argument in Java

Variable Length Argument Rules in Java

                 Java included a feature that simplifies the creation of methods that require variable number of arguments. This is known as vararg. vararg is the short for of Variable Length Arguments.

5 Facts about Variable Length Argument Rules in Java

1. A variable-length argument is specified by three periods (…).


            static void TestVariableArgument(int ... v) {

         This syntax tells the compiler that TestVariableArgument( ) can be called with zero or more arguments.

2. In the case of no arguments, the length of the array is zero.

3. A method can have “normal” parameters along with a variable-length parameter and the variable-length parameter must be the last parameter declared by the method.

4. Overloading a method that takes a variable-length argument is possible.

5. If a method call conflicts with two methods that implements variable argument or other leads to error. 

Tuesday, 22 November 2016

Initializing a blank final variable in Java

How to initialize a blank final variable in Java?

Example Java Program to demonstrate the initialization of blank final variable using Constructor

                  A field can be declared as final. Doing so prevents its contents from being modified, A final variable that is not initialized at the time of declaration is known as blank final variable. The blank final variable can be only initialized using its constructor method.

                  As per the coding convention, it is common to use all upper case letters to represent a final variable. 


                    final in REGNO = 15480;


//Java Program to demonstrate the initialization of blank final variable using Constructor
class FinalInitialize
     final int VALUE;
     FinalInitialize(){       // Constructor
          VALUE=10;           // Initialized final variable inside constructor
          System.out.println("Final Value is : "+VALUE);
public class InitializeFinal {
     public static void main(String[] args) {
          new FinalInitialize();

               In the above program, The FinalInitialize() constructor initiate the value of the final variable VALUE.

Thursday, 10 November 2016

Difference between Instance and Object in Java

Difference between class object and class instance in java

               The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.

Object and Instance in Java
Difference between object and instance in Java

It is obvious to get confused by the words class object and class instance. A class is a template for an object and an object is an instance of a class. To make it clear, we can also say that the instance of a class is object.

There is no need of differentiating the words object and instance as both doesn’t make any difference when is used interchangeably.

For Example:

class Animal

Object of class Animal and instance of class Animal are same. When you create an instance of the class animal, the instance is an object and the type of that object is “class Animal”.

Thursday, 19 May 2016

What is Nashorn?

Brief description about Java Nashorn

               Nashorn is a Javascript Engine developed by Oracle in Java Platform. It is a part of Java 8. The Nashorn name is the German translation of rhinoceros which came from the cover of Javascript book of O'Reilly Associates. The performance of the Nashorn is several times better than the old Javascript Engine Rhino. You can invoke Nashorn from a Java application using the Java Scripting API to interpret embedded scripts, or you can pass the script to the jjs or jrunscript tool. Nashorn is the only JavaScript engine included in the JDK.

               Nashorn's goal is to implement a lightweight high-performance JavaScript runtime in Java with a native JVM. This Project intends to enable Java developers embedding of JavaScript in Java applications via JSR-223 and to develop free standing JavaScript applications using the jrunscript command-line tool.

               This Project is designed to take full advantage of newer technologies for native JVMs that have been made since the original development of JVM-based JavaScript which was started in 1997 by Netscape and maintained by Mozilla. This Project will be an entirely new code base, focused on these newer technologies. In particular the project will utilize the MethodHandles and InvokeDynamic APIs described in JSR-292.

Invoking Nashorn from Java Code

               To invoke Nashorn in your Java application, create an instance of the Nashorn engine using the Java Scripting API.

To get an instance of the Nashorn engine:

1. Import the javax.script package.

2. Create a ScriptEngineManager object.

                The ScriptEngineManager class is the starting point for the Java Scripting API. A ScriptEngineManager object is used to instantiate ScriptEngine objects and maintain global variable values shared by them.

3. Get a ScriptEngine object from the manager using the getEngineByName() method.

             This method takes one String argument with the name of the script engine. To get an instance of the Nashorn engine, pass in "nashorn". Alternatively, you can use any of the following: "Nashorn", "javascript", "JavaScript", "js", "JS", "ecmascript", "ECMAScript".

               After you have the Nashorn engine instance, you can use it to evaluate statements and script files, set variables, and so on. The below example provides simple Java application code that evaluates a print("Hello, World!"); statement using Nashorn.

Example :

//Evaluating a Script Statement Using Nashorn

import javax.script.*;

public class EvalScript {

public static void main(String[] args) throws Exception {

// create a script engine manager

ScriptEngineManager factory = new ScriptEngineManager();

// create a Nashorn script engine

ScriptEngine engine = factory.getEngineByName("nashorn");

// evaluate JavaScript statement

try {

engine.eval("print('Hello, World!');");

} catch (final ScriptException se) { se.printStackTrace(); }



Invoking Nashorn from the Command Line

There are two command-line tools that can be used to invoke the Nashorn engine:

  • jrunscript

This is a generic command that invokes any available script engine compliant with JSR 223. By default, without any options, jrunscript invokes the Nashorn engine, because it is the default script engine in the JDK.

  • jjs

This is the recommended tool, created specifically for Nashorn. To evaluate a script file using Nashorn, pass the name of the script file to the jjs tool. To launch an interactive shell that interprets statements passed in using standard input, start the jjs tool without specifying any script files.

Sunday, 3 April 2016

for Loop Variations in Java

Variations of for loop in Java

               In order to increase the applicability of the for loop, it supports number of variations. for loop can be used without initialization statement, condition statement and iteration statement. They can kept empty.

for loop Variations

Variation 1: No initialization and iteration statement

               In the below program, we have intentionally kept the initialization and iteration part empty. Here we initialized the variable before the for loop and kept the increment statement inside the for loop. 


public class ForLoopVariationType1
    public static void main(String[] args)
        int i=8;
        for(;i<12 i="">



Variation 2: No Condition Statement

               Here, we use the condition and exit statement inside the for loop. This is done by using the break statement inside the for loop body. when the value of i becomes 10 , the break statement terminates the for loop.


public class ForLoopVariationType2
    public static void main(String[] args)
        int i=8;
            if (i==10)



Variation 3: Infinite Loop

               Here is one more for loop variation. You can intentionally create an infinite loop (a loop that never terminates) if you leave all three parts of the for empty.


public class ForLoopVariationType3
    public static void main(String[] args)
            System.out.println("Infinite Loop");


Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop

Note: The same Infinite Loop Message Continues as it is an infinite condition-less loop.

Thursday, 10 March 2016

Nested Switch in Java

How Nested Switch work in Java

               We can use the switch inside another switch as like the same way we use Nested-if conditions. Use switch as a part of statement sequence of an outer switch. This is called Nested Switch. Each switch has its own block hence there is no conflicts between the inside and outside switches

General Model of Nested Switch

     case 1:

          System.out.println("Outer Switch");

     case 2:
               case 1:
                    System.out.println("Inner Switch");

               case 2:
                    System.out.println("Inner Switch case 2");

                    System.out.println("Outer Switch");

          System.out.println("Outer Switch");

Important features of Switch Statements

  • The switch differs from the if statement in that switch can only test for equality, whereas if can evaluate any type of Boolean expression. That is, the switch looks only for a match between the value of the expression and one of its case constants.
  • No two case constants in the same switch can have identical values. Of course, a switch statement and an enclosing outer switch can have case constants in common.
  • A switch statement is usually more efficient than a set of nested ifs.

Saturday, 5 March 2016

Life Cycle of a Java Applet

Java Applet Life Cycle

              The life cycle of a Java Applet has five main steps. 
  1.  Initialize the Applet
  2. Start the Applet
  3. Paint Applet
  4. Stop the Applet
  5. Destroy the Applet
Life Cycle of a Java Applet

1. Initialize the Applet

               In this step, the Applet is initialized. public void init() is the method used to initialize an Applet. It is only invoked once. 

2. Start the Applet

               In this step the Applet is start with the help of public void start() method. The start() method is invoked after calling the init() method. 

3. Paint Applet

               public void paint(Graphics g) method is used to paint the Applet. The method provides graphics class objects that can be used to draw shapes such as oval, rectangle, arc etc. 

4. Stop the Applet

               The applet is stopped with the help of public void stop() method. The method is invoked when the Applet is stopped of the browser is minimized.

5. Destroy the Applet

               This is the final step in the Applet life cycle. The Applet initialized is destroyed in this step. It is only invoked once and the method used to invoke is, public void destroy(). 


Sunday, 3 January 2016

JAVA Program to demonstrate the Modulus Operator

Usage of Modulus Operator in JAVA

A program to display the modulus of Integer and Floating Point numbers

//A Java Program to demonstrate modulus operator

public class ModulusJava
    public static void main(String args[])
            int x=12;
            double y = 12.5;
            System.out.println("x mod 10 = " + x % 10);
            System.out.println("y mod 10 = " + y % 10);


x mod 10 = 2
y mod 10 = 2.5

Friday, 1 January 2016

String Concatenation in Java

Concatenating Strings in Java

How to add two Strings in Java

               In Java, there is class named String contains method concat() for concatenating stings. The concat method can be used as follows:

     Type 1: string1.cancat(string2);
     Type 2: "Sun rises ".concat("in the east");

               Another common way to add strings in java is with the help of the '+' operator. 

     Example: "Sun rises "+"in the east";

Tuesday, 11 August 2015

Difference between Methods and Constructors in Java

Methods Vs Constructors in Java

What is the difference between Methods and Constructors in Java?

               It is obvious that Constructor and Method in Java make confusion for the beginners. Here are few points which illustrate the difference between a constructor and method in Java.





It is not necessary to use the same name of the class to create a Method.

The name of the Constructor should be same as the class name it resides.


Method is an ordinary member function which is used to expose  the behavior of an object

Constructor is a member function of a class used to initialize the state of an object


Methods must have return type unless it is specified as void.

Constructor does not have a return type.


Compiler does not create a method in any case if one is not available.

Java compiler creates default constructor if the program doesn’t have one.


Methods invoked explicitly. 
Invoked using the dot operator.

Constructor invoked implicitly. i. e. Invoked using the keyword ‘new’.

               Hoping that the above table gives an idea about how Constructors are different from methods in Java.

Constructor Method Difference

Saturday, 1 August 2015

Naming conventions in java

Java Naming Conventions

What Is a Naming Convention?

          Naming Conventions is nothing but a standard specifically used by the Java professional to represent the name of the class, interface, method, variable, package etc in a Java Program. In other words, Naming Conventions in Java is a standard rule to follow in selecting name of any identifiers in a program.

Naming Convention

          It is not mandatory to follow the Naming Conventions to run a java program. That’s why it is known as convention and not made as a rule. 

Standard Java Naming Conventions

          Standard Java Naming conventions for different identifiers are listed below


          Package names should be in all lowercase letters (small letters). 

Eg: com.packet.example, crack.analyser, name.preview


          Typical class name should be in nouns and represented by using the first letter capital method (Upper Camel Case Method). Use simple and descriptive nouns as Class name.  

Eg: class LogicalMeter, class Calculator, Class SeperateString


          Method name should be verb and use mixed case letters to represent it in programs. Mixed case letters are also knows as lower camel case letters. 

Eg: toPrint(), colorBackground()


          Constants are declared with the help of ‘static’ and ‘final’ keyword in Java. Constant variables should declare with full Upper Case letters with underscore(_) for word separation.

Eg: static final int MAX_WIDTH, static final int MAX_HEIGHT


          Interface name is also named like class name with Upper Camel Case method. 

Eg: interface ActionListener, interface Runnable


         Variable name should be in mixed case ie, naming start with small letter and use capital for internal words. It is easier to use simple one letter variable for temporary usage. Common variables used for storing integers are I, j, k and m. Common variables used for characters are c, d and e.

Eg:  float myHeight, String userName

Advantage of naming conventions in java

          Naming conventions make programs more understandable by making them easier to read. They can also give information about the function of the identifier-for example, whether it's a constant, package, or class-which can be helpful in understanding the code.

Monday, 27 July 2015

Object and Class in java

The Concept of Object and Class in Java

Object in Java

Basically an entity that has state and behavior is known as an object. It has three main characteristics like state,behavior and identity.

Object is an instance of a class.

Object and Class

Class in java

A class is a group of objects that has common properties.

A class can be defined as a template/ blue print that describes the behaviors/states that object of its type support.

Syntax to declare a class

class {  

    data member;  



Sample Program:

class FirstProgram{

   int a;     //data member
   String name;//data member
   public static void main(String args[]){  
      FirstProgram fp=new FirstProgram();  //creating an object of FirstProgram



Note: The Output of the program shows the default values in the variables 'a' and 'name'.

Monday, 26 January 2015

Arithmetic Compound Assignment Operators

Java Arithmetic Compound Operator

Compound Assignment Operators in Java

               Java gives special operators to combine an arithmetic operator with an assignment and which is known as Compound Assignment Operator. This session describes how it works and its benefits.

Consider the following addition and subtraction statements,

                         a = a + 5;
                         b = b - 5;

These statements can be rewritten as follows with the help of Compound Assignment Operator.

                         a += 5;
                         b -= 5;

Compound Assignment operators are available for all arithmetic and binary operators.


General Form:

                        var = var op expression;

Compound assignment Operator Form:

                         var op= expression;


 General Form  Compound Assignment Operator Form
 a = a - 5;  a -= 5;
 a = a + 5;  a += 5
 a = a % 5;  a %= 5
 a = a / 5  a /= 5
 a = a * 5  a *= 5

Advantages of Compound Assignment Operators

          The Compound Assignment Operators are used by Java Professionals to attain two major benefits.

          1. Compound Assignment Operators are shorthand and saves a few letters every time when you type Java Code.

          2. It is efficient than its equivalent long form in some cases.

Friday, 5 December 2014

10 Facts About Java

Top 10 Interesting Facts About Java

This article refers to few basic facts about Java which show the Purposefulness of Java

  1. 9 out of 10 computers in U.S. run Java and 97% of Enterprise Desktop run it.
  2. Java was originally called Oak.
  3. There are a million Java Developers world Wide.
  4. The median salary for a Java developer in the U.S. is $83973.
  5. Nearly nine of every 10 computers in the U.S. run Java, and 97% of enterprise desktops run the language.
  6. The JUnit testing framework is the top Java technology, used by more than four of five developers. Jenkins is second, used by 70% of developers.
  7. Java is ranked #2 in popularity among programming languages, according to The language C is #1.
  8. 1 Billion Java Downloads per Year
  9. 3 Billion devices run Java
  10. 100% of BLU-RAY Disc Players ship with Java

Sunday, 14 September 2014

Java Applet

What is Applet?

Simple Definition for Java Applet

Use of applet in Programming

An Applet is an application designed to be transmitted over internet and executed by a Java-compatible web browser. Other-words, Applet is a intelligent Java Program that can react to user inputs and dynamically change according to the programmer's design. 

How Java Applet Works 
Applets are embedded within a HTML code by using the applet tag as shown in the picture. The HelloWorld.class file contains the bytecode which created after compiling the java program. The size of the applet is defined inside the Applet Tag.

Thursday, 24 January 2013

Java Program to convert Lower Case Letter in to Uppper Case

Conversion of Lower Case letter to UpperCase in JAVA

toUpperCase(char ch) and toLowerCase(char ch) functions in Java

Syntax: public static char toUpperCase(char ch)

Converts the character argument to uppercase using case mapping information from the UnicodeData file. Note that Character.isUpperCase (Character.toUpperCase(ch)) does not always return true for some ranges of characters, particularly those that are symbols or

Monday, 21 January 2013

Code Comments in Java Program

Commenting Methods used in Java Program

Code comments in JAVA Source Code

Code comments are placed in source files to describe what is happening in the code to someone who might be reading the file, to comment-out lines of code to isolate the source of a problem for debugging purposes, or to generate API documentation. To these ends, the Java language supports three kinds of comments: double slashes, C-style, and doc comments.

Double Slashes

Double slashes (//) are used in the C++ programming language, and tell the compiler to treat everything from the slashes to the end of the line as text.

//A Very Simple Example

class ExampleProgram {
          public static void main(String[] args){
          System.out.println("I'm a Simple Program");

C-Style Comments

Instead of double slashes, you can use C-style comments (/* */) to enclose one or more lines of code to be treated as text.

/* These are C-style comments */
class ExampleProgram {
         public static void main(String[] args){
         System.out.println("I'm a Simple Program");

Doc Comments

To generate documentation for your program, use the doc comments (/** */) to enclose lines of text for the javadoc tool to find. The javadoc tool locates the doc comments embedded in source files and uses those comments to generate API documentation.

/** This class displays a text string at 
* the console.
class ExampleProgram {
          public static void main(String[] args){
          System.out.println("I'm a Simple Program");

Saturday, 19 January 2013

JAVA Program to Add Two Numbers


A program to accept two numbers from keyboard and calculate the sum.

//A small java program to add two numbers

import java.util.Scanner;

class AddTwoNumbers
   public static void main(String args[])
      int a, b, c;
      System.out.println("Enter two integers to calculate the sum ");
      //A simple text scanner which can parse primitive types and strings using regular                                      expressions.
      Scanner in = new Scanner(;
      //Capturing the scanned token as Int and storing it to the variables a and b.
      a = in.nextInt();
      b = in.nextInt();
      c = a + b;
      System.out.println("Sum of entered integers = "+c);


Enter two integers to calculate the sum
Sum of entered integers = 25

Wednesday, 16 January 2013

Java Separators

Separators in Java

Separators used in Java Programming Lanuage

Separators help define the structure of a program. The separators used in HelloWorld are parentheses, ( ), braces, { }, the period, ., and the semicolon, ;. The table lists the six Java separators (nine if you count opening and closing separators as two). Following are the some characters which are generally used as the separators in Java.

It is used to separate the package name from sub-package name & class name. It is also used to separate variable or method from its object or instance.
It is used to separate the consecutive parameters in the method definition. It is also used to separate the consecutive variables of same type while declaration.
It is used to terminate the statement in Java.
This holds the list of parameters in method definition. Also used in control statements & type casting.
This is used to define the block/scope of code, class, methods.
It is used in array declaration.
Separators in Java

Monday, 14 January 2013

Java Operators

Operators in Java

Operators Supported by Java Language

Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. Java supports a rich set of operators. Some of them are =, +, -, *. An Operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used in programs to manipulate data and variables. They usually form a part of mathematical or logical expressions. 
Java operators can be classified into a number of related categories as below:

Arithmetic Operators
+      Additive operator (also used for String concatenation)
-       Subtraction operator
*       Multiplication operator
/       Division operator
%     Remainder operator

Relational Operators
==    Equal to
!=     Not equal to
>      Greater than
>=    Greater than or equal to
<      Less than
<=    Less than or equal to

Logical Operators
&&   Logical AND
||       Logical OR
!       Logical NOT

Assignment Operators
=      Assignment

Increment and decrement Operators
++   Adds 1 to the Operand
--     Subtracts 1 from the Operand

Conditional Operators
?:    Ternary (shorthand for if-then-else statement)

Bitwise Operators
~     Unary bitwise complement
<<   Signed left shift
>>   Signed right shift
>>> Unsigned right shift
&     Bitwise AND
^      Bitwise exclusive OR
|       Bitwise inclusive OR

Special Operators
. (Dot Operator)   - To access instance variables
instanceof             - Object reference Operator

As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest precedence. The operators in the following table are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

Operator Precedence
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

The basic evaluation procedure includes two left-to-right passes through the expression. During the first pass, the high priority operators (if any) are applied as they are encountered. During the second pass, the low priority operators (if any) are applied as they are encountered.