Thursday, December 26, 2013

# 6 Java Object, Class and Reference for Non Primitive Data Types.!

Hello,

First of all Hapy Xmas to every one..! :) 

As you have already know how to work with Primitive Data types (at least I believe :P). Now I will explain the working of Non-Primitive Data Types which are also called as Reference Data Types.

Non-Primitive Data Types:

Our ancestors had already defined some data types so that we can use them is storing the data into variables. If we need to store the user-defined data into a variable then we need to define our own Data type. This brings the Non-Primitive data types into the picture. All user defined data types come under Non-Primitive category. But not vice-versa.  All pre-defined data types are not Primitives..!! Remember this. We have ONLY 8 primitive data types. Any other data type in this Java world is Non-Primitive.

To discuss further, you should be aware of what is a Class , Object and Reference.

Anything and everything in Java Programming language is object except Primitives. So all Non-primitive data types are Objects.

Object – In English language, the meaning of “Object” is a material thing where you can sense it by a touch or a vision. The same meaning applies for Object in Java language as well. But the Object in Java is virtual, neither we can touch it nor see it..! Every object in real time will have a state and behavior. In the same way, the objects in Java will also have state and behavior. The following explanation will give you clear idea.

Class – Class is nothing but a blue print of an object. We define all the properties and characteristics of an object in the class.

Reference – We use reference to point to a particular object. Reference variables are used to store the memory address of objects.
The following real-time example will give you more clear idea about reference, object and Class. (I found an interesting example in StackOverflow Q&A and felt that will be easiest way to explain).

Consider Sanjay (me..:P) as a Civil Engineer where I design planning for house constructions. So now I have a plan for constructing a house.
Using this plan I can create as many houses I (or you) want.

So here the plan is the Class and the house is an object in Java. Plan is a blue print from which we can create number of houses. In the same way from one Class we can create number of Objects. That’s the reason we say Class is the blue print of an object.

Now you and I have built 2 houses from my plan.  So your house and my house look SAME, but your house address is different and so as mine. If I want to invite my friend to my home, I give him my house address so that he won’t get confused even both the houses look same. Here, the address is the reference in Java. To store the address of an object or to point to an object, we create a reference so that JVM can easily identify the object.

We create objects using the following syntax,
House houseObj = new House();


From the above line I am telling JVM,
  1.        to build a house  (object) for me.
  2.        take the construction plan from Class House for bulding.
  3.        store my house reference (address) into the houseObj variable.

So here the houseObj type is a user defined Class House which is a Non-Primitive Data Type.

Sample Java Class looks as following,
public class House
{
	// constructor
	public House()
	{
  	}
 
 	// house properties
 	private String ownerName;
 	private String address;
 
 
 	public String getOwnerName() {
  	return ownerName;
 	}

 	public void setOwnerName(String ownerName) {
  	this.ownerName = ownerName;
 	}

 	public String getAddress() {
  	return address;
 	}

 	public void setAddress(String address) {
	this.address = address;
 	}
}

Hit Points:
  1. Primitive Data Types are NOT objects. Non-Primitive Data Types are objects.
  2. All user defined data types come under Non-primitive data types.
  3. Objects in Java are very similar to the objects in the real world. Every Object will have properties and characteristics.
  4. Object in java refers to virtual thing which possess a state and behavior.
  5. Class is the blue print of an object. You can create as many objects you want from a single class.
  6. Reference is a variable where we store the memory address of an object.

Thanks :-)

Wednesday, December 4, 2013

# 5 Data Types, Primitives and Variables

Hello,

It’s been taken a while for hitting my 5th post. In my previous posts I had talked about setting up the Java Environment and executing your first Java Program with errors and without errors..:P

So from this post I will be chipping into the fundamentals of Java. I believe the first and foremost basics one should know in Java are about Variables and Data Types. So let us discuss about Java Data Types in this post.!

Variables – We have data where we’ll want to store and retrieve data for further operations/calculations. So for holding the data, we require variables.
Data Types – To declare the type of data that we store in the variables, we use Data Types. Sometimes you might want to store a name "LindlarsForLife" which is a String, sometimes you might want to store a number 1234 which is an Integer.

Data Types in Java can be classified as,
  1. Primitive Data Types
  2. Reference Data types

Primitive Data Types - In Java, everything is an object except these primitive types. This is because the primitive data types directly contain values instead of references. This is the reason we say Java is not 100% Object Oriented Programming. Just because of Primitives..!
We will be talking about Reference Data Types iin future posts.

Moving forward, we have 8 primitives in Java.
  1. byte
  2. short
  3. int
  4. long
  5. char
  6. float
  7. double
  8. boolean

Before explaining each primitive in detail, here are few points I want you to know for better understanding of primitives and their working.

2's complements:  We all know that the data will be stored in the system in the form of binary bits (0 and 1). And some of the primitives will store the data in the form of 2's complement of the binary bits. Here comes a question with WHY..! Why the primitives stores in the 2's complement but not in the form of their direct binary bits?
The answer is quite simple. 2's complement is the good way of storing the integers for implementing simple math’s calculations. Try it, that’s true..! :D

Signed and Unsigned Primitives:
The primitive that can hold both Positive and Negative numbers is called Signed Primitive.
The primitive that can hold ONLY Positive numbers is called Unsigned Primitive.
There are NO unsigned primitives in Java. Burn it..!

Syntax:
In most Programming languages, we need to declare the data types before using the variable. Following the syntax,
                   [Data type] [Identifier] = [value];

Now lets see the Primitive Data Types in detail.

byte:
byte data type is an 8-bit signed 2's complement integer.
Minimum value is -128 (-2^7)
Maximum value is 127 (2^7 -1)
Default value is 0

When we need to use byte Data Type? - byte data type is very useful for memory saving. Many java applications give a very high priority for the memory usage.
So when you want to store a number between -128 to 127 (both inclusive) for better and faster performance go for byte data type.

Example:  byte a= -128; byte b= 127; byte c= 100;

short:
Short data type is a 16-bit signed 2's complement integer.
Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (2^15 -1)
Default value is 0

When we need to use short Data Type? - short data type is also used for memory saving.
So when you want to store a number between -32,768 to 32,767 (both inclusive) for better and faster performance go for short data type.

Example: short a= -25,000; short b= 31,000; short c= 100;

int:
int data type is a 32-bit signed 2's complement integer.
Minimum value is - 2,147,483,648.(-2^31)
Maximum value is 2,147,483,647 (2^31 -1)
Default value is 0.

When we need to use int Data Type? - int data type is the default data type that will be used for storing integer values. This data type is large enough to store numbers your program use. If the variable keeps on multiplying and the value keeps on updating then short and byte will not be useful as their limits are small.

Example: int a = 100000, int b = -200000

long:
Long data type is a 64-bit signed 2's complement integer.
Minimum value is -9,223,372,036,854,775,808.(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
This type is used when a wider range than int is needed.
Default value is 0L.

Example: long a = 100000L, int b = -200000L

If you have observed the above example correctly, we add 'L' after the number. Again we get a question with WHY..!

The reason behind this is when you initialize a whole number Java by default assumes that it is an int datatype. So for telling, "Dear Complier, it is not int, it is long data type", we have to add 'L' at the end of the number. If you initialize a long variable without  'L' as shown below, then the compiler will throw an error.

Example:
long a = 12345678901;
- will throw error saying The literal 12345678901 of type int is out of range
long a = 12345678901L;
- will NOT throw any error because the number is converted to                                         long type from int
long a = 123456789;
- will NOT throw error coz the number 123456789 is in the                                                  range of int datatype. The compiler will consider the data                                              type as int in spite of declaring long.

float:
float data type is a single-precision 32-bit IEEE 754 floating point. Float is mainly used to save memory in large arrays of floating point numbers.
Default value is 0.0f.
Float data type is never used for precise values such as currency. If you want to go for precision, better choose BigDecimal (we will discuss more about this in future).
Example: float a = 234.5F;
Here the reason for using ‘F’ is same as the reason for ‘L’. By default the Java compiler takes decimal values as double data type.
double:
double data type is a double-precision 64-bit IEEE 754 floating point.
This data type is generally used as the default data type for decimal values, generally the default choice.
Double data type should never be used for precise values such as currency. Same as float, if your prefer precision better choose BigDecimal.
Default value is 0.0.
Example: double d = 123.4;
boolean:
boolean data type represents one bit of information.
There are only two possible values: true and false.
When we need to use boolean Data Type? – Use this when you want to have a flag or like a switch. IN or OUT. TRUE or FALSE.
Default value is false.
Example: boolean isAvailable = true;
char:
char data type is a single 16-bit Unicode character.
Minimum value is '\u0000' (or 0).
Maximum value is '\uffff' (or 65,535).
Char data type is used to store any single character.
Example: char a ='A';

Hit Points:
  1. Java is not pure Object Oriented Programming Language. Primitive data types are one of the reason for it.
  2. Java doesn't have unsigned data types.
  3. Most of the data types in Java use 2's Complement.
  4. To declare long type we need to use 'L' and to declare float type we need to use 'F'.


Thanks :)

Wednesday, November 20, 2013

# 4 Why to set Java Path?

Hello,

In my previous post, we discussed how to compile/run java programs from C:\Program Files\Java\jdk1.5.0_22\bin folder. In this post you are going to learn how to execute java programs from any folder in the system. In other words, we will learn how to set the path of Java globally.

Path is nothing but a building path of Java where you can find all the Java library files which are needed to compile and run your programs/applications.
There is also another one named Classpath which need to be set for running the Java Applications. As we are in the beginning level, we will discuss more about Classpath in future posts.
Let us start with experiments for better understanding.
  1. Copy a java file (say in our case LindlarsForLife.java ),  on your desktop. Now open your command prompt and navigate the command to the Desktop folder by using “cd” command. In my case,
    C:\Documents and Settings\Administrator>cd C:\Documents and Settings\Administrator\Desktop
    gives me,C:\Documents and Settings\Administrator\Desktop>
  2. Now try to compile your java program from Desktop folder.

    C:\Documents and Settings\Administrator\Desktop>javac LindlarsForLife.java
    When you hit enter, you will get an error as shown below,

    'javac' is not recognized as an internal or external command,
    operable program or batch file. 
  3. At this point we will be wondering, why javac command is not recognized when we have installed Java in the system.
  4. We know that the same javac command was worked when we execute the same java program from the following folder,

    C:\Program Files\Java\jdk1.5.0_22\bin

So here the question is WHY? As I had already mentioned, my blog concentrates on WHY rather than HOW..!!

Why java commands are recognized in one folder but not in other.
The answer is simple; the Java path was not set globally, if you try to execute java commands outside the Java installation folder the java commands are not recognized and the Operating System (O.S) doesn’t understand what you are trying to do.
To overcome this, we need to set the path variable of the O.S to make it understand java commands. This can be done in 2 ways.
  1.        Using Command prompt
  2.        Using My Computer --> Properties

Setting the Java path using command prompt is a temporary process. Whenever you reboot your system, the path will be removed and you need to set it again.
You can set the path in command prompt by using path command as shown below.

C:\Documents and Settings\Administrator>set path=C:\Program Files\Java\jdk1.5.0_22\bin

Setting the Java path using My Computer --> Properties is a permanent process. I suggest you to follow this so that you need not necessarily set it every time you restart your system.

To know more about how to set the Java path in Windows Operating System, you can find the clear details here.

Make sure that you do not touch any of the already existing variables in the Path. Deleting/Modifying any of the existing variables in the Path will affect your systems working environment.


So if you have successfully added the Java Path to the System Environment Variables, now you should be able to compile/run the Java programs from any folder of your system.

You can test this by again trying to compile/run the LindlarsForLife.java from your desktop. This time, you should get the expected output.

Hit Points:
  1. We set the Java Path to tell our system where to find the Java commands so that you can do your programming from anywhere in your system.
  2. Setting the path in command prompt is a temporary process.
  3. Setting the path in My Computer properties is a permanent process.


Thanks. :)

Thursday, November 14, 2013

#3 JDK and JRE. Father and Son..!

Hello,

In this post, you are going to learn the difference between JDK and JRE which plays a major roles in Java Language.

If you have successfully installed Java in your system, then you should have Java folder in your installation path. Generally all the software’s will be installed in C:\Program Files directory (for Windows Operating Systems). If you go inside Java folder, you can see 2 folders.

  1.         jdk xxxxx
  2.         jre xxxxx                              where xxxxx is your Java version.
    
   Let us discuss about these 2 folders.


   JDK stands for Java Development Kit. As the name suggests, this folder contains files which helps the user to develop Java based applications. This folder is just like a tool kit for building java applications. If you go inside jdk xxxxx folder, you can see bin, lib, jre and other folders. There is nothing much to talk about other folders, but we need to talk about bin, lib  and jre folders.
  1.         bin – this folder contains all the executable files which are useful for compiling and running the java programs. 
  2.     .    lib – this folder contains jar files that are required for the executable files in the bin folder.
  3. .       jre – I have explained below about this folder in detail.

    
    JRE stands for Java Runtime Environment. As the name suggests, if we want to run a java program you just need JRE folder, but if you want to compile Java program you need JDK folder. If you have observed, JRE folder exists inside JDK folder and also outside JDK folder. So we can say that, JDK is the super-set of JRE. If you delete your JRE folder which is outside JDK folder, you won’t get any issues while compiling/running java programs as you already have JRE folder inside JDK.
Let us learn how to compose/compile/run a Java program.
Create a text file LindlarsForLife.java inside C:\Program Files\Java\jdkxxxx\bin folder. Copy below content, paste it in the text file and save the file with .java extension.

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

Now open the command prompt (Windows+R, type cmd and hit enter) and follow the below steps.
  1.         You need to go to the java bin directory for identifying java commands.
    For example, I have java 1.5.0_22 version
    C:\>  cd C:\Program Files\Java\jdk1.5.0_22\bin
    After hitting enter, the above command will take you to the bin directory where you have your LindlarsForLife.java file. Your command prompt will change as shown below.
    C:\Program Files\Java\jdk1.5.0_22\bin>
    2.       For compiling LindlarsForLife.java file, we need type as shown below,
    C:\Program Files\Java\jdk1.5.0_22\bin>javac LindlarsForLife.java
    The javac command is used for compiling a java file. When you hit enter for the above command, if you don’t have any errors/exceptions in your program you get a blank command prompt as shown below.
    C:\Program Files\Java\jdk1.5.0_22\bin>
    3.       At this point, if you go and check your bin directory for .class file you can find LindlarsForLife.class.  So we can say that java has compiled our java program and generated .class file.
    *Remember this point, I will be using this .class file again below..!
    4.       Now we need to run this .class file. We can do so by using the following command.
    C:\Program Files\Java\jdk1.5.0_22\bin>java LindlarsForLife
    If you observe, this time we are just writing java instead of javac and we are not mentioning .java extension for the file name. This is because we are trying to run the .class file. The java command will search for .class files in the particular folder and will compare it with the name you have mentioned (here we have mentioned LindlarsForLife). But for javac command we need to explicitly mention the type of file to compile.
    So when we hit enter for the above command, the desired output will be displayed. In our case, the output will be
    Hello..! Welcome to LindlarsForLife..!!

For more clarity, you can see my command prompt how I had executed the commands for compiling and running the LindlarsFoLife.java program


If you get the above output, then CONGRATS.! You have successfully run your first Java Program. :D

If you get any error, then also CONGRATS.! You have successfully got your first Java Program Error. :P So try again by following the above procedure correctly for getting the expected output.

Till now we have been playing inside JDK\bin folder, but now let us play with JRE. We will do the same above procedure with JRE folder and will see what happens.
Copy the LindlarsForLife.java inside JRE\bin folder. Make sure, you copy the file to JRE\bin that is outside JDK folder.

        1.    Now again open the command prompt and go to the jre\bin folder
     C:\Program Files\Java\jdk1.5.0_22\bin>cd C:\ProgramFiles\Java\jre1.5.0_22\bin
             Hit Enter, we get below command prompt.
             C:\Program Files\Java\jre1.5.0_22\bin>
        2.    Let us compile LindlarsforLife.java file.
             C:\Program Files\Java\jre1.5.0_22\bin>javac LindlarForLife.java
             When we hit enter, we get an error saying
              'javac' is not recognized as an internal or external command,
              operable program or batch file.

Why we get an error..?
Because JRE doesn’t understand what is javac command. In more detail, JRE\bin doesn’t contain javac.exe file which is used for compiling and hence it says not recognized command.

From the above experiment we got to know that, JRE cannot compile a java program.
Now let us see if JRE can run a java programming. For testing so, we need a .class file. Yes, I know you guys remember that we have LindlarsForLife.class file inside JDK\bin folder. So let us and copy/paste it in JRE\bin folder.
Let us try to run and see what happens.
C:\Program Files\Java\jre1.5.0_22\bin>java LindlarsForLife
When I hit enter, I get the desired output.
Hello..! Welcome to LindlarsForLife..!

From this experiment we learnt that, JRE can only run .class files.

So the bottom line is -- if we want to compose and compile a java program, we need JDK. JRE alone cannot do that. But if we want to run a java program (.class file), both JDK and JRE can do that..!!

Hit Points:

  1.     JDK is the super set of JRE.
  2.     JDK can compile and run java programs.
  3.     JRE can only run java programs. It cannot compile.

   Thanks. :D

Saturday, November 2, 2013

#2 Hello Java

Hello,

Here is my first Java tutorial. In this post I am going to introduce you to Java. So get ready to say Hello..! :P

Hello Java:
We (humans) use language as a tool for communication or for conveying our thoughts to other person. In the same way we need a language where both the humans and machines can understand so that we can order/command machines to work for us..! :P This is how the Computer programming languages have entered into the world. Java is one of the most popular programming languages. Here is the process what exactly happens with Java programming.
  • Java has certain standards and specifications. We need to follow them for composing a Java program. Java programs need to be saved with .java extension.
  • We have to compile that human-written/readable .java file. When we compile it, Java will generate machine-written/readable .class file. The data inside the .class files will be in 0’s and 1’s (bytecode). That is the reason we say Java is a machine independent language.  In other words, we can carry that .class file to any other system (irrespective of Operating System) in the world and we can execute it.
  • Once the .java file is compiled or we can say, once we get the .class file, we have to run it to see the expected results. Of course, if you do not follow Java’s specifications you will get an error instead of your expected result.

Let us see how to install Java and in my next post you can see how to perform the above mentioned 3 steps.
Install Java:
In this section I mostly concentrated on WHY/WHAT rather than HOW. For your questions which contains HOW, I have referred you to another sites.
So first you need Java setup file to install it in your system. You can download it from https://java.com/en/download/index.jsp.
Installing Java in a Windows Operating System is just like any other software installation process clicking Next --> Next--> I agree --> Next until you get Finish button..:P
For more info, you can see the complete installation process at http://support.skillsoft.com/customer/javainstructions.htm. To confirm that the Java has installed successfully in your system, you can follow below procedure.

  •       Open the command prompt. You can do so by
Start --> Run. Or Windows+R. Type cmd and hit OK button. You will get a window as shown in the below screen-shot.
(Don’t worry if you find the different path C:\Documents and Settings\Administrator in your command prompt.)

  • .       Type java –version command and hit enter. If the Java has installed successfully, then you should be getting something as shown in the below screen-shot.

(I have installed java 1.5 version, I know I am outdated..:P But you guys can get the latest 1.7version.)

If you see something similar as above, then Congrats..! You have successfully installed java.

Hit Points:
  • James Gosling is the father of Java. (Don’t worry he is still alive. Happy and Healthy. :P)
  • Java programs can be written in a notepad and should be saved with .java extension
  • When we compile .java file, we get .class which contains bytecode.
  • We need to execute that .class file to see the results.
  • In my next post you will learn why/how to set Java classpath and how to compile/execute a Java Program.
I hope you had a happy learning. Any suggestions, feedback, concerns, corrections or questions can be communicated through sanjay.lindlars@gmail.com

Thanks.


Saturday, October 19, 2013

#1 Its Lindlars First Step..!

Hello.! 
Welcome..!!

This is my first blog and I am so excited to hit it. First lemme tell you why I am here and what I am gonna do here. I am here for 2 things. One is - 
Few weeks back I got a DSLR camera and I was playing and experimenting with it. When I was in that process, I realized that I have a deep passion regarding Photography. So I started Googling about Photography. Read hundreds of pages to exactly understand the camera and its functionality's. I was inspired and explored new things with the help of my camera. Then I am into the world to capture some images. Many people say that 2 eyes are not enough to capture the beauty of the world. So I believe photographers should have a 3rd eye to see the world from different angle and I am trying to find that angle..:P

So I am here to show you my art of photography and get comments and feedback from you so that I keep on working to improve my skills day by day.

Below are the few images which I liked from my gallery. So I thought of sharing them you and get your opinions. I don't say these are WOW kinda pictures, but I hope you will like them. I didn't do any post production for the pictures. May be I should have. I am not much familiar with the Photoshop kinda tools so I will learn that as well once I am good at capturing pictures.
DSC_0512

Lindlars' photostream on Flickr.

And the second reason for me being here is Java. I am a Java Developer by Profession and I love working on Java stuff. So I would like to create some tutorials in an easy and understandable way which will be helpful for the one's who are interested in Java. In this way, I can learn as well..! :P I know I am selfish..! :D

So for the information, Java tutorials will be for beginners. Those who are experts -- guys you have to hold on for few weeks..:P The tutorials will be in my future blogs..!


If you have any suggestions, feedback, concerns, corrections or questions you can communicate through sanjay.lindlars@gmail.com

Thanks.