Monday, 25 August 2014

Add Two Numbers In Java



You can add two numbers in java by two methods :

1.    By using the parameters at the time of execution of java program which are actually stored in the String array of main method. You can access that parameters by using the name of the array you passed in the main method with the index starting from zero.

The program  is shown below :

1:  class AddTwoNumbers  
2:  {  
3:        public static void main(String[] args)  
4:        {  
5:             int no1, no2;  
6:             //Get the first argument and parse it as int  
7:             no1 = Integer.parseInt(args[0]);  
8:             //Get the second argument and parse it as int  
9:             no2 = Integer.parseInt(args[1]);  
10:            //calculate the sum  
11:            int sum= no1 + no2;  
12:            System.out.println("Sum of two numbers is : "+sum);  
13:        }  
14:  }  

Output of the program :



Make sure that you enter only numbers if you will not enter numbers than it will show you the NumberFormatException because I have parsed the string of numbers as integers in the program. And also you have to enter minimum of two numbers with space at the time of execution of the program. The program takes first two numbers and after adding it will show you the sum of two numbers as output.

2. The second method may be use of Scanner class from java.util package. With the use of Scanner class you can ask to enter the numbers at run time from the user.

The program is shown below :

1:  import java.util.Scanner;  
2:    
3:  class AddTwoNumbersByScanner  
4:  {  
5:       public static void main(String[] args)  
6:        {  
7:             int no1, no2, sum;  
8:             System.out.println("Enter the two numbers ");  
9:             Scanner scan = new Scanner(System.in);  
10:            
11:            //Scan for the two numbers  
12:             no1 = scan.nextInt();  
13:             no2 = scan.nextInt();  
14:            
15:            //calculate the sum  
16:             sum = no1 + no2;  
17:             System.out.println("Sum of two numbers is : "+sum);  
18:        }  
19:  }  
20:    
21:    

Output of the program :


 Remember that you have to enter only the numbers because we are scanning for the numbers in the above program.
The above programs only enters the numbers in 4 bytes range which the size of any integer in java. If you want to add numbers more than 4 bytes you can use BigInteger class from java.math package.

The program is shown below :

1:  import java.util.Scanner;  
2:  import java.math.BigInteger;  
3:    
4:  class AddTwoNumbersBig  
5:  {  
6:       public static void main(String[] args)  
7:       {  
8:             System.out.println("Enter the two numbers ");  
9:             Scanner scan = new Scanner(System.in);  
10:             String no1 = scan.next();  
11:             String no2 = scan.next();  
12:             BigInteger first = new BigInteger(no1);  
13:             BigInteger second = new BigInteger(no2);  
14:             BigInteger sum = first.add(second);  
15:             System.out.println("Sum of two numbers is : "+sum);  
16:        }  
17:  }  
18:    

Output of the program :


Read more

Tuesday, 19 August 2014

ARRAYS IN JAVA



DEFINITION OF AN ARRAY :

An array is a group of similar data elements or it is a group of like-typed variables that are referred to by a common name.

For example, array of numbers like (1,2,4,8) these have same data type which is int.

Arrays of any type can be created and may have one or more dimensions.

Each item in an array (like 2 is one of the item in the above example) is called an element and each element can be accessed by its numerical index.

Note : Index in arrays is always starts from zero.

Consider the figure of array :


In the above diagram you can easily identify the difference between index and an element of array.

WHY WE USE ARRAYS :

This is the most common question for beginners in the programming that why we use arrays. 
You can understand this by considering the following example :

Suppose you want to use 100 or may be 1000 numbers which belongs to same type i.e. int ( may be to store the roll numbers of students ) than you want to create separate variables for each number you will use in your program if you don’t know about the arrays or the other alternative in that case you can use is that you can declare a 100 or 1000 number array which will save most of your time.

Declaration of an array :

 data_type[] name_of_array;  
Or
 data_type name_of_array[];  
Although the second form is only included as a convenience if you are coming from C/C++ but first form is preferred to declare arrays in java.

Initialization of an Array :

One way to create an array is with the new operator.

 name_of_array = new data_type[size_or_number_of_elements];  
   
 name_of_array[0] = 100; //Initialization of first element  
 name_of_array[1] = 200; //Initialization of second element  
   
The other way to initialize array is to directly set the elements. 
For example :

 int[] name_of_array = {1,5, 6, 23, 5, 2};  

One dimension arrays :

A one dimension array is, essentially, a list-typed variables like the one used in the above examples, they all are one dimensional arrays.

Example :
An array named myArray stores 5 numbers.

 int[] myArray; // array declared  
   
 myArray = new int[5]; // array allocates memory  
   

or you can combine these two steps into one step as :

 int[] myArray = new int[5];  

Now initialize the elements :

 myArray[0] = 4;  
   
 myArray[1] = 78;  
   
 .  
   
 .  

Or the other way to create this :



  int[] myArray = {4, 78, 23, 32, 1};  

Once the array is initialized you can access the elements by using the index which always starts from zero.

For example :
If you want to access element 3 than you can use the below statement to print the element 3 of an array.

 System.out.println("Element 3 is " + myArray[2]);  

Multidimensional Arrays :

Multidimensional arrays are actually array of arrays.

To declare a multidimensional array variable, specify each additional index using another set of square brackets.

For example :

  int [][] twoD = new int[3][4];  

Where the left dimension or first dimension specifies the number of rows and the other specifies the number of columns in the array.

A Program to make an array of 10 elements and print them on the screen is shown as an example :

1:  class ArrayDemo  
2:  {  
3:    public static void main(String[] args)  
4:    {  
5:      int[] myArray;  
6:      myArray = new int[10];  
7:    
8:      myArray[0] = 12; // remember the first element starts with zero index.  
9:      myArray[1] = 4;  
10:     myArray[2] = 6;  
11:     myArray[3] = 56;  
12:     myArray[4] = 34;  
13:     myArray[5] = 7;  
14:     myArray[6] = 7;  
15:     myArray[7] = 8;  
16:     myArray[8] = 23;  
17:     myArray[9] = 55;  
18:    
19:     //print the elements on the screen  
20:     for(int i=0; i<myArray.length; i++)  
21:     {  
22:        System.out.println("Element " + i+1 + ": " myArray[i]);  
23:     }  
24:    }  
25:  }  

Read more

Sunday, 2 February 2014

Packages in Java or what is a package?



DEFINITION :

In java, package is a set of classes, interfaces , enumerations etc which are grouped together.

Every class is definitely attached with some package.

MOSTLY USED PACKAGES IN JAVA :

java.lang : Basically provides classes related to printing and scanning.
java.io : provides classes related to input and output.
java.util : provides classes related to date and time.
java.awt : provides classes like Applet, Frame etc and used in applet programming.

To use the package classes, it should be imported with the use of import statement.
You can make your own package, define your own class in that and than you can use
that package and its classes in another package by importing.
These Java packages can be stored in compressed files called JAR files.

Note :

java.lang package is imported in every java program by default, you don't have a need 
to import that package in your program but if you want to use some input and output in your program than there is a need to import the java.io package.

How to declare a package?

Syntax:
package<space><package-name>;
e.g
 package myPackage;  

It should be the first statement in any java program.

How to import a package?
Syntax:
import<space><package-name><.><* or name of class you want to use from that package>;

e.g.
1. To import the class MyClass from myPackage
 import myPackage.MyClass;  

2. To import all classes from myPackage
 import myPackage.*;  

It should be declared after the package declaration outside the class.
Also, according to the code convention the package name should be used in small characters.

EXAMPLE :

1:  package abc;  
2:  import java.util.Date;  
3:    
4:  public class MyClass  
5:  {  
6:       //create a method which we will use in another package.  
7:       public void myMethod()  
8:       {  
9:            System.out.println("This is a different package.");  
10:              
11:            //to print the current date and time.  
12:            Date date = new Date();  
13:              
14:            //without importing the java.util.Date we cannot use the Date class.  
15:            System.out.println(date.toString());  
16:       }  
17:  }  



In another package we can use myMethod() as

1:  package xyz;  
2:  //import the abc package so that you can use the method.  
3:  import abc.MyClass;  
4:    
5:  class DemoPackage  
6:  {  
7:       public static void main(String[] args)  
8:       {  
9:            MyClass obj = new MyClass();  
10:            obj.myMethod();  
11:       }  
12:  }  
Read more

Sunday, 22 September 2013

Wrapper Classes/Type Wrapper in java



DEFINITION :

Wrapper classes in java as the name wraps or encapsulates the primitive data types such as int, char etc. and gives them an object like appearance which is mostly used in Collections because in Collections we can only add objects. They are also known as Type Wrappers because they convert the data types into a class type.

WHY WE USE THEM?

Since java is object oriented language in which every single element should be treated as object whether it is a file, image or anything but it uses primitive data types which are not actual objects and we cannot pass them by reference, they are passed by value and also we cannot make two references which refer to same data.
Java only uses these primitive data types for performance reasons and hence there should a way in which we can convert them into objects and for this designers create
Wrapper Classes.

Basically there are two important uses of wrapper classes :

1. To convert a primitive data types into objects, that is to give them an object form.
2. To convert strings into data types which is known as the parsing operations in which various methods such as parseInt(), parseFloat() etc. are used.

LIST OF WRAPPER CLASSES :

There are 8 wrapper classes for every data type in java. They all lies in java.lang package which is implicitly imported into our programs and hence they are available without importing any package.





These eight Wrapper classes provides methods and Constructors for making the object of primitive data types and getting back the value from object.

EXAMPLE OF USE OF WRAPPER CLASSES :

Consider the code,

int i = 100;
Integer ib = new Integer(i);

In the first statement 'i' is declared as the variable of int data type and then it it Wrapped or boxed into an object of the type Integer which is a wrapper class. This is also known as
boxing.
Now, this Integer type 'ib' can be used anywhere as an object.






We can also get back the data type from the object by using the method intValue() which is static in Integer Wrapper class as :

int iu = ib.intValue();

This is known as Unwrapping or Unboxing.
There are also some constants in the wrapper classes which gives you the maximum and minimum value of data types which is defined by the language. These are :
MAX_VALUE, MIN_VALUE

Here is another example of parsing a String as an integer through the Wrapper classes.

String s = "13";
int value = Integer.parseInt(s);

The method parseInt() gives the NumberFormatException if you pass the String which has a value other than int.

In the new versions of java there is way for autoBoxing and autoUnboxing.

//AutoBoxing
int i = 100;
Integer ib = i;

//AutoUnboxing
int iu = ib;

There is large use of Wrapper classes for object conversion in Collections.
Read more

Sunday, 30 June 2013

DATA TYPES IN JAVA




DEFINITION :

Data type in any language is the type of data that is used to represent the values such as the whole numbers(Integer types) , number with decimal points(floating point), characters etc.
Data type in java language is one of the most fundamental element.
There are two types of data in Java, these are :
1. Primitive type
2. Reference type


PRIMITIVE TYPE :

The primitive type is simple type which represent only single value - not complex objects. The reason for this is the performance. Since if we make simple type as the object than it must contain some property and some behaviour which will result in degraded performance.
They are used for reffering only a single value or we can say that they are not like the actual objects(which has a property and behaviour).


Four types of Primitive data type are :
1. INTEGERS :  byte, short, int, and long - data types in Integers group.
2. FLOATING-POINT NUMBERS : float and double - data types in Floating point group.
3. CHARACTERS : char - data type in the characters group.
4. BOOLEAN : boolean - data type in the boolean group.


Now in java all the data types have a strictly defined range to make it portable. For example, an int is always 32 bits, regardless of the particular platform. However the size can be changed later by Java Runtime Environment which depends upon the processor of your computer.

INTEGERS :
There are four integer types that java supports :
1. byte : 
It is the smallest integer type.
width : 8 bits, range : -128 to +127.
Use : The variables of type "byte" are especially useful when you're working with a stream of data from a network or file.
declaration : declared with byte keyword.
e.g,
byte b;

2. short :
It is probably the least used java type.
width : 16 bits, range : -32,768 to +32,767
Use : Used mostly in 16 bit computers or we can say that 16 bit microprocessors.
declaration : declared with short keyword.
e.g,
short s;

3. int :
It is the most commonly used integer data type.
width : 32 bits, range : -2,147,483,648 to +2.147.483.647
Use : Mostly used in control loops and to index arrays.
declaration : declared with int keyword.
e.g,
int a;

4. long :
It is largest integer type.
width : 64 bits, range : -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
Use : It is useful when big whole numbers are needed like in the calculation of large distances. for e.g, in measuring the distance of earth from the sun.
declaration : declared with long keyword.
e.g,
long g;

Note : All of the above integer types are signed, positive and negative values. Java does not support unsigned, positive only integers.

FLOATING POINT TYPES :
The floating point numbers are also known as the real numbers and are used when evaluating expressions that require fractional precision.
There are two kinds of floating point types :
1. float :
It specifies a "single precision" value or we can say it specifies  the small decimal value as compared with the double.
width : 32 bits, range : 1.4e-045 to 3.4e+038
Use : Mostly used in representing dollers and cents.
declaration : declared with the help of float keyword.
e.g,
float doller;

2. double :
It specifies a "double precision" value. It is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations.
width : 64 bits, range : -4.9e-324 to 1.8e+308
Use : All transcendental math functions, such as sin(), cos(), and sqrt(), return double values.
declaration : declared with the use of double keyword.
e.g,
double pi = 3.1416;

CHARACTERS :
The data type used to represent characters is char.
char :
It represents characters ASCII value.
width : 16 bits, range : 0 to 65,536
The width of char data type is 16 bits because it is represented by "Unicode" which is the combination of all the characters of different languages in the world, such as Latin, Greek, Arabic, English etc.
Also there are no negative chars.
Use : used to represent characters.
declaration : declared with the use of char keyword.
e.g,
char a = 'Y';

BOOLEANS :
The data type used to represent booleans is boolean.
It can have only one of the two possible values, true or false.
The default value of boolean is false.
Use : Mostly used in the conditional expressions that govern the control statements such as if and for.
e.g,
boolean b = true;

Note : It should not be assumed as a string which is different that boolean.


REFERENCE TYPES :

As the name, reference data types are used to refer to a particular object.
for e.g,
My_Class reference = new My_Class();
Here, reference is the reference variable which is used to refer to a My_Class object.

The reference variables are created in the heap. They can be of Array type or any class type.


Java is a strongly typed language because in java every variable has a type, every expression has a type and every type is strictly defined.

Read more

Saturday, 15 June 2013

ME AND MY WECHAT GROUP



     This is the post for the WeChat (the best mobile messanger app) Contest.

The five people I would like to connect with in WeChat are :


1. James Arthur Gosling : He is known as the   

father of java programming language. He created the original design of java and implemented the language's original compiler and virtual machine. I want to connect with him because he is my inspiration. I want to thank him for his wonderful effort in the technology. He is one of the legend who changes the way we think about technology.


2. Sachin Tendulkar : He is little master who
     is the greatest batsman in one day International Cricket and second only to Don Bradman in the all time greatest list in test cricket. I want to connect with him because i am a lover of cricket. I want to learn cricket from him. I want some cricket tips from him.



3. Albert Einstein :  He is the father of physics. Its 
major contribution in physics was the general theory of relativity and develop an energy-mass relation with his formula E=mc2. He is also nobel price winner in 1921. I want to connect with him because of his qualities. He is a great man.




4. Chetan Bhagat : He is an Indian writer who write 

novals. One of  his famous noval "Three mistakes of my life" is my favourite noval. I want to connect with him because he inspired me alot from his novals. He is one of the greatest writers in Indian history. 



Here's my chat with Chetan :
Me : Hey, Chetan. Please write something about me on your next book.
Chetan : Ya sure.. but how can i know about you.?
Me : I will tell you with video calling in WeChat.
Chetan : okay.. Wait for it, i will send you request when i will free.
Me : okay.. Thanks.. It was nice talking to you. :)


5. Supi(fictitious) :  He will break the record of 

Sachin Tendulkar, use more brain than Einstein and write novals. He will make a new programming language. I just want to connect with him because I don't want to miss a chance to connect with the future of all the legends.



Here's some part of my group chat with Einstein and Supi :
Me : Supi(fictitious), How could you do that ?
Supi : It was just an easy job for me.. :D
Me : Hahaha.. You are second Rajnikanth in the world.. :P
Supi : Thanks for your compliment. :)
Me : Einstein, You are gone now. No one will remember you in the future, Its all about Supi. :P
Einstein : ohh... Not know what to do.. :(


About WeChat :



WeChat is a mobile text and messaging communication service developed by Tencent in China. It was first released in January, 2011. It is a mobile messanger app in which voice chatting, group chatting and many more features. Now the time it ranked at number one in the world as compared to other messanger apps.

WeChat you tube channel tells you more about WeChat.

Here are some features that WeChat provides :

1. Free : Most messanger apps in the market are not free. They take charges for use but WeChat is free app.



2. Group and Live Chat : We chat provides you to connect with as many people as you want in a group chat.



3. Connect With Facebook : WeChat gives you the option so that you can connect with facebook friends with just single click.





4. Save Chat History/Backup : Saves your chat history in another file with password.


5. Video Call : Provides you the option of video calling in which you can talk with other person face to face.


6. Voice Chat : You can chat by your voice at anytime between the live chat also.


7. Web WeChat : Chat by the use of your pc.


8. Moments : Share your pics with your friends and public also.


9. Emoticons : Emoticons are the way to express your mood. Select one of the image from different images and share it.


10. Platforms : Supports almost all the platforms.


Hope these features are enough to convince you for WeChat.

Read more

Saturday, 4 May 2013

Why Java is Secure and Portable ?




The answer is
  BYTECODE.!

Bytecode it the key that makes Java language most secure and Portable.


When you compile your java program then on successful compilation , java compiler (javac) generates a class file with .class extension which contains the Bytecodes of your java program. Now the Bytecodes which are generated are secure and they can be run on any machine (portable) which has JVM.


No doubt Java is Platform Independent, but Java is JVM dependent.!
Actually , JVM is an interpreter for Bytecode.
The details of the JVM will differ from platform to platform, but all interpret the same Java Bytecode according to machine/platform.

The Bytecode which are generated by the compiler will be tested by the JVM on the execution of the program or we can say every Java Program is under the control of the JVM which checks the code on the runtime many times for viruses and any malicious.

The Bytecode generated by the compiler are also supported on any machine which has the JVM which makes Java a platform independent language.



What happens if Java Program were not compiled with Bytecodes?

If the Java Program were compile to native code (other than java language) , than different versions of the same program would have to exist for each type of CPU connected to the Internet. Thus, the interpretation of the bytecode is the easiest way to create truly portable programs.



Can Interpretation of Bytecodes makes the Execution Slower?

The answer is NO.!
Since, many old programming languages  like C, C++ etc. only compiled (whole code conversion to machine code) or interpret (line by line conversion) the code on execution but this is not the case with Java language which first compile the source program to Bytecode and than interpret the code on execution. Now this interpretation of the Bytecode is very fast and which makes the Java is much faster language than any other.

These are the reasons which makes Java the most Secure and Portable language than any other language.
Read more