Core Java Misc
Core Java Misc
The JVM
doesn't understand Java typo, that's why you compile your *.java files to obtain *.class files that
contain the bytecodes understandable by the JVM. It's also the entity that allows Java to be a
"portable language" (write once, run anywhere). Indeed there are specific implementations of the
JVM for different systems that's why JVM is not platform independent.
The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other
components to run applets and applications written in the Java programming language. In addition,
two key deployment technologies are part of the JRE: Java Plug-in, which enables applets to run in
popular browsers; and Java Web Start, which deploys standalone applications over a network. It is
also the foundation for the technologies in the Java 2 Platform, Enterprise Edition (J2EE) for
enterprise software development and deployment. The JRE does not contain tools and utilities such
as compilers or debuggers for developing applets and applications.
JRE = JVM + components to run java applications.
The Java Development Kit (JDK) is a superset of the JRE, and contains everything that is in the
JRE, plus tools such as the compilers and debuggers necessary for developing applets and
applications.
JDK = JRE + compliers + debuggers
=====================================================================================
Method Overloading vs Method overriding
Method overloading in Java occurs when two or more methods in the same class have the exact same
name but different parameters (remember that method parameters accept values passed into the
method). Now, two or more methods with the same name in the same class sounds simple enough to
understand. But, what do we mean exactly by different parameters? Well, lets consider a very
simple example.
Suppose we have a class called TestClass which has two methods, and both methods have
the same name. Lets say that name is someMethod. Those two methods would be considered to be
overloaded if if one or both of these conditions is true:
The conditions for method overloading
1.) The number of parameters is different for the methods.
2.) The parameter types are different (like
changing a parameter that was a float to an int).
How to NOT overload methods:
Its also very important to understand that method overloading is NOT something that can be
accomplished with either, or both, of these two things:
1. Just changing the return type of the method.
If the return type of the method is the only thing
changed, then this will result in a compiler error.
2. Changing just the name of the method parameters, but
not changing the parameter types. If the name of the
method parameter is the only thing changed then this
will also result in a compiler error.
Examples of Method Overloading in Java both valid and invalid:
//compiler error - can't overload based on the
//type returned -
//(one method returns int, the other returns a float):
int changeDate(int Year) ;
float changeDate (int Year);
//compiler error - can't overload by changing just
//the name of the parameter (from Year to Month):
int changeDate(int Year);
int changeDate(int Month) ;
//valid case of overloading, since the methods
//have different number of parameters:
int changeDate(int Year, int Month) ;
int changeDate(int Year);
//also a valid case of overloading, since the
//parameters are of different types:
int changeDate(float Year) ;
int changeDate(int Year);
Overloading happens at compile time
Another important point to remember is that overloading is a compile time phenomenon. This just
means that the compiler determines whether a given method(s) is correctly overloaded, and if not a
compiler error is returned as shown in the examples above.
Overriding methods is completely different from overloading methods. If a derived class requires a
different definition for an inherited method, then that method can be redefined in the derived class.
This would be considered overriding. An overridden method would have the exact same method name,
return type, number of parameters, and types of parameters as the method in the parent class, and
the only difference would be the definition of the method.
Example of method overriding
Lets go through a simple example to illustrate what method overriding would look like:
public class Parent {
public int someMethod() {
return 3;
}
}
public class Child extends Parent{
// this is method overriding:
public int someMethod() {
return 4;
}
}
In the sample code above, someMethod is an overridden method in the Child class, because it has the
exact same name, number of parameters, and return type as the someMethod method defined inside
its parent class (conveniently named Parent).
Overriding happens at run time
Another important point to remember is that overriding is a run time phenomenon not a compile
time phenomenon like method overloading.
Every Java program is first compiled into an intermediate language called Java bytecode. The JVM is
used primarily for 2 things: the first is to translate the bytecode into the machine language for a
particular computer, and the second thing is to actually execute the corresponding machine-language
instructions as well. The JVM and bytecode combined give Java its status as a "portable" language
this is because Java bytecode can be transferred from one machine to another.
Machine language is OS dependent
Given the previous information, it should be easier to figure out an answer to the original question.
Since the JVM must translate the bytecode into machine language, and since the machine language
depends on the operating system being used, it is clear that the JVM is platform (operating system)
dependent in other words, the JVM is not platform independent.
The JVM is not platform independent
The key here is that the JVM depends on the operating system so if you are running Mac OS X you
will have a different JVM than if you are running Windows or some other operating system. This fact
can be verified by trying to download the JVM for your particular machine when trying to download
it, you will be given a list of JVMs corresponding to different operating systems, and you will obviously
pick whichever JVM is targeted for the operating system that you are running.
Checked and unchecked exceptions in java with examples
The main difference between checked and unchecked exception is that the checked
exceptions are checked at compile-time while unchecked exceptions are checked at runtime.
What are checked exceptions?
Checked exceptions are checked at compile-time. It means if a method is throwing a
checked exception then it should handle the exception using try-catch block or it should
declare the exception using throws keyword, otherwise the program will give a compilation
error. It is named as checked exception because these exceptions are checked at
Compile time.
Lets understand this with this example: In this example we are reading the
filemyfile.txt and displaying its content on the screen. In this program there are three
places where an checked exception is thrown as mentioned in the comments below.
FileInputStream which is used for specifying the file path and name,
throws FileNotFoundException. The read() method which reads the file content
throws IOException and the close() method which closes the file input stream also
throws IOException.
import java.io.*;
class Example {
public static void main(String args[])
{
FileInputStream fis = null;
/*This constructor FileInputStream(File filename)
* throws FileNotFoundException which is a checked
* exception*/
fis = new FileInputStream("B:/myfile.txt");
int k;
/*Method read() of FileInputStream class also throws
* a checked exception: IOException*/
while(( k = fis.read() ) != -1)
{
System.out.print((char)k);
}
/*The method close() closes the file input stream
* It throws IOException*/
fis.close();
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation
problems:
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException
Why this compilation error?
As I mentioned in the beginning that checked exceptions gets checked during compile time.
Since we didnt handled/declared the exceptions, our program gave the compilation error.
How to resolve the error?
There are two ways to avoid this error. We will see both the ways one by one.
Method 1:
Declare the exception using throws keyword.
As we know that all three occurrences of checked exceptions are inside main() method so one way to
avoid the compilation error is: Declare the exception in the method using throws keyword. You may be
thinking that our code is throwing FileNotFoundException and IOException both then why we are
declaring the IOException alone. Th reason is that IOException is a parent class of
FileNotFoundException so it by default covers that. If you want you can declare that too like this public
static void main(String args[]) throws IOException, FileNotFoundException.
import java.io.*;
class Example {
public static void main(String args[]) throws IOException
{
FileInputStream fis = null;
fis = new FileInputStream("B:/myfile.txt");
int k;
while(( k = fis.read() ) != -1)
{
System.out.print((char)k);
}
fis.close();
}
}
Output:
File content is displayed on the screen.
Method 2: Handle them using try-catch blocks.
The above approach is not good at all. It is not a best exception handling practice. You
should give meaningful message for each exception type so that it would be easy for
someone to understand the error. The code should be like this:
import java.io.*;
class Example {
public static void main(String args[])
{
FileInputStream fis = null;
try{
fis = new FileInputStream("B:/myfile.txt");
}catch(FileNotFoundException fnfe){
System.out.println("The specified file is not " +
"present at the given path");
}
int k;
try{
while(( k = fis.read() ) != -1)
{
System.out.print((char)k);
}
fis.close();
}catch(IOException ioe){
System.out.println("I/O error occurred: "+ioe);
}
}
}
This code will run fine and will display the file content.
Here are the few other Checked Exceptions -
SQLException
IOException
DataAccessException
ClassNotFoundException
InvocationTargetException
What are Unchecked exceptions?
Unchecked exceptions are not checked at compile time. It means if your program is throwing an
unchecked exception and even if you didnt handle/declare that exception, the program wont give a
compilation error. Most of the times these exception occurs due to the bad data provided by user during
the user-program interaction. It is up to the programmer to judge the conditions in advance, that can
cause such exceptions and handle them appropriately. All Unchecked exceptions are direct sub classes
of RuntimeException class.
Lets understand this with an example:
class Example {
public static void main(String args[])
{
int num1=10;
int num2=0;
/*Since I'm dividing an integer with 0
* it should throw ArithmeticException*/
int res=num1/num2;
System.out.println(res);
}
}
If you compile this code, it would compile successfully however when you will run it, it
would throw ArithmeticException. That clearly shows that unchecked exceptions are not
checked at compile-time, they are being checked at runtime. Let's see another example.
class Example {
public static void main(String args[])
{
int arr[] ={1,2,3,4,5};
/*My array has only 5 elements but
* I'm trying to display the value of
* 8th element. It should throw
* ArrayIndexOutOfBoundsException*/
System.out.println(arr[7]);
}
}
This code would also compile successfully since ArrayIndexOutOfBoundsException is also an
unchecked exception.
Note: It doesnt mean that compiler is not checking these exceptions so we shouldnt handle them. In
fact we should handle them more carefully. For e.g. In the above example there should be a exception
message to user that they are trying to display a value which doesnt exist in array so that user would be
able to correct the issue.
class Example {
public static void main(String args[])
{
try{
int arr[] ={1,2,3,4,5};
System.out.println(arr[7]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("The specified index does not exist " +
"in array. Please correct the error.");
}
}
}
Here are the few most frequently seen unchecked exceptions -
NullPointerException
ArrayIndexOutOfBoundsException
ArithmeticException
IllegalArgumentException