Sunday, 29 July 2012

String objects are immutable



String is one of the most important classes in Java API.String objects are immutable. It means that once an object is created it cannot be modified.Immutable objects are automatically thread safe/synchronized.Apart from String class, all the other Wrapper classes like Integer,Boolean,Character,Byte.., etc are also Immutable.

A string object can be created either by using new operator or  by using sting literals.

String txt1 = "Text1";
// this creates an object with value "Text1" and assigns to txt1 in the string constant pool.(String constant pool is maintained by the JVM, for memory management.This way it looks for the string constant pool to find out if there is already an object with the same value, if so, it makes this reference to point to the same object instead of creating another object).

eg., if there had been another object created like this before
String txt2 = "Text1";
then String txt1 = "Text1"; will merely assign the txt1 reference variable to "Text1" object.This way there may be a lot of references pointing to the same object. If some other program is allowed to modify the object, then there might be problems for the other references.This is the reason why String objects have been made immutable. 

String txt1 = new String("Text1");
//this creates a new object with value "Text1" and assigns to txt1 in the heap.

To check the above, we can use the == operator and .equals() method.

== operator checks if the references are pointing to same object.
.equals() checks if the values are same in both the objects.

Code:
public class CheckString {
public static void main(String[] args) {
String txt1 = new String("Text1"); //object created in heap
String txt2 = "Text1"; // created in string constant pool
if(txt1 == txt2)
{
System.out.println("txt1 and txt2 references points to same  object");
 }
if(txt1.equals(txt2))
System.out.println("values are same for both txt1 and txt2");
 String txt3 = "Text1" ; // in String constant pool as already       there is "Text1" object, txt3 is made to point to it instead of     creating new one.
 if(txt2 == txt3)
   System.out.println("txt2 and txt3 points to same object");
 if(txt2.equals(txt3))
   System.out.println("txt2 and txt3 values are equal");     
 }
 }

Solution:

values are same for both txt1 and txt2
txt2 and txt3 points to same object
txt2 and txt3 values are equal


Java Heap Space:
Java's Heap space is the memory what JVM borrows from operating system and allocates for our program.Every object created with new operator is stored in this heap space.Most of the unused objects are garbage collected. But, some times we do encounter,  java.lang.OutofMemory error in our webserver console.To solve this, we can increase the heap size by overriding the -Xms and -Xmx parameters. It mentions the minimum and maximum memory size respectively.Restart the web server and the error goes away..

java -Xms<initial size> -Xmx<maximum size> program_name
eg., java -Xms64m -Xmx128m CheckApp
However if the heap size is set greater than our computer's physical memory, it leads to some error like

Error occurred during the initialization of the JVM.
Could not reserve enough space for object heap
could not create the Java virtual machine.


Solution:
Reduce the heap size lesser than the physical memory.


If the outofMemory does not go away , then we may have a memory leak. Memory leak is nothing but we have an object existing in the memory without reference, which will never be used again and it does not get garbage collected.





Wednesday, 25 July 2012

Access Modifiers in Java

Access modifiers helps to restrict the access of our class by other programs.
Even though we don't specify any access modifier, implicitly it has default access.


public, protected and private are the keywords used in access control.


public: By marking a class , method or variable as public , it can be accessed from anywhere irrespective of the packages.However ,though it is public, to use a class residing in some other package , we have to import it in our class.


A class can be marked only as public or default.

A java file is named with the name of the class. If there are more than one class in the java file , then the source file should be named with the class marked as public and this class should have the main method implemented. There cannot be more than one public class in a java source file.If no class is marked public, then the one with main method should be used as the source file(.java) name.


protected: By marking a method or variable as protected, it can be accessed within the class as well its subclass irrespective of the package.It cannot be accessed if there is no inheritance.


default: If there is no access specified then, implicitly compiler applies default access to it.Like other key words, we cannot explicitly specify this modifier.In this case, the class, method or variables are accessible within the class and even from some other class, but within the same package.


private: By marking a method or variable as private, its access is restricted to its class. Nothing from outside the class can access it.










Thursday, 19 July 2012

Java Program execution - a deeper look.




Java Compiler - javac..


javac is the java compiler used to compile the java program. It is included in the Java Development Kit(JDK). It is responsible to convert the java  source code to bytecode adhering to the specifications of the Java Virtual Machine(JVM).

JVM..
It is the JVM, who interprets or runs the byte code.
JVM is distributed with the dynamically loadable libraries(reusable functions) used by most of the operating systems. These Java Class libraries internally implements the JAVA API. JVM together with these API forms the JRE.
JVMs implementation differs across various operating systems.JVM has a Just in Time(JIT) compiler within it which can interpret the bytecode and convert it into the Machine code during the run time.

Java is platform independent...
As the byte code is created here during the compilation, it can be used in any platform installed with the JVM specific to its operating system. Hence Java is referred to as platform independent language. (However JVM s implementation are platform dependent). A .class file created in one platform can be executed in any other platform.


When a Java interpreter runs a java program, the execution begins with main method. 


public static void main(String args[])


public: This is to ensure that this particular method can be accessed from any where. Marking it private will restrict its access to the particular class.So Java interpreter cannot access it.Hence it has been designed to be public.Other access specifiers are protected and default.

static: By marking a method with static keyword, we need not create an object to access the method. Here when a class file is executed by java interpreter, it has the  name of the class file.
So the main method is invoked by _class_file_name.main()...
If it is not marked static then object should be created to call the method. As all this happens even before object creation , it is designed to be static.


void: Return type has to be void.Our function need not return any thing here.Unlike C++, in Java the program may not terminate when the main method ends.It just begins from main() and in many multi threaded environments, there are other threads running to accomplish the task. Hence, it is too early to return an exit code or in many cases it does not make any sense.So in case we need to return anything like an error code , System.exist() is used for the same.


main: Java interpreter calls the main method . It cannot be of any other name.It is also case sensitive. Method main takes in the argument String args[].It can accept an array of String arguments as command line arguments. args is just a variable name . Any name...eg. abb, azx..are valid.




In the below code , the compilation creates a Hello.class file.Interpreter invokes the main method by calling Hello.main().


package com;
/*
 * Class Hello
 */
public class Hello {
/*
* Method main
* prints the text "Hello"
* execution starts from main method
*/

public static void main(String[] args) {
System.out.println("Hello"); //this statement prints "Hello"
}


}





Sunday, 15 July 2012

Requisites to run a Java Program

To compile and run a java program , we need the following


2.Install the jdk and Jre by running the set up.

2. An IDE(We use eclipse here. Please download Eclipse IDE for Java EE Developers from http://www.eclipse.org/downloads/)

Setting Environment Variables:

We  should set the environment variables in order to successfully execute our java program.

In Windows Operating system,

1.Right click Computer ->Properties ->Advanced Systems settings->Advanced ->Environmental Variables

2.Click on New. 

  •  Variable name should be PATH 
            Should point to the path of bin folder of the jdk folder installed. 

        Click on OK to save this.

  •  Add another environment variable by clicking on new . Variable name :CLASSPATH 
              
This should point to the lib folder of the JRE installed. Click on OK to save this.



  • Add another variable JAVA_HOME. This should point to the JRE Folder installed.
                  
                                       


      Click on OK to save this.


  •       Download the eclipse zip folder  and extract the same to a folder. Run the eclipse.exe file.
  •       Create a new folder and use the same as workspace.
  •       To create a new java project. Click on File -> New -> Java Project
  •       Enter the name of the project, click on OK to continue.
  •       Once the project has been created, right click on the same to create a new Java class. New-> class.(Eg. Hello)
Sample code to test the setup:

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

}

Right click on the code as shown below and and Run the code by clicking on Run as ->Java Application



This will print hello in the console.

Thanks for your time...


Thursday, 12 July 2012

Multiple Inheritance in Java::Diamond Problem



What is Multiple Inheritance???
Multiple Inheritance is a concept  which allows a subclass to inherit from more than one super class.

Unlike C++ , Java does not support multiple inheritance by extending more than one superclass.

Why so????

We have Classes B & C extending Class A ...



If another Class D is allowed to extend Class B as well as Class C...



and if doWork() method is overridden both in Class B as well as Class C

From Class D, it becomes ambiguous to invoke doWork() as it had inherited two different implementations for the same.

The class hierarchy forms a diamond shape when represented by diagram and hence got its name "THE DIAMOND PROBLEM"

This problem is however solved by using Multiple Interface Inheritance..Which we will learn when we read about Interfaces..As of now we have a understanding of why multiple inheritance is not supported by JAVA..by extending more than one super class..