Monday, September 26, 2016

Java Packages.


Import and Static import

There are some Java classes that contain static final fields. One of them is the java.util.Calendar class, that has the static final fields representing days of the week. To use a static final field in the Calendar class, you must first import the Calendar class.
import java.util.Calendar;
if (today == Calendar.SATURDAY) {
}

// You can also import static fields using the import static keywords.
import static java.util.Calendar.SATRDAY;

java.lang.Object

   Methods:
  • clone
  • equals
  • finalize
  • getClass
  • hashCode
  • wait, notify, notifyAll

java.lang.String
  • Java string is immutable object
  • String()
  • String (arrayName)
  • String (arrayName, intOffset, intLength)
  • String Array Methods:
    • length()
    • indexOf (StringName)
    • indexOf (StringName, startIndex)
    • lastIndexOf (StringName)
    • lastIndexOf (StringName, startIndex)
    • trim() // remove all whitespaces before and after the String, but not within between
    • substring (startIndex)
    • substring (startIndex, endIndex)
    • replace (oldChar, newChar)
    • split (delimiter)
    • charAt (index)
  • String Compare Methods
    • equals (String)
    • eqaulsIgnoreCase (String)
    • startsWith (String)
    • startsWith (String, startIndex)
    • endsWith (String)
    • isEmpty()
    • compareTo (String)
      • if returns '0': true equal
      • if returns positive: longer or greater
      • if returns negative: shorter or less
    • compreToIgnoreCase (String) 
      • ref to above
  • Two mutable String API:
    • StringBuilder
      • faster but not thread-safe
    • StringBuffer
      • dated, too slow, StringBuilder is faster
      • thread-safe
String message = new String ("Java is cool!");
String s1 = "Java";
String s2 = "Java";
if (s1 == s2) { // returns true
}

String s1 = new String ("Java");
String s2 = new String ("Java");
if (s1 == s2) { // returns false
}

// if s1 == null without checking, it will generate a runtime error
// also the order matters so is the use of "&&" logical operator
// using "&&" will prevent JVM to evaluate the s1.equals()
// second expression and generate an error

if (s1 != null && s1.equals("Java")) // returns true
{
}
// Another coding style, no need to check if "Java" is null
if ("Java".equals (s1)) {
}

// Create a string from an array of characters
char cityArray[] = {'D','a','l','l','a','s'}; 
String cityString1 = new String(cityArray); 
String cityString2 = new String(cityArray, 0, 3);

// Create a string from an array of bytes
byte cityArray[] = {68, 97, 108, 108, 97, 115}; 
String cityString1 = new String(cityArray); 
String cityString2 = new String(cityArray, 0, 3);


Java Exception

   Keyword:
  • try
  • catch
  • throw
  • throws
  • finally
import java.io.*;
import java.util.List;
import java.util.ArrayList;

void method1 () {
    try {
        method1();
    }
    catch (Exception e) {
    }
}
void method2 () throws Exception {
    method3();
}
void method3 () throws Exception {
    method4();
}
public static int getInput (Scanner in) 
    throws NullPointerException, MyOutOfRangeException {
    throw new Exception();
}
class MyOutOfRangeException extends Exception {
    MyOutOfRangeException(String message){ 
        super(message); // call the base class constructor
    } 
}
public static int getInput2 (Scanner in) 
    throws NullPointerException, MyOutOfRangeException {

    int userChoice = 0;

    if (in == null) {
        throw new NullPointerException("Null Scanner");
    }
    System.out.println(
        "Please enter a value between 1 to 5");
    userChoice = Integer.parseInt(in.next());
    if (userChoice < 1 || userChoice > 5) {
        throw new MyOutOfRangeException
            ("Please enter value between 1 to 5");
    }
    return userChoice;
}

// Code to prevent NullPointerException
if (customerType != null)
{
    if (customerType.equals("R"))
        discountPercent = .4;
}


java.lang.Scanner

  • getInt() 
  • getDouble() 
  • getDoubleWithRange() 
  • hasNext() 
  • hasNextInt() 
  • hasNextDouble() 
  • next() 
  • nextLine()

if (sc.hasNextDouble()) {
    subtotal = sc.nextDouble();
}
else {
    sc.nextLine();    // discard the entire line
    System.out.println(
        "Error! Invalid number. Try again.\n");
    continue;         // jump to the top of the loop
}

// Code to get a valid double value within range
Scanner sc = new Scanner(System.in);
double subtotal = 0.0;
boolean isValid = false;
while (isValid == false) {
        // get a valid double value
        System.out.print("Enter subtotal: ");
        if (sc.hasNextDouble()) {
            subtotal = sc.nextDouble();
            isValid = true;
        }
        else
        {
            System.out.println(
                "Error! Invalid number. Try again.");
        }
        sc.nextLine();
                // discard any other data entered on the line

        // check the range of the double value
        if (isValid == true && subtotal <= 0) {
            System.out.println(
                "Error! Number must be greater than 0.");
            isValid = false;
        }
        else if (isValid == true && subtotal >= 10000)
        {
            System.out.println(
                "Error! Number must be less than 10000.");
            isValid = false;
        } 
}



No comments:

Post a Comment