SlideShare a Scribd company logo
1 of 18
JAVA Questions with answers
1. Differences between JDK and JRE?
Ans.
The "JDK" is the Java Development Kit. I.e., the JDK is bundle of software that you can use to develop Java based
software. The "JRE" is the Java Runtime Environment. I.e., the JRE is an implementation of the Java Virtual Machine
which actually executes Java programs. JDK is a software bundle consists of binary files such as
(javac,java,javadoc,jdb,javap,rmic....),java library files (both old and new)and some header files. Development
environmentrequiresthissoftware.JavaDeveloperKitcontainstoolsneeded to develop the Java programs, and JRE to
run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc…
Compilerconvertsjavacode intobyte code.Javaapplicationlauncheropens a JRE, loads the class, and invokes its main
method.
You need JDK, if at all you want to write your own programs, and to compile them. For running java programs, JRE is
sufficient.
Typically,eachJDKcontainsone (ormore) JRE's alongwiththe variousdevelopmenttoolslikethe Javasource compilers,
bundling and deployment tools, debuggers, development libraries, etc.
JRE or the JavaRuntime EnvironmentisaminimumsetthatincludesaJava interpreter, JavaAPIlibraries,Javabrowser
plug-in,whichmake upthe minimumenvironmenttoexecute Java-basedapplications.JavaRuntime Environment
containsJVM,class libraries,andothersupportingfiles.ActuallyJVMrunsthe program, and itusesthe class libraries,
and othersupportingfilesprovidedinJRE.If youwant to runany java program, youneedto have JRE installedinthe
system.
JVM: JavaVirtual Machine interpretsthe bytecodeintothe machine code dependinguponthe underlyingoperating
systemandhardware combination.Itisresponsible forall the thingslikegarbage collection,arrayboundschecking,
etc…JVMis platformdependent.
The JVMis called"virtual"because itprovidesamachine interface thatdoesnotdependonthe underlyingoperating
systemandmachine hardware architecture.Thisindependence fromhardware andoperatingsystemisacornerstone of
the write-once run-anywhere valueof Javaprograms.
The JVMor JavaVirtual Machine isthe core of the Javaplatformandis a part of boththe JDKand JRE that
translatesJavabytecodesandexecutesthemasnative code onthe clientmachine.
JDK includesaJRE as as subset.
JDK : JDK contailsJREand JVMboth.JDKis requiredto compile.JDKcontainsof many.exe supportingfilesandjavac,
javap,java,javaw,javaws,all theseare helpingtocompile the javaprograms.If we have tocompile ourownwrittenjava
program JDKshouldbe define inourclasspath.aftercompilationitconvertsthe code intothe bytecode.
JRE : JRE isneededforruntime environment.ItcontainsJVM.
JVM: Java Virtual Machine convertsthe bytecode intouserunderstandablecode.withoutJVMwe cannotrun our Java
codeson anysystem.JVMconvertsthe bytecode gotaftercompilationintomachine level code byunderstandingthe
hardware and operatingsystemcombination.
What is Copy Constructor in java?
Copy Constructor in Java
Like C++, Java alsosupportscopyconstructor. But,unlike C++,Java doesn’tcreate adefaultcopyconstructorif youdon’t
write yourown. CopyConstructoris usedtocreate an objectidentical tothe original one andtopreventthe original
beingaltered.
FollowingisanexampleJavaprogramthat showsa simple use of copyconstructor.
// filename: Main.java
class Complex {
private double re, im;
// A normal parametrized constructor
public Complex(double re, double im) {
this.re = re;
this.im = im;
}
// copy constructor
Complex(Complex c) {
System.out.println("Copy constructor called");
re = c.re;
im = c.im;
}
// Overriding the toString of Object class @Override
public String toString() {
return "(" + re + " + " + im + "i)";
}
}
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex(10, 15);
// Following involves a copy constructor call
Complex c2 = new Complex(c1);
System.out.println(c2); // toString() of c2 is called here
}
}
Output:
Copy constructor called
(10.0 + 15.0i)
What is a metaclass? Applications
In object-orientedprogramming,ametaclassis a classwhose instancesare classes.Justasan ordinaryclassdefinesthe
behaviorof certainobjects,ametaclassdefinesthe behaviorof certainclassesandtheirinstances.Notall object-
orientedprogramming languagessupportmetaclasses.Amongthose thatdo,the extenttowhichmetaclassescan
override anygivenaspectof classbehaviorvaries.Eachlanguage hasitsown metaobjectprotocol,asetof rulesthat
governhowobjects,classes,andmetaclassesinteract.
Some environments - suchas Smalltalk - automaticallydefine anotherclassforeachclassyou define.Thisiscalleda
metaclass.Yourclassdefinitiondescribesthe datastructure andmethodsof yourclass.The metaclassdescribesthe
data structure and methodsof the classdescription - yes,the descriptionof yourclassisalsoan object:an instance of
the correspondingmetaclass.
Exactlyone such instance of each metaclassexistsatruntime.If youadd"classinstance variables"and"classmethods"
to yourclass, whatreallyhappensisthatfieldsandinstance methodsare addedtothe metaclassinstead.I.e.youcan
change the structure and behaviorof yourclass description.
In Java,all class descriptionslookandworkthe same:Theyare instancesof java.lang.Class.Youcannotadd anymethods
or fieldsthere forsome classdescriptionswhere youthinkyouneedthis;youcanuse the existingones,though.E.g.
getName() ornewInstance() orgetMethod()...
Thisis howthe literature definesmetaclassesinobjectorientation.Javaobviouslydoesnotsupportmetaclasses.
However,eveninJavayouhave exactlyone classdescriptionforeachloadedclassatruntime.And youcan do a lot
usingtheirmethods(getMethod(),getConstructor(),isArray(),getInterfaces() etc...i.e.usingReflection)
You getthe classdescriptionforanObject'sclassby callinggetClass() onthe object.If youknow the classname,youcan
append .classto itto accomplishthe same,e.g.String.class,whichusesthe classloaderof the code thatcontainsthis
expressionforlocatingthe class.StaticmethodforName() in java.lang.Class hasanoverloadedvariantwhere youcan
pass inthe classname (fullyqualified!) andthe classloadertobe used.
By the way: Aswe mentioned,inSystemshavingmetaclasses,a"classmethod"isjusta normal instance methodof a
metaclass,canbe calledonthe instance of a metaclassandis dynamicallyboundandthus supports polymorphism.
Java's staticmethodshave oftenbeencomparedtosuchclassmethodsbutinfact are - as the name reveals - juststatic
methods,i.e.staticallybound,non-polymorphicmethods;consequentlythe syntax forcallingthemrequiresnoreceiver
object.The onlyinstance methodsactingonclassdescriptionsare those of java.lang.Class.
(sidenote:"classinstance variables"inSmalltalkare instance variablesof metaclasses;youmighthave guessedthatthey
shouldbe called"classvariables"butthese are yetanotherthingandthose twoshouldnotbe confusedwhenworking
withSmalltalk.ButforJavaprogrammersthisdoes,of course,notmatter ;-)
What is early binding and late binding?
The short answeristhat early(orstatic) binding referstocompile time bindingandlate (ordynamic) bindingrefersto
runtime binding(forexamplewhenyouuse reflection).
Early binding &late Bindingisa conceptof OOPS..B'cozthe dataand the method whichwill operate ondataare
sepertaelydefinedinoops(calledabstraction).Andtheywillbinddatamembersandmethodseitheratthe complie time
or runtime time.Thisiscalledencapsulation.
In earlybindingthe dataandmethodare bindsat the complie time where asin late bindingthe dataandmethodwill
bindat the runtime.
Well earlyandlate bindingisagood concept,well considerasituationwhere youhave aclasswitha method,nowyou
call the methodinyourmainmethod usingthe objectof the class,inthissituationthe complierknowswhichmethod
to call before execution,thisisearlybinding...
In late bindingthe complierdoesn'tknowwhichmethodtocall during compile time,the methodcall isresolvedonly
duringruntime...thiscanbe achieved ininheritance orbyusingan interface
hope followingexamplehelpsyou.........
classA
{
publicvoidfoo()
{
System.out.println("ClassA");
}
}
classB extendsA
{
publicvoidfoo()
{
System.out.println("ClassB");
}
}
publicclassC
{
publicstaticvoidmain(String[] args)
{
A a=newA();
B b=newB();
A ref=null;
a.foo();//early binding --- callsmethodfoo() of classA ....decidedatcompile time
b.foo();//earlybinding --- callsmethodfoo() of classB....decidedatcompile time
ref=b;
ref.foo();// late binding--- --- callsmethodfoo() of classB....decidedatRuntime
}
}
Difference between Dynamic Binding & Static Binding in Java
Dynamic Binding or Late Binding
DynamicBindingreferstothe case where compilerisnotable toresolve the call andthe bindingisdone at runtime only.
Let's try to understandthis.Supposewe have aclassnamed'SuperClass'andanotherclassnamed'SubClass'extendsit.
Nowa 'SuperClass'reference canbe assignedtoanobjectof the type 'SubClass'as well.If we have a method(say
'someMethod()') inthe 'SuperClass'whichwe override inthe 'SubClass'thenacall of that methodona 'SuperClass'
reference canonlybe resolvedatruntime asthe compilercan'tbe sure of whattype of objectthisreference wouldbe
pointingtoat runtime.
...
SuperClasssuperClass1=newSuperClass();
SuperClasssuperClass2=newSubClass();
...
superClass1.someMethod();//SuperClassversioniscalled
superClass2.someMethod();//SubClassversioniscalled
....
Here,we see thateventhoughboththe objectreferencessuperClass1andsuperClass2are of type 'SuperClass'only,but
at run time theyrefertothe objectsof types'SuperClass'and'SubClass'respectively.
Hence,at compile time the compilercan'tbe sure if the call to the method'someMethod()'onthese referencesactually
referto whichversionof the method - the superclassversionorthe sub classversion.
Thus,we see that dynamicbindinginJavasimplybindsthe methodcalls(inheritedmethodsonlyastheycanbe
overrideninasub classand hence compilermaynotbe sure of whichversionof the methodtocall) basedonthe actual
objecttype andnot on the declaredtype of the objectreference.
Static Binding or Early Binding
If the compilercanresolve the bindingatthe compile time onlythensuchabindingiscalledStaticBindingorEarly
Binding.All the instance methodcallsare alwaysresolvedatruntime,butall the staticmethodcallsare resolvedat
compile time itself andhence we have staticbindingforstaticmethodcalls.Because staticmethodsare classmethods
and hence theycanbe accessedusingthe classname itself (infacttheyare encourgaedtobe usedusingthe ir
correspondingclassnamesonlyandnotbyusingthe objectreferences) andtherefore accesstothemisrequiredtobe
resolvedduringcompile timeonlyusingthe compile time typeinformation.That'sthe reasonwhystaticmethodscan
not actuallybe overriden.Readmore - Canyouoverride staticmethodsinJava?
Similarly, accesstoall the membervariables inJavafollowsstaticbindingasJavadoesn'tsupport(infact,itdiscourages)
polymorphicbehaviorof membervariables.Forexample:-
classSuperClass{
...
publicStringsomeVariable ="Some VariableinSuperClass";
...
}
classSubClassextendsSuperClass{
...
publicStringsomeVariable ="Some VariableinSubClass";
...
}
...
...
SuperClasssuperClass1=newSuperClass();
SuperClass superClass2=newSubClass();
System.out.println(superClass1.someVariable);
System.out.println(superClass2.someVariable);
...
Output:-
Some Variable inSuperClass
Some Variable inSuperClass
We can observe thatinboththe cases,the membervariable is resolvedbasedonthe declaredtype of the object
reference only,whichthe compileriscapable of findingasearlyas at the compile time onlyandhence astaticbindingin
thiscase.Anotherexample of staticbindingisthatof 'private'methods as they are neverinheritedandthe compile can
resolve callstoanyprivate methodatcompile time only.
What is method signature in java?
The signature of a methodisthe combinationof the method'sname alongwiththe numberandtypesof the parameters
(andtheirorder).
Specific to java, The signature of a method should contain details. It should contain
1. Name of the method
2. Arguments (type, order)
The Java method signature contains only method name and parameter list. It doesn't contain visibility modifier,
return type and throws clause because of the following reason..
Consider the following code:
class A {
public A x(int l) {
//some code
}
}
class B extends A {
public B x(int k) {
//some code
}
}
Now, implementation of method x in class B is an example of overriding, which is also logically correct.
However, this would not have been the case if return type was made part of signature. In that case, JVM would
not know the difference between the two methods since B instanceof A is true.
A method does not declare any exception. can it be overiden in a subclass to through an
exception?
ExceptionHandlingwithMethodOverriding
There are manyrulesif we talkabout methodoverridingwithexceptionhandling.The Rulesare asfollows:
 If the superclassmethoddoesnot declare an exception
o If the superclassmethoddoesnotdeclare anexception,subclassoverriddenmethodcannotdeclare the
checkedexceptionbutitcan declare uncheckedexception.
 If the superclassmethoddeclaresan exception
o If the superclassmethoddeclaresanexception,subclassoverriddenmethodcandeclare same,subclass
exceptionornoexceptionbutcannotdeclare parentexception.
If the superclassmethoddoesnotdeclarean exception
1)Rule: If the superclass method does notdeclareanexception,subclass overriddenmethod cannotdeclare
the checked exception.
1. importjava.io.*;
2. classParent{
3. voidmsg(){System.out.println("parent");}
4. }
5.
6. classChildextends Parent{
7. voidmsg()throws IOException{
8. System.out.println("child");
9. }
10. publicstaticvoidmain(Stringargs[]){
11. Parentp=new Child();
12. p.msg();
13. }
14. }
Output:Compile Time Error
2)Rule: If the superclass method does notdeclareanexception,subclass overriddenmethod cannotdeclare
the checked exception butcandeclareunchecked exception.
1. importjava.io.*;
2. classParent{
3. voidmsg(){System.out.println("parent");}
4. }
5.
6. classChildextends Parent{
7. voidmsg()throws ArithmeticException{
8. System.out.println("child");
9. }
10. publicstaticvoidmain(Stringargs[]){
11. Parentp=new Child();
12. p.msg();
13. }
14. }
Output:child
If the superclassmethoddeclaresanexception
1)Rule: If the superclass method declares anexception,subclassoverriddenmethod candeclaresame,
subclass exceptionornoexceptionbut cannotdeclareparentexception.
Exampleincase subclassoverriddenmethoddeclaresparentexception
1. importjava.io.*;
2. classParent{
3. voidmsg()throws ArithmeticException{System.out.println("parent");}
4. }
5.
6. classChildextends Parent{
7. voidmsg()throws Exception{System.out.println("child");}
8.
9. publicstaticvoidmain(Stringargs[]){
10. Parentp=new Child();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Output:Compile Time Error
Exampleincase subclassoverriddenmethoddeclaressameexception
1. importjava.io.*;
2. classParent{
3. voidmsg()throws Exception{System.out.println("parent");}
4. }
5.
6. classChildextends Parent{
7. voidmsg()throws Exception{System.out.println("child");}
8.
9. publicstaticvoidmain(Stringargs[]){
10. Parentp=new Child();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Output:child
Exampleincase subclassoverriddenmethoddeclaressubclassexception
1. importjava.io.*;
2. classParent{
3. voidmsg()throws Exception{System.out.println("parent");}
4. }
5.
6. classChildextends Parent{
7. voidmsg()throws ArithmeticException{System.out.println("child");}
8.
9. publicstaticvoidmain(Stringargs[]){
10. Parentp=new Child();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Output:child
Exampleincase subclassoverriddenmethoddeclaresno exception
1. importjava.io.*;
2. classParent{
3. voidmsg()throws Exception{System.out.println("parent");}
4. }
5.
6. classChildextends Parent{
7. voidmsg(){System.out.println("child");}
8.
9. publicstaticvoidmain(Stringargs[]){
10. Parentp=new Child();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Output:child
Why parameter for main is a string array?
The signature of the main method is specified in the Java Language Specifications section 12.1.4 and clearly
states:
The method main must be declared public, static, and void. It must specify a formal parameter whose declared
type is array of String.
 it mustbe public otherwise itwouldnotbe possible tocall it
 it mustbe static since youhave noway to instantiate anobjectbefore callingit
 the listof String argumentsis there toallow to passparameterswhenexecutingaJavaprogram fromthe
commandline.Itwouldhave beenpossibletodefine itwithoutargumentsbutismore practical like that(and
similartootherlanguages)
 the returntype is void since itdoesnot make sense tohave anythingelse:aJavaprogram can terminate before
reachingthe endof the mainmethod(e.g.,bycalling System.exit())
You understand that String[] args is an array of strings passed into main as parameters.
java Print "Hello, World!"
class Print {
public static void main(String[] args) {
System.out.println(args[0]);
}
}
However, when you don't include it as a parameter (even if you don't use), it throws an exception. So why is it
required? Also, why can't it be an int[] or boolean[]?
It's a String because the command line is expressed in text. If you want to convert that text into integers or
booleans, you have to do that yourself - how would the operating system or Java bootstrapper know exactly
how you wanted everything to be parsed? I suppose Java could look for a main method with the same number
of parameters as command line arguments, and then try to parse them using Integer.parseInt etc... but this
would be pretty complicated, and would still be inadequate in many situations.
As for it being mandatory - basically the Java designers decided to stick to a single method signature, which is
frankly simpler than allowing for it to be optional. It would be possible though - in C#, you can have any of
static void Main()
static void Main(string[] args)
static int Main()
static int Main(string[] args)
Ultimately it doesn't make a lot of difference, to be honest. There's no significant downside in having to include
the parameter.
That's how the language was designed. C and C++ both do it in a similar fashion, though with a separate count,
information that's included in the string array for Java.
You could have designed it to take integers or booleans but that would have added more work to the Java
runtime for potentially little benefit.
Strings can be used to transmit any sort of information into the main program (including integers and booleans).
Not so for integers if you want to pass in a string (short of the user having to manually encode it as UTF-8 or
something, not something that would endear people to the language).
Just remember to declare it. By all means, raise a change request on the language if you wish (to make it
optional, or allow other signatures) but I suspect that will not get very far.
User defined exceptions and system defined exception...example
How to Create User Defined Exception in Java
Apart from existing Exceptions in java, we can create our own Exceptions (User defined exceptions in java), we
will how to..
Required files
 Client.java [ My business logic will goes here ]
 MyOwnExceptionClass.java [ This is our own Exception class ]
Note: Our user defined class must extend from Exception class, and we must override the toString() method to
display our exception message.
Client.java
package java4s;
public class Client {
public static void main(String[] args)throws Exception
{
int price = -120;
if(price < 0)
throw new MyOwnExceptionClass(price);
else
System.out.println("Your age is :"+price);
}
}
MyOwnExceptionClass.java
package java4s;
public class MyOwnExceptionClass extends Exception {
private int price;
public MyOwnExceptionClass(int price){
this.price = price;
}
public String toString(){
return "Price should not be in negative, you are entered" +price;
}
}
Output:
Java has a powerful concept for exception and error handling. An exception is an error that occurs at runtime. It
is either generated by the Java Virtual Machine (VM) in response to an unexpected condition or it is generated
by your code as a result of executing a throw statement.
Understanding System – defined Exceptions
Exceptions generated from runtime are called unchecked exceptions, since it is not possible for the compiler to
determine that your code will handle the exception. Exception classes that descend from RuntimeException and
Error classes are unchecked exceptions. Examples for RuntimeException are illegal cast operation,
inappropriate use of a null pointer, referencing an out of bounds array element. Error exception classes signal
critical problems that typically cannot be handled by your application. Examples are out of memory error, stack
overflow, failure of the Java VM.
Thrown exceptions are referred to as checked exceptions. The compiler will confirm at compile time that the
method includes code that might throw an exception. Moreover the compiler requires the code that calls such a
method to include this call within a try block, and provide an appropriate catch block to catch the exception.
java.lang.Object
|
+--java.lang.Throwable
|
+--java.lang.Exception
| |
| +--java.lang.ClassNotFoundException
| |
| +--java.io.IOException
| | |
| | +--java.io.FileNotFoundException
| |
| +--java.lang.RuntimeException
| |
| +--java.lang.NullPointerException
| |
| +--java.lang.IndexOutOfBoundsException
| |
| +--java.lang.ArrayIndexOutOfBoundsException
|
+--java.lang.Error
|
+--java.lang.VirtualMachineError
|
+--java.lang.OutOfMemoryError
When an (either checked or unchecked) exception is thrown, execution will attempt to immediately branch to
the first catch block whose associated exception class matches the class or a superclass of the thrown exception.
If the exception does not occur within a try block or the thrown exception is not caught in a matching catch
block, execution of the method immediately terminates and control returns to the invoker of the method, where
this process is repeated. The result is that the exception chain is escalated until a matching catch block is found.
If not, the thread containing the thrown exception is terminated.
First Example
The following Demo1 class demonstrates the behaviour of exceptions and applications.
import java.io.*;
class Demo1 {
public static FileInputStream f1(String fileName)
throws FileNotFoundException
{
FileInputStream fis = new FileInputStream(fileName);
System.out.println("f1: File input stream created");
return fis;
}
public static FileInputStream f2(String fileName)
{
FileInputStream fis = null;
try
{
fis = new FileInputStream(fileName);
}
catch (FileNotFoundException ex)
{
System.out.println("f2: Oops, FileNotFoundException caught");
}
finally
{
System.out.println("f2: finally block");
}
System.out.println("f2: Returning from f2");
return fis;
}
public static void main(String args[])
{
FileInputStream fis1 = null;
FileInputStream fis2 = null;
String fileName = "foo.bar";
// String fileName = null;
System.out.println( "main: Starting " + Demo1.class.getName()
+ " with file name = " + fileName);
// get file input stream 1
try {
fis1 = f1(fileName);
}
catch (FileNotFoundException ex)
{
System.out.println("main: Oops, FileNotFoundException caught");
}
catch (Exception ex)
{
System.out.println("main: Oops, genreal exception caught");
}
// get file input stream 2
fis2 = f2(fileName);
System.out.println("main: " + Demo1.class.getName() + " ended");
}
}
Compile and run the Demo1 class will generate output as follows (assuming that the file foo.bar does not exist):
main: Starting Demo1 with file name = foo.bar
main: Oops, FileNotFoundException caught
f2: Oops, FileNotFoundException caught
f2: finally block
f2: Returning from f2
main: Demo1 ended
The example program tries to create two file input streams. Therefore two methods f1 and f2 are implemented.
First, the main program calls f1 method. Because the constructor of the FileInputStream throws a
FileNotFoundException the method f1 must be defined with the throws FileNotFoundException in the method
definition. The thrown exception is not handled in the method but forwarded to the invoker. Note, that the
system output before the return statement is never executed.
So the invoker, in our example the main program, must catch this exception. The method f1 is called in a try
block. The following catch blocks catch either a FileNotFoundException or a general Exception. In our
example, the exception is caught in the first catch block and the system output is generated. Since the exception
in f1 is caught and handled, the execution of the program is not terminated.
Second, the example program creates another FileInputStream invoking the f2 method. This method catches the
FileNotFoundException, so this exception must not be forwarded to the invoker. The try ... catch statement is
followed by a finally block. This block is always executed, regardless whether or not an exception occurs
within the try block. This generates the system output in our example. Again, the exception is caught and the
program executes, this generates the system output in f2 and main.
This was a straight forward example with caught exceptions. What happens with uncaught exceptions? Change
the fileName assignment in the main method: Comment out the first assignment and activate the second String
fileName = null; then compile and execute Demo1 again. The generated output is:
main: Starting Demo1 with file name = null
main: Oops, genreal exception caught
f2: finally block
java.lang.NullPointerException
java.io.FileInputStream Demo1.f2(java.lang.String)
void Demo1.main(java.lang.String[])
Exception in thread main
This time, we try to create two FileInputStream objects using null instead of a file name. Invoking f1 will
generate a NullPointerException which is caught in the main program. Next f2 is called which could handle
only the FileNotFoundException but not a NullPointerException. Nevertheless the finally block is executed and
then the control returns to the main program. Because there is no try ... catch statement around the call to f2
and no matching catch block is found, the thread is terminated. Note, that f2 and main can not execute the
system output statements any more.
Second Example
The second example will show some special behaviour in catch and finally blocks:
import java.io.*;
class Demo2 {
public static FileInputStream f1(String fileName)
{
FileInputStream fis = null;
try
{
fis = new FileInputStream(fileName);
}
catch (FileNotFoundException ex)
{
System.out.println("f1: Oops, FileNotFoundException caught");
throw new Error("f1: File not found");
}
System.out.println("f1: File input stream created");
return fis;
}
public static FileInputStream f2(String fileName)
{
FileInputStream fis = null;
try
{
fis = new FileInputStream(fileName);
}
catch (FileNotFoundException ex)
{
System.out.println("f2: Oops, FileNotFoundException caught");
return fis;
}
finally
{
System.out.println("f2: finally block");
return fis;
}
// Compiler error: statement not reacheable
// System.out.println("f2: Returning from f2");
// return fis;
}
public static void main(String args[])
{
FileInputStream fis1 = null;
FileInputStream fis2 = null;
String fileName = "foo.bar";
// String fileName = null;
System.out.println( "main: Starting " + Demo2.class.getName()
+ " with file name = " + fileName);
// get file input stream 1
try {
fis1 = f1(fileName);
}
catch (Exception ex)
{
System.out.println("main: Oops, general exception caught");
}
catch (Throwable th)
{
System.out.println("main: Oops, throwable object caught");
}
// get file input stream 2
fis2 = f2(fileName);
System.out.println("main: " + Demo2.class.getName() + " ended");
}
}
}
Compile and run Demo2 will generate the following output:
main: Starting Demo2 with file name = foo.bar
f1: Oops, FileNotFoundException caught
main: Oops, throwable object caught
f2: Oops, FileNotFoundException caught
f2: finally block
main: Demo2 ended
Again f1 is called to get a new FileInputStream with a given file name. The thrown FileNotFoundException in
f1 is caught in the following catch block. But this time an Error is thrown so that the method is terminated
immediately. Because Error is not a subclass of Exception the first catch block does not match. But the second
catch block matches all throwable objects.
Calling f2 method will generate a FileNotFoundException too. This exception is caught in f2 and the method
returns directly from the catch block. Remember, that the finally block is executed regardless whether an
exception is caught or not.
In both methods f1 and f2, the FileNotFoundException is caught and handled, so the program can terminate
normally. Change again the fileName assignment in the main method and compile and run Demo2 again:
main: Starting Demo2 with file name = null
main: Oops, general exception caught
f2: finally block
main: Demo2 ended
The NullPointerException thrown in f1 is not caught, so the exception is forwarded to the invoker. The main
program catches Exception, which is a superclass of the thrown exception.
The call to f2 method seems to work fine even the thrown NullPointerException is not caught directly. Note,
that the finally block is executed regardless whether an exception is caught or not. Since the finally block
terminates with a return statement, the program executes without failure. So be careful returning within finally
blocks, this breaks the exception chaining to the invoker and it simulates error free program execution.
Summary
 Normal program execution is immediately branched when an exception is thrown.
 Checked exceptions must be caught or forwarded. This can be done in a try ... catch statement or by
defining the exception in the method definition.
 The exception is caught by the first catch block whose associated exception class matches the class or a
superclass of the thrown exception.
 If no matching catch block is found in the exception chain, the thread containing the thrown exception is
terminated.
 The finally block after a try ... catch statement is executed regardless whether an exception is caught or
not.
 Returning within a finally block breaks the exception chain to the invoker even for uncaught exceptions.
Why is java called a strongly typed language?
A strongly typed programming languages is one that requires the type of a variable to be explicitly stated. C is a
strongly typed language. You must declare the type of data a variable will store for C to interpret it:
int myVariable;
myVariable = 25;
Perl is a loosely typed language. There is no need to declare the variable type before using it:
$myVariable = 25;
$myVariable = "A String.";
Java iscalleda Strong TypedLanguage because youHave to state the type of a variable inthe momentyoucreate it,for
instance
inta = 22;
Stringhello= "hello"
As a example of nonstrongtypedlanguagesyoumayfindJavaScriptwhere youdon'thave tostate the type of the
variable,youmayhave :
a = 22;
a = "a string";
var b = 33;
var b = "anothernewstring"
See?the variable aor b can have differenttypesof values,integer,strings,doubles,etcetcetc,withoutthe compiler
raisesanywarning.
Java isa stronglytypedlanguage inthe sense thatall the data that youencounterduringaJava program isto be
properlyassigneda"datatype".
Withoutassigningaparticulardata type to anyvariable, youare not allowedtoinitialize the variable,andsuchvariables
are notrecognizedatall.Thus,all variablesinJavamusthave a data type.
Data type is the type of the data thatyou are referringto.Isitan integer,adecimal,alongdecimal,asmall integer,a
short integer,aBooleanvalue,acharactervalue,ora String of characters?
Whendeclaringyourvariable inJava,youwill needtofollowthissyntax inwhichthe datatype of the variable is
predefinedbyyou:
<data type> <variable name>;
For example,
"inta;" declaresa variable of type "int"andname "a".
"char a;" declaresa variable of type "char"and name "a".
"double a;"declaresavariable of type "double"andname "a".
and so on...
The importantpointto discusshere isthatyou cannotdeclare a variable withoutanddatatype andspecifyitsdatatype
at the time of initialization.Noristhe datatype of a variable dynamicallydeclaredinJava.Youhave toassignthe proper
data type to yourvariable.
So whatis the difference betweenC++and Java?Both require todeclare a data type fora variable.
The difference isthatonce youdeclare adata type in Java,youcannot give the value of anyother data type toit. This
will require explicitconversionof the datatype.

More Related Content

What's hot

Java j2ee interview_questions
Java j2ee interview_questionsJava j2ee interview_questions
Java j2ee interview_questionsppratik86
 
50+ java interview questions
50+ java interview questions50+ java interview questions
50+ java interview questionsSynergisticMedia
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview QuestionsKuntal Bhowmick
 
Technical interview questions
Technical interview questionsTechnical interview questions
Technical interview questionsSoba Arjun
 
3.java database connectivity
3.java database connectivity3.java database connectivity
3.java database connectivityweb360
 
Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOPHitesh-Java
 
Extreme Interview Questions
Extreme Interview QuestionsExtreme Interview Questions
Extreme Interview QuestionsEhtisham Ali
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language Hitesh-Java
 
Dev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetDev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetdevlabsalliance
 

What's hot (15)

Java j2ee interview_questions
Java j2ee interview_questionsJava j2ee interview_questions
Java j2ee interview_questions
 
Best interview questions
Best interview questionsBest interview questions
Best interview questions
 
50+ java interview questions
50+ java interview questions50+ java interview questions
50+ java interview questions
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview Questions
 
Technical interview questions
Technical interview questionsTechnical interview questions
Technical interview questions
 
Design pattern
Design patternDesign pattern
Design pattern
 
Hibernate
HibernateHibernate
Hibernate
 
3.java database connectivity
3.java database connectivity3.java database connectivity
3.java database connectivity
 
Hibernate Advance Interview Questions
Hibernate Advance Interview QuestionsHibernate Advance Interview Questions
Hibernate Advance Interview Questions
 
Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOP
 
Extreme Interview Questions
Extreme Interview QuestionsExtreme Interview Questions
Extreme Interview Questions
 
Hibernate notes
Hibernate notesHibernate notes
Hibernate notes
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
 
Hibernate I
Hibernate IHibernate I
Hibernate I
 
Dev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetDev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdet
 

Similar to Java questions with answers

College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answersKrishnaov
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for MainframersRich Helton
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Mr. Akaash
 
Java programming basics
Java programming basicsJava programming basics
Java programming basicsHamid Ghorbani
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting StartedRakesh Madugula
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruNithin Kumar,VVCE, Mysuru
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machineNikhil Sharma
 
Javanotes ww8
Javanotes ww8Javanotes ww8
Javanotes ww8kumar467
 

Similar to Java questions with answers (20)

Java introduction
Java introductionJava introduction
Java introduction
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
 
Java basic
Java basicJava basic
Java basic
 
JAVA for Every one
JAVA for Every oneJAVA for Every one
JAVA for Every one
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
 
Programming in Java
Programming in JavaProgramming in Java
Programming in Java
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...
 
Java notes
Java notesJava notes
Java notes
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting Started
 
1.introduction to java
1.introduction to java1.introduction to java
1.introduction to java
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, Mysuru
 
java basic .pdf
java basic .pdfjava basic .pdf
java basic .pdf
 
Java1
Java1Java1
Java1
 
Java
Java Java
Java
 
OOPS JAVA.pdf
OOPS JAVA.pdfOOPS JAVA.pdf
OOPS JAVA.pdf
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machine
 
Javanotes ww8
Javanotes ww8Javanotes ww8
Javanotes ww8
 
Java notes
Java notesJava notes
Java notes
 

More from Kuntal Bhowmick

Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loopsMultiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loopsKuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...Kuntal Bhowmick
 
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)Kuntal Bhowmick
 
1. introduction to E-commerce
1. introduction to E-commerce1. introduction to E-commerce
1. introduction to E-commerceKuntal Bhowmick
 
Computer graphics question for exam solved
Computer graphics question for exam solvedComputer graphics question for exam solved
Computer graphics question for exam solvedKuntal Bhowmick
 
DBMS and Rdbms fundamental concepts
DBMS and Rdbms fundamental conceptsDBMS and Rdbms fundamental concepts
DBMS and Rdbms fundamental conceptsKuntal Bhowmick
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interviewKuntal Bhowmick
 
Operating system Interview Questions
Operating system Interview QuestionsOperating system Interview Questions
Operating system Interview QuestionsKuntal Bhowmick
 
Computer Network Interview Questions
Computer Network Interview QuestionsComputer Network Interview Questions
Computer Network Interview QuestionsKuntal Bhowmick
 
Distributed operating systems cs704 a class test
Distributed operating systems cs704 a class testDistributed operating systems cs704 a class test
Distributed operating systems cs704 a class testKuntal Bhowmick
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solutionKuntal Bhowmick
 
CS291(C Programming) assignment
CS291(C Programming) assignmentCS291(C Programming) assignment
CS291(C Programming) assignmentKuntal Bhowmick
 

More from Kuntal Bhowmick (20)

Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loopsMultiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
 
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
 
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
 
1. introduction to E-commerce
1. introduction to E-commerce1. introduction to E-commerce
1. introduction to E-commerce
 
Computer graphics question for exam solved
Computer graphics question for exam solvedComputer graphics question for exam solved
Computer graphics question for exam solved
 
DBMS and Rdbms fundamental concepts
DBMS and Rdbms fundamental conceptsDBMS and Rdbms fundamental concepts
DBMS and Rdbms fundamental concepts
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interview
 
Operating system Interview Questions
Operating system Interview QuestionsOperating system Interview Questions
Operating system Interview Questions
 
Computer Network Interview Questions
Computer Network Interview QuestionsComputer Network Interview Questions
Computer Network Interview Questions
 
C interview questions
C interview  questionsC interview  questions
C interview questions
 
C question
C questionC question
C question
 
Distributed operating systems cs704 a class test
Distributed operating systems cs704 a class testDistributed operating systems cs704 a class test
Distributed operating systems cs704 a class test
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solution
 
CS291(C Programming) assignment
CS291(C Programming) assignmentCS291(C Programming) assignment
CS291(C Programming) assignment
 

Recently uploaded

HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 

Recently uploaded (20)

HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 

Java questions with answers

  • 1. JAVA Questions with answers 1. Differences between JDK and JRE? Ans. The "JDK" is the Java Development Kit. I.e., the JDK is bundle of software that you can use to develop Java based software. The "JRE" is the Java Runtime Environment. I.e., the JRE is an implementation of the Java Virtual Machine which actually executes Java programs. JDK is a software bundle consists of binary files such as (javac,java,javadoc,jdb,javap,rmic....),java library files (both old and new)and some header files. Development environmentrequiresthissoftware.JavaDeveloperKitcontainstoolsneeded to develop the Java programs, and JRE to run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc… Compilerconvertsjavacode intobyte code.Javaapplicationlauncheropens a JRE, loads the class, and invokes its main method. You need JDK, if at all you want to write your own programs, and to compile them. For running java programs, JRE is sufficient. Typically,eachJDKcontainsone (ormore) JRE's alongwiththe variousdevelopmenttoolslikethe Javasource compilers, bundling and deployment tools, debuggers, development libraries, etc. JRE or the JavaRuntime EnvironmentisaminimumsetthatincludesaJava interpreter, JavaAPIlibraries,Javabrowser plug-in,whichmake upthe minimumenvironmenttoexecute Java-basedapplications.JavaRuntime Environment containsJVM,class libraries,andothersupportingfiles.ActuallyJVMrunsthe program, and itusesthe class libraries, and othersupportingfilesprovidedinJRE.If youwant to runany java program, youneedto have JRE installedinthe system. JVM: JavaVirtual Machine interpretsthe bytecodeintothe machine code dependinguponthe underlyingoperating systemandhardware combination.Itisresponsible forall the thingslikegarbage collection,arrayboundschecking, etc…JVMis platformdependent. The JVMis called"virtual"because itprovidesamachine interface thatdoesnotdependonthe underlyingoperating systemandmachine hardware architecture.Thisindependence fromhardware andoperatingsystemisacornerstone of the write-once run-anywhere valueof Javaprograms. The JVMor JavaVirtual Machine isthe core of the Javaplatformandis a part of boththe JDKand JRE that translatesJavabytecodesandexecutesthemasnative code onthe clientmachine. JDK includesaJRE as as subset. JDK : JDK contailsJREand JVMboth.JDKis requiredto compile.JDKcontainsof many.exe supportingfilesandjavac, javap,java,javaw,javaws,all theseare helpingtocompile the javaprograms.If we have tocompile ourownwrittenjava program JDKshouldbe define inourclasspath.aftercompilationitconvertsthe code intothe bytecode. JRE : JRE isneededforruntime environment.ItcontainsJVM. JVM: Java Virtual Machine convertsthe bytecode intouserunderstandablecode.withoutJVMwe cannotrun our Java
  • 2. codeson anysystem.JVMconvertsthe bytecode gotaftercompilationintomachine level code byunderstandingthe hardware and operatingsystemcombination. What is Copy Constructor in java? Copy Constructor in Java Like C++, Java alsosupportscopyconstructor. But,unlike C++,Java doesn’tcreate adefaultcopyconstructorif youdon’t write yourown. CopyConstructoris usedtocreate an objectidentical tothe original one andtopreventthe original beingaltered. FollowingisanexampleJavaprogramthat showsa simple use of copyconstructor. // filename: Main.java class Complex { private double re, im; // A normal parametrized constructor public Complex(double re, double im) { this.re = re; this.im = im; } // copy constructor Complex(Complex c) { System.out.println("Copy constructor called"); re = c.re; im = c.im; } // Overriding the toString of Object class @Override public String toString() { return "(" + re + " + " + im + "i)"; } } public class Main { public static void main(String[] args) { Complex c1 = new Complex(10, 15); // Following involves a copy constructor call Complex c2 = new Complex(c1); System.out.println(c2); // toString() of c2 is called here } } Output: Copy constructor called (10.0 + 15.0i) What is a metaclass? Applications
  • 3. In object-orientedprogramming,ametaclassis a classwhose instancesare classes.Justasan ordinaryclassdefinesthe behaviorof certainobjects,ametaclassdefinesthe behaviorof certainclassesandtheirinstances.Notall object- orientedprogramming languagessupportmetaclasses.Amongthose thatdo,the extenttowhichmetaclassescan override anygivenaspectof classbehaviorvaries.Eachlanguage hasitsown metaobjectprotocol,asetof rulesthat governhowobjects,classes,andmetaclassesinteract. Some environments - suchas Smalltalk - automaticallydefine anotherclassforeachclassyou define.Thisiscalleda metaclass.Yourclassdefinitiondescribesthe datastructure andmethodsof yourclass.The metaclassdescribesthe data structure and methodsof the classdescription - yes,the descriptionof yourclassisalsoan object:an instance of the correspondingmetaclass. Exactlyone such instance of each metaclassexistsatruntime.If youadd"classinstance variables"and"classmethods" to yourclass, whatreallyhappensisthatfieldsandinstance methodsare addedtothe metaclassinstead.I.e.youcan change the structure and behaviorof yourclass description. In Java,all class descriptionslookandworkthe same:Theyare instancesof java.lang.Class.Youcannotadd anymethods or fieldsthere forsome classdescriptionswhere youthinkyouneedthis;youcanuse the existingones,though.E.g. getName() ornewInstance() orgetMethod()... Thisis howthe literature definesmetaclassesinobjectorientation.Javaobviouslydoesnotsupportmetaclasses. However,eveninJavayouhave exactlyone classdescriptionforeachloadedclassatruntime.And youcan do a lot usingtheirmethods(getMethod(),getConstructor(),isArray(),getInterfaces() etc...i.e.usingReflection) You getthe classdescriptionforanObject'sclassby callinggetClass() onthe object.If youknow the classname,youcan append .classto itto accomplishthe same,e.g.String.class,whichusesthe classloaderof the code thatcontainsthis expressionforlocatingthe class.StaticmethodforName() in java.lang.Class hasanoverloadedvariantwhere youcan pass inthe classname (fullyqualified!) andthe classloadertobe used. By the way: Aswe mentioned,inSystemshavingmetaclasses,a"classmethod"isjusta normal instance methodof a metaclass,canbe calledonthe instance of a metaclassandis dynamicallyboundandthus supports polymorphism. Java's staticmethodshave oftenbeencomparedtosuchclassmethodsbutinfact are - as the name reveals - juststatic methods,i.e.staticallybound,non-polymorphicmethods;consequentlythe syntax forcallingthemrequiresnoreceiver object.The onlyinstance methodsactingonclassdescriptionsare those of java.lang.Class. (sidenote:"classinstance variables"inSmalltalkare instance variablesof metaclasses;youmighthave guessedthatthey shouldbe called"classvariables"butthese are yetanotherthingandthose twoshouldnotbe confusedwhenworking withSmalltalk.ButforJavaprogrammersthisdoes,of course,notmatter ;-) What is early binding and late binding? The short answeristhat early(orstatic) binding referstocompile time bindingandlate (ordynamic) bindingrefersto runtime binding(forexamplewhenyouuse reflection). Early binding &late Bindingisa conceptof OOPS..B'cozthe dataand the method whichwill operate ondataare sepertaelydefinedinoops(calledabstraction).Andtheywillbinddatamembersandmethodseitheratthe complie time or runtime time.Thisiscalledencapsulation. In earlybindingthe dataandmethodare bindsat the complie time where asin late bindingthe dataandmethodwill bindat the runtime. Well earlyandlate bindingisagood concept,well considerasituationwhere youhave aclasswitha method,nowyou call the methodinyourmainmethod usingthe objectof the class,inthissituationthe complierknowswhichmethod to call before execution,thisisearlybinding...
  • 4. In late bindingthe complierdoesn'tknowwhichmethodtocall during compile time,the methodcall isresolvedonly duringruntime...thiscanbe achieved ininheritance orbyusingan interface hope followingexamplehelpsyou......... classA { publicvoidfoo() { System.out.println("ClassA"); } } classB extendsA { publicvoidfoo() { System.out.println("ClassB"); } } publicclassC { publicstaticvoidmain(String[] args) { A a=newA(); B b=newB(); A ref=null; a.foo();//early binding --- callsmethodfoo() of classA ....decidedatcompile time b.foo();//earlybinding --- callsmethodfoo() of classB....decidedatcompile time ref=b; ref.foo();// late binding--- --- callsmethodfoo() of classB....decidedatRuntime } } Difference between Dynamic Binding & Static Binding in Java Dynamic Binding or Late Binding DynamicBindingreferstothe case where compilerisnotable toresolve the call andthe bindingisdone at runtime only. Let's try to understandthis.Supposewe have aclassnamed'SuperClass'andanotherclassnamed'SubClass'extendsit.
  • 5. Nowa 'SuperClass'reference canbe assignedtoanobjectof the type 'SubClass'as well.If we have a method(say 'someMethod()') inthe 'SuperClass'whichwe override inthe 'SubClass'thenacall of that methodona 'SuperClass' reference canonlybe resolvedatruntime asthe compilercan'tbe sure of whattype of objectthisreference wouldbe pointingtoat runtime. ... SuperClasssuperClass1=newSuperClass(); SuperClasssuperClass2=newSubClass(); ... superClass1.someMethod();//SuperClassversioniscalled superClass2.someMethod();//SubClassversioniscalled .... Here,we see thateventhoughboththe objectreferencessuperClass1andsuperClass2are of type 'SuperClass'only,but at run time theyrefertothe objectsof types'SuperClass'and'SubClass'respectively. Hence,at compile time the compilercan'tbe sure if the call to the method'someMethod()'onthese referencesactually referto whichversionof the method - the superclassversionorthe sub classversion. Thus,we see that dynamicbindinginJavasimplybindsthe methodcalls(inheritedmethodsonlyastheycanbe overrideninasub classand hence compilermaynotbe sure of whichversionof the methodtocall) basedonthe actual objecttype andnot on the declaredtype of the objectreference. Static Binding or Early Binding If the compilercanresolve the bindingatthe compile time onlythensuchabindingiscalledStaticBindingorEarly Binding.All the instance methodcallsare alwaysresolvedatruntime,butall the staticmethodcallsare resolvedat compile time itself andhence we have staticbindingforstaticmethodcalls.Because staticmethodsare classmethods and hence theycanbe accessedusingthe classname itself (infacttheyare encourgaedtobe usedusingthe ir correspondingclassnamesonlyandnotbyusingthe objectreferences) andtherefore accesstothemisrequiredtobe resolvedduringcompile timeonlyusingthe compile time typeinformation.That'sthe reasonwhystaticmethodscan not actuallybe overriden.Readmore - Canyouoverride staticmethodsinJava? Similarly, accesstoall the membervariables inJavafollowsstaticbindingasJavadoesn'tsupport(infact,itdiscourages) polymorphicbehaviorof membervariables.Forexample:- classSuperClass{ ... publicStringsomeVariable ="Some VariableinSuperClass"; ... } classSubClassextendsSuperClass{ ... publicStringsomeVariable ="Some VariableinSubClass";
  • 6. ... } ... ... SuperClasssuperClass1=newSuperClass(); SuperClass superClass2=newSubClass(); System.out.println(superClass1.someVariable); System.out.println(superClass2.someVariable); ... Output:- Some Variable inSuperClass Some Variable inSuperClass We can observe thatinboththe cases,the membervariable is resolvedbasedonthe declaredtype of the object reference only,whichthe compileriscapable of findingasearlyas at the compile time onlyandhence astaticbindingin thiscase.Anotherexample of staticbindingisthatof 'private'methods as they are neverinheritedandthe compile can resolve callstoanyprivate methodatcompile time only. What is method signature in java? The signature of a methodisthe combinationof the method'sname alongwiththe numberandtypesof the parameters (andtheirorder). Specific to java, The signature of a method should contain details. It should contain 1. Name of the method 2. Arguments (type, order) The Java method signature contains only method name and parameter list. It doesn't contain visibility modifier, return type and throws clause because of the following reason.. Consider the following code: class A { public A x(int l) { //some code } } class B extends A { public B x(int k) { //some code } } Now, implementation of method x in class B is an example of overriding, which is also logically correct. However, this would not have been the case if return type was made part of signature. In that case, JVM would not know the difference between the two methods since B instanceof A is true.
  • 7. A method does not declare any exception. can it be overiden in a subclass to through an exception? ExceptionHandlingwithMethodOverriding There are manyrulesif we talkabout methodoverridingwithexceptionhandling.The Rulesare asfollows:  If the superclassmethoddoesnot declare an exception o If the superclassmethoddoesnotdeclare anexception,subclassoverriddenmethodcannotdeclare the checkedexceptionbutitcan declare uncheckedexception.  If the superclassmethoddeclaresan exception o If the superclassmethoddeclaresanexception,subclassoverriddenmethodcandeclare same,subclass exceptionornoexceptionbutcannotdeclare parentexception. If the superclassmethoddoesnotdeclarean exception 1)Rule: If the superclass method does notdeclareanexception,subclass overriddenmethod cannotdeclare the checked exception. 1. importjava.io.*; 2. classParent{ 3. voidmsg(){System.out.println("parent");} 4. } 5. 6. classChildextends Parent{ 7. voidmsg()throws IOException{ 8. System.out.println("child"); 9. } 10. publicstaticvoidmain(Stringargs[]){ 11. Parentp=new Child(); 12. p.msg(); 13. } 14. } Output:Compile Time Error 2)Rule: If the superclass method does notdeclareanexception,subclass overriddenmethod cannotdeclare the checked exception butcandeclareunchecked exception. 1. importjava.io.*; 2. classParent{ 3. voidmsg(){System.out.println("parent");} 4. } 5. 6. classChildextends Parent{ 7. voidmsg()throws ArithmeticException{ 8. System.out.println("child"); 9. } 10. publicstaticvoidmain(Stringargs[]){ 11. Parentp=new Child(); 12. p.msg();
  • 8. 13. } 14. } Output:child If the superclassmethoddeclaresanexception 1)Rule: If the superclass method declares anexception,subclassoverriddenmethod candeclaresame, subclass exceptionornoexceptionbut cannotdeclareparentexception. Exampleincase subclassoverriddenmethoddeclaresparentexception 1. importjava.io.*; 2. classParent{ 3. voidmsg()throws ArithmeticException{System.out.println("parent");} 4. } 5. 6. classChildextends Parent{ 7. voidmsg()throws Exception{System.out.println("child");} 8. 9. publicstaticvoidmain(Stringargs[]){ 10. Parentp=new Child(); 11. try{ 12. p.msg(); 13. }catch(Exception e){} 14. } 15. } Output:Compile Time Error Exampleincase subclassoverriddenmethoddeclaressameexception 1. importjava.io.*; 2. classParent{ 3. voidmsg()throws Exception{System.out.println("parent");} 4. } 5. 6. classChildextends Parent{ 7. voidmsg()throws Exception{System.out.println("child");} 8. 9. publicstaticvoidmain(Stringargs[]){ 10. Parentp=new Child(); 11. try{ 12. p.msg(); 13. }catch(Exception e){} 14. } 15. } Output:child Exampleincase subclassoverriddenmethoddeclaressubclassexception 1. importjava.io.*;
  • 9. 2. classParent{ 3. voidmsg()throws Exception{System.out.println("parent");} 4. } 5. 6. classChildextends Parent{ 7. voidmsg()throws ArithmeticException{System.out.println("child");} 8. 9. publicstaticvoidmain(Stringargs[]){ 10. Parentp=new Child(); 11. try{ 12. p.msg(); 13. }catch(Exception e){} 14. } 15. } Output:child Exampleincase subclassoverriddenmethoddeclaresno exception 1. importjava.io.*; 2. classParent{ 3. voidmsg()throws Exception{System.out.println("parent");} 4. } 5. 6. classChildextends Parent{ 7. voidmsg(){System.out.println("child");} 8. 9. publicstaticvoidmain(Stringargs[]){ 10. Parentp=new Child(); 11. try{ 12. p.msg(); 13. }catch(Exception e){} 14. } 15. } Output:child Why parameter for main is a string array? The signature of the main method is specified in the Java Language Specifications section 12.1.4 and clearly states: The method main must be declared public, static, and void. It must specify a formal parameter whose declared type is array of String.  it mustbe public otherwise itwouldnotbe possible tocall it  it mustbe static since youhave noway to instantiate anobjectbefore callingit  the listof String argumentsis there toallow to passparameterswhenexecutingaJavaprogram fromthe commandline.Itwouldhave beenpossibletodefine itwithoutargumentsbutismore practical like that(and similartootherlanguages)  the returntype is void since itdoesnot make sense tohave anythingelse:aJavaprogram can terminate before reachingthe endof the mainmethod(e.g.,bycalling System.exit())
  • 10. You understand that String[] args is an array of strings passed into main as parameters. java Print "Hello, World!" class Print { public static void main(String[] args) { System.out.println(args[0]); } } However, when you don't include it as a parameter (even if you don't use), it throws an exception. So why is it required? Also, why can't it be an int[] or boolean[]? It's a String because the command line is expressed in text. If you want to convert that text into integers or booleans, you have to do that yourself - how would the operating system or Java bootstrapper know exactly how you wanted everything to be parsed? I suppose Java could look for a main method with the same number of parameters as command line arguments, and then try to parse them using Integer.parseInt etc... but this would be pretty complicated, and would still be inadequate in many situations. As for it being mandatory - basically the Java designers decided to stick to a single method signature, which is frankly simpler than allowing for it to be optional. It would be possible though - in C#, you can have any of static void Main() static void Main(string[] args) static int Main() static int Main(string[] args) Ultimately it doesn't make a lot of difference, to be honest. There's no significant downside in having to include the parameter. That's how the language was designed. C and C++ both do it in a similar fashion, though with a separate count, information that's included in the string array for Java. You could have designed it to take integers or booleans but that would have added more work to the Java runtime for potentially little benefit. Strings can be used to transmit any sort of information into the main program (including integers and booleans). Not so for integers if you want to pass in a string (short of the user having to manually encode it as UTF-8 or something, not something that would endear people to the language). Just remember to declare it. By all means, raise a change request on the language if you wish (to make it optional, or allow other signatures) but I suspect that will not get very far. User defined exceptions and system defined exception...example How to Create User Defined Exception in Java Apart from existing Exceptions in java, we can create our own Exceptions (User defined exceptions in java), we will how to.. Required files
  • 11.  Client.java [ My business logic will goes here ]  MyOwnExceptionClass.java [ This is our own Exception class ] Note: Our user defined class must extend from Exception class, and we must override the toString() method to display our exception message. Client.java package java4s; public class Client { public static void main(String[] args)throws Exception { int price = -120; if(price < 0) throw new MyOwnExceptionClass(price); else System.out.println("Your age is :"+price); } } MyOwnExceptionClass.java package java4s; public class MyOwnExceptionClass extends Exception { private int price; public MyOwnExceptionClass(int price){ this.price = price; } public String toString(){ return "Price should not be in negative, you are entered" +price; } } Output: Java has a powerful concept for exception and error handling. An exception is an error that occurs at runtime. It is either generated by the Java Virtual Machine (VM) in response to an unexpected condition or it is generated by your code as a result of executing a throw statement. Understanding System – defined Exceptions Exceptions generated from runtime are called unchecked exceptions, since it is not possible for the compiler to determine that your code will handle the exception. Exception classes that descend from RuntimeException and
  • 12. Error classes are unchecked exceptions. Examples for RuntimeException are illegal cast operation, inappropriate use of a null pointer, referencing an out of bounds array element. Error exception classes signal critical problems that typically cannot be handled by your application. Examples are out of memory error, stack overflow, failure of the Java VM. Thrown exceptions are referred to as checked exceptions. The compiler will confirm at compile time that the method includes code that might throw an exception. Moreover the compiler requires the code that calls such a method to include this call within a try block, and provide an appropriate catch block to catch the exception. java.lang.Object | +--java.lang.Throwable | +--java.lang.Exception | | | +--java.lang.ClassNotFoundException | | | +--java.io.IOException | | | | | +--java.io.FileNotFoundException | | | +--java.lang.RuntimeException | | | +--java.lang.NullPointerException | | | +--java.lang.IndexOutOfBoundsException | | | +--java.lang.ArrayIndexOutOfBoundsException | +--java.lang.Error | +--java.lang.VirtualMachineError | +--java.lang.OutOfMemoryError When an (either checked or unchecked) exception is thrown, execution will attempt to immediately branch to the first catch block whose associated exception class matches the class or a superclass of the thrown exception. If the exception does not occur within a try block or the thrown exception is not caught in a matching catch block, execution of the method immediately terminates and control returns to the invoker of the method, where this process is repeated. The result is that the exception chain is escalated until a matching catch block is found. If not, the thread containing the thrown exception is terminated. First Example The following Demo1 class demonstrates the behaviour of exceptions and applications. import java.io.*; class Demo1 { public static FileInputStream f1(String fileName) throws FileNotFoundException
  • 13. { FileInputStream fis = new FileInputStream(fileName); System.out.println("f1: File input stream created"); return fis; } public static FileInputStream f2(String fileName) { FileInputStream fis = null; try { fis = new FileInputStream(fileName); } catch (FileNotFoundException ex) { System.out.println("f2: Oops, FileNotFoundException caught"); } finally { System.out.println("f2: finally block"); } System.out.println("f2: Returning from f2"); return fis; } public static void main(String args[]) { FileInputStream fis1 = null; FileInputStream fis2 = null; String fileName = "foo.bar"; // String fileName = null; System.out.println( "main: Starting " + Demo1.class.getName() + " with file name = " + fileName); // get file input stream 1 try { fis1 = f1(fileName); } catch (FileNotFoundException ex) { System.out.println("main: Oops, FileNotFoundException caught"); } catch (Exception ex) { System.out.println("main: Oops, genreal exception caught"); } // get file input stream 2 fis2 = f2(fileName);
  • 14. System.out.println("main: " + Demo1.class.getName() + " ended"); } } Compile and run the Demo1 class will generate output as follows (assuming that the file foo.bar does not exist): main: Starting Demo1 with file name = foo.bar main: Oops, FileNotFoundException caught f2: Oops, FileNotFoundException caught f2: finally block f2: Returning from f2 main: Demo1 ended The example program tries to create two file input streams. Therefore two methods f1 and f2 are implemented. First, the main program calls f1 method. Because the constructor of the FileInputStream throws a FileNotFoundException the method f1 must be defined with the throws FileNotFoundException in the method definition. The thrown exception is not handled in the method but forwarded to the invoker. Note, that the system output before the return statement is never executed. So the invoker, in our example the main program, must catch this exception. The method f1 is called in a try block. The following catch blocks catch either a FileNotFoundException or a general Exception. In our example, the exception is caught in the first catch block and the system output is generated. Since the exception in f1 is caught and handled, the execution of the program is not terminated. Second, the example program creates another FileInputStream invoking the f2 method. This method catches the FileNotFoundException, so this exception must not be forwarded to the invoker. The try ... catch statement is followed by a finally block. This block is always executed, regardless whether or not an exception occurs within the try block. This generates the system output in our example. Again, the exception is caught and the program executes, this generates the system output in f2 and main. This was a straight forward example with caught exceptions. What happens with uncaught exceptions? Change the fileName assignment in the main method: Comment out the first assignment and activate the second String fileName = null; then compile and execute Demo1 again. The generated output is: main: Starting Demo1 with file name = null main: Oops, genreal exception caught f2: finally block java.lang.NullPointerException java.io.FileInputStream Demo1.f2(java.lang.String) void Demo1.main(java.lang.String[]) Exception in thread main This time, we try to create two FileInputStream objects using null instead of a file name. Invoking f1 will generate a NullPointerException which is caught in the main program. Next f2 is called which could handle only the FileNotFoundException but not a NullPointerException. Nevertheless the finally block is executed and then the control returns to the main program. Because there is no try ... catch statement around the call to f2 and no matching catch block is found, the thread is terminated. Note, that f2 and main can not execute the system output statements any more. Second Example The second example will show some special behaviour in catch and finally blocks:
  • 15. import java.io.*; class Demo2 { public static FileInputStream f1(String fileName) { FileInputStream fis = null; try { fis = new FileInputStream(fileName); } catch (FileNotFoundException ex) { System.out.println("f1: Oops, FileNotFoundException caught"); throw new Error("f1: File not found"); } System.out.println("f1: File input stream created"); return fis; } public static FileInputStream f2(String fileName) { FileInputStream fis = null; try { fis = new FileInputStream(fileName); } catch (FileNotFoundException ex) { System.out.println("f2: Oops, FileNotFoundException caught"); return fis; } finally { System.out.println("f2: finally block"); return fis; } // Compiler error: statement not reacheable // System.out.println("f2: Returning from f2"); // return fis; } public static void main(String args[]) { FileInputStream fis1 = null; FileInputStream fis2 = null; String fileName = "foo.bar"; // String fileName = null; System.out.println( "main: Starting " + Demo2.class.getName() + " with file name = " + fileName);
  • 16. // get file input stream 1 try { fis1 = f1(fileName); } catch (Exception ex) { System.out.println("main: Oops, general exception caught"); } catch (Throwable th) { System.out.println("main: Oops, throwable object caught"); } // get file input stream 2 fis2 = f2(fileName); System.out.println("main: " + Demo2.class.getName() + " ended"); } } } Compile and run Demo2 will generate the following output: main: Starting Demo2 with file name = foo.bar f1: Oops, FileNotFoundException caught main: Oops, throwable object caught f2: Oops, FileNotFoundException caught f2: finally block main: Demo2 ended Again f1 is called to get a new FileInputStream with a given file name. The thrown FileNotFoundException in f1 is caught in the following catch block. But this time an Error is thrown so that the method is terminated immediately. Because Error is not a subclass of Exception the first catch block does not match. But the second catch block matches all throwable objects. Calling f2 method will generate a FileNotFoundException too. This exception is caught in f2 and the method returns directly from the catch block. Remember, that the finally block is executed regardless whether an exception is caught or not. In both methods f1 and f2, the FileNotFoundException is caught and handled, so the program can terminate normally. Change again the fileName assignment in the main method and compile and run Demo2 again: main: Starting Demo2 with file name = null main: Oops, general exception caught f2: finally block main: Demo2 ended The NullPointerException thrown in f1 is not caught, so the exception is forwarded to the invoker. The main program catches Exception, which is a superclass of the thrown exception. The call to f2 method seems to work fine even the thrown NullPointerException is not caught directly. Note, that the finally block is executed regardless whether an exception is caught or not. Since the finally block
  • 17. terminates with a return statement, the program executes without failure. So be careful returning within finally blocks, this breaks the exception chaining to the invoker and it simulates error free program execution. Summary  Normal program execution is immediately branched when an exception is thrown.  Checked exceptions must be caught or forwarded. This can be done in a try ... catch statement or by defining the exception in the method definition.  The exception is caught by the first catch block whose associated exception class matches the class or a superclass of the thrown exception.  If no matching catch block is found in the exception chain, the thread containing the thrown exception is terminated.  The finally block after a try ... catch statement is executed regardless whether an exception is caught or not.  Returning within a finally block breaks the exception chain to the invoker even for uncaught exceptions. Why is java called a strongly typed language? A strongly typed programming languages is one that requires the type of a variable to be explicitly stated. C is a strongly typed language. You must declare the type of data a variable will store for C to interpret it: int myVariable; myVariable = 25; Perl is a loosely typed language. There is no need to declare the variable type before using it: $myVariable = 25; $myVariable = "A String."; Java iscalleda Strong TypedLanguage because youHave to state the type of a variable inthe momentyoucreate it,for instance inta = 22; Stringhello= "hello" As a example of nonstrongtypedlanguagesyoumayfindJavaScriptwhere youdon'thave tostate the type of the variable,youmayhave : a = 22; a = "a string"; var b = 33; var b = "anothernewstring" See?the variable aor b can have differenttypesof values,integer,strings,doubles,etcetcetc,withoutthe compiler raisesanywarning.
  • 18. Java isa stronglytypedlanguage inthe sense thatall the data that youencounterduringaJava program isto be properlyassigneda"datatype". Withoutassigningaparticulardata type to anyvariable, youare not allowedtoinitialize the variable,andsuchvariables are notrecognizedatall.Thus,all variablesinJavamusthave a data type. Data type is the type of the data thatyou are referringto.Isitan integer,adecimal,alongdecimal,asmall integer,a short integer,aBooleanvalue,acharactervalue,ora String of characters? Whendeclaringyourvariable inJava,youwill needtofollowthissyntax inwhichthe datatype of the variable is predefinedbyyou: <data type> <variable name>; For example, "inta;" declaresa variable of type "int"andname "a". "char a;" declaresa variable of type "char"and name "a". "double a;"declaresavariable of type "double"andname "a". and so on... The importantpointto discusshere isthatyou cannotdeclare a variable withoutanddatatype andspecifyitsdatatype at the time of initialization.Noristhe datatype of a variable dynamicallydeclaredinJava.Youhave toassignthe proper data type to yourvariable. So whatis the difference betweenC++and Java?Both require todeclare a data type fora variable. The difference isthatonce youdeclare adata type in Java,youcannot give the value of anyother data type toit. This will require explicitconversionof the datatype.