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

Explain the statement there is more to java than the language?

All programming languages are abstract things - collections of rules which dictate how symbols may form words, how words may form statements, and how statements may form programs.

Programming languages need "other stuff" in order to actually be useful. For most languages this will include either a compiler or an interpreter which can turn source code into executable programs.

Java's "other stuff" includes a compiler, which turns Java source code into Java byte code, and the Java Virtual Machine (JVM), which allows Java byte code to execute on your computer.

What is out of scope in returning objects in java?

if u declare variable in method & tray to use this variable outside the method then it is out of scope

Why java script called as platform independent?

java also called as platform independent.because we will use java application at any operationg system and any hardware. it not contain error. so we called java as platform independent..

Write a program that sorts three integers The integers are entered from the input dialogs and stored in variables num1num2 and num3 respectively The program sorts the numbers so that num1 num2num3?

Scanner misterscan = new Scanner(System.in);

int num1, num2, num3;

int [] temp = new int[3];

for (int k = 0; k < 3; k ++)

{

System.out.print("Enter num: ");

temp[k] = misterscan.nextInt();

}

Arrays.sort(temp); //Uses merge sort, and since I am lazy I cheated.

num1 = temp[0];

num2 = temp[1];

num3 = temp[2];

How many interfaces can a class inherit and can same interface be inherited by two different classes explain?

A class can inherit as many interfaces as it needs, using multiple-inheritance. And yes, the same interface can be inherited by two different classes.

Multiple inheritance occurs when a class is derived from two or more base classes. For instance, if you have a list class and a node class, then you could easily inherit from both to produce a tree class, since a tree is both a list and a node. The tree therefore inherits the interface of both a list and node and combines them into a single entity.

Just as a square and a circle are types of shape, a circle class and a square class can both inherit from the same generic shape class. Since both the circle and the square have a common interface, collections of shapes are possible, regardless of their actual type. Taxonomy is another example of this. Cats and dogs and bats are all types of mammal, thus they can all share a common interface provided by a mammal class. By the same token, mammals, reptiles and birds can share a common interface provided by an animal class. Moreover, trees, flowers and other vegetation share a common interface with animals: the class of living things. How accurately your classes reflect reality is entirely up to you: if you wish to model a dog kennel, then a common dog class is all you need to provide the base class for all dogs.

How do you write a javascript to swap two numbers without using third one?

By using the algorithm of bitwise EORing (Exclusive ORing) the numbers together:

If the two numbers are X and Y, then to swap them:

X = X EOR Y

Y = Y EOR X

X =X EOR Y

will swap them.

With knowledge of that algorithm, one then uses the syntax of Javascript to implement it.

How do you implement RSA algorithm in java?

This is a perfectly running code.....

package javaapplication1;

import java.security.*;

import java.io.*;

import javax.crypto.Cipher;

public class NewClass {

public static void main(String args[])

{

String srci="";

try{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Please enter any string you want to encrypt");

srci=br.readLine();

}

catch(IOException ioe)

{

System.out.println(ioe.getMessage());

}

try

{

KeyPairGenerator kpg=KeyPairGenerator.getInstance("RSA");

kpg.initialize(512);//initialize key pairs to 512 bits ,you can also take 1024 or 2048 bits

KeyPair kp=kpg.genKeyPair();

PublicKey publi=kp.getPublic();

Cipher cipher = Cipher.getInstance("RSA");

cipher.init(Cipher.ENCRYPT_MODE, publi);

byte[]src=srci.getBytes();//converting source data into byte array

byte[] cipherData = cipher.doFinal(src);//use this method to finally encrypt data

String srco=new String(cipherData);//converting byte array into string

System.out.println();

System.out.println("Encrypted data is:-"+srco);

PrivateKey privatei=kp.getPrivate();//Generating private key

Cipher cipheri=Cipher.getInstance("RSA");//Intializing 2nd instance of Cipher class

cipheri.init(Cipher.DECRYPT_MODE, privatei);//Setting to decrypt_mode

byte[] cipherDat = cipheri.doFinal(cipherData);//Finally decrypting data

String decryptdata=new String(cipherDat);

System.out.println("Decrypted data:-"+decryptdata);

}

catch(Exception e)

{

System.out.println(e.getMessage());

}

}

}

Incase of errors mail me on the below given address....

fs.fabianski@gmail.com

-Fabianski Benjamin

India

Is object a member of a class?

Yes, you would need to define your variables. Also initialize them

What are Labeled loops?

Java supports labeled loops which allow you to break out of multiply nested loops by using the label on a break statement.

Here is an example:

FINDBIGGER:

for (i = 0; i < max1; i++)
{
for (j = 0; j < max2; j++)
{
if ( array[i] > array[j] )
break FINDBIGGER;
else if ( array[i] < array[j] )
break;
}
System.out.println("The break will end up here!");
}
System.out.println("The break FINDBIGGER will end up here!");


Note that technically this is not a goto - Java does not support gotos.

If a data-item is declared as a protected access specifier then it can be accessed?

A class method or attribute (data item) that is declared protected can be accessed only by methods of the same class or by methods of derived classes of the class.

When should the method invokeLater be used?

invokeLater should be used when your code is performing a GUI change in the Swing UI library, and you cannot guarantee that the change is being made in the Event Dispatching Thread (which can cause data problems, as Swing is not "thread-safe"). So, invokeLater should be used if (1) you are using Swing, and (2) you are using Thread, and (3) the thread from 2 needs to update a GUI element that is part of Swing.

Is it essential to catch all the exceptions and justify your answer?

Checked exceptions should be caught. Otherwise, compile errors are generated.

Write Client and server program in C language using UDP?

Write and run a client and a server program in C-language using UDP

Why use interfaces in Java?

an Interface is nothing but a contract as to how a class should behave. It just declares the behavior as empty methods and the implementing class actually writes the code that will determine the behavior.

When you implement an interface, you're agreeing to adhere to the contract defined in the interface. That means you're agreeing to provide legal implementations for every method defined in the interface, and that anyone who knows what the interface methods look like can rest assured that they can invoke those methods on an instance of your implementing class. (Thy need not bother much about how you have implemented it. All they bother about is whether a method of the name mentioned in the interface is available or not)

Now, you might stop me and ask, what if I implement an interface and opt not to write code for a method that I am supposed to? The answer is simple. The compiler wouldn't let you do that. You cannot successfully implement an interface without providing method implementation for all the methods declared inside the interface. This is how the java system ensures that when someone knows a certain method name in an interface and has an instance of a class that implements it, can actually call that method without fear that the method isnt implemented inside the class.

Assuming an interface, Convertible, with two methods: openHood(), and setOpenHoodFactor(), the following class will compile:

public class Ball implements Convertible { // Keyword 'implements'

public void openHood() { }

public void setOpenHoodFactor(int bf) { }

}

Ok, I know what you are thinking now. "This has got to be the worst implementation class that you have seen". Though it compiles and runs as well, it is actually doing nothing… the interface contract guarantees that the class implementing it will have a method of a particular name but it never guaranteed a good implementation. In other words, the compiler does not bother whether you have code inside your method or not. All it cares is if you have methods of the matching names as in the interface. That's all…

Implementation classes must adhere to the same rules for method implementation as a class extending an abstract class. In order to be a legal implementation class, a nonabstract implementation class must do the following:

• Provide concrete (nonabstract) implementations for all methods from the declared interface.

• Follow all the rules for legal overrides.

• Declare no checked exceptions on implementation methods other than those declared by the interface method, or subclasses of those declared by the interface method.

• Maintain the signature of the interface method, and maintain the same return type (or a subtype).

• It does not have to declare the exceptions declared in the interface method declaration

Source code for notepad in java?

import java.awt.*;

import java.awt.event.*;

import java.awt.datatransfer.*;

import java.io.*;

public class Editor extends Frame

{

String filename;

TextArea tx;

Clipboard clip = getToolkit().getSystemClipboard();

Editor()

{

setLayout(new GridLayout(1,1));

tx = new TextArea();

add(tx);

MenuBar mb = new MenuBar();

Menu F = new Menu("file");

MenuItem n = new MenuItem("New");

MenuItem o = new MenuItem("Open");

MenuItem s = new MenuItem("Save");

MenuItem e = new MenuItem("Exit");

n.addActionListener(new New());

F.add(n);

o.addActionListener(new Open());

F.add(o);

s.addActionListener(new Save());

F.add(s);

e.addActionListener(new Exit());

F.add(e);

mb.add(F);

Menu E = new Menu("Edit");

MenuItem cut = new MenuItem("Cut");

MenuItem copy = new MenuItem("Copy");

MenuItem paste = new MenuItem("Paste");

cut.addActionListener(new Cut());

E.add(cut);

copy.addActionListener(new Copy());

E.add(copy);

paste.addActionListener(new Paste());

E.add(paste);

mb.add(E);

setMenuBar(mb);

mylistener mylist = new mylistener();

addWindowListener(mylist);

}

class mylistener extends WindowAdapter

{

public void windowClosing (WindowEvent e)

{

System.exit(0);

}

}

class New implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

tx.setText(" ");

setTitle(filename);

}

}

class Open implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

FileDialog fd = new FileDialog(Editor.this, "select File",FileDialog.LOAD);

fd.show();

if (fd.getFile()!=null)

{

filename = fd.getDirectory() + fd.getFile();

setTitle(filename);

ReadFile();

}

tx.requestFocus();

}

}

class Save implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

FileDialog fd = new FileDialog(Editor.this,"Save File",FileDialog.SAVE);

fd.show();

if (fd.getFile()!=null)

{

filename = fd.getDirectory() + fd.getFile();

setTitle(filename);

try

{

DataOutputStream d = new DataOutputStream(new FileOutputStream(filename));

String line = tx.getText();

BufferedReader br = new BufferedReader(new StringReader(line));

while((line = br.readLine())!=null)

{

d.writeBytes(line + "\r\n");

d.close();

}

}

catch(Exception ex)

{

System.out.println("File not found");

}

tx.requestFocus();

}

}

}

class Exit implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

System.exit(0);

}

}

void ReadFile()

{

BufferedReader d;

StringBuffer sb = new StringBuffer();

try

{

d = new BufferedReader(new FileReader(filename));

String line;

while((line=d.readLine())!=null)

sb.append(line + "\n");

tx.setText(sb.toString());

d.close();

}

catch(FileNotFoundException fe)

{

System.out.println("File not Found");

}

catch(IOException ioe){}

}

class Cut implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

String sel = tx.getSelectedText();

StringSelection ss = new StringSelection(sel);

clip.setContents(ss,ss);

tx.replaceRange(" ",tx.getSelectionStart(),tx.getSelectionEnd());

}

}

class Copy implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

String sel = tx.getSelectedText();

StringSelection clipString = new StringSelection(sel);

clip.setContents(clipString,clipString);

}

}

class Paste implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

Transferable cliptran = clip.getContents(Editor.this);

try

{

String sel = (String) cliptran.getTransferData(DataFlavor.stringFlavor);

tx.replaceRange(sel,tx.getSelectionStart(),tx.getSelectionEnd());

}

catch(Exception exc)

{

System.out.println("not string flavour");

}

}

}

public static void main(String args[])

{

Frame f = new Editor();

f.setSize(500,400);

f.setVisible(true);

f.show();

}

}

Programm to calculate and display no of each differebt character present in a string suppose String is Mumbai output should be M2u1b1a1i1?

In Java

// the string we want to process

final String str = "Mumbai";

// convenience conversion to characters

final char[] str_chars = str.toCharArray();

// letters used to keep track of which characters we've counted

final Set letters = new HashSet();

// iterate through each character in str

for (int i = 0; i < str_chars.length; ++i) {

// store lower case version of ch so we only need to convert once

final char ch_l = Character.toLowerCase(str_chars[i]);

// only process this letter if we haven't done so yet

if (!letters.contains(ch_l)) {

// store letter

letters.add(ch_l);

// count number of times this letter is in str

int count = 1;

for (int j = i + 1; j < str_chars.length; ++j) {

if (ch_l == Character.toLowerCase(str_chars[j])) {

++count;

}

}

// output

System.out.format("%c%d", str_chars[i], count);

}

}

What is it called when a teacher speaks in class?

a lecture... most of the time. Or a discussion. Explanation... ellaboration... and sometimes when the teacher has had enough, a good old 'uittrap'

How do you convert given number of days into month in java?

(Assume that each month is of 30 days) Example : Input - 69 Output - 69 days = 2 Month and 9 days */ classDayMonthDemo{ public static void main(String args[]){ int num = Integer.parseInt(args[0]); intdays = num%30; int month = num/30; System.out.println(num+" days = "+month+" Month and "+days+" days"); } }

What are the similarities between constructor overloading and function overloading?

The only similarity is that both constructor and function overloads are distinguished by their signature -- the number and type of their arguments. Functions differ in that they also have a return type, which is also part of the signature, whereas constructors have no return type, not even void.

What is the difference between Oracle 10i and Oracle 10g?

Oracle 8i and 9i were databases with 'i' referring to the Internet. For version 10 onwards, Oracle named the database as 10g, 'g' referring to the grid. 10i and 11i are ERP systems, nothing to do with the database.

How can you optimize code in java?

The same as in any other language. - In general, code optimization is not an easy job. You have to know the language well, look out for inefficiencies, and replace them with more efficient versions. Sometimes it is obvious, to an experienced programmer, just by looking at the code, that there is an inefficiency. At other times, you'll have to test the speed of different alternatives. If a specific method is slower than expected, a careful analysis may be required to figure out what is wrong (if anything).

How many methods in runnable interface?

chase that feeling like ive been looking for something thats good for the rich and the blind and the poor