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 java math class?

the Math class contains a number of mathematical functions that we may commonly need to use in our programs. Instead of coding it ourselves, the founders of java have created a class that would help us with the same.

For example:

Math.round() is used to round off a decimal value to its nearest whole number

Math.cos() will return the mathematical cosine of the value

Math.log() will return the logarithmic value of the number

etc...

What is the difference between function and method?

functions have independent existence means they are defined outside of the class e.g. in c main() is a function while methods do not have independent existence they are always defined inside class e.g. main() in Java is called method.

########

I've been studying OOP lately and had this question myself, so I will share my thoughts;

I was taught that "A Function should do 1(one) thing and do it well."

In specific Regards to PHP;

The difference between a Method and a Function is that a Method is tied to a specific class.

Hope this helps.

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

function can return value where as method can't that is the main difference between function and method

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

Actually you are describing the difference between a function and a procedure. Function returns a value, procedure does not unless you are using c#, then everything is a function.

In c# a function, to paraphrase the first answer, does and thing and does it well. A method contains functions. The most important method is the Main method. All functionality of a program must be referenced in the Main method because when you run a program, it starts at the beginning of the Main method, and stops wehn it hits end of the Main method.

Where can one learn about JSF implementations?

One can learn about JSF implementations, Of course on Java it's self. Another way one can learn about JSF implementations is at a public library one can look at a book related to the topic.

What is function in oop?

A function is a block of code that has a name and it has a property that it is reusable i.e. it can be executed from as many different points in a C Program as required.

Function groups a number of program statements into a unit and gives it a name. This unit can be invoked from other parts of a program. A computer program cannot handle all the tasks by it self. Instead its requests other program like entities - called functions in C - to get its tasks done. A function is a self contained block of statements that perform a coherent task of same kind

The name of the function is unique in a C Program and is Global. It neams that a function can be accessed from any location with in a C Program. We pass information to the function called arguments specified when the function is called. And the function either returns some value to the point it was called from or returns nothing.

We can divide a long C program into small blocks which can perform a certain task. A function is a self contained block of statements that perform a coherent task of same kind.

Structure of a Function

There are two main parts of the function. The function header and the function body.

int sum(int x, int y)

{

int ans = 0; //holds the answer that will be returned

ans = x + y; //calculate the sum

return ans //return the answer

}

How do you check whether the given no is prime or not in java?

Use Euclid's algorithm to find the greatest common factor. This algorithm is much simpler to program than the method taught in school (the method that involves finding prime factors). If the greatest common factor is 1, the numbers are relatively prime.

What is the role of class x after talking ICSE in class XI?

simple ...............................................................................................................................................................................................................................................study

How to create a custom exception in Java?

There could be an exception which cannot reach the user as it looks, instead it could be replaced by some other exceptions. In this case, the only solution is to write out our own exception and show the details regarding that exception.

Exceptions could be thrown inside a Web Service for various reasons. The possible types of exceptions that could be thrown are RuntimeException, RemoteException, SOAPFaultException and User Defined Exception.

Java supports exception handling by its try-catch constructs. Exceptions are conditions which the JVM or applications developed in Java are unable to handle. The Java API defines exception classes for such conditions. These classes are derived from java.lang.Throwable class. User-defined exceptions are those exceptions which an application provider or an API provider defines by extending java.lang.Throwable class.

The Web Service developer might try throwing a RuntimeException such as NullPointerException or ArrayIndexOutOfBoundsException inside the Web Service. But, throwing RuntimeException inside the Web Service is considered to be a bad exercise because RuntimeException will always be converted into RemoteException at the client side. While the client is waiting to catch the RuntimeException after invoking a Web Service, he will get only the RemoteException instead of RuntimeException. Eventually, he cannot perform proper error handling for RuntimeException.

The problem with throwing RemoteException is that the different client side libraries will interpret this exception in different ways. It is not portable.

The appropriate exception that the Web Service application could throw is SOAPFaultException. The SOAPFaultException contains four parts: faultcode, faultstring, actor, and detail. This exception can give you the complete information about the error condition. The faultcode might tell you whether the error has happened because of the Server, Client, or something else. For example, when a client doesn't provide security information such as username and password in the HTTP/SOAP header but the service mandates them, the pre-processing logic in the service implementation might obviously throw an authentication exception. This kind of error is considered to be a Client error. The faultstring contains the corresponding description of the error condition that has happened. This string message is human readable and the developer can easily debug the problem with the help of it. The detail element contains the actual exception message and its complete stack trace.

Actually, the detail element is an instance of the javax.xml.soap.Detail class and can be created by using the javax.xml.soap.SOAPFactory.createDetail() API.

User-Defined Exceptions Although SOAPFaultException gives necessary information that is needed to debug the problem, the Web Service client might want to do something more with a fault message that he had received. The one thing that he might want to do is to have a configurable and dynamic text description of the error that occurred. The other thing could be to have the internationalization support for the error messages. By providing text description in languages other than English, he could try addressing needs of all set of people. The list may grow more and more.

To achieve the previously stated goals, a user-defined exception with some specific format could be thrown in the service. Based on the exception that the client has received, he can decide what to do with fault message. The user-defined exception thrown inside the Web Service is directly mapped into wsdl:fault element in the Web Services Description Language (WSDL) of the Web Service. You could see the fault element as one of the child elements of operation element of the portType. The other two child elements of operation are input and output. The fault element, an optional field in the operation element, defines the abstract format of the error message that might be thrown by the Web Service. The wsdl:message element pertaining to WSDL:fault can contain only one message part, and the message part could be either a complexType or simple XMLType.

I propose here how a user-defined exception, MyCustomException, could be defined to better handle error messages. The MyCustomException contains an appropriate fault message that is as defined in the WSDL definition. The fault message contains the following three parts:

Error Code, containing a five-letter identifier plus a three-digit identifier

For example, GENEX001 could mean a generic error, whereas AUTEX001 could mean an authentication error.

Text describing the fault, including substitution variables (mentioned as {0}, {1}, and so forth)

For example, the corresponding text description for Error Code GENEX001 will be something like "Number that you have entered is {0}."

A list of values corresponding to the substitution variables defined in the above text.

For example, for the above case, the variable list will contain only one value (say 1) because the text description above contains only one substitution variable.

After processing the text using relevant logic, the final text description would be "Number that you have entered is 1." With the above approach:

Faults can be identified, using the error code, without the need for applications or people to parse or understand the fault text (which may be in a unknown language). Text description can be defined in many languages, and corresponding variables can be placed accordingly in a language-independent manner. Internationalization support can be offered by the Services by providing alternate language forms of fault messages automatically by replacing the text description portion only. Sample: Service, Exception Class, WSDL, and Client In this section, you will see a sample for service, exception, WSDL, and client. These samples will use Weblogic implementation.

Service Implementation This service takes two inputs: int number and String message. If the number is 1, SOAPFaultException will be thrown. If the number is 2, MyCustomException will be thrown; otherwise, the method will return successfully.

package WS.exception; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPFactory; import javax.xml.soap.Detail;

public class ExceptionService{ public String echo(int number, String message) throws MyCustomException{ System.out.println("Number: "+number+", Message: " + message); switch(number){ case 2: throw new MyCustomException( "GENEX001", "Number that you have entered is {0}", new String[]{String.valueOf(number)} ); case 1: Detail detail = null; try{ detail = SOAPFactory.newInstance().createDetail(); //add error message here detail.addTextNode( "Choice 1 means SOAPFaultException"); }catch(SOAPException ex){ throw new MyCustomException( "SEREX001", "Error while creating detail element", new String(){}); }

throw new javax.xml.rpc.soap.SOAPFaultException( new javax.xml.namespace.QName("env.Server"), "Number that you have entered is "+number, "NO ACTOR", detail); }

return "SUCCESS"; } }

I would like to make you understand the concept using a very simple code import java.lang.RuntimeException; class MyException extends RuntimeException { MyException(String str) { super(str); }

}

class testRunTime { void calculate() throws MyException { try { int x=0; int i=10/x;

}catch(MyException e) { e.printStackTrace();

} }

public static void main(String aa[]) { testRunTime tt=new testRunTime(); tt.calculate(); } }

just copy paste these code and run to understand what's the logic behind it with cheers Maneesh K Sinha ph-91-9867302855

Since Java is an Object Oriented programming language, it allows inheritance of all kinds of classes including Throwable classes.

For example, if you are building a website where users log in and buy stuff, you don't want your system to break down if a user has an expired credit card. You probably don't want to ignore that either.

public class CreditCardExpiredException extends Exception{...}

This special exception is thrown manually since it is user-defined.

public void login () throws CreditCardExpiredException, UserDoeNotExistException { if ( CreditCardExpired() ) { throw new CreditCardExpiredException() ; } if ( FileNotFound() ) { throw new UserDoeNotExistException() ; } }

public void Initializer () { try { login() ; } catch ( CreditCardExpiredException ex ) { /** @todo Handle this exception */ } catch ( UserDoeNotExistException ex ) { /** @todo Handle this exception */ } }

Where CreditCardExpiredException and UserDoeNotExistException are user defined Exceptions (extend the class Exception)

You have to handle or declare checked exceptions in Java.

To handle an exception you use a try catch block such as:

try {

BufferedReader in = new BufferedReader(new FileReader("filename"));

catch(IOException) {

System.out.println("Caught IO Exception");

}

To declare an exception

public static void raiseException throws IOException {

BufferedReader in = new BufferedReader(new FileReader("filename"));

}

For user defined exceptions one extends from Throwable as follows:

class MyThrowable extends Throwable { };

public class TestThrow {

public static void main(String... args) {

try {

testMethod(-10);

} catch (MyThrowable my) {

System.out.println("Something is wrong");

}

}

public static void testMethod(int i) throws MyThrowable {

// throw if i < 0

if (i < 0) {

throw new MyThrowable();

}

}

}

Methods of execution in the US?

Here are the modern ways of execution in the USA by order of usage

Lethal Injection

Electric Chair

Gas Chamber

Firing Squad

Hanging

What is need for static method?

Static methods are methods that can be invoked without creating an instance of the class that contains them. They are needed in cases where the programmer would not want to create multiple instances of a class to execute a method.

Why should you never put a semicolon at the end of the while loop's parentheses?

There are rare occasions where you would do that, but in general you don't want to do that for most while loops because the semi-colon is a statement by itself (it becomes part of the loop).

For example,

while (a > b) ;

would terminate the loop body, whereas:

while (a > b) b++ ;

would have the increment of 'b' as part of the loop.

In the first example it might cause an infinite loop, depending on whether or not a is greater than b.

The semi-colon character means the semantic end of a statement. Putting it with the while logically doesn't make much sense most of the time.

Note: Never say never, for example the following is completely legal:

while ((*to++ = *from++)!='\0');

What is compiled time and run time?

Compile time is when the compiler translates your source code into computer language. Run time is when the actual program runs.

What are the uses of File Input Stream and File Output Stream in java programming?

These streams are classified as mode streams as they read and write data from disk files. the classes associated with these streams have constructos that allows us to specify the path of the file to which they are connected. The FileInputStream class allows us to read input from a file in the form of a stream. The FileOutputStream class allows us to write output to a file stream. Example,

FileInputStream inputfile = new FileInputStream ("Empolyee.dat");

FileOutputStream outputfile = new FileOutputStream ("binus.dat");

What is diamond problem in oop inheritance?

The diamond problem in object-oriented programming occurs in languages that support multiple inheritance, where a class inherits from two classes that both descend from a common superclass. This creates ambiguity as to which version of the superclass's methods or properties should be inherited by the subclass. For example, if class A has subclasses B and C, and class D inherits from both B and C, it becomes unclear whether D should use the implementation from B or C when accessing methods from A. To resolve this, some languages implement specific rules or mechanisms, like method resolution order (MRO) or virtual inheritance.

Create a program that compute the sum and average of 20-elements array x?

public int sum(int[] x) {
int sum = 0;
for(int i : x) {
sum += i;
}
return sum;
}

public int average(int[] x) {
// Note that this returns an int, truncating any decimal
return sum(x) / x.length;
}

When is exception handling necessary for stream handling?

Exception handling is necessary for string handling as there might be some unexpected situation during string handling which may lead to program crash or abrupt termination

What is cloneable interface?

Cloneable is a TAGGED or MARKER interface

A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.

The interface Cloneable declares no methods.

Attempts to clone instances that do not implement the Cloneable interface result in the exception CloneNotSupportedException being thrown.

You want to override clone() to make it public instead of protected. For example, public Object clone() throws CloneNotSupportedException {

return super.clone();

}

If all your clone() methods call super.clone(), as is recommended, then eventually it will get passed up the inheritance chain all the way to Object.clone() to do the actual cloning, which is why you want to implement the Cloneable interface, so Object.clone() will agree to do it.

If it does not get passed to Object.clone() eventually, then you do not need to implement Cloneable.

How do you write a program that takes a list of all positive integers from input and counts as the integers are input?

// create an BufferedReader from the standard input stream

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

String currentLine = "";

int total = 0;

// read integers

System.out.print("Input an integer: ");

while (!(currentLine = in.readLine()).equals("")) {

int input = 0;

try {

input = Integer.valueOf(currentLine);

total += input;

} catch (final NumberFormatException ex) {

System.out.println("That was not an integer.");

}

System.out.print("Input an integer: ");

}

How do you reverse a string with array and function?

<?php

$str = "1234567";

$strArr = str_split($str); //split up $str by 1 character

$strlen = strlen($str) - 1; //get length of $str - 1 since the $strArr starts at 0

for($i=$strlen;$i>=0;$i--)

{

echo $strArr[$i];

}

?>

What is containership in oops concept?

In container class we can only access the public part of base class. For accessing of private and protected part of base class we use friend functions.

If String str US then what is the value of str.substring(2 4)?

In C++, the return value will be an empty string because 2 is equal to the string length (the second parameter, 4, is simply ignored). If the first parameter were greater than the string length, an out_of_range exception will be thrown instead.