Methods in the Math class in Java
public static double abs(double a)
Returns the absolute value of the specified double..
public static double acos(double a)
Returns the arc cosine of an angle, in the range of 0.0 through pi.
public static double asin(double a)
Returns the arc sine of an angle, in the range of –pi/2 through pi/2.
public static double atan(double a)
Returns the arc tangent of an angle, in the range of –pi/2 through pi/2.
public static double cos(double a)
Returns the cosine of an angle.
public static double exp(double a)
Returns Euler’s number e raised to the power of the specified double.
public static double log(double a)
Returns the natural logarithm (base e) of the specified double.
public static double log10(double a)
Returns the base 10 logarithm of the specified double.
public static double max(double a, double b)
Returns the greater of the two specified double values.
public static double min(double a, double b)
Returns the smaller of the two specified double values.
Example of continue with a label in Java
start: for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { if (j == 2) { continue start; } System.out.println(i + ":" + j); } }
The result of running this code is as follows:
0:0
0:1
1:0
1:1
2:0
2:1
Produce three beeps with a 500 milliseconds interval between two beeps in Java
java.awt.Toolkit.getDefaultToolkit().beep(); try { Thread.currentThread().sleep(500); } catch (Exception e) { } java.awt.Toolkit.getDefaultToolkit().beep(); try { Thread.currentThread().sleep(500); } catch (Exception e) { } java.awt.Toolkit.getDefaultToolkit().beep();
Use if with a series of else statements in Java
if (a == 1) { System.out.println("one"); } else if (a == 2) { System.out.println("two"); } else if (a == 3) { System.out.println("three"); } else { System.out.println("invalid"); }
Dangling else problem in Java
The else statement in the code below is dangling because it is not clear which if statement the else statement is associated with. An else statement is always associated with the immediately preceding if. Using braces makes your code clearer.
if (a > 0 || b < 5) if (a > 2) System.out.println("a > 2"); else System.out.println("a < 2");
Character literals that are escape sequences in Java
‘b’ the backspace character
‘t’ the tab character
‘\’ the backslash
”’ single quote
‘”‘ double quote
‘n’ linefeed
‘r’ carriage return
Primitive data types in Java
| Primitive | Description | Range |
|---|---|---|
| byte | Byte-length integer (8 bits) | -128 (-27) to 127 (27-1) |
| short | Short integer (16 bits) | -32,768 (-215) to 32,767 (-215-1) |
| int | Integer (32 bits) | -2,147,483,648 (-231) to 2,147,483,647 (-231-1) |
| long | Long integer (64 bits) | -9,223,372,036,854,775,808 (-263) to 9,223,372,036,854,775,807 (263-1) |
| float | Single-precision floating point (32-bit IEEE 7541) | Smallest positive nonzero: 14e-45 Largest positive nonzero: 3.4028234e38 |
| double | Double-precision floating point (64-bit IEEE 754) | Smallest positive nonzero: 4.9e-324 Largest positive nonzero: 1.7976931348623157e308 |
| char | A Unicode character | [See Unicode 6 specification] |
| boolean | A boolean value | true or false |
Separators in Java
| Symbol | Name | Description |
|---|---|---|
| () | Parentheses | Used in:
|
| {} | Braces | Used in:
|
| [] | Brackets | Used in:
|
| < > | Angle brackets | Used to pass parameter to parameterized types. |
| ; | Semicolon | Used to terminate statements and in the for statement to separate the initialization code, the expression, and the update code. |
| : | Colon | Used in the for statement that iterates over an array or a collection. |
| , | Comma | Used to separate arguments in method declarations. |
| . | Period | Used to separate package names from subpackages and type names, and to separate a field or method from a reference variable. |
Example of Simple Retry Technique to Deal with Timeouts in Android
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; public class TestHttpGet { public String executeHttpGetWithRetry() throws Exception { int retry = 3; int count = 0; while (count < retry) { count += 1; try { String response = executeHttpGet(); /** * if we get here, that means we were successful and we can * stop. */ return response; } catch (Exception e) { /** * if we have exhausted our retry limit */ if (count < retry) { /** * we have retries remaining, so log the message and go * again. */ System.out.println(e.getMessage()); } else { System.out.println("could not succeed with retry..."); throw e; } } } return null; } public String executeHttpGet() throws Exception { BufferedReader in = null; try { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI("http://w3mentor.com/")); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String result = sb.toString(); return result; } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Example of multipart POST using Android
import java.io.ByteArrayInputStream; import java.io.InputStream; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.InputStreamBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; public class TestMultipartPost extends Activity { public void executeMultipartPost()throws Exception { try { InputStream is = this.getAssets().open("data.xml"); HttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost("http://w3mentor.com/Upload.aspx"); byte[] data = IOUtils.toByteArray(is); InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(data),"uploadedFile"); StringBody sb1 = new StringBody("someTextGoesHere"); StringBody sb2 = new StringBody("someTextGoesHere too"); MultipartEntity multipartContent = new MultipartEntity(); multipartContent.addPart("uploadedFile", isb); multipartContent.addPart("one", sb1); multipartContent.addPart("two", sb2); postRequest.setEntity(multipartContent); HttpResponse res = httpClient.execute(postRequest); res.getEntity().getContent().close(); } catch (Throwable e) { // handle exception here } } }
Perform a HTTP POST Request with the HttpClient in Android
HTTP POST calls are made with the HttpClient by calling the execute() method of the HttpClient with an instance of HttpPost. We should pass URL-encoded name/value form parameters as part of the HTTP request.
import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; public class TestHttpPost { public String executeHttpPost() throws Exception { BufferedReader in = null; try { HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost("http://w3mentor.com/Upload.aspx"); List<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("filename", "xyz")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters); request.setEntity(formEntity); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String result = sb.toString(); return result; } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Example of HTTP GET Request using HttpClient in Android
import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; public class TestHttpGet { public void executeHttpGet() throws Exception { BufferedReader in = null; try { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI("http://w3mentor.com/")); HttpResponse response = client.execute(request); in = new BufferedReader (new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String page = sb.toString(); System.out.println(page); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
We can add parameters to an HTTP Get request as
HttpGet method = new HttpGet("http://w3mentor.com/download.aspx?key=valueGoesHere"); client.execute(method);
Android View() function
Syntax
View (Context context)
Return type
View
Description
To create Object View
Example
public Class AndroidBamboo extends Activity (public void OnCreate (Bundle SavedInstanceState) (Super.onCreate (SavedInstanceState); View View = New View (this); SetContentView (View); ))
Primitive data types in java
There are eight primitive types of data in java: byte, short, int, long, char, float, double, and boolean.
They are broadly classified as:
- Integers – byte, short, int, and long
- Floating-point – float and double.
- Characters
- Boolean
Byte
The smallest integer type in java and has a range from -128 to 127. Byte is used when working with a stream of data from a network or file. Byte variables are declared by use of the byte keyword.
Declaration:
byte b, c;
int
Integer is the most commonly used data type. It is commonly used as a signed 32-bit type ranging from -2,147,483,648 to 2,147,483,647. It is mostly used to control loops and to index arrays.
Integer variables are declared by use of the int keyword.
Declaration:
int b, c;
long
Long is a signed 64-bit type.
Command to execute java jar application
To run an application packaged as a JAR file we require the Main-class manifest header. The command is:
java -jar app.jar
Run an applet packaged as a JAR file
<applet code=AppletClassName.class archive="JarFileName.jar" width=width height=height> </applet>
JAR file operations in Java
Operation Command
To create a JAR file jar cf jar-file input-file(s)
To view the contents of a JAR file jar tf jar-file
To extract the contents of a JAR file jar xf jar-file
To extract specific files from a JAR file jar xf jar-file archived-file(s)
Reserved keywords in Java
abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while
Recursive factorial in Java
/** * This class shows a recursive method to compute factorials. This method * calls itself repeatedly based on the formula: n! = n * (n-1)! **/ public class Factorial { public static long factorial(long x) { if (x < 0) throw new IllegalArgumentException("x must be >= 0"); if (x <= 1) return 1; // Stop recurse else return x * factorial(x-1); // Recurse by calling function } }
Compute factorial of a number in Java
/** * A useful method for computing factorial of a given number **/ public class Factorial { /** Compute and return x!, the factorial of x */ public static int factorial(int x) { if (x < 0) throw new IllegalArgumentException("x must be >= 0"); int fact = 1; for(int i = 2; i <= x; i++) // loop fact *= i; // shorthand for: fact = fact * i; return fact; } }
