answersLogoWhite

0

📱

Java Programming

The Java programming language was released in 1995 as a core component of the Java platform of Sun Microsystems. It is a general-purpose, class-based, object-oriented language that is widely used in application software and web applications.

5,203 Questions

What is the syntax in creating an object?

class_name object_name=new class_name();

eg: A a=new A();

How can the base class data be accessed from database directly using derived class?

In order to access a base class member the base class member must be declared protected or public. Private data is only accessible to members of the same class and to friends of the class. I'm not entirely sure what you mean by accessing from a database. A derived class does not require a database in order to access its base class members, it only requires protected access at the very least. Note that although you can declare derived classes to be friends of their base classes and thus allow private access, it would be an unusual design since base classes should never know anything about any of their derivatives.

Java program Create two threads such that one of the thread print even numbers and another prints odd numbers up to a given range?

public class BasicThreads {

public static void main(String[] args) {

Thread odd = new Thread (new NumberPrinter());

Thread even = new Thread(new NumberPrinter());

odd.start();

even.start();

}

}

class NumberPrinter implements Runnable {

private static boolean printEven;

@Override

public void run() {

int start = printEven ? 2 : 1;

String type = printEven ? "Even Printer " : "Odd Printer ";

printEven = !printEven;

for ( ; start < 20 ; start += 2) {

System.out.println(type + start);

try {

Thread.sleep(100);

}

catch (Exception ex){

}

}

}

}

Is run time initialization of an array an initialization or an assignment?

It is an initialisation. You cannot assign values to a dynamic array until it has been initialised. Static arrays can be initialised at compile time. They can also be assigned at compile time.

void main()

{

// Compile time:

// =========

// Initialise a static array.

int arr1[10];

// Initialise and assign a static array.

int arr2[10] = {0,1,2,3,4,5,6,7,8,9};

// Runtime:

// ======

// Dynamic array (size unknown, no memory allocated)

int* pArr[];

// Initialise (size known, allocate memory, 40 bytes):

pArr = ( int* ) malloc( 10 * sizeof( int ));

// Assign (set values of elements):

int x;

for(x=0;x<10;++x)

pArr[x] = x;

// Uninitialise (release memory).

free( pArr );

return( 0 );

}

Write a program to print a right angle triangle containing digit in java?

let s1,s2,s3 be three sides of a triangle.

import java.lang.*;

import java.io.*;

import java.util.*;

class Triangle

{

public static void main(String args[])

{

boolean test=false;

int s1,s2,s3;

Scanner input = new Scanner(System.in);

System.out.println("enter the side1 of triangle");

s1=input.nextInt();

System.out.println("enter the side2 of triangle");

s2=input.nextInt();

System.out.println("enter the side3 of triangle");

s3=input.nextInt();

if((s1*s1)==(s2*s2)+(s3*s3))

{

test=true;

}

else if((s2*s2)==(s1*s1)+(s3*s3))

{

test=true;

}

else if((s3*s3)==(s1*s1)+(s2*s2))

{

test=true;

}

if(test==true)

System.out.println("Entered sides form a right angle triangle.....");

else

System.out.println("Entered sides dosn't form a right angle triangle.....");

}

}

What is an exception With an example program explain how it is handled?

An exception is literally that: an exception. Exceptions are thrown when something that shouldn't happen does. For example, if you're trying to turn "Hi" into an Integer, you'll get a NumberFormatException (in Java.) If there is nothing in place to handle an exception, the program will crash. Try-catch blocks are used for exception handling within methods, and exception throwing is used to give out exceptions, or let a different method handle it.

Example program (Java):

class ex{

public static void main(String[] args){

String Strx = "5a";

int x = 0;

try{

x += Integer.parseInt(Strx);

}catch(NumberFormatException e){ // If Strx is not an Integer

x += Integer.parseInt("5");

}

System.out.println("The value of x is " + x); // The value of x is 5

}

}

Alternatively, you could remove the try-catch blocks, and simply write "public static void main(String[] args) throws NumberFormatException" in the 2nd line of the program.

What is non-instantiable class?

A non-instantiable class is the class whose object can be created but cannot be initialized.

for example the interfaces and the abstract classes in java.

Write a Program for Array implementation of queue and stack using exception handling.?

include <iostream>

using namespace std;

#define SIZE 10

template <class StackType> class stack {

StackType stck[SIZE];

int topOfStack;

public:

void init() {

topOfStack = 0;

}

void push(StackType ch);

StackType pop();

};

template <class StackType>

void stack<StackType>::push(StackType ob)

{

try {

if(topOfStack==SIZE) throw SIZE;

} catch(int) {

cout << "Stack is full.\n";

return;

}

stck[topOfStack] = ob;

topOfStack++;

}

template <class StackType>

StackType stack<StackType>::pop()

{

try {

if( topOfStack == 0)

throw 0;

} catch(int) {

cout << "Stack is empty.\n";

return 0;

}

topOfStack--;

return stck[topOfStack];

}

int main()

{

stack<char> stack1, stack2;

int i;

stack1.init();

stack2.init();

stack1.push('a');

stack2.push('x');

stack1.push('b');

stack2.push('y');

stack1.push('c');

stack2.push('z');

for(i = 0; i <3; i++)

cout << "Pop stack1: " << stack1.pop() << endl;

for(i = 0; i <4; i++)

cout << "Pop stack2: " << stack2.pop() << endl;

// demonstrate double stacks

stack<double> doubleValueStack1, doubleValueStack2; // create two stacks

// initialize the stacks

doubleValueStack1.init();

doubleValueStack2.init();

doubleValueStack1.push(1.1);

doubleValueStack2.push(2.2);

doubleValueStack1.push(3.3);

doubleValueStack2.push(4.4);

doubleValueStack1.push(5.5);

doubleValueStack2.push(6.6);

for(i = 0; i <3; i++)

cout << "Pop doubleValueStack1: " << doubleValueStack1.pop() << endl;

for(i = 0; i <4; i++)

cout << "Pop doubleValueStack2: " << doubleValueStack2.pop() << endl;

return 0;

}

Why is encapsulation needed?

Imagine that we both work for the same project and first you wrote the code for a class, and then I used your class in my program. Later on, you didn't like the way the class behaved, because some of its instance variables were being set (by me from my code) to values you hadn't anticipated. Their code brought out errors in your code. (Relax, I wont do that, dont worry.) Since, it is a Java program, so you should be able just to ship out a newer version of the class, which I could replace in my programs without changing any of my own code.

The above scenario highlights two of the promises or rather i should say benefits of Object Orientation (OO): flexibility and maintainability. But these benefits will not come automatically. You have to do something. You have to write your classes and code in a way that supports flexibility and maintainability. Just because Java supports OO concepts, it cannot write code for you. Can it?? For example, imagine if you made your class with public instance variables, and those other programmers were setting the instance variables directly, as the following code demonstrates:

public class BadExample {

public int size;

public int weight;

...

}

public class AnotherBadExample {

public static void main (String [] args) {

BadExample b = new BadExample ();

b.size = -5; // Legal but bad!!

}

}

Now go back the scenario we spoke about a paragraph ago. BadExample is your class and AnotherBadExample is my code. I have modified one of your variables in a way that it helps my code logic but that totally alters the way your class works. Now you are in trouble. How are you going to change your class in such a way that no one can alter your values directly (like what i have done in my code)? Your only choice is to write a method say setSize(int newVal) inside your class and then change the access modifier of the variable size to say, private. This will ensure that you handle instances when someone is trying to set a value to the size variable that you dont want and at the same time ensure that no one can access the size variable directly and mess with your code.

But, unfortunately, by doing that, you have broken my code. If I try to compile my AnotherBadExample class, i will get errors because the size variable is no longer visible for me.

How can we address this situation now? The best way is: not write such code where public variables are available for anyone and everyone to modify.

The ability to make changes in your code without breaking the code of all others who use your code is a key benefit of encapsulation. You should always hide implementation details. To elaborate, you must always have your variables as private and then have a set of public methods that others can use to access your variables. Since the methods are public anyone can access them, but since they are in your class you can ensure that the code works the way that is best for you. So in a situation that you want to alter your code, all you have to do is modify your methods. No one gets hurt because i am just using your method names in my code and the code inside your method doesnt bother me much.

If you want maintainability, flexibility, and extensibility (and I guess, you do), your design must include encapsulation. How do you do that?

Why do you declare a string as char asterisk?

Declaring strings as char* is generally faster than declaring an array of type char.

Consider the following:

#include<stdio.h>

int main (void) {

char c1[12] = "Hello world";

char c2[] = "Hello world";

char* c3 = "Hello world";

// ...

return 0;

}

The string literal, "Hello world" is duplicated three times in the source code but in the resultant machine code that string only appears once (in the data segment). This is known as string-pooling; it makes no sense to maintain separate copies of the exact same value in the data segment.

Given that there is only one copy of the string, it would be natural to assume that c1, c2 and c3 all refer to the same memory location but they don't. In fact, the only one that does refer to the data segment copy is the third one.

If we examine the assembly for the c1 initialisation we find the following:

mov eax, DWORD PTR ??_C@_0M@KIBDPGDE@Hello?5world?$AA@

mov DWORD PTR _c1$[ebp], eax

mov ecx, DWORD PTR ??_C@_0M@KIBDPGDE@Hello?5world?$AA@+4

mov DWORD PTR _c1$[ebp+4], ecx

mov edx, DWORD PTR ??_C@_0M@KIBDPGDE@Hello?5world?$AA@+8

mov DWORD PTR _c1$[ebp+8], edx

The symbol ??_C@_0M@KIBDPGDE@Hello?5world?$AA@ identifies the string in the data segment but the assembly clearly shows data is being copied (moved) to a new location 32-bits (4 bytes) at a time. The new location is the address of c1. The same thing happens for c2, making yet another copy of the string.

However the c3 initialisation consists of just one instruction.

mov DWORD PTR _c3$[ebp], OFFSET ??_C@_0M@KIBDPGDE@Hello?5world?$AA@

The difference is that instead of copying the string to new memory, we simply copy the address of the string.

This is low-level stuff of course, but it makes no sense to copy objects from the data segment or indeed anywhere else when we can simply refer to them directly using a pointer. We only need to copy objects when we actually intend to make some change to the object without affecting the original object. In all other cases we can simply refer to them.

Does it matter in what order catch statements for FileNotFoundException and IOException are written?

Yes, it does. The child exceptions classes must always be caught first and the "Exception" class should be caught last

How do you serialize an object to a file?

Imagine you want to save the state of one or more objects. If Java didn't have serialization, you'd have to use one of the I/O classes to write out the state of the instance variables of all the objects you want to save. The worst part would be trying to reconstruct new objects that were virtually identical to the objects you were trying to save. You'd need your own protocol for the way in which you wrote and restored the state of each object, or you could end up setting variables with the wrong values. For example, imagine you stored an object that has instance variables for height and weight. At the time you save the state of the object, you could write out the height and weight as two ints in a file, but the order in which you write them is crucial. It would be all too easy to re-create the object but mix up the height and weight values-using the saved height as the value for the new object's weight and vice versa.

The purpose of Serialization is to help us achieve whatever complicated scenario we just witnessed in an easier manner.

Serializing Objects

What does it really mean to save an object? If the instance variables are all primitive types, it's pretty straightforward. But what if the instance variables are themselves references to objects? What gets saved? Clearly in Java it wouldn't make any sense to save the actual value of a reference variable, because the value of a Java reference has meaning only within the context of a single instance of a JVM. In other words, if you tried to restore the object in another instance of the JVM, even running on the same computer on which the object was originally serialized, the reference would be useless.

But what about the object that the reference refers to? Look at this class:

class Car {

private Engine theEngine;

private int CarSize;

public Car(Engine Engine, int size) {

theEngine = Engine;

CarSize = size;

}

public Engine getEngine() { return theEngine; }

}

class Engine {

private int EngineSize;

public Engine(int size) { EngineSize = size; }

public int getEngineSize() { return EngineSize; }

}

Now make a Car... First, you make a Engine for the Car:

Engine c = new Engine(3);

Then make a new Car, passing it the Engine:

Car d = new Car(c, 8);

Now what happens if you save the Car? If the goal is to save and then restore a Car, and the restored Car is an exact duplicate of the Car that was saved, then the Car needs a Engine that is an exact duplicate of the Car's Engine at the time the Car was saved. That means both the Car and the Engine should be saved.

And what if the Engine itself had references to other objects-like perhaps a Color object? This gets quite complicated very quickly. If it were up to the programmer to know the internal structure of each object the Car referred to, so that the programmer could be sure to save all the state of all those objects. That would be a nightmare with even the simplest of objects.

Fortunately, the Java serialization mechanism takes care of all of this. When you serialize an object, Java serialization takes care of saving that object's entire "object graph." That means a deep copy of everything the saved object needs to be restored. For example, if you serialize a Car object, the Engine will be serialized automatically. And if the Engine class contained a reference to another object, THAT object would also be serialized, and so on. And the only object you have to worry about saving and restoring is the Car. The other objects required to fully reconstruct that Car are saved (and restored) automatically through serialization.

Remember, you do have to make a conscious choice to create objects that are serializable, by implementing the Serializable interface. If we want to save Car objects, for example, we'll have to modify the Car class as follows:

class Car implements Serializable {

// the rest of the code as before

// Serializable has no methods to implement

}

And now we can save the Car with the following code:

import java.io.*;

public class SerializeCar {

public static void main(String[] args) {

Engine c = new Engine(3);

Car d = new Car(c, 8);

try {

FileOutputStream fs = new FileOutputStream("testSer.ser");

ObjectOutputStream os = new ObjectOutputStream(fs);

os.writeObject(d);

os.close();

} Catch (Exception e) { e.printStackTrace(); }

}

}

But when we run this code we get a runtime exception something like this

java.io.NotSerializableException: Engine

What did we forget? The Engine class must ALSO be Serializable. If we modify the Engine class and make it serializable, then there's no problem:

class Engine implements Serializable {

// same

}

Here's the complete code:

import java.io.*;

public class SerializeCar {

public static void main(String[] args) {

Engine c = new Engine(3);

Car d = new Car(c, 5);

System.out.println("before: Engine size is "

+ d.getEngine().getEngineSize());

try {

FileOutputStream fs = new FileOutputStream("testSer.ser");

ObjectOutputStream os = new ObjectOutputStream(fs);

os.writeObject(d);

os.close();

} Catch (Exception e) { e.printStackTrace(); }

try {

FileInputStream fis = new FileInputStream("testSer.ser");

ObjectInputStream ois = new ObjectInputStream(fis);

d = (Car) ois.readObject();

ois.close();

} Catch (Exception e) { e.printStackTrace(); }

System.out.println("after: Engine size is "

+ d.getEngine().getEngineSize());

}

}

class Car implements Serializable {

private Engine theEngine;

private int CarSize;

public Car(Engine Engine, int size) {

theEngine = Engine;

CarSize = size;

}

public Engine getEngine() { return theEngine; }

}

class Engine implements Serializable {

private int EngineSize;

public Engine(int size) { EngineSize = size; }

public int getEngineSize() { return EngineSize; }

}

This produces the output:

before: Engine size is 3

after: Engine size is 3

How do you use Necromancer class?

If that's for some game, please clarify what game you are talking about - or make sure the question gets in the correct category of questions.

What is the advantage of hibernate in j2ee?

Hibernate is capable of mapping all Object Oriented relationships (such as inheritance,interfaces, associations, composition, ternary associations) between objects. Hibernate follows both Bottom-up (existing database to OO model) and Top-down (OOModel to design the database schema) approaches: asanthine s

How can you crack a jar file?

its easy just extract if its jar or else use j2me to crack the activation using net beans ide or eclipse

What is the simularities of parameter and arguments?

Arguments are fields that are given to a method when it is called, while parameters are the name for the received variables. For example:

public static void main(String[] args){

int arg1 = 0;

boolean arg2 = false;

String arg3 = "Some string";

function_a(arg1, arg2, arg3);

// These variables are called arguments because they are being passed

// to the function.

}

public static void function_a(int par1, boolean par2, String par3){

// These variables are called parameters because they are being received

// when the function is called.

}

I hope this helps.

What is the fundamental difference between while loops and numeric for loops?

There is no such difference, for and while loops are convertible:

in: for (exp1; exp2; exp3) stmt;

out: { exp1; while (exp2) { stmt; exp3; }}

in: while (exp) stmt;

out: for (; exp; ) stmt;

How do you use Java Native Interface to access Delphi code from Java classes?

The Delphi code would need to be compiled into a DLL, and the DLL is then called from java using the JNI. See http://home.pacifier.com/~mmead/jni/delphi/JavaToDPR/ to get started.

Why constructor is used?

Objects are constructed. You can't make a new object without invoking a constructor. In fact, you can't make a new object without invoking not just the constructor of the object's actual class type, but also the constructor of each of its superclasses including the Object class itself! Constructors are the code that runs whenever you use the keyword new. The constructor typically contains he initialization code that you want to run when someone is instantiating an object of a class that you are coding.

Do void methods have parameters?

A void method is just like any other method; it may or may not have parameters.