Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Saturday, July 26, 2014

JDBC Connectivity in Java

JDBC is used to establish connection with database through java program. Java Database connectivity is four step procedures. Let us see each step in detail for oracle database connectivity.

1. Loading database driver: first step is to load the driver class called “OracleDriver” into main memory.
Class.forName( "oracle.jdbc.driver.OracleDriver" );
Here “oracle.jdbc.driver” is package name and “OracleDriver” is a class name which contains driver methods.

2.Establish a Database Connection: second step is to create connection object by mentioning driver name, server address, user name and password.
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl”,”Username”,"Password” );
Here “jdbc” is database, “oracle” is sub database, “thin” is driver type, “127.0.0.1” is host name, “1521” is port number used for connection, “orcl” is name of service used (SID), “Username” is database username and “Password” is password for corresponding user.

3.Execute SQL Statements: Once connection with database is created, we need to execute SQL queries using above connection object.
Statement stmt = conn.createStatement();
stmt.executeUpdate(“QUERY”);
Here we have created statement stmt using connection object and “QUERY” is SQL statement that has to be executed using executeUpdate().

4.Close Database Connection: Once all the SQL transactions are done with database, we need to close the connection with database.

conn.close();

Wednesday, July 23, 2014

What is difference between String,StringBuffer and StringBuilder

The main difference is w.r.t. whether the objects are mutable or immutable.
Immutable means that once the object is created the value inside the object cannot be changed. Mutable object allows the value inside object to be changed whenever needed.
The main difference between String, StringBuffer and StringBuilder is that Sting objects are immutable whereas StringBuffer and StringBuilder objects are mutable.
Suppose we have String object as
String str="Hello";
str = "Good Morning";
str is assigned value “Hello” and further if str is assigned new value “Good Morning” . it will not replace “Hello” with “Good Morning” and it will have both the strings in string literal pool but str will start pointing to “Good Morning”. If we keep on changing value of str like this, string literal pool will have all those previous strings which increases size of string literal pool and every time new string object is created.
So if there are frequent changes in string contents then StringBuffer or StringBuilder should be used.
DIFFERENCE BETWEEN STRINGBUFFER AND STRINGBUILDER
StringBuffer and StringBuilder both have same methods with only difference of synchronization. All the methods of StringBuffer are synchronized while the methods of StringBuilder are not synchronized. The synchronized methods are thread safety implemented for thread environment. So if you are using threads in your program, StringBuffer should be used otherwise StringBuilder can be used.
Here is an example which will clear the exact difference between them.
String a = "Hi";
StringBuffer b = new StringBuffer("Hello");
StringBuilder c = new StringBuilder("Hello");
a=a.append("Java");
b=b.append("Java");
c=c.append("Java");
Here new object is created for String with value “Hi Java”, whereas in case of StringBuffer and StringBuilder, the same object is updated with the value “Hello Java”.

Finally when to use which string class
• String: if string operations are not used in your programs then you should use String class.
• StringBuffer: if you are using threads then you should use StringBuffer class as methods are synchronized
• StringBuilder: if you are not using threads then should use StringBuilder class.

What is difference between Typecasting and Coercion in Java

In computer science, typecasting, and coercion are different ways of changing an entity of one data type into another either implicitly or explicitly. This is done to take advantage of certain features of type hierarchies or type representations.
The process by which a compiler automatically converts a value of one type into a value of another type is called as 
Coercion.
Let us see, how coercion and casting are different in following example.
Coercion (implicit):
double d = 3.0 ;
int i =1 ;
if (d > i) d = i;
Cast (explicit):
double da = 3.3;
double db = 3.3;
double dc = 3.4;
int result = (int)da + (int)db + (int)dc;
 //result == 9

integer i is getting converted into type double implicitly. Implicit conversion from int to double is possible since size of int(4 Byte) is less than the size of double(8 Byte). Whereas conversion of double to int is not an implicit conversion rather its explicit conversion since size of double is larger than size of int.
compiler does implicit conversion only when there is no precision loss, for example
int j = da // double (da=3.3) can not be converted into int implicitly since after conversion there is loss of precision by 0.3.

Friday, July 18, 2014

What is Garbage Collection in Java ?

The Garbage collection is automatic memory management mechanism provided by java in order to reclaim memory occupied by ideal objects or objects which are no longer used in our program. Garbage collector frees programmer from manually dealing with memory de-allocation. The Garbage Collector is a demon thread which starts running automatically as soon as we execute program. So java program in execution, consists of two threads main thread and garbage collector thread. Garbage collection internally uses finalize() method of object which gives a chance to reclaim any type of resources hold by the object. We can manually call garbage collection using System.gc() but since we do not know when the object needs to be reclaimed and when the object is not in use. Manually calling System.gc() is just a hint to JVM that garbage collection is needed.

Generally Garbage collection internally runs mark and sweep algorithm which is two phase procedure.

Phase 1: Mark
The first phase in garbage collection is marking. GC will mark all the objects as alive, ideal and not referenced. It will internally create the graph of alive and ideal objects.
All the alive objects are directly reachable from the root objects. As long as object is referenced, it is marked as alive. The objects those are referenced but are not used for long time are marked as ideal and the remaining objects are marked as not referenced.

Phase 2: Sweep/Compact
In this phase, GC actually starts reclaiming the objects memory. First it will reclaim the memory of all the objects which are not referenced. Now if any class wants to create new object and if sufficient memory is not available in that case GC will look for ideal objects and will reclaim their memory. If the objects are ideal and sufficient memory is available for creating more objects then garbage collector will not reclaim ideal objects memory.

Here GC moves all the alive objects to the bottom of heap and leaves free space at the top of heap. As objects are moved, the pointers to these objects become invalid, so GC corrects these pointers and helps to solve memory fragmentation problem.

Why file name is same as class name containing main method in java ?

Whenever any member is declared as static, it can be used before any of its object is created, just by using class name. Hence static members are used just by using class name. When JVM calls main(), it does not have any instance of class having main() method. So this main() method is called as classname.main().

JVM needs classname to call main() method. How does JVM know what is your classname ?. When java program is compiled as javac filename.java, (filename is same as class name containing main() method) JVM knows your classname using which it calls main().

So file name is same as class name containing main method in java.

Thursday, July 17, 2014

Why Java Is Platform Independent

Getting output from java program is two step procedure, compilation and interpretation. Output of java compiler is not executable code but it is compiled code. JVM is an interpreter for byte code. Byte code is set of instructions which are to be executed by java run time system called as Java Virtual Machine (JVM). Each JVM has its own executable format so this byte code (.class file) becomes platform independent as this byte code runs on JVM and not on actual OS.
So once we have compiled java program, it can be executed on any platform. The details of the JVM differ from platform to platform and each OS has its own JVM format.  So in java it is “write once; run anywhere, anytime”.

So java is platform independent and JVM is highly platform dependent.

Why Java Is Preferred?

The developers preferred java over traditional programming languages like C and C++.Java is preferred due to its unique feature platform independent, robustness and more secure.
·         Simple: Java inherits most of the syntax of C and many of the OOPs features of C++. In addition to this is has its own add in features which are easy for professional programmers to learn.
·         Object Oriented: Java uses OOPs concepts for faster programming. It has most of the packages and interfaces built-in which are easily reused and extended. The class and object structure provides data encapsulation, abstraction, inheritance and polymorphism.
·         Robust:  Java is robust because of two reasons memory management and exception handling. In traditional programming C,C++ dynamic memory management is very difficult as memory allocation and de-allocation must be done by programmer but java does this dynamic memory allocation and de-allocation without any extra efforts. Exceptional conditions may arise in traditional programming which may leads to abnormal termination of programs but java provides exception handling which helps to handle and eliminate these run time errors.
·         Secure: All java programs run over JVM platform and not on Operating system. So any OS related updates or modification does not affect execution of java program. Java also provides packages and access modifiers which in turn provides security. Java applets are executed inside sandbox which creates an environment which provides restricted access to OS resources and allows user to run untrusted code from unknown source safely. Java uses byte code verifier module which checks java code automatically before executing it. Java provides run time array boundary check which is not provided in traditional programming. In traditional programming memory references can be manipulated but in java you cannot manipulate references which interns provides secure memory access.
·         Platform Independent: Traditional languages C, C++ were designed to compile for specific platform (processors, OS). In java executable code runs over JVM platform which is independent of OS. So once we have byte code (.class file) we can execute it on any OS. So java code needs to be compile only once and we can execute it any number of times across different platforms (processors, OS). So it is “write once, run anywhere, anytime”. 
·      Multithreaded: Java provides multithreaded programming which allows doing many things simultaneously. Each thread performs separate task. For example using text editor with spell check feature enabled which allows editing and spelling check simultaneously.

Tuesday, July 15, 2014

Why Java is preferred over C and C++

When it comes on selecting a programming language, we need to consider few parameters like security, robustness, ease in programming and few other parameters, because of below mentioned parameters java is preferred over C++ :

·         Robust:  Java is robust because of two reasons memory management and exception handling. In C,C++ programming dynamic memory management is very difficult as memory allocation and de-allocation must be done by programmer but Java does this dynamic memory allocation and de-allocation without any extra efforts.

·         No Pointers: Use of pointer is avoided in Java. In C++ programming memory references can be manipulated but in Java, you cannot manipulate references which in turn provide secure memory access.

·         Platform Independence and Portability: Traditional languages C, C++ were designed to compile for specific platform (processors, OS). In Java executable code runs over JVM platform which is independent of OS. So once we have byte code (.class file) we can execute it on any OS. So Java code needs to be compiled only once and we can execute it any number of times across different platforms (processors, OS). So Java provides platform independence and portability.

·         Secure: Java provides sandbox security model for applet execution which creates an environment which provides restricted access to OS resources and allows user to run un-trusted code from unknown source safely. All Java programs run over JVM platform and not on Operating system. So any OS related updates or modifications do not affect execution of Java program.  Java uses byte code verifier module which checks Java code automatically before executing it.


·         Multithreading : its support to multithreading made java enabled for multitasking which allows available resources to be used optimally. Java has built in support for multithreading but in C++, multithreading is entirely dependent on Operating System.

Why java is Secure

When it comes across the security issue of programming languages, Java is surplus over traditional programming languages like C and C++. Java is more secure than C and C++ for the following reasons:

·         Its JVM and not OS: All Java programs run over JVM platform and not on Operating system. So any OS related updates or modification does not affect execution of Java program.

·         Sandbox Security Model: Java applets are executed inside sandbox which creates an environment, which provides restricted access to OS resources and allows user to run un-trusted code from unknown source safely.

·         No Pointer Manipulation: In traditional programming memory references can be manipulated but in Java we cannot manipulate references. Thus you cannot cause an object reference to point to an arbitrary memory location, which in turn provides secure memory access.

·         Byte Code Verifier:  Byte code verifier checks correctness of class files and API libraries. Java uses this byte code verifier module which checks Java code automatically before executing it.

·         Array Boundary Check: Java provides run time array boundary check which is not provided in traditional programming.

·         Packages and Access Modifiers: This combination of packages and access modifiers allows your class to have detailed knowledge of each other, but not expose that knowledge outside that package.

·         Run Time Exception Handling: Exceptional conditions may arise in traditional programming which may lead to abnormal termination of programs but Java provides exception handling which helps to handle and eliminate this abnormal termination.

·         Dynamic Memory Allocation and De-allocation: In traditional programming C,C++ dynamic memory management is very difficult as memory allocation and de-allocation must be done by programmer but Java does this dynamic memory allocation and de-allocation without any extra efforts. Java uses new operator to dynamically allocate memory and Garbage Collection technique to handle automatic memory de-allocation.


·         Two Level of Code Checking: Code is checked two times, first at compile time and then at run time which can be considered as more secure than single level of code checking.

Why main method is public static void in java

HelloWorld.java is a sample program which contains main method.
To Compile: javac HelloWorld.java
To Execute: java HelloWorld

Lets see what is meaning of public static and void keyword in main() declaration

·         public: The main method is called by JVM when we execute “Java HelloWorld”. But since the JVM is out of scope of main method of the class HelloWorld. to make it accessible by JVM, so main method is public in java.

·         static: static keyword allows us to access members without creating object of that class with the help of class name. When JVM calls main method, it does not have any instance of the class having main method. JVM calls main method internally using class name like HelloWorld.main().So main method is static in java.

·       void: when any method does not returns any value its return type must be void. As main method does not return any value, so main method is void in java.

Saturday, July 12, 2014

Does Java support Multiple Inheritance?

Answer to this question is yes, java does not support multiple inheritance but by introducing the concept of interface it just gives the feeling of multiple inheritance but still it is not multiple inheritance.

Multiple inheritance means inheriting more than one class into single class. A class may implement more than one interface but it can inherit only one class. Interface does not contain method implementation but it contains abstract methods which need to be implemented by the class which uses that interface. So it just gives feeling of multiple inheritance but it is not multiple inheritance as the class which uses those interfaces must implement the methods present in those interfaces.

Multiple inheritance gives rise to diamond problem. Let us see that this problem is.

In the above diagram, two classes B and C are derived from same class A and class D is derived from two classes B and C using multiple inheritance. The problem with above type of inheritance is that when an instance of D is calling any method of class A, it is not clear whether to call version of method derived from class B or class C. You can see in the figure above that the classes essentially form the shape of a diamond, this problem is called the diamond problem.

In the designers' opinion, multiple inheritance causes more problems and confusions than it solves. The use of multiple inheritance results into diamond problem so for the sake of simplicity, multiple inheritance is not supported in java. 

Java is Compiled and Interpreted Both

It seems little confusing for java beginner to understand the exact difference between compilation and interpretation. Java is compiled language because java code is compiled to get byte code. Java is interpreted language because this byte code is interpreted into native code.

Actually getting output from java program is two steps process compilation and interpretation. The executable used for these steps are java compiler (javac) and java interpreter (java). First step is compilation in which the java compiler compiles the source code to generate byte code in the form of .class file. Actually this byte code is not machine code but it is just an intermediate code. In the second step java interpreter uses this byte code to generate native code for under lying operating system. The JIT (Just In Time) compiler comes into action in second interpretation step. The JIT reads the byte code to generate native code dynamically so that program runs fast.


Finally in short, java is compiled to byte code which is then used by JVM where it gets interpreted to native code. So java is compiled and interpreted both.

What is JVM JRE and JDK

JVM, JDK and JRE are most commonly used in java programming. Many people think that these are same or gets confused about their differences. JVM, JDK and JRE are interlinked with each other and works together in cooperative manner.
  •  JVM (Java Virtual Machine): Interpreter + JIT
JVM is code executing component of Java that executes byte code (.class file). The output of Java compilation is byte code and only JVM can understand the byte code. JVM interprets this byte code to native code depending upon underlying processor and architecture. JVM has two main components interpreter and Just In Time (JIT) compiler. JIT is compiler which helps for optimizing byte code to machine code conversion and hence results into reduced execution time.  Note that Java is platform independent but JVM is not platform independent. Each JVM has its own structure of executable which differs from platform to platform. For each OS there is different JVM available. So JVM is highly platform dependent.
  • JRE (Java Runtime Environment): JVM + byte code verifier + class loader
JRE contains an environment for execution of Java program. JRE consist of JVM, class loader and byte code verifier. Class loader module loads all the .class files (byte code) and required libraries which are then verified by byte code verifier. Then this verified code is interpreted by JVM which creates native code.
  •  JDK(Java Development Kit): JRE + Development tool
JDK contains tools like compiler and debugger to develop Java program. It provides predefined set of libraries, API classes and other files which is used by JVM at runtime. It also includes JRE, interpreter (java), compiler (javac), document generator (javadoc).


Setting Path Environment Variable in Java


For the beginner one of the difficult and confusing task is to set path and classpath environment variables.
Path is nothing but setting up an environment for operating system. Path is a system variable used to tell to Operating System all locations of executable files. Operating System will look in this path variable for executable files.
Classpath is nothing but setting up an environment for java. Classpath is pure java variable, which is used to tell the Java Virtual Machine or the Java compiler where to look for user-defined classes and packages.

For example,assume that Java is installed in C:\Program Files\Java\jdk1.7.0_25\ and your code is in C:\Sample\example.java, then path and classpath should be set to like this:
classpath=C:\Sample
path= C:\Program Files\Java\jdk1.7.0_25\bin;
Or
path=%JAVA_HOME%\bin;
where JAVA_HOME is pointing to Home directory “C:\Program Files\Java\jdk1.7.0_25”, where jdk is installed

Let us see what exactly means by setting path variable
Whenever you try to compile a program using javac, JVM will search for javac in current directory where your program is residing, If it does not find javac and other executables in current directory then it will search in the directories where the path variable is set to. So setting path variable allows you to execute your program from any directory as location of executables java and javac is retrieved through path variable.
If you have not set path variable then it will show error like “javac is not a recognized command” . hence to remove this error set path environment variable as follows:
  • Command to set path variable from command prompt

·         Set path=”C:\Program Files\Java\jdk1.7.0_25\bin”
·         Set path=%path%;”C:\Program Files\Java\jdk1.7.0_25\bin”
Here in second command we are just adding our path value to existing value of path variable.
  • Command to remove value from path variable

·         Set path=
This will remove directory path from environment variable.
  • Check whether environment variables are set correctly or not

·         If your environment variables are set correctly, then windows should recognize these commands.
C:\> java OR
C:\> javac
·         you can see current value of path variable by following command
C:\> echo %path%