Que. Difference Between C++ and Java. Ans
Que. Difference Between C++ and Java. Ans
Patel
C++ Java
C++ support object oriented programming but it is Java is a pure object oriented programming
not pure object oriented language. language.
C++ generates object code and the same code may Java is interpreted for the most part and hence
not run on different platforms. Means C++ is platform independent.
platform-dependent.
C++ uses compiler only. Java uses compiler and interpreter both.
C++ support operator overloading. Java does not support operator overloading.
C++ have template classes. Java does not have template classes.
C++ support multiple inheritance of classes. The Java does not support multiple inheritance of
keyword virtual is used to resolve ambiguities classes. This is accomplished using a new feature
during multiple inheritance if there is any. called “interface”.
C++ support global variables. Java does not support global variables. Every
variable and method is declared within a class and
forms part of that class.
C++ support pointers. (Asst. Prof. Viral S. Patel) Java does not use pointers.
C++ support structures and unions. Java does not support unions, structures.
C++ does not have Boolean data type. Java has Boolean data type. And this type of
variable can store true or false value.
C++ has destructor function. Java has replaced the destructor function with a
finalize() function.
C++ support typedef. Java does not support typedef.
In C++ we can declare unsigned integers. It is not possible to declare unsigned integers in
java.
C++ have many header files. There are no header files in Java.
C++ have delete operator. C++ does not have Java does not have delete operator. Java has
garbage collection. garbage collection that automatically frees blocks
of memory.
In C++ objects are pass by value or pass by In java objects are pass by reference only.
reference.
C++ have simple break and continue statements. Java has enhanced break and continue statements
called label break and label continue concept.
In C++ ‘<<’ and ‘>>’ operators are overloaded for In java ‘<<’ and ‘>>’ operators are not overloaded
I/O operations. for I/O operations.
In C++ ‘>>>’ operator is not available like ‘>>>’ In java ‘>>>’ operator is used as unsigned right
operator used in java. shift.
C++ has only single-line and multi-line comments. Java has single-line, multi-line comments and also
has documentation comment which is begin with
/** and end with */.
C++ has no built in support for threads. Java has built in support for threads.
C++ has goto statement. There is no goto statement in java.
In C++ there is no concept of package. In java there is a concept of package.
C++ is mainly used for system programming. Java is mainly used for application programming. It
is widely used in window, web-based, enterprise
and mobile applications.
Simple
Java was designed to be easy for the professional programmer to learn and use effectively. If
we already understand the basic concepts of object-oriented programming, learning Java will be
even easier.
Because Java inherits the C/C++ syntax and many of the object-oriented features of C++,
most programmers have little trouble learning Java.
Secure
Most users worried about the possibility of infecting their systems with a virus. This type of
program can gather private information, such as credit card numbers, bank account balances, and
passwords, by searching the contents of your computer’s local file system.
Java answers of these concerns by providing a “firewall” between a networked application
and your computer. (Asst. Prof. Viral S. Patel)
When we use a Java-compatible Web browser, we can safely download Java applets without
fear of viral infection or malicious intent.
Java achieves this protection by confining a Java program to the Java execution environment
and not allowing it access to other parts of the computer.
Portable
Many types of computers and operating systems are in use throughout the world—and many
are connected to the Internet. For programs to be dynamically downloaded to all the various
types of platforms connected to the Internet, some means of generating portable executable code
is needed. Java interpretation of bytecode is the easiest way to create truly portable programs.
Object Oriented
In java “everything is an object” paradigm. The object model in java in java is simple and easy
to extend.
Robust
Two of the main reasons for program failure: memory management mistakes and mishandled
exceptional conditions (run-time errors). The program must execute reliably in a variety of
systems.
Java is robust as deallocation is completely automatic in Java, because Java provides garbage
collection for unused objects and providing object-oriented exception handling.
Multithreaded
Java supports multithreaded programming, which allows to write programs that do many
things simultaneously. The Java run-time system comes with an elegant yet sophisticated
solution for multiprocess synchronization that enables you to construct smoothly running
interactive systems.
Architecture-Neutral
A central issue for the Java designers was that of code longevity and portability. One of the
main problems facing programmers is that no guarantee exists that if you write a program today,
it will run tomorrow—even on the same machine. Operating system upgrades, processor
upgrades, and changes in core system resources can all combine to make a program malfunction.
The Java designers made several hard decisions in the Java language and the Java Virtual
Machine in an attempt to alter this situation. Their goal was “write once; run anywhere, any
time, forever.”
Distributed
Java is designed for the distributed environment of the Internet, because it handles TCP/IP
protocols. Java allowed objects on two different computers to execute procedures remotely. Java
revived these interfaces in a package called Remote Method Invocation (RMI). This feature
brings client/server programming.
Dynamic
Java programs carry with them substantial amounts of run-time type information that is used to
verify and resolve accesses to objects at run time. This is crucial to the robustness of the applet
------------------------------------------------------------------------------------------------------------------
The public keyword is an access specifier, main( ) must be declared as public, since it must be
called by code outside of its class when the program is started.
The keyword static allows main( ) to be called without having to instantiate a particular
instance (object) of the class. This is necessary since main( ) is called by the Java interpreter
before any objects are made.
The keyword void simply tells the compiler that main( ) does not return a value.
In main( ), there is only one parameter. String args[ ] declares a parameter named args, which is
an array of instances of the class String. Objects of type String store character strings. In this
case, args receives any command-line arguments present when the program is executed.
■ Boolean This group includes boolean, which is a special type for representing true/false
values.
Explicit Conversion :
Also known as Narrowing Conversion
Numeric types are not compatible with char or Boolean.
char and Boolean are not compatible with each other
It will take place if the one of the following two conditions are met:
1. Two types are not compatible
2. Destination type is smaller than the source type
Que. What is automatic type promotion in java. Explain Automatic Type Promotion Rules.
Which type of problem causes during automatic type promotion and how can we solve it?
Explain with example.
Ans. Java automatically promotes each byte or short operand to int when evaluating an
expression. Means automatically promotes lower data type to higher data type.
For example,
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
The result of the intermediate term a * b easily exceeds the range of either of its byte
operands. To handle this kind of problem, This means that the sub-expression a * b is performed
using integers—not bytes.
f is float variable, b is byte variable, i is int variable, c is char variable, d is double and s is sort
variable.
Output:
20 20 20
Output:
333
Wrapper class type to corresponding basic data type conversion is called Unboxing
conversion.
From type Boolean to type boolean
From type Byte to type byte
From type Short to type short
From type Character to type char
Que. Explain ‘break, label break, continue, label continue and return’ in java as jump
statements.
Ans.
Using break to Exit a Loop : When a break statement is encountered inside a loop, the loop is
terminated and program control resumes at the next statement following the loop. The break
statement can be used with any of Java’s loops (while, do..while, for loops)
Example :
class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<10; i++)
{
if(i == 5)
break;
System.out.print(i + “ “);
}
System.out.println("Loop complete.");
}
}
class BreakOnlyInnerLoop
{
public static void main(String args[])
{
for(int i=0; i<3; i++)
{
for(int j=0; j<5; j++)
{
if(j == 2)
break;
System.out.print(j+ “ “);
}
System.out.print(i+ “ “);
}
System.out.println("Loops complete.");
}
}
Using break to Exit a outer Loop in nested loops concept as a Form of Goto : Here, label is
the name of a label that identifies a block of code. When this form of break executes, control is
transferred out of the named block of code. One of the most common uses for a labeled break
statement is to exit from nested loops. (Asst. Prof. Viral S. Patel)
Example:
class BreakOuterLoop
{
public static void main(String args[])
{
outer : for(int i=0; i<3; i++)
{
for(int j=0; j<5; j++)
{
if(j == 2)
break outer;
System.out.print(j+ “ “);
}
System.out.print(i+ “ “);
}
System.out.println("Loops complete.");
}
}
class Continue
{
public static void main(String args[])
{
for(int i=0; i<5; i++)
{
if(i == 2)
continue;
System.out.print(i + “ “);
}
System.out.println("Loop complete.");
}
}
Using continue in nested Loop to continue outer loop : continue may specify a label to
describe which enclosing loop to continue.
Example :
class Continue
{
public static void main(String args[])
{
outer : for(int i=0; i<3; i++)
{
for(int j=0; j<5; j++)
{
if(j == 2)
continue outer;
System.out.print(j+ “ “);
}
System.out.println("Loops complete.");
}
}
Return :
The return statement is used to explicitly return from a method. That is, it causes program control
to transfer back to the caller of the method.
Example :
class Return
{
public static void main(String args[])
{
for(int i=0; i<3; i++)
{
for(int j=0; j<5; j++)
{
if(j == 2)
return;
System.out.print(j+ “ “);
}
System.out.print(“This statement does not exit.“);
}
System.out.println("This statement also does not exit.“);
}
}
Output: 0 1
For example:
int a = 35;
00000000 00000000 00000000 00100011 35 >> 2
a = a >> 2; // a now contains 8 00000000 00000000 00000000 00001000 8
int a = -8;
11111111 11111111 11111111 11111000 –8 >>1
a = a >> 1; // a now contains -4 11111111 11111111 11111111 11111100 –4
The >>> is right shift unsigned operator. It shifts bits towards right. Zeros are fill in the left
bits regardless of sign.
For example:
int a = -1; 11111111 11111111 11111111 11111111 –1 in binary as an int
>>>24
a = a >>> 24; 00000000 00000000 00000000 11111111 255 in binary as an int
Here, using a single & ensures that the Here there is no risk of causing a run-time
increment operation will be applied to exception where denom is zero. If this line of
e whether c is equal to 1 or not. code were written using single & , both sides
would have to be evaluated, causing a run-time
exception when denom is zero.
Que. What is class and object ? How to create object and reference of class ?
Ans. Class is a user defined data type. A class is a template for an object and Object is a
instance of a class. (Asst. Prof. Viral S. Patel)
A class creates a logical framework that defines the relationship between its members. When
objects of a class are creating an instance of that class.
Thus, a class is a logical construct. An object has physical reality. An object occupies
space in memory.
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
// ...
type methodnameN(parameter-list)
{
// body of method
}
}
Example :
class Box
{
…
}
class DemoBox
{
public static void main(String args[])
{
Box mybox; // declare reference for object name
mybox = new Box(); // allocate memory of object
Box mybox1 = new Box(); // declare reference and allocate memory simultaneously
It is illegal in Java to declare two local variables with the same name inside the same or
enclosing scopes. When a local variable has the same name as an instance variable, the local
variable hides the instance variable.
Because ‘this’ refer directly to the object, we can use it to resolve any name space collisions
that might occur between instance variables and local variables.
// Use this to resolve name-space collisions.
Box(double width, double height, double depth)
{
this.width = width;
this.height = height;
this.depth = depth;
}
In some languages, such as C++, dynamically allocated objects must be manually released by
use of a delete operator.
Java takes a different approach; it handles deallocation automatically. The technique that
accomplishes this is called garbage collection.
It works like this: when no references to an object exist, that object is assumed to be no
longer needed, and the memory occupied by the object can be reclaimed. There is no explicit
need to destroy objects as in C++. Garbage collection only occurs sporadically (if at all) during
the execution of your program. It will not occur simply because one or more objects exist that are
no longer used.
Que. Explain static keyword. Also explain calling sequence of static variables, methods and
blocks in java with example. (7)
Ans. When a member (variable or method) of class declared static, it can be accessed before any
objects of its class are created, and without reference to any object.
Variables declared as static: When variables declared as static, they work like global
variables. When objects of its class are declared, no copy of a static variable is made (means
static variable is not part of object memory). All instances (objects) of the class share the
same static variable. (Asst. Prof. Viral S. Patel)
Methods declared as static: The most common example of static method is main method.
Main is declared as static because it must be called before any objects exist.
Static methods and variables can be used independently of any object. We can access them
only by specify the name of their class followed by the dot operator.
classname.method( )
classname.variableOfClass
Example :
class StaticDemo
{
static int a = 42;
static void callme()
{
System.out.println("a = " + a);
}
}
class StaticByName
{
public static void main(String args[])
{
StaticDemo.callme();
System.out.println("a = " + StaticDemo.a);
}
}
output:
a = 42
Example:
class UseStatic
{
static int a = 3;
static int b;
static void meth(int x)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static
{
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[])
{
meth(42);
}
}
Output :
Static block initialized.
x = 42
a = 3
b = 12
As soon as the UseStatic class is loaded, all of the static statements are run. First, a is set to 3,
then the static block executes (printing a message), and finally, b is initialized to a * 4 or 12.
Then main( ) is called, which calls meth( ), passing 42 to x.
Que. Explain Overloading and Overriding methods with example. (Prof. Viral S. Patel)
Ans. Overloading :
In Java it is possible to define two or more methods within the same class that share the same
name, as long as their parameter declarations are different. This methods are said to be
overloaded and the process is referred to as method overloading.
Overloaded methods must differ in the type and/or number of parameters.
The return type alone is insufficient to distinguish two versions of a method.
Example :
Class A class Overload
{ {
void disp()
{ public static void main(String args[])
System.out.println(“No parameters”); {
} A ob = new A();
void disp(int a) ob.disp();
{ ob.disp(10);
System.out.println(“a: “+a); ob.disp(10, 20);
} ob.disp(123.25);
void disp(int a, int b) }
{
System.out.println(“a and b: “+a+” “+b); }
}
Void disp(double a) Output :
{ No parameters
System.out.println(a); a: 10
} a and b: 10 20
double a: 123.25
}
Overriding :
In a class hierarchy, when a method in a subclass has the same name and type signature as a
method in its superclass, then the method in the subclass is said to override the method in the
superclass.
When an overridden method is called from within a subclass, it will always refer to the
version of that method defined by the subclass. The version of the method defined by the
superclass will be hidden. (Asst. Prof. Viral S. Patel)
If we need to access the superclass version of an overridden function, we can do so by using
super keyword which is resolved at compile time. Dynamic method dispatch is the
mechanism by which a call to an overridden method is resolved at run time, rather than compile
time.
Example :
class A class Override
{ {
void show() public static void main(String args[])
{ {
System.out.println("SUPER A”); A a = new A(); // object of type A
} B b = new B();
} C c = new C();
b.show(); // this calls show() in B
class B extends A c.show(); // this calls show() in C
{ A r; // obtain a reference of type A
void show() r = a; // r refers to an A object
{ r.show(); // calls A's version of show()
System.out.println("SUB B”); r = b; // r refers to a B object
} r.show(); // calls B's version of show()E
} }
}
When an overridden method is called through a superclass reference, Java determines which
version of that method to execute based upon the type of the object being referred to at the
time the call occurs.
Example :
class A class Dispatch
{ {
void callme() public static void main(String args[])
{ {
System.out.println("Inside A's"); A a = new A(); // object of type A
} B b = new B(); // object of type B
} C c = new C(); // object of type C
A r; // obtain a reference of type A
class B extends A r = a; // r refers to an A object
{ r.callme(); // calls A's version of callme
// override callme() r = b; // r refers to a B object
void callme() r.callme(); // calls B's version of callmeE
{ JAVAr = c; // r refers to a C object
System.out.println("Inside B's"); r.callme(); // calls C's version of callme
} }
} }
class C extends A
Output :
{
// override callme()
Inside A’s
void callme() Inside B’s
{ Inside C’s
System.out.println("Inside C's");
}
}
This program creates one superclass called A and two subclasses of it, called B and C.
Subclasses B and C override callme( ) declared in A. Inside the main( ) method, objects of type
A, B, and C are declared. Also, a reference of type A, called r, is declared. The program then
assigns a reference to each type of object to r and uses that reference to invoke callme( ). As the
output shows, the version of callme( ) executed is determined by the type of object being referred
to at the time of the call.
A native method is a Java method (either an instance method or a class method) whose
implementation is written in another programming language such as C. We can integrate native
methods into Java code. These methods can be called from inside your Java program just as you
call any other Java method.
For example:
public native int meth() ;
After we declare a native method, we must write the native method and follow some
complex series of steps to link it with Java code. Most native methods are written in C. The
mechanism used to integrate C code. (Asst. Prof. Viral S. Patel)