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.
A variable used to store a value being computed in increments during a loop's execution is called?
an accunmulator
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.
True - an instance of an abstract class cannot be created.
False - derive (subclass) from a class, not the object (the instance).
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.
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 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
// 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: ");
}
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.
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.
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];
}
?>
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.
How do you find the average of 5 numbers using static method in java?
Add the five numbers; divide the result by 5.
Spinning is an aerobic exercise that takes place on a stationary bicycle.
During the class you vary your pace, pedaling as fast as you can, other times cranking up the tension and pedaling slowly from a standing position. This helps you to focus and work on your mind as well as your body.
Ipv4 is connectionless or connection oriented?
It's neither. IP is a transport layer protocol. Connection/Connectionless imply the network layer.
Look up the OSI model.
Actually you are correct, but it doesn't just go that far. The definition of connectionless is the ability to send and receive packets without already establishing connectivity between two or more specific entities. IPv4 is connectionless, meaning if I send information via IPv4 I can just send the packets without having to do much more than click "return".
Hope this helps.