Java does not stand for anything. Java is a programming language created by James Gosling and now developed by Sun Microsystems. The name was chosen at random. It may have something to do with staying awake late a night?
A source program is the program written in which language?
It is programming that is licensed in such a way that it provides the source code for everyone to view and suggest changes to, and is usually at no cost or a very lost cost to anyone that wants the program and its source code.
What is the Diff between Access Specifiers and Access Modifiers?
An Access Modifier is a key word in java that determines what level of access or visibility a particular java variable/method or class has. There are 4 basic access modifiers in java. They are:
1. Public
2. Protected
3. Default and
4. Private
Private is the most restrictive access modifier whereas public is the least restrictive. Default is the access protection you get when you do not specifically mention an access modifier to be used for a java object.
Difference between reference variable and instance variable?
An object is the actual storage space in memory in which some collection of data resides.
A reference variable is a variable which refers to the memory location of an object.
Look at the pseudocode below:
Object obj = new Object();
Here obj is the reference variable, and the data to which it refers is the object.
How overcome problem of NullPointerException?
A NullPointerException is thrown when you attempt to access an object reference which is null.
Example:
String str = null;
str.equals("x"); // <- NullPointerException
To fix it, you must read the error message and find out what object is null. Determining how to ensure that this object is not set to null in the future must be made on a case-by-case basis.
Yes, you can uninstall the Java Runtime Environment from Microsoft Windows.
If you are a user with sufficient privileges, you can use the "Add/Remove Programs" control panel to find and remove the "Sun Java" entry.
This will not harm your computer.
How are an objects instance variables initialized of a class has only a default constructor?
You have to explicitly initialise all instance variables, otherwise their values will be initialised to whatever happens to be in memory at the time they are instantiated.
Consider the following class which has no explicit initialisation:
#include <iostream>
class object
{
public:
object(){}
public:
const int getData( void ) const { return( m_data ); }
private:
int m_data;
};
int main()
{
object O;
printf( "O.m_data = %d\n", O.getData() );
return( 0 );
}
Example output:
O.m_data = -858993460
This is not particularly useful; we must ensure m_data is initialised before we access its value.
One way to initialise object::m_data is from within the body of the constructor:
object(){ m_data = 0; } // inefficient initialisation
However this is quite inefficient because object::m_data will have already be instantiated by the time we got to the constructor body. This is akin to the following C-style initialisation:
int x; // instantiate x
x = 0; // initialise x
When what we really want to do is:
int x = 0;
Or use the more formal construction semantics:
int x(0);
Both achieve the same thing. They both initialise the variable x at the point of instantiation, not after instantiation. Fortunately, C++ allows us to initialise all instance variables at the point of instantiation, via the constructor's initialisation section:
object():m_data(0){} // efficient initialisation
While initialising a single primitive data type in the constructor body isn't going to cause major problems in terms of efficiency, with more complex data types the inefficiencies can very quickly add up. Thus it is important to use the initialisation section as much as possible and to only use the body of the constructor when there is no option.
The initialisation section is particularly important when dealing with derived classes. Consider the following:
#include <iostream>
class base
{
public:
base():m_int(0){}
base(const base& object):m_int(object.m_int){}
public:
const int getInt( void ) const { return( m_int ); }
void setInt( const int data ) { m_int = data; }
private:
int m_int;
};
class derived : public base
{
public:
derived():m_float(0.0){}
derived(const derived& object):m_float(object.m_float){}
public:
const float getFloat( void ) const { return( m_float ); }
void setFloat( const float data ) { m_float = data; }
private:
float m_float;
};
int main()
{
derived d;
d.setInt( 1 );
d.setFloat( 2.0 );
printf( "d.getInt() = %d, d.getFloat() = %f\n", d.getInt(), d.getFloat() );
derived c(d); // call copy constructor.
printf( "c.getInt() = %d, c.getFloat() = %f\n", c.getInt(), c.getFloat() );
return( 0 );
}
Example output:
d.getInt() = 1, d.getFloat() = 2.000000
c.getInt() = 0, c.getFloat() = 2.000000
Note that c should be an exact copy of d, but there's clearly a difference in the integer variables inherited from the base class. This is because the derived class copy constructor called the base class default constructor, not the base class copy constructor as you might have expected. To resolve this we must explicitly call the base class copy constructor and the only way to do so is via the initialisation section of the derived class:
derived(const derived& object):base(object),m_float(object.m_float){}
Note that the derived class' copy constructor now includes a call to base(object) in the initialisation section. This ensures the base class copy constructor is called. Although object is actually an instance of derived, because it derived from base it is also a kind of base, thus the call is legitimate. Now if we run the code we'll get the expected result:
d.getInt() = 1, d.getFloat() = 2.000000
c.getInt() = 1, c.getFloat() = 2.000000
As your classes become more and more complex you will inevitably find yourself creating overloaded constructors to provide a wide variety of initialisation methods. But keep in mind that it costs absolutely nothing to use the initialisation sections even if several constructors end up using the exact same initialisations. And while it is tempting to move all of the common initialisation code into a private method of the class and have each constructor call that method (known as a construction helper function), this simply adds yet more inefficiency by introducing yet another unnecessary function call. Helper functions such as these are undoubtedly useful during the initial development of a class but as soon as the class is finalised, get rid of the helper function and move all that functionality into the initialisation sections where they belong. In the case of derived classes, base class constructors will be called whether you like it or not, so it makes sense to call the most appropriate base class constructor from within the initialisation section of each of your derived class constructors. Remember that if you do not specify a base class constructor, its default constructor will be called implicitly, which may or may not be the most appropriate constructor in all cases (not least in the case of the copy constructor).
Fibonacci series with do while in java?
#include
#include
void main()
{
int a=0,b=1,c,i=2,n;
clrscr();
printf("enter no");
scanf("%d",&n);
if(n==0)
printf("%d\n",a);
else
printf("%d\n %d\n",a,b);
while(i<=n) {
c=a+b;
printf("%d",c);
a=b;
b=c;
i++;
}
getch();
}
What is object in programming?
Object in context of a class is the root of the class hierarchy in Java in the java.lang package.
Every class has Object as a superclass whether it's explicit or not. All objects, including arrays, implement the methods of this class.
Explain what is meant by object-oriented concept of abstraction?
Data abstraction is the means by which we lift the level of abstraction away from the machine (low-level) and closer to the application domain (high-level). As far as the machine is concerned, all data is binary, however the exact same binary representation can mean entirely different things within different contexts. Abstraction allows us to separate these contexts and thus give much greater meaning to the underlying representation.
Java code to find the sum in all integer?
The following will sum all integers from 1-100. Adjust according to your needs.
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
System.out.println("The sum is " + sum);
The following will sum all integers from 1-100. Adjust according to your needs.
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
System.out.println("The sum is " + sum);
The following will sum all integers from 1-100. Adjust according to your needs.
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
System.out.println("The sum is " + sum);
The following will sum all integers from 1-100. Adjust according to your needs.
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
System.out.println("The sum is " + sum);
When to use a constructor in java?
Private constructors generally have one of two uses.
The first is for implementing the singleton design pattern, in which you only ever want one instance of the class in existence. So you don't want new instances of the class being generated over and over. You do something like:
class Singleton {
// All classes can access this instance of the class and no other.
public static instance = new Singleton();
private Singleton() {
}
}
The second is for limiting the creation of classes which contain only static methods or constants.
Of course, private constructors are useful any time you want to limit the way other classes/packages/programmers interact with your class.
Why method inner classes can only access final variables from method?
I think the main reason is because the inner class may "outlive" the method in which it was created. If this happens, then the memory storing those variables would be lost and we would run into problems when trying to access them. If the variables are defined as final, then Java knows that those values will never change and it can move/copy them when the class is created.
Write a program to calculate the sum of n numbers using array?
int myArray[N]; //where N is a constant
int mySum = 0;
...
for (int arrayIndex1 = 0; arrayIndex1 < N; arrayIndex1++)
{
cin >> myArray[arrayIndex1];
}
...
for (int int arrayIndex2 = 0; arrayIndex2 < N; arrayIndex2++)
{
mySum +=myArray[arrayIndex2];
}
...
You mean source-file? The simplest format is one single main function:
int main (void)
{ puts ("Hello, World"); return 0; }
Example of procedural programming language and object oriented programming language?
example of procedural programming are those programming language that have structure e.g basic,fortran,c++,c and pascal e.t.c
Disadvantages of multiple inheritance?
If a single class inherits from two other classes, each of which has the same function implemented, how can we tell which one to call? This ambiguity often leads to non-deterministic behavior of classes in multiple inheritance languages.
How does one set a timer in Java?
To create a timer you might try the java.util.Timer class.
Check out the following methods:
void schedule(TimerTask task, long delay, long period)
Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay.
void scheduleAtFixedRate(TimerTask task, long delay, long period)
Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.
If you just want a one-time event you can still use a Timer instance and schedule a single TimerTask or just create a new Thread with anonymous Runnable class that sleeps for 3 minutes before doing something.
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(TimeUnit.MINUTES.toMillis(3));
// do stuff here
} catch (InterruptedException e) {
// handle interruption
}
}
}).start();
WHAT IS A CONSTRUCTOR
"It is a special type of method same name as class name that determines how an object is initialized when it's created".
what is constructor in java
Like other methods, we can also define constructor Method in our java program but unlike other methods, we cannot call a constructor directly; Java called constructor automatically when an object has created. When we use new keyword to create an object of a class, java does three thing;
Allocates memory for the object.
Initialize that object instance variable, with their initial value or to a default.
Call the constructor Method of the class.
If a class doesn't have defined any constructor method, we will still create an object of that class but we have to set instance variable or call other methods that object needs to initialize itself to that object afterward.
By defining constructor method in our own classes, we can set initial values of instance variable, call method based on those variable or call methods on other objects, or calculate initial properties of our object. We can also overload constructor, as we would regular methods, to create an object that has specific properties based on the argument we give to new.
BASIC CONSTRUCTOR
by defining a constructor looks like a regular method, with 2 basic difference.
Constructor and class name are always same.
It doesn't have any return type
For example, in the below table a simple class person, with a constructor that initializes it's instance variable based on the argument to new. The class also includes a method for the object to introduce itself, and a main() method to test each of these class.
class Person
{
String name;
int age;
Person (String n, int a)
{
name = n;
age = a;
}
void printPerson ()
{
System.out.print("Hi, I am " +name);
System.out.println(" I am "+ age + " years old.");
}
public static void main(String args[])
{
Person p;
p = new Person ("Ajab", 20);
p.printPerson();
p = new Person ("Rizwan", 30);
p.printPerson();
The output of the program is given below:
Hi, I am Ajab. I am 20 years old.
Hi, I am Rizwan. I am 30 years old
CONSTRUCTOR OVERLOADING
like other methods, constructor can also take different number and types of parameters, enabling us to create our objects with exactly the properties you want it to have, or for it to be able to calculate properties from different kinds of input.
constructor overloading in Java
For example, the MyRectone class in the given table creates a MyRectone Constructor and passing different parameter instead of creating different methods for the given arguments.
class MyRectone
{
int x1 = 0;
int y1 = 0;
int x2 = 0;
int y2 = 0;
MyRectone ( int x1, int x2, int x2, int y2)
{
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
MyRectone (Point topLeft, Point bottomRight)
{
x1 = topLeft.x;
y1 = topLeft.y;
x2 = bottomRight.x;
y2 = bottomRight.y;
}
MyRectone ( Point topLeft, int w, int h)
{
x1 = topLeft.x;
y1 = top left.y;
x2 = ( x1 + w);
y2 = (y1 + h);
}
void printRect ()
{
System.out.print ("MyRectone: ");
}
public static void main (String args [] )
{
MyRectone rect;
System.out.println ("Calling MyRectone with coordinates 35,35 70,70");
rect = new MyRectone (35,35,70,70);
rect.printRect();
System.out.println ("Calling MyRectone with coordinates (15,15) (30,30)");
rect = new MyRectone (15,15,30,30);
rect.printRect();
System.out.print (" Calling buildRect w/1 point (10,10),");
System.out.println ("width (50) and height (50)");
rect = new MyRectone ( new Point (10,10), 50, 50);
rect.printRect();
Output
Calling MyRectone with coordinates 35,35 70,70:
MyRectone:
Calling buildRect w/1 points (15,15), (30,30):
MyRectone:
Calling buildRect w/1 point (10,10), width (50) and height (50):
MyRectone:
CALLING ANOTHER CONSTRUCTOR
Some constructor may be a superset of another constructor defined in your class; that is, they might have the same behavior plus a little bit more. Rather than duplicating identical behavior in multiple constructor Methods in our class, it makes sense to be able to just call that first constructor from inside the body of the second constructor. Java provides a special syntax for doing this. To call a constructor defined on the current class, use this form:
this (arg1, arg2, arg3 …..);
The arguments to this are, of course, the arguments to the constructor.
What is meant by instancing a class?
The class can be considered a template to create objects. When you create an object, you create it on the basis of the specified class - the object is an instance of the class, and the act of creating the object is also known as "instantiating" the class.
Write a program in java to find gcf of two numbers?
There are two basic steps to finding the greatest number. 1) convert the input from Strings to ints (or doubles or whatever number type you are expecting), 2) find the greatest number.
/*
For this example we're going to answer the question exactly,
with no regard to expandability (for dealing with more numbers).
*/
public static void main(String[] args) {
// step 1 - convert input from Strings to ints
int a = 0, b = 0, c = 0;
// we need to wrap a try-catch block around this to
// deal with any input that cannot be converted from
// a String to an int
try {
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
c = Integer.parseInt(args[2]);
}catch(NumberFormatException ex) {
// do whatever you need to do here to manage the
// exception
}
// step 2 - find the greatest number
int max = a;
if(b > max) {
max = b;
}
if(c > max) {
max = c;
}
// at this point the value in max is the greatest of the three
// numbers passed in through the command line
}
OR ELSE YOU SHOULD TRY THE ANOTHER STYLE FOR COMMAND LINE ARGUMENT , AS IT IS GIVEN BELOW.
class Max_command
{
public static void main(String args[])
{
for(String name : args)
{
System.out.println(name);
}
int i,max=0;
for(i=0;i<=args.length;i++)
{
int a=Integer.parseInt(args[i]);
if(a>max)
{
max=a;
}
if(i==args.length-1)
{
System.out.println("Max is --> "+max);
}
}
}
}
Why the concept of inheritance was introduced in OOP?
In object-oriented programming, inheritance allows the creation of is-a relationships. For example, a car is a vehicle, and a bike is a vehicle, so those could be modeled through a vehicle class, and a pair of car and bike classes, both derived from (inheriting from) the vehicle class. Derived classes like car and bike share common vehicle properties, such as speed, location, direction, number of wheels, etc.
Why you use constructor chaining?
Constructor Chaining
We know that constructors are invoked at runtime when you say new on some class type as follows:
Lamborghini h = new Lamborghini();
But what really happens when you say new Lamborghini() ? (Assume Lamborghini extends Car and Car extends Object.)
1. Lamborghini constructor is invoked. Every constructor invokes the constructor of its superclass with an (implicit) call to super(),
2. Car constructor is invoked (Car is the superclass of Lamborghini).
3. Object constructor is invoked (Object is the ultimate superclass of all classes, so class Car extends Object even though you don't actually type "extends Object" into the Car class declaration. It's implicit.) At this point we're on the top of the hierarchy.
4. Object instance variables are given their explicit values. By explicit values, we mean values that are assigned at the time the variables are declared, like "int x = 27", where "27" is the explicit value (as opposed to the default value) of the instance variable.
5. Object constructor completes.
6. Car instance variables are given their explicit values (if any).
7. Car constructor completes.
8. Lamborghini instance variables are given their explicit values (if any).
9. Lamborghini constructor completes.