Basics of Java

Hello World in Java

This is a quick basic java program.

Every Java program has to have at least one class. Every Java program has to have at least one "main" method (not one main per class, just one per application).

We print in Java using "System.out.print" or "System.out.println". When we use "println", Java automatically adds a " " after whatever we print.

The filename for the class must be the same as the file. So you would save this as Hello.java.

public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}

}

Compiling and Running Java

If you have a file called "Hello.java":

javac Hello.java
java Hello

Basic Class in Java

// Class declaration
public class Dog
{
int age; // instance variable

// constructor
public Dog()
{
age = 30;
}

// main method (optional, but every java program must have at least one)
public static void main(String[] args)
{
System.out.println("Hello!");
}

//method
void bark()
{
System.out.println(age);
}
}

References

Book a = new Book();Book b = new Book();
Book c = b; // b and c now point to the same object. c is a reference to the object pointed to by book b. If you change the value of b, like so:
b.pages = 200; // now c.pages equals 200 as well.

Arrays

Java arrays need a size. They don't expand or shrink automatically.

int[] myArray; // an array of ints
myArray2 = new int[7]; //an array of 7 ints

myArray2[0] = 20; //setting the first int in myArray2

Generating a Random Number

// generate a number between 1 and 100
int num1 = (int) (Math.random() * 100) + 1;

Casting

float a = 10.25;
int b = (int)a; // casting the float to an int

//To convert a string to an integer, you want to do this:
String a = "3";
int b = Integer.parseInt(a);

For Loops and For Each Loops

Foreach loops are called enhanced loops in Java.

//for loop
for (int i=0; i<100; i++) {}

//enhanced for loop aka foreach loop
for (String somevar: somearray) {}

Convert a String To an Integer

String a = "3";
int b = Integer.parseInt(a);

Invoke One Overloaded Constructor From Another

Just use this(), or this(arguments) from within the first constructor to invoke the appropriate constructor depending on what arguments you're passing. This is useful if you have several constructors but don't want duplicated code in all of them.

Deleting an Object

To delete an object, you get rid of its reference. All objects are on the garbage collection heap, and when all references to an object are destroyed, it becomes eligible for garbage collection. That's the nice thing about Java – it takes care of garbage collection for you, as opposed to C++. Here are the three ways you can get rid of an objects reference:
1:
void go()
{
  Life z = new Life();
}
// reference z is now dead because it is out of scope


2:
Life z = new Life();
z = new Life();
// the first object has no references because its reference now points to a different object


3:
Life z = new Life();
z = null;

Constants

You make something a constant with the "final" keyword. By convention, constant variable names are in ALL CAPS.
public static final double PI = 3.1415926;

Final methods can never be overridden:
final void round(int num) {...}

Final classes can never be extended:
public final class String{...}

A final class automatically means that it's methods can never be overridden, because to override them you have to extend the class first.

List of Primitives in Java

Java has 8 primitives:

boolean
char
byte
short
int
long
float
double


Notice that String isn't on the list. It's a class. That's why the first letter is capitalized.

Wrapping a primitive

Sometimes you want to treat a primitive like an object. To convert a primitive to an object, you wrap it in the correct class. Here's the right class for each primitive:

boolean - Boolean
char - Character
byte - Byte
short - Short
int - Integer
long - Long
float - Float
double - Double


Here's how you wrap a value:
int i = 100;
Integer i_wrapped = new Integer(i);


Here's how you unwrap a value:
int i_unwrapped = i_wrapped.intValue();

Autoboxing

Autoboxing means that most of the time, Java will wrap/unwrap your primitives for you as required. For example, suppose you have this method declaration:

public int add(int i, int j){...}


You can either pass in two ints or two Integers or an int and an Integer. Java will automatically unwrap your Integers for you. This works the other way around too, so it the method declaration was actually this:

public int add(Integer i, Integer j){...}


and you passed in two ints, no problem! Consider them wrapped. That's autoboxing, and it's available in Java 5 or greater.

You can also do stuff like this:
Integer i = new Integer(20);
i++;
int j = i * 10;

Convert an Integer To a String

int i = 10;
String s = ""+i;

Concatenating Strings

String a = "salman";
String b = "rushdie";
String name = a + " " + b; // name is now "salman rushdie"

Add Commas in a Number

Use the String.format() method. "%, d" is the format String below.

int i = 1000000; // You can't tell easily, but that's one million
String m = String.format("%, d",i); // m now contains 1,000,000

Formatting Numbers

This is similar to printf in C.

Once again, here's the line to put commas in a number:
String m = String.format("%, d",i); // m now contains 1,000,000


The first argument to the format() method is the format String. This specifies how you want your other arguments formatted.

The format String
The percent (%) sign says, "insert argument here". Here's the overall structure of the format string. The '%' sign and the type are mandatory, everything else is optional (but must go in that order if you decide to use any of it):

format_diagram


Type
The type is what the number will be displayed as. Make sure the argument you give and the type you specify are compatible. For example, if you specify "%d" (i.e. you want the number to show as a decimal) you can give an argument of 42.25.
%d decimal
%f floating point
%x hex
%c character
%tc complete date and time (Sun Nov 28 14:52:41 MST 2008)
%tr just the time (03:01:47 PM)

Examples:
String i = String.format("%x",42); // i now contains 2a (42 in hex)
String j = String.format("%c",42); // j now contains "*"
String t = String.format("%tr",new Date()); // t now contains something like "03:01:47 PM"


Flags
Flag: '-'
Means: Left-justify.

Flag: '+'
Means: The result will include a sign.

Flag: ' '
Means: The result will include a leading space for positive values.

Flag: '0'
Means: The result will be zero-padded.

Flag: ','
Means: Put commas in a number.

Flag: '('
Means: Enclose negative numbers in parens

Here's the full official Java Doc page.

Formatting dates

Complete date and time (Sun Nov 28 14:52:41 MST 2008)
%tc

Just the time (03:01:47 PM)
%tr
String t = String.format("%tr",new Date()); // t now contains something like "03:01:47 PM"


Day of the week, month and day (Sunday, October 10)
%tA, %tB %td
String d = String.format("%tA, %tB %td",new Date(),new Date(),new Date());

//another way to do that
String d = String.format("%tA, %<tB %<td",new Date(),new Date(),new Date());

Dates and Times in Java

The Date class (java.util.Date) is deprecated in Java. Don'tuse it for anything other than a timestamp. For everything else, use Calendar (java.util.Calendar).
To make a new Calendar:
  Calendar cal = Calendar.getInstance();


You get back a Calendar that's appropriate for your locale. The western world gets a GregorianCalendar, other places get islamic or buddhist calendars etc.

Working with a Calendar:
Calendar c = Calendar.getInstance();
c.set(2004,0,7,15,40); // year, month (Jan), day (7th), hour, minute
c.add(c.DATE,35); //35 days added to the date, we're now in February
c.get(c.YEAR);


The key Calendar fields are:
DATE / DAY_OF_MONTH
HOUR / HOUR_OF_DAY
MILLISECOND
MINUTE
MONTH
YEAR

Try/Catch

If a method might throw an exception, you have to tell the compiler you know that by calling the method in a try / catch block.

try
{
  //try some risky code();
} catch (Exception ex)
{
  // Do something if you get an error
}


// HERE'S ONE FOR CATCHING MULTIPLE EXCEPTIONS
try
{
  //try some risky code();
} catch (DogException ex)
{
  // Do something if you get an error
} catch (CatException cx)
{
  // Do something else
}

Throwing Exceptions

If a method might throw an exception, you have to declare it like so:

public void Bark() throws DogException, CatException
{

}

You have to declare and catch all exceptions except RuntimeExceptions and its subclasses. A RuntimeException occurs when there's an error in your code.

User Input at the Command Line

import java.io.*; //put this at the top of your .java file

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String text = null;
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
text = br.readLine();
} catch (IOException ex) {
      ex.printStackTrace();
}

Output

System.out.println("some text"); // puts a line break after this text
System.out.print("some text"); // no line break after the text

Write to a file

import java.io.*; //put this at the top of your .java file

    String text = "some text here";
    String file = "test.txt";
    try {
      FileWriter writer = new FileWriter(file);
      writer.write(text);
      writer.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    }

Read a File

import java.io.*; // put this at the very top of your .java file.

    String file = "test.txt";
    String text = "";
    try {
      FileReader r = new FileReader(file);
     int c;
     while ((c = r.read()) != -1) {
  text+=(char) c;
  }
      r.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    }    

Serialize (save) an object

You can save objects out to a file in Java. This is called serializing the object. To bring it back, you deserialize the object.
Advantages over just saving to a text file
You can just save the data from an object to a text file, but serializing is a lot quicker and safer.

Disadvantages over just saving to a text file
A serialized file won't be human-readable like a text file will. If you open it you'll just see a bunch of funny-looking characters. And you won't be looking into a mirror :)

Whatever object you're trying to serialize also has to implement Serializable. You don't need to write any functions though. All you need to say is
public class myClass implements Serializable

import java.io.*; // put this at the top of your file

    Object obj = new Object();
    String file = "test.ser";
    try {
      FileOutputStream fs = new FileOutputStream(file);
      ObjectOutputStream os = new ObjectOutputStream(fs);
      os.writeObject(obj);
      os.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    }

Deserialize an object

Exact opposite of serialize.

import java.io.*; // put this at the top of your code

    Object obj = null;
    String file = "test.ser";
    try {
      FileInputStream fileStream = new FileInputStream(file);
      ObjectInputStream os = new ObjectInputStream(fileStream);
      obj = os.readObject();
      os.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return obj;

String Comparison

Do not use == !
Use .equals() instead.

Formatting Numbers

Put commas in numbers and round numbers too!

import java.text.NumberFormat;
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
formatter.format(someNumber);

Get the Size / Length of an Array

arr.length;

Trim Whitespace From a String

String s = " xyz ".trim();
System.out.println(s); // prints out "xyz";