How to check the given number is even or odd using if-else statement in Java ?.

Introduction
Java beginners have many questions related to the use of if-else statement and other decision making statements. There one of the main question is to know how an if-else statement work ?. Today I am providing a simple source code to make you understand how if-else statement work in Java. To illustrate this , I am explaining if-else through a program. Let us begin our example by simple program to check whether a given number is even or odd by applying if-else statement. This program also teaches us basic of array definition as well as use of modulus operator. Before moving to the source code and explanation of the code. I will give you some idea about basic elements used in this program.

Syntax :

if(boolean-expression)
{
  if-code;
}
else
{
  else-code;
}

rest-of-code;


if-else statement flow chart



if-else statement working

If the boolean-expression is true if-code gets executed. If boolean-expression is false else-code gets executed. In this decision making statements generally either of the block gets executed whether its if-code or else-code, after either execution rest-code gets executed. Using if-else statement to check whether a given number is even or odd public class EvenOrOdd {    public static void main(String[ ] args) {       int[ ] numbers = new int[ ]{11,23,34,45,56,67,78,89,90,104};               for(int i=0; i < numbers.length; i++){         if(numbers[i]%2 == 0)            System.out.println(numbers[i] + " is even number.");         else            System.out.println(numbers[i] + " is odd number.");       }    } }
A Closer Look at the Sample Program Let us analyze the code step-by-step, after having known few basic functionalities of the elements used. Line 2 to 3 :- Line 2 begins with a main method. Generally its a starting point for every Java program. JVM upon execution of program first looks for this method. Line 3 begins with definition and initialization of an array variable. We define an array variable by statement say in our case as : int [ ] numbers, here we have defined an int array which can hold int values with a index. When we write new operator we are creating an object. Here we are creating an object of an int array holding values such as 11, 23 , 35, 45 etc. Line 5 to 9 :- Line 5 begins with a for loop. Generally, we need a for loop to loop through array variables one by one because we need to check for the each element stored in array that whether its even or not. To loop through all the elements of an array we can use length variable defined for array object. length variable gives us the total length of an array. After looping through the array by the test condition applied on length variable we come across if-else statement on line 6. IF-ELSE statement applies a boolean expression to have a decision making flow between even or odd. Here we check in if statement that number retrieved in each for loop execution is even or not. If boolean expression is true, if body gets executed and number gets print stating its even or if statement boolean expression comes out to be false else body gets executed stating that number is odd integer. Testing Boolean Condition :- Modulus Operator is used to test the boolean condition. Generally Modulus Operator % performs division between two operands and returns their remainder. Here let say in our case if number in for loop come as 45. So it will divide 45 by 2 and return remainder which is 1. Generally this 1 indicates that 45 is odd. If the number return with remainder as 0 , it indicates that number is even. Thus based on above logic if-else statement gets the decision making.

Variables and Data Types in Java

Introduction
Lets get started with my yet another hub on Java Tutorials. I am going to give a good tutorial on Variables and Data types used in Java programming language. The objective of this hub is to make you familiar with few questions i.e.
  1. What is a Variable ?.
  2. What is a Data Type ?.
  3. How to declare Variables ?.
  4. How to initialize a Variable ?.
  5. How to access a Variable ?.
  6. What are Constants ?.
  7. How is Automatic Conversions done ?.
  8. How Explicit Conversions work ?.
Lets begin with explanation of each of questions above.

What is a Variable ?.

Variables are the temporary elements in Java which are used to store information about a program. Variables are highly used in Java. It resides in memory and are temporary placeholder for information needed to use in a program. Since value of a variable exists in memory therefore as soon as program exits value is lost. Each variable in Java has a type and a value. Since Java is strongly typed language, therefore each variable used is associated with type. Generally few language out there in market are loosely typed i.e any information can be stored in variable, Whereas in Java data type provides user information that whether variable is integer, string or float etc. The value of variable can be changed anytime in a program, unless the variables are marked with a keyword final. Generally final variables are constants, once a value is assigned to them it does not change.

What is a Data Type ?.

Java is a strongly typed language. It means that for each variable defined there must be a data type associated with it. In Java data types provides developers an idea about the size of variables, a range of values that a variable can therefore store and also about operators that can be used with it. All data stored in a variables are Objects, having exception as primitive data types. Data types used in Java are platform independent, i.e a integer can store same size of data on different platforms such as windows, unix etc. There size to store data is platform independent. This has helped developers a lot, because they now don't need to convert one data type to other when switching the same code on different platforms.
Now let us look at some of the data types available to us in Java.
  • Integer Data Types
Integer Data Types has capability to store integer values. Generally there are 5 types of Integer data types available in Java. Let look and classify them.

 

  • Floating Point Data Types
Floating Point Data Types has capability to store integer and floating point values. Generally there are 2 types of floating point data types available in Java. Lets look and classify them.



  • Boolean Data Types
Boolean Data Types has capability to store true and false values. Lets look and classify them.


How to Declare a Variable ?

Now that we know something about variables and data types, we can easily understand how to declare a variable. Generally by word declare we mean the creation of a variable. Creation of variable can be done any point of time in a code. Lets look at few examples below :-

// Declaring a variable follows below simple syntax.
// [data type][space][identifier][;]
// Few Examples :

int i ; // int -> data type and i -> identifier
float j ; // float -> data type and j -> identifier
long salary ;  // long -> data type and salary -> identifier


How to initialize a Variable ?.

After declaration of a variable, we usually assign it a value. Thus by the term initialize we mean that providing a value to a variable at the time of declaration. By default a local variable gets a value which is left over in memory. Here local variable means that a variable is been declared in a method or a block of code. Generally initialization of a variable is done by assignment operator called as ' = '. Lets look at few examples :-

// Initialization of a variable follows below simple syntax.
// [data type][space][identifier][=][value][;]
// Few Examples :

int i=0 ; // int -> data type,i -> identifier and 0 -> value
float j=3.2f ; // float -> data type , j -> identifier and 3.2f -> value
long salary=1000L ; // long -> data type salary -> identifier and 1000L -> value


How to access a variable ?.

After having some basic knowledge about the variables such declaring and initialization. We can move ahead to look for how to access a variables value. By accessing we mean how can we get out of variable value stored in it. Before accessing a value of a variable, it should be initialized. If you try to access value compiler will throw an error at compile time. Generally in order to access a variable we just use identifier name that's it. One thing should be in mind that variable accessed should not be coded in double quotes "". As double quotes are by deault String literals. Instead of printing the value , it will print the identifier name. Below example code shows how to access a variable.

/* This is Simple Java program call it as Welcome.java.
   It prints some text on the console.*/

public class Welcome 
{
   // main method begins execution of Java application
   public static void main( String[ ] args )
   {
      int hubscore = 50; // declaring and initializing a variable

      System.out.println( "Welcome Java Programs to Hubpages! with hubscore : "+hubscore ); // hubscore in quotes is String and outside quotes its name of variable which will print value in it.
   } // end method main
} // end class Welcome


// Output of the program

Welcome Java Programs to Hubpages! with hubscore : 50


What are Constants ?. Constants are the variable whose value we do not want to get change after it has been assigned a value. Generally to achieve this feature we have to use keyword called as final. A final keyword will make the variable constant. Any attempt to change value of final variable after its initialization would throw a compile time error. As a best practice we generally use capital letters in giving a name to an identifier. Let see how syntax looks like: // Syntax for declaring and initializing a constant // [final][data type][identifier][=][value][;] final int constants = 10 ;  How is Automatic Conversions done ?. When creating a Java application or code we usually have to convert one data type to another. This is somewhat quite hectic task. Java has an excellent feature of automatic conversion. In Java basically there are two types of conversion : 1. Upcasting 2. Downcasting. Upcasting is done automatically and called as Automatic conversion. While downcasting is done explicitly and called as Explicit conversion, which we will see later. In Automatic conversion also upcasting, Java let us do the upcasting. Here below image shows that small data types can be assigned to large data types without any much headache. Java does it for us.
// Automatic Conversion in Java // int data type automatically gets assigned to float data type int age = 10; float oldAge = age; // Everything is handled by Java just size matters // small data type ---upcasted-- > large data types How Explicit Conversions work ?. Explicit conversions basically downcasting is been handled by the programmer itself. If we want to convert large data type to small data type then we have to write some extra code for that. Generally we have to use a special operator for that. The special operator is named as Cast Operator. Cast operator looks like ( data type ) . Here data type in brackets is the data type to which we want to convert. Let see example code :- // We want to convert double (larger data type) to float // (smaller data type) final double PI = 3.14; float newPi = (float)PI; // Cast operator (float) converts double to float and // assign it to newPi

How to use Arithmetic Operators in Java ?.

Introduction:- 

Hello friends, In order to learn Java programming you must be very clear in Java fundamentals. You must have clear idea say how to use different kinds of operators in Java source code. Today in order to make you familiar with Operators used in Java, I will be providing you tutorial on Arithmetic Operator. Read more If you want some depth understanding on what are Arithmetic operator in Java ?. Here in this hub I will be telling you basic use of Arithmetic operator. I will be presenting before you the source code and than try to explain you code step-by-step. Our program code in this hub will require Java's basic knowledge such as : How to write your first Java program ?. and how to create, compile and run a java program ?.

Arithmetic Operator Explanation :-

The Java programming language uses arithmetic operators very extensively. Arithmetic operators are used where we have to perform basic mathematical computations. The mathematical computations such as addition, subtraction, division, multiplication etc . The operators used are: + for addition, - for subtraction, * for multiplication, / for division and % for modulus operator.

Program to demonstrate working of Arithmetic Operators :-


public class Arithmetic { 

  public static void main(String[ ] args) {
    int a = Integer.parseInt(args[0]);
    int b = Integer.parseInt(args[1]);
    int sum  = a + b;
    int prod = a * b;
    int quot = a / b;
    int rem  = a % b;
    int sub  = a - b;

    System.out.println(a + " + " + b + " = " + sum);
    System.out.println(a + " * " + b + " = " + prod);
    System.out.println(a + " / " + b + " = " + quot);
    System.out.println(a + " - " + b + " = " + sub);
    System.out.println(a + " % " + b + " = " + rem);
    System.out.println(a+ " = " +quot+ " * " +b+ " + " +rem);
  }
}


Output and Explanation of working of above sample code :-
When we run above program by command say : java Arithmetic 10 6 We get the following output on the console window:
10 + 6 = 16
10 * 6 = 60
10 / 6 = 1
10 - 6 = 4
10 % 6 = 4
10 = 1 * 6 + 4
Here we pass two command-line arguments "10" and "6". These two strings are passed as an argument to main method and gets stored in the form of an array. Where args[0] is assigned "10" value and args[1] is assigned "6" value. In order to use numeric value in program we need to parse string tointeger value. To do parsing we use Integer class which has method called as parseInt. This is static method and has argument which is a String. This method takes the String value and parses to numeric type. This values are assigned to int variables a and b.

Line 6 to 10:- All the lines from 6 to 10 do the Arithmetic Operations. Line 6 performs the addition of a and b by the use of + operator.Line 7 performs the multiplication of a and b by the use of * operator. Line 8 performs the division of a by b by the use of / operator. Line 9 performs the mod of a by b by the use of % operator. Line 10 performs the subtraction of b from a by the use of - operator.

Line 12 to 17:- Lines from 12 to 17 just prints the values calculated by applying above Arithmetic Operators. It uses System.out.println() method to perform all printing of values to console window.


Write a program to find factorial of a number in Java with and without recursion ?

Introduction :-

Hello friends, Today let us begin with a new Java program. Many of serious programmers who are just beginning to code in Java, come across a problem that is, how to write a program that calculate factorial of a number with and without recursion. Learning Java by an example is the most effective technique to inculcate this versatile language. Generally, whatever you know about language its additional when you have power to code small snippets. Learning by coding will not only give you command over the language but also develop the skills in you to code successfully. Java has a good implementation of using the recursion. I will be going to demonstrate the program with and without using concepts of recursion.


Factorial of a number formula :- In general logic to find a factorial of a number is simple and easy. The formula for finding the factorial of a number is : Factorial of a (n) number = n.(n-1).(n-2).(n-3). ...... .32.1 , If suppose we need to find factorial of number 5, it will be 5.4.3.2.1 = 120. In this hub I will be explaining you the code step by step that how a factorial of a number is calculated and printed on the console. The last section would be the code which will demonstrate the working of factorial number calculations. Factorial of a number without recursion :-  On example 1, I will be teaching you how to find factorial of a number without using idea of recursion. I will explain the code few lines first , followed by code and then rest of the explanation. The code will give you insight to some basic coding principles used in Java. Let us go for explanation for the code below : A closer look at the program stated below :- Line 1- Java has the ability to reuse the code. There are many predefined classes in Java which we will be using in our factorial calculation program. On line-1 we are importing Scanner class which is been kept in java.util package. Generally to help compiler in locating the class used in the program we use it regularly. Line 3 to 5 - Our Java program begins with a declaration of class named Factorial this class is declared as public so that it can be accessible to all Java class. Class Factorial contains a main method which is the entry point for every Java program. It is a static method so it is called by the JVM without any objects creation on heap. On next line there is a Java statement which just prints the String written in "". The println method just prints whatever is given to it in double quotes. Here in below example it first ask user , "Enter the number of for factorial calculations:". It asks user to enter a number for which he wants to calculate the factorial.
Click here to download complete source code 
import java.util.Scanner;

public class Factorial {
    public static void main (String[ ] args) {
      System.out.println("Enter the number for 
      factorial calculations : "); 

      Scanner scanner = new Scanner(System.in);
      
      int a = scanner.nextInt();
      double fact= 1;

      System.out.println("Factorial of " +a+ ":");
      for (int i= 1; i<=a; i++){
        fact=fact*i;
      }
      System.out.println(fact);
   }
} 
Line 7 to 11 :- On line 7, a new Scanner object is created on heap. The Scanner Class is used to read data from a keyboard or disk. Here variable name is scanner and type is Scanner. Here new operator is used to create a physical Scanner object on the heap. This Scanner object is used to read data from the keyboard. System.in passed into constructor of Scanner object generally reads data from the keyboard in bytes. It is the Scanner object which will convert bytes into types such as ints. Line 10 code uses Scanner method nextInt() to obtain user input as Integer, which he types on the keyboard. Generally upon execution of line, the program waits for user to type an int value from keyboard and press enter. Upon pressing enter value types by user gets assigned to int variable called as a. Factorial of a number with recursion :- On example 2, I will be teaching you how to find factorial of a number using idea of recursion. I will explain the code few lines first , followed by code and then rest of the explanation. The code will give you insight to some basic coding principles used in Java. Let us go for explanation for the code below : A closer look at the program stated below :- Whole code works same as above example. Only difference in the code is one is without recursion and other is with recursion. Line 11 calls static method fact by passing an integer to it. When returning from fact method it calls again fact method with integer value one less than previous integer value. The call sits on the stack till all the methods gets executed when value return from fact is 1. Now fact methods waiting on call gets executed sequentially, till last fact method gets executed and returns the calculated factorial value. Click here to download complete source code 
import java.util.Scanner;

public class Factorial {
  public static void main (String[ ] args) {
    System.out.println("Enter the number for "
         + "factorial calculations : "); 

    Scanner scanner = new Scanner(System.in);
      
    int a = scanner.nextInt();
    int result = fact(a);
    System.out.println("Factorial of " +a+ " is :"+result);
      
  }
  static int fact(int b){
   if(b <= 1)
     return 1;
   else
     return b * fact(b-1);
  }
}

Method Overloading in Java

Introduction

In Java, when we come across a question that what do you mean by method in Java ?. We can simply state its definition saying method is the small block of code that usually performs some specific tasks and help dividing program into specific modules. Generally we need methods because we want to use the concept of code reusability , that means suppose we have written few lines of code which are frequently been used in program. So each time if we want to execute the same code say with different values we wont type again and again. We simply create a method which will have that generic code which can be used by say different arguments passed through it. Thus, it will not impact performance.



What do you mean by Method Overloading in Java ?. 

By Method Overloading, we mean that we can declare methods of same name in a class as long as they have different signatures. By different signatures we mean method can be of same name but with different set of parameters. This difference in parameters can be determined by number , their types and order of their types. Generally, these methods almost perform same actions but they do it with different parameters and their types. Compiler calls an overloaded method based on the number of parameters passed to it, based on different data types used in that and based on order of parameters used.

Example using Method Overloading :- 

Below is the code that demonstrate the concept of method overloading. Here if we look closely to the example we have overloaded method by the name max(). This method is overloaded in the below sample code. If we closely look at the difference of max method declaration. We can see it has been defined by three different ways, lets look into that more closely :-
  • int max(intnum1, intnum2)
  • double max(doublenum1, doublenum2)
  • double max(doublenum1, doublenum2, doublenum3)
In first case, we have max method with two integer parameters. In second case, we have max method with two double parameters. in third case, we have max method with three double parameters. Thus difference in number, data types of parameters and order creates a method which can be overloaded. One note: method overloading has nothing to do with the return types. Generally, return types may or may not be same when we want a method to be overload.

A program to show concept of Method Overloading :


public class MethodOverloading {
  public static void main(String[ ] args) {
    System.out.println("The maximum between 4 and 6 is "
      + max(4, 6));
     
    System.out.println("The maximum between 4.2 and 6.4 is "
      + max(4.2, 6.4));
     
    System.out.println("The maximum between 4.2, 6.4 and 8.6 is "
      + max(4.2, 6.4 , 8.6));
  }
   
  public static int max(int num1, int num2){
    if (num1 > num2)
       return num1;
    else
       return num2;
  }
   
  public static double max(double num1, double num2){
    if (num1 > num2)
       return num1;
    else
       return num2;
  }
   
  public static double max(double num1, double num2, double num3){
    return max( max( num1,num2 ), num3 );
  }

}


Output and explanation of above code:-

Generally, above code is Java code, which performs operation to find the greatest number between the two / three variable. Let us look at the output printed on the console.
The maximum between 4 and 6 is 6
The maximum between 4.2 and 6.4 is 6.4
The maximum between 4.2, 6.4 and 8.6 is 8.6
Generally, in above line of code we have to understand how method max works. In the first case, we have defined two integer argument for max method.It takes two arguments and finds greatest number between the two through if-else construct. In the second case, we have defined two double argument for max method.It takes two arguments and finds greatest number between the two through if-else construct. In the third case, we have defined three double argument for max method.It takes three arguments and finds greatest number between the three through if-else construct and recursion.

How to read a text file through Java program. ?

Introduction

Hello friends, Lets begin with another source code in java with example and explanation. Today, I am posting a hub on Java Source Code category with program "How do I read a text file in Java "?. Learning Java by example is fun. To run below code you must have JDK installed along with some basic knowledge, How to compile a Java program ?. , How to run a Java program.? and some basic Java fundamentals. Lets begin first writing the source code and then explaining the code step-by-step in a tutorial form.
Given below is the snap shot of the student.txt file from which our source code reads the data and prints out to console window. Remember the path given in the program as "E:\\student.txt" is the path where I have kept student.txt file. You can place the file wherever you want on your machine, but just replace the path in the Java program to yours.

Snap Shot of Student.txt file to read data




How do i read text file in Java ?

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Reader {
    public static void main(String[ ] args) {
        File file = new File("E:\\student.txt");       
        BufferedReader reader = null;
        StringBuilder line = new StringBuilder();

        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;
            
            while ((text = reader.readLine()) != null) {
               line.append(text)
               .append(System.getProperty("line.separator"));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(line.toString());
    }
}

Snap shot of the output on console window






Working of Example



Lets look at the code above line by line. I will be explaining you what each line does. I will be taking you with little-little snippets and explaining overall functionality of the source code. Line 1 to 5 - Basically it contains import statements for the classes required by our source code to get executed by printing the text. The imports are generally from the I/O package libraries. Our code uses these classes in the program below. Some of them are main classes of I/O package such as BufferedReader, File, FileReader, FileNotFoundException and IOException. Line 9 to 11 - If we look at line 9, we will find that a new file is created on the path "E:\\student.txt", if no file exists. But in our case file is already placed on the path with some content written on it. This file we gave as a string to just create an object of class File not a file on system. Line 10 creates a null BufferedReader object. Generally BufferedReader is an class which acts as a buffer to hold chunks of character data. This class we need because its fast and it reads character data fast with large chunks of storage.Line 11 we create a StringBuilder object because this variable will store all the data present in student.txt document and prints it on the console. Line 13 to 15 :- Line 13 starts with a try-catch-finally block, generally when we deal with the I/O files many exceptions can occur. To catch such exceptions we must put our code in try-catch-finally block. Line 14 we create a BufferedReader object which wraps up a newly created FileReader object to which holds our File object to read the data. Generally FileReader object can read stream of characters from a file. FileReader can read characters from the student.txt file provided to it by File object. Line 15 creates a null string with a text variable , this variable is temporary placeholder or say counter for the next while loop. It will hold chunk of character on which while loops places a test condition. Line 17 to 19 :- Line 17 starts with a while loop. As we have access to file student.txt by FileReader object to read the file and its wrapper class BufferedReader class which holds FileReader class to process information transfer and storage fast. while loop applies looping on Counter variable text which holds the line by line data of character. This line of characters is been provided to text variable by method called as readLine() defined in BufferedReader class. This method reads and outputs character with one full line. The test condition in while loop makes it loop till text variable outputs null. On line 18 and 19 each loop will hold one-one line of characters in line variable by append() method. Generally append() method is defined in StringBuilder class which performs the task to append two strings together. As soon as one line gets stored in line variable we need one line separator which shifts line variable to hold string now from next line. So to get that line separator we put code that places line separator by the System properties called as line.separator. Line 21 to 25 :- Here we used try-catch statement because there may come a exception when say file student.txt is not found on the path specified in the code i.e 'E:\\student.txt', so it throws FileNotFoundException. If there is any exception occured while transferring of characters IOException may occur. Line 26 to 34 :- Generally try-catch-finally occur together. Here finally is optional but most important, it gets executed once in code whether exception occurs or not. All the resource releasing code is written in finally block. Since BufferedReader object holds critical resource for I/O operation, we should release it in our code. Its generally good practice to release the critical resources. Line 35 : - After all iterations and appending of characters line-by-line in line variable , we use print statement to print all the character of file on the console.

How to create and run a simple Java Program ?.

Introduction
Hello friends, Lets begin our hub with a simple Java program that prints or displays a message on Console as "Welcome Java Programs on Hubpages!". If we go in basics a Console is nothing but a simple display device of computer, where we can even put text that is input to program. Lets look at the program code that displays the text we want.

WelcomeJavaPrograms.java

public class WelcomeJavaPrograms {
  public static void main(String[ ] args){
    System.out.println("Welcome Java Programs on Hubpages!");   
  }
} 




Output of the program
Line 1 :- It starts by defining a class by the name WelcomeJavaPrograms. In Java programming language every program whether small or large must start with atleast one class. If we follow the naming convention of classes in Java, we have to name the class starting with an Uppercase letters. Important thing to note here is class name should match with the source file name which you will be using to store the code. So in our case above the source file name where above code goes must be WelcomeJavaPrograms.java. The entire class definition should come between opening and closing curly braces that is between { }.  Line 2 :- It starts by defining a method named as main. The main method is the entry point for all Java programs. Each program small or large, if you want to execute you should have a method named main in there. The execution point starts from there, as JVM (Java Virtual Machine) first searches the main method. If we look into what is a method ? . We can analyze it as block of statements that needs to be executed step-by-step. When we look into our example program we see that main method has only statement to execute that is System.out.println statement. Generally not going into much deep as of now just have an idea that this statement displays message "Welcome Java Programs on Hubpages!" on the console window. After each statement in Java we usually place a semi-colon to indicate compiler that particular statement is ended there. In above simple program many keywords are been used as class, public, main, static and void. These keywords have a special or significance meaning to compiler. Compiler understand what a particular keyword does in a program. Here if we look into the details of public keyword, it is an modifier which generally controls class or method visibility to other classes. When we declare public infront of class or method than that class or method are accessible by other classes which are outside. If we use keyword as private than its working is quite opposite to public keyword and it makes class or method private to code which is been defined outside the class. In our program above main method is been declared as public because it is been accessed by the code outside of the class. If we use static keyword before main method, we mean that main method is static and gets called without having to instantiate or making objects of the class. Since main method is been called by Java Virtual Machine no objects are needed for calling the main method. The last void keyword just gives the compiler information that main method would not return any value to the Java Virtual machine. Generally when we call any method we might have to pass some information to the method, which it uses to execute some statements. We usually pass this information as a parameters within the angle brackets of the method. If there are no parameters we define method with empty angle brackets i.e (). In our above program main method requires a argument which is String array named as String[] args having name of the parameter as args. This String of array receives information of the command line which it needs when executing the main method.   Line 3:- Brief understanding about the System.out.println() method, generally println method prints the string passed to it. System is a class which has access to the system and out is the output stream which connects the console and calls println method which prints the message to the console passed to it as argument.   Line 4:- It starts with a Java comment. Comments are very much important in each and every Java program. Comments allow us to place information about program in code. Generally its been avoided by the compiler and has no effect on execution of Java program. Usually it helps in debugging the code and helps other programmers to understand the code without going through whole code. In Java there are single-line comment and multi-line comment. Single-line comment usually starts with a two forward slashes (//). Multi-line comments are in between /* and */. Whenever compiler upon compilation of program sees // it avoids all written text after that on the same line. Whenever compiler sees /*, it tries to find */ and ignores all the code between them. T Let us look at examples of single-line comment and multi-line comment: // I am new to Hubpages, please help me!. /* I am writing my first Java program on Hubpages kindly have a look and comment. */ In Java block generally is a group of statements and starts by { and ends by }. Every program in Java has a block which encloses a class and also methods have there own blocks that to starts and ends with { and }. In every Java program each and every opening braces must have its closing brace. Java is a case-sensitive language, so writing class keyword as Class would result in compilation error. There are many syntax rules that Java follows and if you fail to obey those rules than on compiling program you will get compilation errors. Generally, missing of braces, missing of semi-colons, mistyping of keywords would result in compilation errors.

How to Create, Compile and Execute a Java program

Introduction : -
Java is extensively used programming language. It is been loved by many programmers from beginners to experts. Java is surely programming language of the future. If we look into the phases of program development, we come across many phases such as:





Step 1 : Creation of a Java program :-
By creating of a Java program we mean of writing of a Java program on any editor or IDE. This includes modifying of the program on editor, even after program has been written once. Creation of a Java program is not limit to only write program on editor and than leave it. Generally, creating of a Java program means writing a program on a editor or IDE, making all the corrections needed and than saving the program on secondary storage device as hard drive. After creating a Java program you should provide .java extension to file. It signifies that the particular file is a Java source code. Also , whatever progress we do from writing, editing , storing and providing .java extension to a file , it basically comes under creating of a Java program.

















Step 2 : Compiling a Java Program
Our next step after creation of program is the compilation of Java program. Generally Java program which we have created in step 1 with a .java extension, it is been compiled by the compiler. Suppose if we take example of our program say WelcomeJavaPrograms.java, when we want to compile this we use command such as javac. We can call it as The Java compiler. After opening command prompt or shell console we compile Java program with .java extension as
javac WelcomeJavaPrograms.java.

After executing the javac command, if no errors occur in our program we get a .class file which contains the bytecode. It means that the compiler has successfully converted Java source code to bytecode. Generally bytecode is been used by the JVM to run a particular application. Java Virtual Machine or JVM is a virtual machine that lies between our bytecode and underlying operating system. The final bytecode created is the executable file which only JVM understands.


















Java source code with .java extension is the high level programming language that only a programmer understands. While bytecode produced after compilation is the low-level language that only JVM understands. JVM is implemented on many operating systems which helps programmer to just compile program once, because the same .class file can be executed on different platforms with same JVM. This portion also provides portabilty feature, that you don't have to write again-and-again Java source code for the different platforms. As Java compiler is invoked by javac command, the JVM is been invoked by java command. On the console window you have to type :

java WelcomeJavaPrograms
This command will invoke the JVM to take further steps for execution of Java program.






















Step 3 : Program loading into memory by JVM:-
JVM requires memory to load the .class file before its execution. The process of placing a program in memory in order to run is called as Loading. There is a class loader present in the JVM whose main functionality is to load the .class file into the primary memory for the execution. All the .class files required by our program for the execution is been loaded by the class loader into the memory just before the execution.


































Step 4: Bytecode Verification by JVM :-
In order to maintain security of the program JVM has bytecode verifier. After the classes are loaded in to memory , bytecode verifier comes into picture and verifies bytecode of the loaded class in order to maintain security. It check whether bytecodes are valid. Thus it prevent our computer from malicious viruses and worms.












Step 5 : Execution of Java program : -
Whatever actions we have written in our Java program, JVM executes them by interpreting bytecode. If we talk about old JVM's they were slow, executed and interpreted one bytecode at a time. Modern JVM uses JIT compilation unit to which we even call just-in-time compilation. These compilers executes several instructions in parallel. They are also called as Java HotSpot compiler because JVM uses them to find hot spots in bytecode. By the term hot spots we mean that JVM analyze bytecode by searching those spots in program which are executed frequently. These frequent executable bytecodes parts are being translated to faster machine language code by Java HotSpot compiler. Now the significance behind this is whenever JVM encounter such parts again in bytecode it processes machine language code which are much faster as compared to execution of one byte code at a time.If we analyse above steps , we will find that there are two compilation phases. One in which source code is translated to bytecodes and second when hot spot parts of bytecodes are translated to machine language.

































Video Tutorial for above post :- 


How to print a Fibonacci series on console through Java program ?.

Introduction
Learning Java by example is the most effective approach. Java is very simple and easy programming language, when it comes to code. In order to master Java you should code on daily basis. It can be any code, whether simple java example or advanced java example. Learning by coding will not only give you command over the language but also develop the skills in you to code successfully. Let us start today with a simple and famous program that is : How to print Fibonacci Series in Java ?.
Fibonacci Series : 0, 1, 1, 2, 3, 5, 8, 13, 21, … Here this series starts with 0 and 1 and than each coming digit is the sum of previous two digits. That means it goes as 0+1 = 1, 1+1=2, 1+2 = 3, 2+3= 5 and so on ....In this hub I will be explaining you the code step by step that how a fibonacci number is calculated and printed on the console. The last section would be the code which will demonstrate the working of a fibonacci series.


A closer look at the program stated below :- 
Line 1- Import declarations : Java has the ability to reuse the code. There are many predefined classes in Java which we will be using in our fibonacci series program. On line-1 we are importing Scanner class which is been kept in java.util package. Generally to help compiler in locating the class used in the program we use it regularly. Line 3 to 5 - Our Java program on line - 3 begins with a declaration of class named Fibonacci this class is declared as public so that it can be accessible to all Java class. Class Fibonacci contains a main method which is the entry point for every Java program. It is a static method so it is called by the JVM without any objects creation on heap. On next line there is a Java statement which just prints the String written in "". The println method just prints whatever is given to it in double quotes. Here in below example it first ask user , "Enter the number of terms you want from fibonacci series :". It asks user to enter a number to which he wants to see the fibonacci series terms. Fibonacci Series Program Code:-
import java.util.Scanner;

public class Fibonacci {
    public static void main (String[ ] args) {
      System.out.println("Enter the number of terms you want from fibonacci series : "); 
      
      Scanner scanner = new Scanner(System.in);
      
      int i = scanner.nextInt();
     
      fiboPrint(i);
    }
public static final void fiboPrint(long n){
      
   int f0 = 0;
   int f1 = 1;

   for (int i = 0; i < n; ++i) {
      System.out.println(f0 + " ");

      final int temp = f1;
      f1= f1+ f0;
      f0 = temp;
} 
    } 
}
Line 7 to 11 :- On line 7, a new Scanner object is created on heap. The Scanner Class is used to read data from a keyboard or disk. Here variable name is scanner and type is Scanner. Here new operator is used to create a physical Scanner object on the heap. This Scanner object is used to read data from the keyboard. System.in passed into constructor of Scanner object generally reads data from the keyboard in bytes. It is the Scanner object which will convert bytes into types such as ints. Line 9 code uses Scanner method nextInt() to obtain user input as Integer, which he types on the keyboard. Generally upon execution of line, the program waits for user to type an int value from keyboard and press enter. Upon pressing enter value types by user gets assigned to int variable called as i. Line 11, calls an static method fiboPrint passing an int i to it. The int value which user entered is passed as an parameter to the method fiboPrint. Line 15 to 16 :- On line 11 fiboPrint method is called and value of int is passed to variable n which has a long data type. On line 15 to 16 we have two local variables by the name f0 and f1 which are int and initialized with value 0 and 1. Line 18 to 23:- On line 18, a for loop statement is written. This for loop has int i as initialization step. Loop also has boolean condition which compares int i to int n passed by the user in fiboPrint method. It has increment expression which increments i by value 1 each time after for loop gets executed. Line 19, prints the value of f0 each time the for loop gets executed. On line21, we create a temp variable who stores value f1. On line 22, f1 is assigned a value which is addition of f1 and f0. On line 23, we assign value temp to variable f0. If the user enters number as 5, the output would be 0, 1, 1, 2, 3, etc ....

How to Calculate Area and Circumference of Circle in a Java Program

In this post, I will teach you How to calculate Area of Circle and Circumference / Perimeter of Circle ? through Java source code. I assume you know how to write and understand simple Java program. For calculating Area and Circumference of Circle, you should know their formulas.

  • Area of Circle = PI * R* R , where PI = 22/7, R= Radius of given Circle.
  • Circumference of Circle = 2 * PI * R , where PI=22/7, R=Radius of given Circle.


Java program: To Calculate Area and Circumference of Circle

 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Circle {
    public static void main(String[ ] args){
        int radius = 0;
        System.out.println("Enter radius of a circle : ");
        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            radius = Integer.parseInt(br.readLine());
        }
        catch(NumberFormatException ne)
        {
            System.out.println("Invalid radius value" + ne);
            System.exit(0);
        }
        catch(IOException ioe)
        {
            System.out.println("IO Error :" + ioe);
            System.exit(0);
        }
        radius = 5;
        double perimeter = 2 * Math.PI * radius;
        double area = Math.PI * radius * radius;
        
        System.out.println("Area of a circle is " + area);
        System.out.println("Perimeter of a circle is " + perimeter);

        }
}  
Output of the program on Console window Enter radius of a circle : 7 Area of a circle is 78.53981633974483 Perimeter of a circle is 31.41592653589793 A Closer Look at the Sample Program Line 1 to 3 :- If we look at the source code of the program, the program starts with a import statements. Generally we have to import the classes which we require in our source code. These classes which we import are helper classes. Without importing these classes if you use them in your program, you get compile time errors. In this sample program we import three classes. Line 5 to 8 :- After importing the three classes, we create a Java class with a name Circle. In Circle.java class we have a main method which is the starting point for the execution of code. In main method we create a integer variable radius and assign it a value 0. Generally we will need this variable to store the radius provided by the user.Then we wrote a System.out.println(""); code, this prints String asking user to enter value of radius. Line 9 to 23 :- Moving ahead we wrote a try-catch statements which helps us in catching errors and issues. If we look into code two exception are been caught, i.e. NumberFormatException and IOException. If we enter an invalid integer then NumberFormatException occurs and if there is any errors in transferring of Strings from console then IOException occurs. BufferedReader class is used which creates buffer to store characters from InputStreamReader. The InputStreamReader converts byte stream to character stream. Next line we use parseInt() method of the Integer class, because this method has capability to convert numeric format to internal format. Now we use Math class which stores value for PI. Math class contains all defined mathematical functions and it is present in the package java.lang.*; Line 25 to 29 : - At last few lines of code Area and Perimeter is being calculated using the formulas stated above. Thus the final result is then printed.

Top 50 Java Keywords-The Complete Reference and Guide

Introduction:-
Java has a large list of keywords. They are extensively used in writing the source code. Java keywords are basic things that a programmer should know in order to code. Understanding Java keywords is difficult for some programmers. Today I will take you through a guide which will make you familiar with the basics of Java keywords. I will provide you with the definition of most frequent Java keywords used. I will try my best to make you understand the fundamentals behind their existence in Java programming language. If you are beginner to Java, it will help you in many possible ways. If you are going for SCJP (Sun Certified Java Programmer) exam than this hub is a must read for you. Let us first look at list of keywords in Java in ascending order:

1. abstract: - Java provides abstract keyword to signify something empty. By empty we mean that it has no definition or implementation. Keyword abstract is used before the classes and methods. At the time of declaring a class we mark it as abstract. An abstract class cannot be instantiated. It means an abstract class cannot have Objects. Generally when we place keyword abstract before a class, we make sure that this class is basically an abstract implementation or generic class and the functional characteristics can only be added by extending the class. We cannot create objects of abstract class but we can make their sub-class and create objects of that. By abstract method, we mean that method doesn't have any body. An abstract method doesn't have any statements to execute. Classes that contain abstract method must also be assigned as abstract class and implementation to their abstract method must be provided by extending those classes. If subclasses fail to provide implementation to super-class abstract methods, than they are also marked as abstract.

2. assert: - Java provides us with a debugging keyword called as assert. In Java, assert is a normal Java statement which a programmer puts in the code, that he/she thinks will always be true. Generally, assert statements are being used by the programmer for the debugging purpose. Assertion statements can be turned on or off. While running a program if we enable assertion than wherever our assert statement gets failed Assertion Error is thrown by the program and whole program gets terminated. Generally, assertions are placed by programmer in the code where he believes that statement will be true. After enabling assertion if there is a failure, programmer gets an idea that in code there is some bug. The code fails with an Assertion Error.

3. boolean: - A boolean keyword in Java is a data type for a variable which can store two values, true or false. Generally, boolean keyword is a data type which has size of 1 bit. In Java I am not sure about the size that whether it store 1 bit or not.

4. break: - In Java, 'break' keyword is of quite high importance. As the name suggest, break statement breaks code from one point and transfer flow to other part of program to execute. Generally let say in if block you have placed a break statement. If your code enters if statement an encounters break statement it will stop executing further if block and come out of if block and continue to execute. That is when you encounter break statement execution breaks that block of code and control gets transfer to next statement just after the block. Generally break statement are mostly used with switch statement. If break is used within a labeled block, than as soon as break gets encountered, the program starts executing just after labeled block.

5. byte :- In Java, byte keyword is used as a data type for storing 8 bits of information for an integer. If it’s used before a method definition than that method, when called will always return a byte value.

6. case :- In Java, case keyword is used within switch statements. A condition in switch statement is compared with the cases in switch statement. Whatever case matches with the switch expression that case is executed.

7. catch :- In Java, catch keyword has a group of statements that catches exception, if there is any exception in try block proceeding to it. The statements have a way to deal with the exception or have a way to let programmer know that something is needed to be correct.

8. char :- In Java, char keyword is used as a data type which can store 16 bit Unicode character. If the keyword is placed before method declaration than the method upon execution returns a value which is a char.

9. class :- In Java, class keyword is used to define a class. Generally a class acts as a blue print for an object. It defines implementation for the object. It has statements defining variables, methods, inner classes etc. An Object when instantiated for a particular class has all the physical implementation of what is defined in the class.

10. const :- It is a reserved keyword in Java but it has no use in Java and Java has provided it no function to perform.

11. continue :- In Java, the continue keyword is used when we want rest of the statement after continue keyword to get skipped and want program to continue with the next iteration.

12. default :- In Java, default keyword is used within switch statement. It is used their optionally, if no Java case matches with the expression than the default case is executed by the program.

13. do :- In Java, do keyword is used to implement do-while loop. Generally, do keyword is used when we want to loop a block of statement once. After that the boolean condition gets evaluated, if condition is yes the loop execute again, but if condition comes out to be false the loop exits.

14. double :- In Java, double keyword is used as a data type for storing 64 bits of information for a float type. If it’s used before a method definition than that method when called will always return a double value.

15. else :- In Java, else keyword is used along with if keyword to create an if-else statement. Generally, a condition is evaluated in if block brackets. If the condition evaluates to true if block body gets executed. If the condition is evaluated to false else block body gets executed.

16. enum :- It is used in Java language to declare a data type consisting of a set of named values. They are constants.

17. extends :- In Java, extends keyword is used specify the super class of a subclass, also in interface declaration to specify one or more super interfaces. If we take an example say let say class A extends class B, here class A adds functionality to class B by adding fields or methods. It goes same with interfaces.

18. final :- Generally, final keyword is used to make elements constant. That is once assigned cannot be changed. A final class cannot be sub-classed. A final variable cannot be assigned a new value after it has been assigned to a value. A final method cannot be overridden.

19. finally :- In Java, finally keyword is used to define a block of statements after try to catch blocks. This block executes after try block, or after catch block, or before any return statement.

20. float :- In Java, float keyword is used as a data type for storing 32 bits of information for a float type. If it’s used before a method definition than that method when called will always return a float value.

21. for :- In Java, for keyword is used to create looping statement that is for loop. In this for loop a counter variable is initialized, than a boolean condition is evaluated and compared with counter variable or any expression which turns out to either true or false. If the condition comes out to be true a block of statements following for keyword executes, if condition comes out to be false for loop terminates.

22. goto :- In Java, a goto keyword is a reserved keyword which is not used in the Java language and has no function provided to it.

23. if :- In Java, if keyword is used (optionally) along with else keyword to create an if-else statement. Generally, a condition is evaluated in if block brackets. If the condition evaluates to true if block body gets executed. If the condition is evaluated to false else block body gets executed.

24. implements :- In Java, implements keywords is used in class declaration. Generally, implements keyword implements functionality of interfaces. Interfaces are abstract in nature; their functionality is implemented in the class which implements it.

25. import :- In Java, import statement is used at the start of a Java file, just after package declaration. Generally, import statement gets those classes in a program whose functionality we want to use in the program. It is also used in importing static members.

26. instanceof :- In Java, instanceof operator is a binary operator which is used to test an IS-A relationship between a class and object. Object is first operand and Class or Interface is a second operand.

27. int :- In Java, int keyword is used as a data type for storing 32 bits of information for an integer type. If it’s used before a method definition than that method when called will always return an int value.

28. interface :- In Java, interface is a special type of structure which contains abstract methods, constant fields which are generally static or final.

29. long :- In Java, long keyword is used as a data type for storing 64 bits of information for an integer type. If it’s used before a method definition than that method when called will always return a long value.

30. native :- This keyword is generally used in declaring method signifying that method's implementation is not in the same source file but in different source file and in different language too.

31. new :- Java has a keyword called as new, which has been used to create a new instance of a class on heap. It is used is object creation and providing memory to it.

32. package :- Packages have been created by the package keyword. In the package classes are kept which constitute a relation between each other.

33. private :- In Java, private keyword can be used in declaration of methods, fields, inner class. This makes the methods, fields and inner class access to own class members.

34. protected :- In Java, protected keyword can be used in declaration of methods, fields, inner class. This makes the methods, fields and inner class access to own class members, to sub class and classes of same package.

35. public :- In Java, public keyword can be used before class, methods, fields. This makes the class , methods and fields accessible from any other class.

36. return :- In Java, return keyword is used to pass a value from a method to caller method. It also signifies end of execution of a method.

37. short :- In Java, short keyword is mainly used when we want to declare a field that can hold 16 bit of integer data. It is also placed before method declaration which signifies that method will return only short integer.

38. static :- In Java, static keyword is used when you want to declare method, fields and inner class as class members rather object members, generally static members belong to a class rather than instance of that class. Therefore only one copy is made for them and used by the class as its own implementation.

39. strictfp :- To ensure portability of floating point we ensure that they are platform independent.

40. super :- In Java, super keywords is used to access overridden methods and hidden members of super class by its subclass. It is also used in constructor of a subclass to pass control over super class constructor.

41. switch :- In Java switch keyword is used to have multi-decision making statements. Generally switch is mostly used with keywords case, break and default. This decision making block evaluates an expression first. After the expression is evaluated the value is compared with various case statements. Any value that matches with the expression, case associated with it gets executed. If no expression matches the default case gets executed.

42. synchronized :- In java, synchronized keyword is used before the method declaration and before block of code to get mutual lock for an object. It means that the method or block of code gets locked by the object till it gets fully unlocked or gets fully executed by that object. Generally classes, fields and interfaces cannot be declared as synchronized. The static method gets code synchronization by class itself.

43. this :- In Java, this keyword is used as a reference to currently executable object. Generally if we want to access class members we can use this keyword to access them. If we want to refer to a current object we use this keyword. We also use this keyword to transfer control from one constructor to another in the same class.

44. throw :- In Java, when we want to throw a declared exception, the execution points to the catch block which has provided statements to overcome the exception. If no catch block is declared in the current method than the exception is passed to the calling method. It continues till it found exception handler. If no exception handler is found over the stack that exception is then transferred to the Uncaught Exception handler.

45. throws :- In Java, we use throws keyword in the method declarations. If we get an exception in a method and method has no implementation for that exception, than method throws an exception. The exception thrown has been handled by the method who has called to current method in execution.

46. transient :- Whenever we declare a variable as transient, that variable is not the part of Object serialization. When an object gets saved through default serialization all the non-transient variable retain their value after deserialization. If you want the variable should have default value after deserialization than make it transient.

47. try :- In Java, whenever we want to do exception handling we use try keyword. Generally try block is used where we are sure that exception can occur. In try block statements are executed normally and as soon as exception occur it is handled my catch keyword following try block. It must have at least one catch or finally block.

48. void :- In Java, when we use void before any method declaration, we make sure that method doesn't return any value.

49. volatile :- In Java, volatile keyword provides a lock free mechanism. If a variable is assigned as volatile than all the threads accessing it can modify its current value without keeping a separate copy. A volatile keyword is accessed by all threads simultaneously. They operate on current value of variable rather than cached value.

50. while :- In Java, while keyword is used to create looping statement that is while loop. In this while loop a boolean condition is evaluated and compared with counter variable or any expression which turns out to either true or false. If the condition comes out to be true a block of statements following while keyword executes, if condition comes out to be false the while loop terminates.

51. false :- In Java, false keyword is the literal for the data type Boolean. Expressions are compared by this literal value.

52. null :- In Java, null keyword is the literal for the reference variable. Expressions are compared by this literal value. It is a reserved keyword.

53. true :- In Java, true keyword is the literal for the data type Boolean. Expressions are compared by this literal value.

How to concatenate two strings together in Java source code

Introduction :-
In Java, Concatenating two strings together is of high importance. Java programmer who is a beginner must know how to concatenated two string ?. Learning Java by example is the most effective proven technique. Java fundamentals are necessary to get an idea for writing an efficient code. Our program code in this leaf will need Java's basic knowledge such as : How to write your first Java program ?. and how to create, compile and run a java program ?.Java provides many mechanism to concatenated two strings. I will be discussing two of the mechanism here.

1. String concatenate operator (+).
2. String class method concat().

So to learn Java effectively , you should know these two mechanism to concatenate two strings. Let us begin with both the methods by an example and its explanation.
Concatenation of two Strings Explanation :-
By Concatenation of two Strings we mean that adding or appending one string to another string. We can also state that it is adding of two strings together. Concatenation of strings comes handy when dealing with the strings in a complex code. Generally concatenation of strings can occur in many ways. Most of the mechanism used is been coded into the sample code below. Let us look into the code step-by-step and see what it does?.


Program to demonstrate working of String Concatenation

public class Concatenation { 
    public static void main(String[ ] args) { 
        String ruler1 = " a ";
        String ruler2 = ruler1 + "b" + ruler1;
        String ruler3 = ruler2 + "c" + ruler2;
        String ruler4 = ruler3 + "d" + ruler3;
        
        System.out.println(ruler1);
        System.out.println(ruler2);
        System.out.println(ruler3);
        System.out.println(ruler4);
               
        String ruler5 = " 1 ";
        String ruler6 = "2";
        String ruler7 = ruler5.concat(ruler6);
        System.out.println(ruler7);
    }
}

Output and Explanation of working of above sample code :-
Above program shows us the working of string concatenation operator + and String class concat method. When we run above program we get output as:
a
a b a
a b a c a b a
a b a c a b a d a b a c a b a
1 2
Line 4 to 6:- All the three lines shows the code how + operator is used to concatenate the strings together. Line 4 code String ruler2 = ruler1 + "b" + ruler1; takes ruler1 string value which is " a " appends value "b" to it. So our new value becomes " a b". Now our code takes value " a b" and appends " a " to it. So after line 4 gets completely executed ruler2 gets value as " a b a ". Same execution is done for line 5 and 6.

Line 15:- This line shows us the code for the String method called as concat(). This method takes one string as an argument and appends it to the value of the string calling that method. So in our case ruler5.concat( ruler6 ) takes ruler5 value and appends ruler6 value to it and assign that value to ruler7. In our case it takes " 1 " and appends "2" to it. Finally ruler7 gets the value as " 1 2".

Line 8 to 11 and Line 16:- All these 5-6 lines just prints the values of ruler1, ruler2, ruler3, ruler4 and ruler7 on the console.

Command-Line Arguments in Java programming language


Introduction :-

Hello friends, having question in mind, How to use Command-Line Arguments in Java ?. In this hub I will be teaching you how to utilize java command-line utilities?. Learning Java by example is the most effective proven technique. Java fundamentals are necessary in order to get an idea for writing a efficient code. Our program code in this hub will require Java's basic knowledge such as : How to write your first Java program ?. and how to create, compile and run a java program ?.




Click here to download complete source code 

Command-Line Argument Explanation :-
 
A normal Java application before running, can accept multiple command line arguments from the programmer via console or IDE runtime configuration. The arguments are specified by the user at the command line which are required by the Java applications. The user enters command line arguments while launching the program by java command. This passing of arguments by java command is optional. The main method gets arguments from command line and stores it in an array of String. The array elements are initialized by whatever user types after class-name in java command. Let us take an example, suppose we want to launch a class say Hubpages.java with command line arguments, we type command after compilation as :

java Hubpages I am hubber
 
Here Hubpages is the name of class we want to launch, "I", "am", "hubber" would be three String passed to program's main method, which will store all three in the form of array of Strings. Generally, space between I, am and hubber makes them separate strings. If we want them to be one string we use double quotes "". In our example we can pass it as one single string as "I am hubber". Let us look at the below sample code and try to figure out what would be the output.

Program to demonstrate working of Command-Line Arguments

public class Argument {
   public static void main(String[ ] args) {
        System.out.print("Hi, ");
        System.out.print(args[0] + " " );
        System.out.print(args[1] + " " );
        System.out.println(". How are you?");
    }
}


Output and Explanation of working of above sample code :-

When we run above program by command say : java Argument Java Programs We get the following output on the console window:
Hi, Java Programs . How are you?
Here we pass two command-line arguments "Java" and "Programs". These two strings are passed as an argument to main method and gets stored in the form of an array. Where args[0] is assigned "Java" value and args[1] is assigned "Programs" value. These values are printed on console by System.out.print method.

Parsing Numeric Command-Line Arguments :- 

Suppose the programmer wants to enter a numeric value on command-line and let say for an example he inputs 10. Now the problem in this case is that though he had input value as 10 which is a numeric value of data type int, main method will store it as a string which is equal to "10". In order to use numeric value in program we need to parse string tointeger value. To do parsing we use Integer class which has method called as parseInt. This is static method and has argument which is a String. This method takes the String value and parses to numeric type which we can use in our program numerically. Let us look into through sample code below :

public class Argument {
   public static void main(String[ ] args) {
        
       int number1 = Integer.parseInt(args[0]);
       int number2 = Integer.parseInt(args[1]);


       int sum = number1 + number2;
       
       System.out.print("The sum of two number is : " + sum);
       
    }
}


Output and Explanation of working of above sample code :-

When we run above program by command say : java Argument 10 20 We get the following output on the console window:
The sum of two number is : 30
Here we pass two command-line arguments "10" and "20". Remember these two values are strings and they need to be first convert into numeric value. For this we have used Integer class method called as parseInt. It takes string and parses it to integer value. If value provided to this method is not a number, we get an exception such as NumberFormatException.

How to convert Decimals to Hexadecimals in a Java program

Introduction :- 

Hello friends, Today let us begin with a new Java program. Many of serious programmers who are just beginning to code in Java, come across a problem that is, How to convert Decimals to Hexadecimals in a Java program. Learning Java by an example is the most effective technique to inculcate this versatile language. Generally, whatever you know about language its additional when you have power to code small snippets. Learning by coding will not only give you command over the language but also develop the skills in you to code successfully.Hexadecimals are often used in computer systems programming.

package com.hubberspot.conversion.example;

import java.util.Scanner;

public class DecimalToHexConversion {

  public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.print("Enter decimal number you like: ");
    int deci = input.nextInt();

    System.out.println("The hexadecimal number for decimal " + 
  deci + " is " + convert(deci));
  }

  public static String convert(int decimal) {
    String hex = "";

    while (decimal != 0) {
       int hexValue = decimal % 16; 
       hex = toHexChar(hexValue) + hex;
       decimal = decimal / 16;
    }

    return hex;
  }

  public static char toHexChar(int hexValue) {
    if (hexValue <= 9 && hexValue >= 0)
       return (char)(hexValue + '0');
    else  
       return (char)(hexValue - 10 + 'A');
  }
}

Output of the program : 


Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot