0% found this document useful (0 votes)
94 views

Que. Difference Between C++ and Java. Ans

The document compares the key differences between C++ and Java. Some of the main differences include: - C++ supports operator overloading while Java does not - Java is platform independent while C++ is platform dependent - Java uses both a compiler and interpreter while C++ uses just a compiler - Java does not support pointers, global variables, or multiple inheritance like C++ The document then discusses why pointers are not supported in Java, citing security and reliability concerns. It also provides an overview of common Java features or "buzzwords" such as being simple, secure, portable, object-oriented, robust, and distributed. Finally, it outlines the basic structure of a Java program including packages, imports, classes

Uploaded by

keyur kevadiya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views

Que. Difference Between C++ and Java. Ans

The document compares the key differences between C++ and Java. Some of the main differences include: - C++ supports operator overloading while Java does not - Java is platform independent while C++ is platform dependent - Java uses both a compiler and interpreter while C++ uses just a compiler - Java does not support pointers, global variables, or multiple inheritance like C++ The document then discusses why pointers are not supported in Java, citing security and reliability concerns. It also provides an overview of common Java features or "buzzwords" such as being simple, secure, portable, object-oriented, robust, and distributed. Finally, it outlines the basic structure of a Java program including packages, imports, classes

Uploaded by

keyur kevadiya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

SY BCA - SEM 4 – JAVA Asst. Prof. Viral S.

Patel

Que. Difference between C++ and Java.


Ans.

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.

S. V. Patel College of CS & BM, Surat Page |1


SY BCA - SEM 4 – JAVA Asst. Prof. Viral S. Patel

Que. Why pointers don’t exist in java.


Ans. Pointers don’t exist in java for two reasons :
Pointers are inherently insecure. By using pointer it is possible to access memory addresses
and data from outside of program’s code. A malicious program could make use of this fact to
damage the system, perform unauthorized accesses (such as obtaining passwords), or otherwise
violate security restrictions.
Even if pointers could be restricted to the confines of the Java run-time system (which is
theoretically possible), the designers of Java believed that they were inherently troublesome.

Que. Explain the Features of Java (or Java Buzzwords)


Ans.
 Simple
 Secure
 Portable
 Object-oriented
 Robust
 Multithreaded
 Architecture-neutral
 Interpreted
 High performance
 Distributed
 Dynamic

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.

S. V. Patel College of CS & BM, Surat Page |2


SY BCA - SEM 4 – JAVA Asst. Prof. Viral S. Patel

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.”

Interpreted and High Performance


Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java bytecode. This code can be interpreted on any system that provides a
Java Virtual Machine.
 Java, however, was designed to perform well on very low-power CPUs. As explained earlier,
while it is true that Java was engineered for interpretation, the Java bytecode was carefully
designed so that it would be easy to translate directly into native machine code for very high
performance by using a just-in-time compiler.

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

S. V. Patel College of CS & BM, Surat Page |3


SY BCA - SEM 4 – JAVA Asst. Prof. Viral S. Patel

environment, in which small fragments of bytecode may be dynamically updated on a running


system. (Asst. Prof. Viral Patel)

Que. Explain Java Program Structure.


Ans.
Document Section /* comment */
Package Statement Package P1
Import Statements Import java.io.*
Class Definitions (Interface/Inherit Statements ) Class A extends B implements C,D
{ {
Data members int a,b;
User Defined methods void disp( ) { …………….}
Main Method public static void main(String args[]) { ………}
} }

 A package is a collection of classes, interfaces and sub-packages. A sub package


contains collection of classes, interfaces and sub-sub packages etc. java.lang.*;
This package is imported by default and this package is known as default package.
 Import statement is used to import classes of other package in current package.
 Class is used for developing user defined data type and every java program must start
with a concept of class. Class can extends other class and can implements interfaces.
 Data member represents either instance or static they will be selected based on the name
of the class.
 User-defined methods represents either instance or static they are meant for performing
the operations either once or each and every time.
 Each and every java program starts execution from the main() method. And hence
main() method is known as program driver.
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 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.
Each and every main() method of java must take array of objects of String.

Que. What is compiler ?


Ans. Compiler is a program that convert High level language program/code in low level
language program/code.

Que. What is Java Compiler ?


Ans. Compile java code (.java source file) and convert in bytecode ( .class file).

Que. What is Interpreter ?


Ans. An interpreter is a computer language processor (computer program) that reads a program
line-by-line (statement-by-statement) and directly executes instructions written in a
programming or scripting language, without requiring them previously to have been compiled
into a machine language program.

S. V. Patel College of CS & BM, Surat Page |4


SY BCA - SEM 4 – JAVA Asst. Prof. Viral S. Patel

Que. What is Java Interpreter ?


Ans. A java interpreter is usually referred to as the Java Virtual Machine (or JVM). It reads line
by line bytecodes and executes the bytecodes ( .class file ).

*Note : Following figure just for understand


------------------------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------------------------

Que. What is bytecode ?


Ans. The output of a Java compiler is bytecode. Bytecode is a highly optimized set of
instructions designed to be executed by the the Java Virtual Machine (JVM). This bytecode
interpreted by all JVM so java become platform independent.

Que. What is JVM ? or What is Java’s Magic ?


Ans. The output of a Java compiler is not executable code. Rather, it is bytecode.
Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time
system, which is called the Java Virtual Machine (JVM). That is, in its standard form, the
JVM is an interpreter for bytecode.
JVM will differ from platform to platform, All interpret the same Java bytecode. So only the
JVM needs to be implemented for each platform.
JVM make Java program secure as the execution of every Java program is under the control of
the JVM. (Asst. Prof. Viral S. Patel)

Que. What is JIT ?


Ans. JIT is just-in-time compiler for bytecode, which is included in the Java 2 release. When the
JIT compiler is part of the JVM, it compiles bytecode into executable code in real time, on a
piece-by-piece, demand basis. Java performs various run-time checks, so JIT compiles codes
as it is needed during execution. (Asst. Prof. Viral S. Patel)

Que. What is JRE ?


Ans. The Java Runtime Environment (JRE) facilitates the execution of programs developed in
Java. It contains JVM, set of libraries and other files that JVM uses at runtime.

Que. Write down the significance of CLASSPATH.


Ans. CLASSPATH environment variable used to specify/set path of the class file which we
want to execute. If this path is not set then operating system give ClassNotFoundException or
NoClassDefFoundError.

S. V. Patel College of CS & BM, Surat Page |5


SY BCA - SEM 4 – JAVA Asst. Prof. Viral S. Patel

Que. Explain the meaning of ‘ public static void main(String args[]) ‘.


Ans. This is the line at which the program will begin executing. All Java applications begin
execution by calling main( ). Java is case-sensitive. Thus, Main is different from main. It is
important to understand that the Java compiler will compile classes that do not contain a main( )
method. However,the Java interpreter would report an error because it would be unable to find
the main( ) method.

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.

Que. Explain the meaning of ‘ System.out.println(“Hello !!! Prof. Viral Patel”) ‘.


Ans. System is a predefined class that provides access to the system, and out is the output
stream that is connected to the console. println( ) displays the string like “Hello !!! Prof. Viral
Patel” in new line which is passed to it. println( ) can be used to display other types of
information, too.

Que. Explain different types of data in java.


Ans. Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float,
double, and boolean. These can be put in four groups:
■ Integers This group includes byte, short, int, and long, which are for wholevalued
signed numbers.
byte => 8 bits
short => 16 bits
int => 32 bits
long => 64 bits
■ Floating-point numbers This group includes float and double, which represent
numbers with fractional precision.
Float => 32 bits
Double => 64 bits
■ Characters This group includes char, which represents symbols in a character
set, like letters and numbers.
Char => 16 bits
Java uses Unicode to represent characters. Unicode defines a fully international character set
that can represent all of the characters found in all human languages. It is a unification of dozens
of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many
more. For this purpose, it requires 16 bits. Thus, in Java char is a 16-bit type.

S. V. Patel College of CS & BM, Surat Page |6


SY BCA - SEM 4 – JAVA Asst. Prof. Viral S. Patel

■ Boolean This group includes boolean, which is a special type for representing true/false
values.

Que. Explain Type Conversion (Prof. Viral S. Patel)


Ans. Java can perform type conversion automatically or perform explicit conversion.
Automatic Conversion :
Also known as Widening conversion.
It will take place if the following two conditions are met:
1. Two types are compatible
2. Destination type is larger than the source type
Example : int to float, int to long

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

Example : int to byte


Example of int to byte explicit conversion:
int a;
byte b;
b = (byte) a; // explicitly casting int to byte as byte is smaller than int data type.
Range of a byte reduced modulo means The remainder of an integer division by the byte’s range
256. If a=257 then b will be 1 as 257%256=1.

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.

Example Type Promotion Rules :


double result = (f * b) + (i / c) - (d * s);

S. V. Patel College of CS & BM, Surat Page |7


SY BCA - SEM 4 – JAVA Asst. Prof. Viral S. Patel

f is float variable, b is byte variable, i is int variable, c is char variable, d is double and s is sort
variable.

first result of the sub expression f * b is of type float.


Second result of the sub expression i / c is of type int.
Third result of the sub expression d * s is of type double.
The outcome of float plus an int is a float.
Then the resultant float minus the last double is to double, which is the type for the final result of
the expression.

Problem : Some time give compile time error.


For example :
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!

Solution : Explicit Cast.


For example,
byte b = 50;
b = (byte)(b * 2);

Que. Explain Wrapper class in java. (Asst. Prof. Viral S. Patel)


Ans. Java provides classes that correspond to each of the simple types. In essence, these classes
encapsulate, or wrap, the simple types within a class. Thus, they are commonly referred to as
wrapper classes.
Wrapper class in java provides the mechanism to convert primitive into object and object into
primitive. Autoboxing and unboxing feature facilitates the process of generates a code implicitly
to convert primitive type to the corresponding wrapper class type and vice-versa.
One of the eight classes of java.lang package are known as wrapper class in java.

The list of eight wrapper classes are given below:

Primitive Type Wrapper class


Boolean Boolean
Char Character
Byte Byte
Short Short
Int Integer
Long Long
Float Float
Double Double

Wrapper class Example: Primitive to Wrapper


public class WrapperExample1{

S. V. Patel College of CS & BM, Surat Page |8


SY BCA - SEM 4 – JAVA Asst. Prof. Viral S. Patel

public static void main(String args[]){


//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a); //converting int into Integer
Integer j=a; //autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}}

Output:
20 20 20

Wrapper class Example: Wrapper to Primitive


public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue(); //converting Integer to int
int j=a; //unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}}

Output:
333

Que. What is boxing conversion and Unboxing conversion ?


Ans. Basic data type to corresponding wrapper class type conversion is called Boxing
conversion.
 From type boolean to type Boolean
 From type byte to type Byte
 From type short to type Short
 From type char to type Character
 From type int to type Integer
 From type long to type Long
 From type float to type Float
 From type double to type Double
Example :
int a=20;
Integer i=Integer.valueOf(a); //converting int into Integer
Integer j=a; //autoboxing, now compiler will write Integer.valueOf(a) internally

 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

S. V. Patel College of CS & BM, Surat Page |9


SY BCA - SEM 4 – JAVA Asst. Prof. Viral S. Patel

 From type Integer to type int


 From type Long to type long
 From type Float to type float
 From type Double to type double
Example :
Integer a=new Integer(3);
int i=a.intValue(); //converting Integer to int
int j=a; //unboxing, now compiler will write a.intValue() internally

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.");
}
}

output: 0 1 2 3 4 Loop complete.


Using break in nested loops : When used inside a set of nested loops, the break statement will
only break out of the innermost loop.
Example:

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.");

S. V. Patel College of CS & BM, Surat P a g e | 10


SY BCA - SEM 4 – JAVA Asst. Prof. Viral S. Patel

}
}

Output: 0 1 0 0 1 1 0 1 2 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.");
}
}

Output: 0 1 Loops complete.

Using continue in single loop:


The Java continue statement is used to continue current flow of the program and skips the
remaining code at specified condition.
Example :

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.");
}
}

output: 0 1 3 4 Loop complete.

S. V. Patel College of CS & BM, Surat P a g e | 11


SY BCA - SEM 4 – JAVA Asst. Prof. Viral S. Patel

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.print(“This statement does not exit.“);


}

System.out.println("Loops complete.");
}
}

Output: 0 1 0 1 0 1 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

Que. Which keyword equivalent to go to statement in java.


Ans. We can use label continue or label break statements for equivalent to go to statement in
java. (Asst. Prof. Viral S. Patel)

S. V. Patel College of CS & BM, Surat P a g e | 12


SY BCA - SEM 4 – JAVA Asst. Prof. Viral S. Patel

Que. Difference between >> and >>>.


Ans. The >> is signed right shift operator. The right shift operator >> shifts all of the bits in a
value to the right a specified number of times. Rightmost bit is lost when this shift occur.
leftmost position after ">>" depends on sign extension. If the number is negative, then 1 is used
as a filler and if the number is positive, then 0 is used as a filler.

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

Que. What will be the output of following statements ?


System.out.println("ans:"+2+2);
System.out.println("ans:"+(2+2));
System.out.println(2+2);
Ans.
ans: 22
ans: 4
4

Que. What is the difference between & and &&.


Ans.
& &&
1 It is Binary AND operator. It is Boolean AND operator. Also called as short
circuit logical operator.
2 In the case of & operator we must If we use the && operator, java will not bother
have to evaluate the both side to evaluate the right-hand expression.
expression first.
3 For example, For example,
if (c==1 & e++ < 100) d = 100; if (denom != 0 && num / denom > 10)

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.

S. V. Patel College of CS & BM, Surat P a g e | 13


SY BCA - SEM 4 – JAVA Asst. Prof. Viral S. Patel

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.

General form of class :


class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;

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

S. V. Patel College of CS & BM, Surat P a g e | 14


SY BCA - SEM 4 – JAVA Asst. Prof. Viral S. Patel

Box mybox1 = new Box(); // declare reference and allocate memory simultaneously

Box mybox2 = new Box(2,3,4); // declare, allocate and initialize simultaneously.


mybox2.display( ); // calling method of class using object
}
}

Que. Explain this keyword. (3 to 4)


Ans. Sometimes a method will need to refer to the object that invoked it. To allow this, Java
defines the this keyword. this can be used inside any method to refer to the current object.

// A redundant use of this.


Box(double w, double h, double d) //constructor Box ob1 = new Box(2,3,4);
{ // this refer to object ob1 here
this.width = w;
this.height = h; Box ob2 = new Box(5,6,7);
this.depth = d; //this refer to object ob2 here
}
void display( ) // method ob1.display();
{ // this refer to object ob1 here.
System.out.println(this.width+” “+this.height+” “+this.depth);
}

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;
}

Que. What is Garbage Collection ? (2 or 3)


Ans. Since objects are dynamically allocated by using the new operator, such objects must be
destroyed and their memory released for later reallocation.

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

S. V. Patel College of CS & BM, Surat P a g e | 15


SY BCA - SEM 4 – JAVA Asst. Prof. Viral S. Patel

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.

Methods declared as static have several restrictions :


 They can only call other static methods.
 They must only access static data.
 They cannot refer to this or super in any way.

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

In calling sequence of static variables, static methods and blocks :


1. Fist static variables statements execute
2. Then static block is execute
3. Then static main method is execute

S. V. Patel College of CS & BM, Surat P a g e | 16


SY BCA - SEM 4 – JAVA Asst. Prof. Viral S. Patel

4. Then other static methods are execute.

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

S. V. Patel College of CS & BM, Surat P a g e | 17


SY BCA - SEM 4 – JAVA Asst. Prof. Viral S. Patel

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
} }
}

class C extends A Output :


{ SUB B // by overriding method
void show() SUPER A // solved by super key word
{
SUB C
super.show(); // this calls A's show()
System.out.println("SUB C”); SUPER A // by using run time polymorphism
} SUB B // by using run time polymorphism
}

Que. Explain dynamic method dispatch with example.


Or
Explain run-time polymorphism.
Ans. Overridden methods in Java are similar to virtual functions in C++ language.
Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time.
Dynamic method dispatch is important because this is how Java implements run-time
polymorphism. (Asst. Prof. Viral S. Patel)
 A superclass reference variable can refer to a subclass object. Java uses this fact to resolve
calls to overridden methods at run time.

S. V. Patel College of CS & BM, Surat P a g e | 18


SY BCA - SEM 4 – JAVA Asst. Prof. Viral S. Patel

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.

Que. What is Native code ? What is Native Method in Java?


Ans.
Native code is known as machine code to run with a particular processor and its set of
instructions.

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)

S. V. Patel College of CS & BM, Surat P a g e | 19

You might also like