Some Java Skills


This is not intended to be an exhaustive reference, but I've tried to provide a list of some of the more common things we do in Java.

Skill
How-to & example
Where to look up
Print message
// Use printf function:
System.out.printf("hello!\n"); 
     
8/29 slide 3
Print values
// %d for integer, %f for real(double)
int value = 7;   
double recip = 1.0 / 7; 
System.out.printf("reciprocal of %d is %f\n", value, recip);
8/29 slide 4
Format precision
// Use %.2f for 2 decimal places of precision
System.out.printf("Payment amount is $ %.2f\n", amount);
8/29 slide 5
Initialize scanner
// Let's declare 2 scanners:  kbd to read from the keyboard,
// and in to read from a file.
Scanner kbd = new Scanner(System.in);
Scanner in = new Scanner(new FileInputStream("input.txt"));
9/12 slide 6
Use scanner
// Most often we use nextInt(), nextDouble() and nextLine()
double value = in.nextDouble();
9/3 slide 7
Declare variable
// Let's declare some variables and set them to some default
// initial values.
int numCards = 52;
boolean found = false;
double sum = 0.0;
String dessert = "ice cream";
9/3 slide 5
Convert int to double
// Multiply by 1.0
     
9/5 slide 2
Convert double to int
// We can simply use a "cast" and this will chop off the decimal places.
// If you want to round a real number to the nearest integer, we should first
// call Math.round().
double exactValue = 6.7;
int truncatedValue = (int) exactValue;
int roundedValue = (int) Math.round(exactValue);
9/5 slide 2
Convert int to String
// Append (concatenate) onto an empty string.
int value = 42;
String s = "" + value;
9/15 slide 2
Convert String to int
// Use Integer.parseInt()
String s = "456";   
int value = Integer.parseInt(s);
9/15 slide 2
Make choices
// Use if statement.  Note the use of ==, !=, && and ||
if (year % 400 == 0 ||
year % 100 != 0 && year % 4 == 0)
System.out.printf("Leap year\n");
9/5 slides 5-8
Test for divisibility
// See if value is an even number
if (value % 2 == 0)
  System.out.printf("%d is an even number\n", value);
	  
9/5 slide 6
String length
// Use length() function on the string.
String message = "dinner is ready!";
int length = message.length();
9/8 slide 4
Obtain char from string
// Use charAt(), and put the position # inside the parentheses.
// Remember that indices start at 0.
char thirdChar = message.charAt(2);
9/8 slide 4
See if string contains ...
// indexOf can look for either a single character or a substring
// returns -1 if the pattern doesn't exist
int location = message.indexOf("ready"); 
9/8 slide 4
Part of string
// Use substring
String phoneNumber = (305)667-1651;
String areaCode = phoneNumber.substring(1,4);
9/8 slide 5
Equal strings?
// Use equals() instead of ==
if (enteredPassword.equals(correctPassword))
  System.out.printf("Welcome!\n");
9/8 slide 7
Compare
// compareTo subtracts the two strings.  
// e.g. Negative result means the first string appears earlier in dictionary.
if(s1.compareTo(s2) < 0)
System.out.printf("%s comes before %s in the dictionary\n", s1, s2);
9/8 slide 7
Concatenate
// use +
9/8 slide 6
Do something 10 times
// Use while loop, with a variable that counts.
int i = 0;
while (i < 10) {
// insert the code that you want to perform
i = i + 1;
}
9/10 slides 6-8
Error checking of input
// Use while loop with a boolean variable
// In this example, we are trying to obtain a positive number.
boolean needInput = true;
while (needInput)
{ System.out.printf("Please enter positive int:");
value = kbd.nextInt();
if (value > 0)
needInput = false;
else
System.out.printf("Sorry, your input is " +
"invalid. Try again.\n");
}
9/15 slide 4
Declare array
// Here is an array of 50 integers, called a.
int [] a = new int [50];
9/15 slide 7
Find max in array
// First, assume first value contains largest value.
// Then, look at each of the elements and compare to what
// we currently think is the max. Update the max if necessary.
// Note that a.length stores the size of the array. :)
int max = a[0];
int i = 0; while (i < a.length) {
if (a[i] > max)
max = a[i];
}
System.out.printf("The largest number is %d\n", max);
9/15 Array.java
Read entire file
// While loop:  as long as there are still lines in the file,
// keep reading lines one at a time.
// Let's assume the variable in refers to a file we've opened.
while (in.hasNextLine())
{
String line = in.nextLine();
// do something with this line, as appropriate
}
 
Format a string without printing it out
// Use the String.format function.  It works like printf.
// This is useful when we write toString() functions.
// For example, let's suppose we want to write out a team's
// win-loss-overtime loss record.
// Note: as with printf, we should not end with \n.
String s = String.format("%d-%d-%d", wins, losses, overtimeLosses);
 
Define a class
// Simple example:  a rectangle.  We need to define our attributes,
// at least one constructor... and whatever other functions we desire.
public class Rectangle
{
private int length;
private int width;

public Rectangle(int length, int width)
{
this.length = length;
this.width = width;
}
public int findArea()
{
return length * width;
}
}
 
Write a function
// First, we need to ask ourselves 3 questions to help us plan:
// 1. Do we need parameters (extra information) ?
// 2. Do we change any attributes?
// 3. Should we return some kind of result?
// Let's look at the withdraw example from the Account class:
public boolean withdraw (double amount)
{
if (amount > this.balance)
return false;
else
{
this.balance = this.balance - amount;
return true;
}
}
 
Default constructor
// Often a default constructor will need to get input in order
// to set the values of the attributes. Let's do one for Rectangle.
public Rectangle()
{
System.out.printf("Please enter length: ");
Scanner kbd = new Scanner(System.in);
this.length = kbd.nextInt();
System.out.printf("Please enter width: ");
this.width = kbd.nextInt();
}
 
Initial value constructor
// See the "define a class" example above.
// It uses an initial-value constructor.
9/26 slide 3
Copy constructor
// There should be 1 parameter:  the object we want to copy.
// Let's do one for Rectangle.
public Rectangle (Rectangle r)
{
this.length = r.length;
this.width = r.width;
}
9/26 slide 3
Declare constant
// Let's suppose all bank accounts have the same interest rate.
public static void double RATE = 3.25;
9/26 slide 4
Create object
// Once we've defined a class (new data type), we'd like to
// create objects (variables) of this new type.
// First, you have to decide which constructor is appropriate,
// then pass the right parameters.
Rectangle tableTop = new Rectangle (6, 3);
 
Declare array attribute
// Do this in 2 steps.
// First, declare the name of the array at the top of the class
// where we normally declare our attributes.
// Second, at the beginning of the constructor(s), we need to
// allocate space for the array.
// For example, let's say we want a hand to have 13 cards.
public class Hand
{
private Card [] c;

public Hand()
{
c = new Card [13];
// rest of the program
10/1 slide 5
Declare object attribute
// Same idea as with the array attribute:  declare the attribute at 
// the beginning of the class.  Then, inside the constructor, don't
// forget to allocate space.
 
Format string inside toString
// Use String.format() just like you would use printf.
// Aside:  Recall that inside toString() we generally do not use \n
// at the end of the string.  This is because whoever is calling
// toString() will likely be printing \n after our string,
// and we would not want to inadvertently have two \n in a row.
// An exception to this rule would be if our string has multiple lines
// anyway.


String s = String.format("%-20s %5d", name, value);
10/6 slide 3
toString with loop
// The purpose of toString() is to provide a text representation of
// an object.  Usually we want to put the attributes inside a string
// so that it can be printed out later.  
// But if an attribute is an array (or ArrayList), we will need a loop.
// The following example may be suitable for a shopping list.
public String toString()
{
  String build = "";
  for (int i = 0; i < shoppingList.length; ++i)
  {
    build += shoppingList[i].toString() + "\n";
  }
  return build;
}
10/6 slide 3
sum attribute of object array
// Sometimes we need to find the sum of an array.  But the array 
// cells each contain an object, not just a number.  For example,
// for a shopping list, we have an array of Items, and we want to
// find the sum of all the item's prices.  For each item, we need
// to look up the price and add it to our total.
double total = 0.00;
for (int i = 0; i < shoppingList.length; ++i)
  total += shoppingList[i].getPrice();
10/6 slide 3
array parameter
// When you pass an array as a parameter to a function, you can just
// type its name, just like it were any other kind of variable.
// However, when declaring the function, be sure to remember the "[]"
// in the formal parameter list.


// In Driver:
   City c = new City(name, tempArray, rainArray);
// In City:
   public City(String n, double [] temp, double [] rain) ...
10/8 slide 3
random integer
// First, create Random generator object.  Then, when you want a
// random integer, call nextInt().  The parameter to nextInt()
// indicates how many possible values to choose from, starting at 0.
// For example, we can generate a value from 0-19:
Random gen = new Random();
int value = gen.nextInt(20);



// You may need to do some arithmetic if this is not the range you want.
10/15 slide 1
random real
// The Random class also has a nextDouble() function.  It takes no
// parameter and always returns a value between 0.0 and 1.0.
// We can multiply and/or add to adjust the desired range.  For example,
// to obtain a number between 0.0 and 10.0:

double value = gen.nextDouble() * 10;
10/15 slide 1
for-loop
// This is the most common type of loop in Java.  (The other kinds
// are the while loop and do-while loop.)
// The format of a for-loop is:
//    for (INITIALIZATION; CONDITION; INCREMENT)
//      BODY

// Let's find the sum of all the values in an array using a for loop:
int sum = 0;
for (int i = 0; i < a.length; ++i)
  sum += a[i];
10/17 slide 9
do-while loop
// Least common kind of the 3 kinds of loops.  
// The loop is guaranteed to do at least 1 iteration because we don't
// check the condition until the bottom of the loop.
// Here is how we can do error checking with a do-while loop:

boolean needInput = true;

do

{

  System.out.printf("Enter a positive number:  ");

  value = in.nextInt();
  if (value > 0)
    needInput = false;
  else

    System.out.printf("Sorry, try again...\n");

} while (needInput);
10/17 slide 15
search with break
// Example of using break statement:
// If you are searching an array, and you want to stop the search
// immediately once you've found something.  Let's look for 0.

for (int i = 0; i < a.length; ++i)
  if (a[i] == 0)
  {
    found = true;
    break;
  }
10/20 slide 2
printing 2-D output
// Nested loop.  Outer loop is responsible for all the rows, and
// inner loop handles a single row.  We need to print \n after
// each row.  Here is a grid of '*' with 4 rows and 7 columns:

for (int i = 0; i < 4; ++i)

{
  for (int j = 0; j < 7; ++i)

    System.out.printf("*");
  System.out.printf("\n");
}
10/20 slide 8
traverse 2-D array
// 2-D array needs nested loop for rows and columns.
// Suppose the array is called a.  Then a.length is the number of
// rows and a[0].length is the number of columns.
// Let's count the positive elements.
int count = 0;

for (int i = 0; i < a.length; ++i)
  for (int j = 0; j < a[0].length; ++j)
    if (a[i][j] > 0)
      ++count;
10/22 slide 3
just 1 row of array
// To do something on just 1 row of an array, we only need one loop.
// Here, the row number is fixed and the column number needs to vary.
// Let's say we want to set all of the 2nd row elements to 0.
// (To handle a column would be analogous.)
for (int col = 0; col < a.length; ++col)
  a[1][col] = 0;
10/22 slide 4
switch statement
// Can replace a lot of tedious if-else statements.  For example,
// we can write out the name of a card's suit.
String suitName = "":
switch (suitChar)
{
  case 'c':  suitName = "clubs"; break;
  case 'd':  suitName = "diamonds"; break;
  case 'h':  suitName = "hearts"; break;
  case 's':  suitName = "spades"; break;
  default:  suitName = "ERROR"; break;
}
10/24 slide 4
swapping values
// Need to introduce a temporary variable that is the same type as
// what we are swapping.  Let's swap 2 Cards called c1 and c2.
Card temp = c1;
c1 = c2;
c2 = temp;
10/27 slide 5
swap sort
// Although there are more efficient ways to sort, this technique
// is straightforward to explain:  Look at each possible pair of
// elements.  If they are out of order, swap them.
// In this example, we sort descendingly, so "<" means out of order.

for (int i = 0; i < a.length; ++i)
  for (int j = i+1; j < a.length; ++j)
    if (a[i] < a[j])

    {
      int temp = a[i];
      a[i] = a[j];
      a[j] = temp;
    }



// If the base type of the array is not a primitive type, then
// we need to teach Java how to compare elements.  Instead of
// using < or >, we write a compareTo function like String has.
10/27 slides 6,8
declaring static function
// If Driver needs additional functions besides main(), we can
// make them static.  
public static void sort(Card [] c)

...
10/27 slide 9
Javadoc comment
/** These are comments we put at the top of the file and before
 *  each function.  When compiling, our comments come out as HTML.
 *  They begin with a slash and two stars.  They end with a
 *  star and a slash.  Inside the comment, we can specify
 *  certain features about a function such as the parameters
 *  and return value.  For a comment that goes at the top of
 *  the source file, we need to put the Javadoc comment after
 *  the "import" statements.
 */
10/29 slide 7
using ArrayList
// When you declare, be sure to specify the base type in <>.
// The most important functions are:  add, get, set and size.
ArrayList<Card> hand = new ArrayList<Card>();

hand.add(new Card('Q', 'd'));



// Let's count the aces in our list of card.
// Assume that the Card class has a function isAce():
int count;

for (int i = 0; i < hand.size(); ++i)
  if (hand.get(i).isAce())
    ++count;
10/31 slide 4
try & catch
// Suppose we want the user to enter a file name.  It's possible
// that the file does not exist, and this is called an exception.

Scanner in = null;
try
{
  in = new Scanner(new FileInputStream(fileName));
}
catch(FileNotFoundException e)
{
  System.out.printf("Can't open file.  Try again...\n");
}
11/7 slide 7
conditional operator
// A shortcut to doing an "if" statement.  Helpful if the choice
// needs to be made in the middle of another expression.
System.out.printf("I found %d %s.\n", numLogins,
                  (numLogins == 1) ? "login" : "logins");
11/10 slide 3
use char as integral type
// char can be treated like integers.  For example, we can use
// a for-loop with a character variable to print out the alphabet:
for (char c = 'a'; c <= 'z'; ++c)
  System.out.printf("%c", c);
11/10 slide 5