Basic grammers for java

1 minute read

Variables

// byte array
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

Type conversion

1. String to others

// String ---> Boolean, boolean
Boolean boolean1 = Boolean.valueOf("true");
boolean b = Boolean.valueOf("true");
// cf. boolean b = string.equalsIgnoreCase("true");

// String ---> int
String from = "123";
int to = Integer.parseInt(from);

// String ---> byte array
byte[] textBytes = str.getBytes();
byte[] textBytes = str.getBytes(Charset.forName("UTF-8"));
byte[] textBytes = str.getBytes("UTF-8");

2. Change to string

// boolean ---> String
String.valueOf(b)

// int ---> String
int from = 123;
String to = Integer.toString(from);

// double ---> String    
double f = Math.random();
rndNum.setText(String.valueOf(f));

// JSONObject ---> JSON String
dataJsonArr = json.getJSONArray("routes");
Log.e(TAG, "DEBUGGING:" + dataJsonArr.toString());

3. Etc

// Interger ---> int
Integer intObj = new Integer(i);

String format

String.format(Locale.US,"[%d]%s", position, getItem(position).title);

Split, Tokenize (spaces are used to separate words)

  1. java.util.StringTokenizer : Not used these days
  2. java.util.Scanner
  3. String[] String.split
String phrase = "the music made   it   hard      to        concentrate";
String delims = "[ ]+";
String[] tokens = phrase.split(delims);

for (int i = 0; i < tokens.length; i++)
  System.out.println(tokens[i]);

Java exception

try
{
  parseTask.execute(result); // Now we start the task to parse the xml
} catch(Exception ex) {
  Log.e("Exception Message: ", ex.getMessage());
}

URL functions

toString() : Full URL string
getProtocol() : Protocol(scheme) information such as http
getHost() : Host information
getPort() : Port
getPath() : Path (Starts with '/')
getQuery() : Parameter information
getFile() : path + query
getAuthority() : host + port
getRef()

# Delete File

try {
  File file = new File(C.MenuFilePath, C.MenuFileName);
  if(file.exists())
  {
    boolean result = file.delete();
    Log.i(TAG, "File is deleted " + C.MenuFilePath + "/" + C.MenuFileName + " " + result);
    finish();
  }
  else
  {
    Log.e(TAG, "Failed to delete file " + C.MenuFilePath + "/" + C.MenuFileName);
  }
} catch (Exception e) {
  Log.e(TAG, "ERROR:" + e.getMessage());
}

Tags:

Categories:

Updated:

Leave a comment