JAVA Beginners part 14

To convert a number to String

couple of ways to do it.

a) use concatenation.
‘+’ operator is overloaded in Java as String concatenator. Anything added to String using ‘+’ will be a string.

double d = 42.5;
String doubles = “”+d;

b) use the tostring method from the class Double.
double d = 42.5;
String doubled = Double.toString(d);


Java does not specify formatting of strings like C. In C it is not possible to format a number into a nice String.
Java has a formatter class in java.util which is flexible to do this job. Call static String.format() method and pass the argument and formatting instructions.


public class testformats
public static void main(String[] args)
String s = String.format(“%,d”,100000000);

String.format() method, has two parts.

a) formatting instructions
b) argument to format. it can be more than one. it is expected that if the formating instructions specifies float then the arguments has to be all float.

in above example

%,d = says that the second argument has to be formatted as a decimal integer and insert commas.
% means variable/ the argument that is being passed to the method.

format(“i have %.2f bugs to fix”,4765.50789);

i have 4765.50 bugs to fix

the % tells to format the second argument like .2f which is 2 characters after the decimal in the floating point number.

format(“i have %,.2f bugs to fix”,4765.50789);

i have 4,765.50 bugs to fix

more on format

format specifier can have up to five different parts.
Note – the order is mandatory.

%[argument number][flags][width][.precision]type

argument says the format is applicable to which argument
flags says about commas,negative numbers
width says the least digits that will be used
.precision says the number of decimal places
type is mandatory d for decimal , f for float

Type is mandatory and it always comes last. A part from % type is the only one needed.
The argument must be compatible with the type specified.

d decimal %d,42
f float %f,42.50

x hexadecimal %x,42
c character %c,42 [ this will print the symbol representative of the ASCII value of 42 ]


More than one arguments
int one = 200
double two = 300.50

String s = String.format(” the ran is %,d out of %,.2f “,one,two);

The order is important. %d refers to one and %f refers to two.

Date format
complete date and time

String. format (“%tc”, new Date() );
output = Sun Nov 28 14 :52:41 MST 2004

just the time

String. format (“%tr”, new Date() ) ;
output = 03:01 :47 PM
day of the week, month and day

date today = new date();
output = Sunday , November 28

same as above without repeating the argument

date today = new date();
the angular bracket is a flag that tells the formatter to use the previous argument again
output = Sunday , November 28


Calendar is an Abstract Class. So it is not possible to create an instance of it.
Calendar cal = new Calendar(); wont work

still for some reason we would want to have an object that extends calendar.

Calendar cal = Calendar.getInstance();
The above is not creating an instance of Calendar , it is creating an instance of a concrete Calendar subclass, in this case most probably the returning subclass would be GregorianCalendar. 

Probably one of reasons why we are creating a super class reference of Calendar and returning instance of subclass, rather than directly creating an object of GregorianCalendar is the calendar could be anyone not just GregorianCalendar ( Buddhist or Japanese), Calendar.getInstance() will give you a Calendar using the default time zone and locale.



Euler Problem 6 better way

When you can use a simple mathematical formula why create such a mess with so many lines of code. My long code was 32 lines vs 16, 5 variables vs 3,2 loops vs no loops and obviously the effort in writing such a big code.

For date manipulation.

struggling with dates. page 325 and 326,332

static import, looks confusing

Some old-fashioned code:

import java.lang.Math;
class nostatic
       public static void main(String [] args)
           System.out.println(“sqrt” + Math.sqrt(2.0));

same code with static imports.

import static java.lang.System.out;
import static java.lang.Math.*;

class withstatic
       public static void main(String [] args)
             out.println(“sqrt” + sqrt(2.0));

System.out = out in this is a static variable.
Static variable is more than just a Global variable. Its is a class variable, which is same for each instance of the class.


Java Sound API, is split into two parts MIDI and Sampled.

MIDI file has information about how a song should be played but it doesn’t have the actual sound data. its like the sheet music instructions.MIDI stands for Musical Instrumental Digital Interface. it is standard protocol used to communicate between musical instruments.

MIDI doesn’t include any sound, it is like a music page which when supplied to a instrument can playback. another analogy is like MIDI is a html doc and instrument is like the web browser.

MIDI only has the instructions to play. It doesn’t say anything about anything about the actual sound you hear, for that you need an instrument.

Sequencer. We need an Object that can take all the instructions of MIDI and send it to the right instruments. this the thing that plays the music. Here we used sequencer as a playback device even though it can do a lot of things.


Introduction to Handling Java Exceptions.

Put the risky code in the try/catch.

A try/catch block tells the compiler that you know an exceptional thing could
happen in the method you are calling and you are prepared to handle it.

above example with try/catch


Exception is an object of type exception.
catch argument is declared as type exception.

Throwable ( has two key methods, getMessage() and printStackTrace())
Exception extends Throwable

IOException extends Exception
InterruptedException extends Exception


Compiler check for everything except runtime exceptions. So if you are throwing an exception then you need to declare it as well. then if you are calling a method that could throw and exception then you need to catch it and handle it.

Checked exceptions are checked at compile time by the JVM and its related to resources(files/db/stream/socket etc). The motive of checked exception is that at compile time if the resources are not available the application should define an alternative behavior to handle this in the catch/finally block.

Unchecked exceptions are purely programmatic errors, wrong calculation, null data or even failures in business logic can lead to runtime exceptions. Its absolutely fine to handle/catch unchecked exceptions in code.

Reason why you declare the exception is , such that the person who calls the code that could throw and exception will know that by looking at the declaration and can handle it using a suitable try/catch block.


Most Runtime exceptions come from a problem in your code logic rather than a condition, example you cannot guarantee a server is up or a file is there.

Finally Block, is where you put the code that must run regardless of an exception. you can put all your cleanup code in one place instead of duplicating it.

try block has to come with either catch or finally. finally can be blank as well. but when using catch you need to specify the exception.
{} // will not work

it has to be something like

catch( ArithmeticException e)
if you dont know what other exceptions that could arise then you can simply extend the Exception interface and catch exception explained below . it is the generic method.

You cannot put the code between the try and catch.

Try without catch and only finally will still needs to have declaration of the exception.

set PATH=%PATH%;C:\Program Files\Java\jdk1.6.0_37\bin

set CLASSPATH=C:\Program Files\Java\jdk1.6.0_37\lib;C:\Users\ullalm\JAVA_Test

A method must declare all the checked exceptions it can throw, if the exceptions have a common super class then you even just declare the superclass.

public class laundry
           public void dolaundry throws pantsexception, shirtsexception
public class stuff
          public void go()

              Laundry laundry = new Laundry ();
             catch(pantsexception p)
            catch(shirtsexception s)
when it comes to the order of the exceptions in the catch , the bigger exception or the more generic exception should go last. JVM will start from first one and works all the way down to find a broad one. The higher one in the inheritance order will go the last in the catch.

If you were to mix and match the compiler will give and error.the siblings can be placed in any order, which is the exceptions in the same level.

public void methodA() throws AnException

//do something
         throw new AnException();

If AnException is a checked exception (in other words, if it doesn’t extend RuntimeException) then methodA won’t compile. Checked exceptions must always be declared.
new exception may be.
public void methodA()

//do the same thing
            throw new AnException();

If AnException is an unchecked exception (if it does extend RuntimeException), then either is allowed by the java compiler, and either is interpreted equivalently by the java runtime. methodA is still probably still preferred in this case, for the reasons of documentation. The javadoc for your method will show that it might throw AnException. It’s good to let users of your method know what Exceptions they should expect.
known exception.


Flow of the exception in the code ( Duck it meaning no try/catch)

public class washer
laundry laundry = new laundry();

public void foo() throws clothingexception

public static void main(String[] args) throws clothingexception
washer a = new washer();;

here, main calls foo, foo calls laundry, laundry throws clothingexception
since the exception is not handled it is thrown back to the caller which is foo,
foo also does not handle the exception so it is thrown back to main
main also does not handle the exception so now it is thrown back to JVM.
Now JVM has to handle the exception.

Remember it is not enough to have a catch block. you have to catch the thing being thrown , which is the correct exception in the Inheritance order.






next page 360

More in next part.


Head First Java 2nd Edition



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s