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();
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
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:
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.