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

Wednesday 24 April 2013

Music – Something that makes us (HP Connected Indiblogger meet)




An Experience :

Last Saturday (20 April) , I had attended the indiblogger meet at Hilton Garden Inn Gurgaun Baani Square. I am sharing the experience of that meet with all of you which was organized by HP.
I am writing about music in my blog which is all about the java language just because I want to share the experience of my first indiblogger meet. There is a music on java too


 which encouraged me for writing the post about the music.

Although since the music is something that is connected with us in every way of life and makes us so, I could not stop mine for not sharing my views in the HP connected blogger meet.
Music gives us the inspiration to do everything we want. Whether you are sad , whether you are happy or whether you are feared than music is the one thing that feels you better. It is the art that changes your mood. We are living in the world of music. It is the feeling that creates us.
There were some pretty cool interviews in the meet.
Prateek Shah or rather more affectionately 'Prateeksha' made us all laugh to the core.!!


About HP connected service :
HP connected music service works with the windows 8 installed hp laptops. It gives us the service in which you can listen to over 1 million songs and 20,000 artistes which can be played with one click.
No need to pay for tracks again and again in this service. Music downloading for million songs is free for one year after activation of the service.

This service provided by hp because of the parternship with Universal Music and Hungama.
The site looks like this when you open it after the activation of the service :



With the help of this service you can find the latest talks about the artists. With the help of search bar you can search many of the artists or their songs in one click.
The installation steps are given in the website of HP.

This service  works with windows 8 installed hp laptops. There is no limit of downloading songs from HP connected Site once you have activated this service.
Note : These pros and cons are from my view. I am not responsible if you find any kind of changes in these pros and cons.

My Favorite Artist and the song :
One song that always remain close to my heart is- In the End by Linkin Park.




It is an ultimate sound of music for me. I first heard it in my college and it stayed in the heart for forever. The lyrics especially – “I tried so hard and got so far but in the end it doesn’t even matter” well expressed that I found myself listening to this song ever and ever again.
Other artists and their songs I want to hear are Mohit Chauhan , A. R. Rahman etc.

Music is a pure magic. It is a wonderful gift to humanity. We can express our emotions with the help of music. It is the thing that help you out of the selfish world.

Inspiration behind my love for music :

Inspiration is matter of finding something that we like. I like the music since my childhood. It is all the matter to find something that make you smile, rocks you and they all comes in the form of music. 
There is no way of telling what inspiration i have behind my love for music but it is the music which makes you feel good or bad according to the situation.
Music is something that is related to our soul not our body. It is a Universal language.

Conclusion :

If you have plan to buy a laptop and you are a music addict than must go for HP Notebook preinstalled windows 8 and enjoys the HP Connected music. Just try once this service and you will go to the world of music.
Read more

Friday 19 April 2013

The 'new' operator in java




The 'new' operator in java is responsible for the creation of new object or we can say instance of a class.
Actually, it dynamically allocates memory in the heap with the reference we define pointed from the stack.
The dynamically allocation is just means that the memory is allocated at the run time of the program. The advantage of this approach is that your program can create as many or as few objects as it needs during the execution of your program.

For example :
Before creating a new object of the class we create the 'reference' variable of the class as

Demo obj;
(Where Demo is the class whose object we want to create)

Now this statement only creates a reference variable of a class or the "Demo" class data type.
There are data types such as integers, characters etc. but we don't need to create these with the help of
new operator because they are not implemented as objects in java rather they are implemented as normal variables because of the efficiency. Since all objects have some properties and behavior and require java to treat them differently than it treats the simple types.
Object version of these data types is also present with the help of wrapper classes which concept is not needed yet.
All the reference variables lies in the stack of the memory and hence 'obj' is .
Currently the reference "obj" is pointed to the null or it is not pointing to any object.

If we use the new operator than the actual or physical creation of the object is occurred.
The statement is :
obj = new Demo();

This statement does two things :
1. It creates the actual or physical object in the heap with the variable 'obj' pointing to the object from the stack.
2. It calls the constructor of the "Demo" class for the initialization of the object.


Basically, the "Demo()" in the statement is the default constructor.
A constructor defines what occurs when an object of the class is created.
Most real-world classes explicitly defines their own constructors within their class definition and if no explicit constructor is specified in the class then java will automatically supply a default constructor.

Also the two statements can be combined into one statement as :
Demo obj = new Demo();

Now at this time the 'obj' which has points to the actual object of the Demo class can call any not restricted methods.
Consider the case, when we declare another reference of the class and equating that variable with the previous reference i.e, obj
Demo obj1;
obj1 = obj;

It is to be noted that the above statement cannot create new object in the memory but the 'obj1' reference variable now points to the same object which is pointed by the 'obj'



Also at any time if we point 'obj' object to null than it does not mean than the 'obj1' object is destroyed.

obj = null;

This means that the 'obj1' object will points to the same object but the 'obj' will not points to any object.


So, this is all about the 'new' operator.
Read more

Wednesday 10 April 2013

ACCESS SPECIFIERS/MODIFIERS IN JAVA



ACCESS SPECIFIERS/MODIFIERS IN JAVA


Access Specifier/Modifier in any language defines the boundary and scope for accessing the method, variable and class etc.

Java has defined four types of access specifiers. These are :
1.    Public
2.    Private
3.    Protected
4.    Default

If you do not define any access specifier/modifier than java will take “default” access specifier as the default for variables/methods/class.

SYNTAX For declaring a class with access specifier :
<access-specifier><class-keyword><class-name>

For e.g.
public class Demo

    public access specifier :
If you declare any method/function as the public access specifier than that variable/method can be used anywhere.

public Access Specifier Example :
   package abc;  
   
 public class AccessDemo  
 {  
   
      public void test()  
      {  
            System.out.println("Example of public access specifier");  
      }  
 }  

In any other package if we want to access the class "AccessDemo" then we only need to import the abc package as shown in the following code :

    package xyz;  
 import abc.AccessDemo;  
   
 public class AccessExample  
 {  
   
      public static void main(String[] args)  
      {  
           AccessDemo ad = new AccessDemo();  
           ad.test();  
      }  
 }  

     private access specifier :
If you declare any method/variable as private than it will only accessed in the same class which declare that method/variable as private. The private members cannot access in the outside world. If any class declared as private than that class will not be inherited. :

private Access Specifier Example :

    class AccessDemo   
 {  
       private int x = 56;  
   
      public void showDemo()   
      {  
           System.out.println("The Variable value is " + x);  
      }  
    
      private void testDemo()   
      {  
           System.out.println("It cannot be accessed in another class");  
      }  
 }  
    
   
 public class AccessExample   
 {  
    
      public static void main(String[] args)   
      {  
           AccessDemo ad = new AccessDemo();  
           ad.testDemo(); // Private method cannot be used  
           ad.x = 5; // Private variable cannot be used  
    
           ad.showDemo(); // run properly  
      }  
 }  
   

    default access specifier :
If you define any method/variable as default or not give any access specifier than the method or variable will be accessed in only that package in which they are defined.

They cannot be accessed outside the package.

default Access Specifier Example :

In one package we define the variable default as below code :

    package abc;  
   
 class AccessDemo   
 {  
      default int a = 4;  
 }  

Now in any other package if we want to change the value of a, it is not possible because the other package has not access permission for "a" variable.

 package xyz;  
 import abc.AccessDemo;  
   
   
 class AccessExample   
 {  
      public static void main(String[] args)  
      {  
           AccessDemo ad = new AccessDemo();  
           ad.a = 67; //It is not possible.  
      }  
 }  

    protected access specifier :
It has same properties as that of private access specifier but it can access the methods/variables in the child class of parent class in which they are declared as protected.

When we want to use the private members of parent class in the child class then we declare those variables as protected.

protected Access Specifier Example :

 class AccessDemo   
 {  
      protected int x = 34;  
    
       public void showDemo()   
      {  
            System.out.println("The variable value is " + x);  
       }  
 }  
    
 class ChildAccess extends AccessDemo  
 {  
       // child class which inherits  
       // the properties of AccessDemo class  
 }  
    
 public class AccessExample   
 {  
    
       public static void main(String[] args)   
      {  
            ChildAccess ca = new ChildAccess();  
    
            ca.showDemo(); // run properly  
            ca.x = 45; // run properly  
 }   
 }  
Read more

Friday 8 March 2013

FIRST JAVA PROGRAM - HELLO WORLD!





In order to write your first Java Program, you require :
1. JDK installed on your computer.
    You can install it from here : 
    http://www.oracle.com/technetwork/java/javase/downloads/index.html

2. Setting of environmental variable path.

3. A simple text editor.

First Java Program - Hello World!

The code looks like this :



After writing the above code in notpad, save it anywhere with filename "Hello.java".
Note : All the java programs must be saved with the name equal to classname with an extension .java.

Now for compiling open the command prompt and go to the location of your file in which the java code was saved and type :

javac Hello.java

and press enter. 



If nothing happens it means the program is correct or not containing any error.
Now you need to Execute the program and for executing just type :

java Hello

and press enter



Now you can see that the output is "Hello World!" shown in the cmd.

EXPLANATION OF PROGRAM :

The code is shown as :


public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}

Since java is based on object oriented concepts, hence all the code must be stored in a class.
In above i am taking a class named "Hello" . You can use any name but make sure that the code is stored with the same name as that of the class . This is because when the code is compiled using java compiler then a class file (which contain byte codes)  is created with the same name as that of your file name.
And when you execute your program then the JVM (Java Virtual Machine) search for the class file and by using the name of class file it finds your program.
So, we can say that the name of file is same as that of the class name because JVM easily linked the class file with program file.

Now in the class there is a main method, which starts the execution of program.
In main method "public" is used as access specifier.
"static" is used because we want the main method should be run without making the objects of the class.
"void" is used because method is not return anything.
and parameters is passed as "String[] args" for handling the input given by user, which is not used in this program.

"System.out.println()" method is used for writing the output on the screen.

Read more

Wednesday 6 March 2013

SETTING OF ENVIRONMENTAL VARIABLE PATH FOR JAVA



HOW TO SET THE ENVIRONMENTAL VARIABLE PATH FOR JAVA.



In Windows inorder to set

Step 1 : Right Click on  "My Computer"  and click on properties .




Step 2 : Click on Advanced tab




Step 3: Click on Environment Variables






Step 4: Now copy the path of your jdk/bin from the program files which lies in the folder named java in your computer where you install the jdk.
It is mostly stored in the C - drive.
Make sure that you choose jdk not jre.







Now copy the path as shown below..



Step 5: Now go to the Environment variables dialog box and create a new class path  
                 for JAVA_HOME.








Step 6 : Paste the path in the "variable value" column and set "variable name" as path.

After editing click OK.
Step 7 :Your are done setting up your environment variables for your Java , In order to test it go to command prompt and type
  javac



Now click "Enter" and If you get the output as shown below your path for java is set.


If you have any problem regarding this please comment below.

Read more