Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 88

Name: Mr. Lodelio R.

Millo
Educational Background

This course provides the students with
fundamental understanding of structured
programming using Java. It introduces the
different concepts that are commonly
associated with structured programming. The
course is design to provide students an in-
depth look at Java Programming using the
structured approached in a business problem-
solving environment
This course aims to enhance students knowledge in advance
JAVA programming.

At the end of the course, the students are expected to:

Appreciate the use of existing java classes such as Math,
String, StringBuffer, Wrapper, Process, Runtime and
System classes.
Learn how to use to streams to get input from user,
manipulate it and display the result.
Understand the role of the Java programming language as
a front-end for database applications.
Understand two-tier and three-tier architectures for
distributed computing.
Tour of java.lang Package
Introduction to java.lang
Math Class
The Character, String and Buffer Classes
Wrapper Classes
The Process of Runtime Classes
The System Classes
Basic Formatting Classes
Formatting Number, Currencies and Percentages
NumberFormat Class
DecimalFormat Class
Formatting Date and Time
Scanner Class
Introduction to File Handling and Stream
Console I/O
Writing the Standard Output
Reading from the Standard Input
File and File I/O
Creating New File Object
File Methods and Facilities
File Stream I/O
Advance I/O Stream
I/O Fundamentals
Data within Stream
Byte Stream
The InputStream Methods
The OutputStream Methods
Character Streams
The Reader Methods
The Writer Methods
String Tokenizer
Basics Byte Stream Classes
The FileInputStream and the FileOutputStream Classes
The BufferedInputStream and the BufferedOutputStream Classes
The DataInputStream and the DataOutputStream Classes
Basic Character Stream Classes
The InputStreamReader and the OutputStreamWriter Methods
Byte and Character Conversion
Using Other Character Encoding
The FileReader and the FileWriter Classes
The BufferedReader and the BufferedWriter Classes
The RandomAccessFile Class
Database Access and MySQL Using JDBC
What is JDBC
Connecting to the databases
Basic Database Access and MySQL
The JDBC Support Classes
Back-up and Restore MySQL Database
Swing GUI Component
Using JFrame, JInternalFrame, JTextbox, JTextArea
Using JMenu, JMenuItem, JComboBox, JList
Using Basic Controls
Threads
The Three part of a Thread
Creating a Thread
Starting a Thread
Thread Scheduling
Basics Controls of Threads
Terminating a Threads
Testing a Threads
Accessing Thread Priority
Putting Threads on Hold
Other Way to Create Thread
Selecting a Way to Create a Threads
Using Synchronized in Java Technology
The Object Lock Flag
Releasing the Lock Flag
Thread States
DeadLock
Come to class prepared and ready to share. Always come to school
earlier or on time. (Check your schedule)
Respect peoples idea and opinion.
Wear proper uniform
Eating and using cellular phone or any electronic gadget which is not
required to use is not allowed during class encounter/lesson.
Read in advance.
Listen to the direction of your instructor.
Late submission will not be accepted.
Be responsible for the things that you missed. Excuse absences are the
one with medical certificate and death of the immediate family
members. Other than those you are considered absent.
Observe cleanliness and orderliness.
Obey your professor.
Do your very best.
Class Standing (60%) :
Quizzes/Seatworks 25%
Long Quiz/Project 15%
Attendance 10%
Assignments/Oral Participation 10%

Major Exam (40%)

TOTAL (100%)


FINAL GRADE = (PRELIM + MIDTERM + PRE-FINAL + FINAL)/4


After the completing the lesson, you should
be able to appreciate and use the following
classes
Math
String
StringBuffer
Wrapper
Process
System
It is a collection of predefined constants and
methods for performing different
mathematical operations such as
trigonometric functions and logarithm.
Most of its methods are defined as static

public static double abs(double a)
Returns the positive value of the parameter. An overloaded method. Can also take in a
float or an integer or a long integer as a parameter, in which case the return type is
either a float or an integer or a long integer, respectively.
public static double random()
Returns a random positive value greater than or equal to 0.0 but less than 1.0.
public static double max(double a, double b)
Returns the larger value between two double values, a and b. An overloaded method. Can
also take in float or integer or long integer values as parameters, in which case the
return type is either a float or an integer or a long integer, respectively.
public static double min(double a, double b)
Returns the smaller value between two double values, a and b. An overloaded method.
Can also take in float or integer or long integer values as parameters, in which case the
return type is either a float or an integer or a long integer, respectively.
public static double ceil(double a)
Returns the smallest integer greater than or equal to the specified parameter a.

public static double floor(double a)
Returns the largest integer that is lesser than or equal to the specified parameter a.
public static double exp(double a)
Returns Euler's number e raised to the power of the passed argument a.
public static double log(double a)
Returns the natural logarithm (base e) of a, the double value parameter.
public static double pow(double a, double b)
Returns the double value of a raised to the double value of b.
public static long round(double a)
Returns the nearest long to the given argument. An overloaded method. Can also take in a
float as an argument and returns the nearest int in this case.
public static double sqrt(double a)
Returns the square root of the argument a.
.
public static double rint(double a)
Returns the closest integers, the even integer is returned
public static double sin(double a)
Returns the trigonometric sine of the given angle a.
public static double cos(double a)
Returns the trigonometric cosine of the given angle a.
public static double tan(double a)
Returns the trigonometric tangent of the given angle a.
public static double asin(double a)
Returns the trigonometric arcsine of the given angle a.
public static double acos(double a)
Returns the trigonometric arccosine of the given angle a.
public static double atan(double a)
Returns the trigonometric arctangent of the given angle a
public static double toDegrees(double angrad)
Returns the degree value approximately equivalent to the given radian value.
public static double toRadians(double angdeg)
Returns the radian value approximately equivalent to the given degree value
class MathDemo {
public static void main(String args[]) {
System.out.println("absolute value of -5: " + Math.abs(-5));
System.out.println("absolute value of 5: " +Math.abs(-5));
System.out.println("random number(max value is 10): " + Math.random()*10);
System.out.println("max of 3.5 and 1.2: " + Math.max(3.5, 1.2));
System.out.println("min of 3.5 and 1.2: " + Math.min(3.5, 1.2));
System.out.println("ceiling of 3.5: " + Math.ceil(3.5));
System.out.println("floor of 3.5: " + Math.floor(3.5));
System.out.println("e raised to 1: " + Math.exp(1));
System.out.println("log 10: " + Math.log(10));
System.out.println("10 raised to 3: " + Math.pow(10,3));
System.out.println("rounded off value of pi: " + Math.round(Math.PI));
System.out.println("square root of 5 = " + Math.sqrt(5));
System.out.println("10 radian = " + Math.toDegrees(10) + " degrees");
System.out.println("sin(90): " + Math.sin(Math.toRadians(90)));
}
}
absolute value of -5: 5
absolute value of 5: 5
random number(max value is 10): 4.0855332335477605
max of 3.5 and 1.2: 3.5
min of 3.5 and 1.2: 1.2
ceiling of 3.5: 4.0
floor of 3.5: 3.0
e raised to 1: 2.7182818284590455
log 10: 2.302585092994046
10 raised to 3: 1000.0
rounded off value of pi: 3
square root of 5 = 2.23606797749979
10 radian = 572.9577951308232 degrees
sin(90): 1.0
Introduction
Problem: Write a program that determines the time it
takes a ball to hit the ground after it has been dropped
from an 800-foot tower. The mathematical formula to
calculate the time in seconds that it takes to fall a
given distance in feet is:


Where g is the gravitational constant equal to 32.2
ft/sec
2
.

Output
It will take 7.049073768502414 seconds to fall 800 feet.
g height time / * 2 =
public class FallTime {

public static void main (String[]args){
int height;
double time;

height = 800;
time = Math.sqrt(2*height/32.2);

System.out.println("It will take " + time + " seconds to fall " + height + " feet.");
}
}
Problem: Write a program that accepts the
rectangular coordinates of two points (x
1,
y
1
)
and (x
2,
y
2
) and calculates and returns the
distance between two points. The distance, d,
between two points is given by the formula



2
1 2
2
1 2
) ( ) ( y y x x d + =
import java.util.*;
public class DistanceTwoPoints {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of x1: ");
int x1 = sc.nextInt();
System.out.print("Enter the value of x2: ");
int x2 = sc.nextInt();
double a = Math.pow(x2-x1,2);
System.out.print("Enter the value of y1: ");
int y1 = sc.nextInt();
System.out.print("Enter the value of y2: ");
int y2 = sc.nextInt();
double b = Math.pow(y2-y1,2);
double d = Math.sqrt(a+b);
System.out.println("Distance between two points is: "+d);
}
}
Problem: Write a Java program that convert
the rectangular (x,y) coordinates of a point
into polar form. That is, given an x and y
position on a Cartesian coordinate system.
Calculate the distance from the origin, d, and
the angle from the x axis, , specified by the
point. The values of d and are referred to as
the points polar coordinates.


u
u
Formula:




Algorithm
Get the x and y coordinates values
Calculate the polar (r and ) coordinates values
Display the polar coordinates values


u
2 2
y x d + =
0 ), / ( tan
1
= =

x x y u
(X, Y)
r
u
X - axis
Y - axis
public class ConvertXY {
public static void main(String[] args) {
double x =3.0; double y = 4.0; double distance, angle;
//convert to Polar coordinates
distance = getDistance(x,y);
angle = getAngle(x,y);
System.out.println("The polar coordinates are: ");
System.out.println("Distance from the origin: " + distance);
System.out.println("Angle (in degrees) from the x-axis: "+ angle);
}

public static double getDistance(double x, double y){
return Math.sqrt(Math.pow(x,2)+ Math.pow(y,2));
}
public static double getAngle(double x, double y){
return Math.toDegrees(Math.atan(y/x));
}
}
Write a program that simulates the roll of 2
six sided dice and then outputs the value of
each die, and the total sum of the dice. Save
as DiceRoll.java.
public class PairOfDice {

private int die1; // Number showing on the first die.
private int die2; // Number showing on the second die.

public PairOfDice() {
// Constructor. Rolls the dice, so that they initially
// show some random values.
roll(); // Call the roll() method to roll the dice.
}
public void roll() {
// Roll the dice by setting each of the dice to be
// a random number between 1 and 6.
die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;
}
public int getDie1() {
// Return the number showing on the first die.
return die1;
}
public int getDie2() {
// Return the number showing on the second die.
return die2;
}
public int getTotal() {
// Return the total showing on the two dice.
return die1 + die2;
}
} // end class PairOfDice

The Main Program


public class Main {

public static void main(String[] args) {

PairOfDice dice; // A variable that will refer to the dice.
int rollCount; // Number of times the dice have been rolled.

dice = new PairOfDice(); // Create the PairOfDice object.
rollCount = 0;

/* Roll the dice until they come up snake eyes. */

do {
dice.roll();
System.out.println("The dice come up " + dice.getDie1()
+ " and " + dice.getDie2());
rollCount++;
} while (dice.getTotal() != 2);

/* Report the number of rolls. */

System.out.println("\nIt took " + rollCount + " rolls to get a 2.");

} } // end class RollFor2
A quantity known as the body mass index
(MBI) is used to calculate the risk of weight-
related health problems. BMI is computed by
the formula of

Where w is weight in kilograms and h is
height in centimeters. A BMI of 20 to 25 is
considered normal. Write an application
that accepts weight and height (both
integers) and output the BMI.
( )
2
0 . 100 / h
w
BMI =
If you invest P peso at R percent interest rate
compounded annually in N years, your
investment will grow to




pesos. Write an application that accepts P, R,
N and computes the amount of money
earned each years.
( ) | |
100 / 1
100 / 1
1
R
R P
N

+
Write a loan calculator program that
computes both monthly and total payments
for a given loan amount, annual interest rate,
loan period.
The formula for computing the monthly
payment

Where L is the loan amount, R is the monthly
interest rate and N is the number of payment
( )
N
R
LR
ment monthlypay
] 1 / 1 [ 1 +
=
Algorithm
Get three input values: loanAmount, interestRate,
and loanPeriod
Compute the monthly and total payments
Output the result



Input Output
Loan
Amount
Annual
Interest
Rate
Loan Period
(in years)
Monthly
Payment
Total
Payment
10000 10 10 132.151 15858.088
15000 7 15 134.824 24268.363
In this problem, you will complete the code
for a program that computes the surface area
and volume of a solid cone given the radius of
its base and height. The relevant equations
are:

V = r
2
h / 3
A = r
2
+ r (r
2
+h
2
)

public class Cone { public static void main
(String[] args)
{ //1. declare double variables: h, r, V, and A.
// 2. assign a value for h and r
// 3. compute volume, V, and surface area, A
// 4. display the results } }
String
Combination of character literals
Can be represented by array of characters or
simply by using String class
String object is immutable or cannot be change
StringBuffer
Object of StringBuffer is similar to a String object,
except for the fact that the StringBuffer object is
mutable or can be modified
public char charAt(int index)
Returns the character located in the specified index.
public int compareTo(String anotherString)
Compares this string with the specified parameter. Returns a negative value if
this string comes lexicographically before the other string, 0 if both of the
strings have the same value and a positive value if this string comes after the
other string lexicographically.
public int compareToIgnoreCase(String str)
Like compareTo but ignores the case used in this string and the specified
string.
public boolean equals(Object anObject)
Returns true if this string has the same sequence of characters as that of the
Object specified, which should be a String object. Otherwise, if the specified
parameter is not a String object or if it doesn't match the sequence of symbols in
this string, the method will return false.
public boolean equalsIgnoreCase(String anotherString)
Like equals but ignores the case used in this string and the specified string.
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Gets the characters from this string starting at the srcBegin index up to the srcEnd index and
copies these characters to the dst array starting at the dstBegin index.
public int length()
Returns the length of this string.
public String replace(char oldChar, char newChar)
Returns the string wherein all occurrences of the oldChar in this string is replaced with
newChar.
public String substring(int beginIndex, int endIndex)
Returns the substring of this string starting at the specified beginIndex index up to the
endIndex index.
public char[] toCharArray()
Returns the character array equivalent of this string.
public String trim()
Returns a modified copy of this string wherein the leading and trailing white space are
removed.
public static String valueOf(-)
Takes in a simple data type such as boolean, integer or character, or it takes in an object as a
parameter and returns the String equivalent of the specified parameter.
public String toLowerCase()
Returns a new string with all characters in lowercase.
public String toUpperCase()
Returns a new string with all characters in upper case.
public String concat(String anotherString)
Concatenates str to the end of a string.
public boolean endsWith(String suffix)
Test if the string ends with the specified string
public int hashCode()
Returns an integer number derived from the string
public int indexOf(int ch)
Returns the position of the first occurrence of the specified character
public int lastIndexOf(int ch)
Returns the position of the last occurrence of the specified character.
public boolean startsWith(String prefix)
Test if the string begins with the specified string
public boolean startsWith(String prefix, int startPos)
Test if the string begins with the specified string, starting at the specified position.






String name = new String ("Jonathan");
System.out.println(name = " + name);
System.out.println("Jonathan compared to jonathan : " +name.compareTo ("jonathan"));
System.out.println("Jonathan compared to jonathan (ignore case): "
name.compareToIgnoreCase("jonathan"));
System.out.println("Is Jonathan equal to Jonathan? " + name.equals("Jonathan"));
System.out.println("Is Jonathan equal to jonathan? " + name.equals("jonathan"));
System.out.println("Is Jonathan equal to jonathan (ignore case)? " +
ame.equalsIgnoreCase("jonathan"));
char charArr[] = "Hi XX".toCharArray();
"Jonathan".getChars(0, 2, charArr, 3);
System.out.print("getChars method: "); System.out.println(charArr);
System.out.println("Length of name: " + name.length());
System.out.println("Replace a's with e's in name: " + name.replace('a', 'e'));
System.out.println("A substring of name: " + name.substring(0, 2));
System.out.println("Trim \" a b c d e f \": \"" + " a b c d e f ".trim() + "\"");
System.out.println("String representation of boolean expression 10>10: " + String.valueOf(10>10));
System.out.println("String representation of boolean expression 10<10: " + (10<10));
System.out.println("name: " + name);}}
name: Jonathan
3rd character of name: n
Jonathan compared to Solomon: -9
Solomon compared to Jonathan: 9
Jonathan compared to jonathan: -32
Jonathan compared to jonathan (ignore case): 0
Is Jonathan equal to Jonathan? true
Is Jonathan equal to jonathan? false
Is Jonathan equal to jonathan (ignore case)? true
content of charArr after getChars method: Hi Jo
Length of name: 8
Replace a's with e's in name: Jonethen
A substring of name: Jo
Trim " a b c d e f ": "a b c d e f"
String representation of boolean expression 10>10: false
String representation of boolean expression 10<10: false
name: Jonathan
class Sample2

public static void main(String[]args){

String name, first, middle , last, space, monogram;
space= ;
name = JOptionPane.showInputDialog(Enter your full name (first, middle, last): );
first = name.substring(0, name.indexOf(space));
name = name.substring(name.indexOf(space)+1, name.length());
middle = name.substring(0,name.indexOf(space));
last = name.substring(name.indexOf(space)+1, name.length());

monogram = first.substring(0,1) + middle.substring(0,1) + last.substring(0,1);

JOptionPane.showMessageDialog(null, Your monogram is + monogram);


}}
public int capacity()
Returns the current capacity of this StringBuffer object.
public StringBuffer append(-)
Appends the string representation of the argument to this StringBuffer object. Takes in single parameter which may be of these
data types: boolean, char, char [], double, float, int, long, Object, String and StringBuffer. Still has another overloaded version.
public char charAt(int index)
Returns the character located in the specified index.
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Gets the characters from this object starting at the srcBegin index up to the srcEnd index and copies these characters to the dst
array starting at the dstBegin index.
public StringBuffer delete(int start, int end)
Deletes the characters within the specified range.
public StringBuffer insert(int offset, -)
Inserts the string representation of the second argument at the specified offset. A overloaded method. Possible data types for
the second argument: boolean, char, char [], double, float, int, long, Object and String. Still has another overloaded version.
public int length()
Returns the number of characters in this StringBuffer object.
public StringBuffer replace(int start, int end, String str)
Replaces part of this object, as specified by the first two arguments, with the specified string str.
public String substring(int start, int end)
Returns the substring of this string starting at the specified start index up to the end index.
public String toString()
Converts this object to its string representation.
class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Jonathan");
System.out.println("sb = " + sb);
/* initial capacity is 16 */
System.out.println("capacity of sb: " + sb.capacity());
System.out.println("append \'O\' to sb: " + sb.append("O"));
System.out.println("sb = " + sb);
System.out.println("3rd character of sb: " + sb.charAt(2));
char charArr[] = "Hi XX".toCharArray();
/* Need to add 1 to the endSrc index of getChars */
sb.getChars(0, 2, charArr, 3);
System.out.print("getChars method: ");
System.out.println(charArr);
System.out.println("Insert \'jo\' at the 3rd cell: " + sb.insert(2, "jo"));
System.out.println("Delete \'jo\' at the 3rd cell: " + sb.delete(2,4));
System.out.println("length of sb: " + sb.length());
System.out.println("replace: " + sb.replace(3, 9, " Ong"));
/* Need to add 1 to the endIndex parameter of substring*/
System.out.println("substring (1st two characters): " + sb.substring(0, 3));
System.out.println("implicit toString(): " + sb);}}
sb = Jonathan
capacity of sb: 24
append 'O' to sb: JonathanO
sb = JonathanO
3rd character of sb: n
getChars method: Hi Jo
Insert 'jo' at the 3rd cell: JojonathanO
Delete 'jo' at the 3rd cell: JonathanO
length of sb: 9
replace: Jon Ong
substring (1st two characters): Jon
implicit toString(): Jon Ong
Curve Plotting

( ) 3 8
2
+ = x y
import java.io.*;
public class Sample1 {
public static void main(String[] args) throws IOException{
int x,y;
//71 spaces
StringBuffer line = new StringBuffer ("| ");
for (x=1;x<=15;x++){
y= (int) Math.pow(x-8,2.0)+3;
line.setCharAt(y,'*');//set the character to an asterisk
System.out.println(line);
line.setCharAt(y,' '); //reset character to a blank
}
}
}
| *
| *
| *
| *
| *
| *
| *
| *
| *
| *
| *
| *
| *
| *
| *
object representations of simple non-object
variables
Can use to declare reference data type
Can access methods of the Object Class
unlike the primitive data types


class Test {
static void Swap(Integer j, Integer k) {
int tmp = k.intValue();
k = new Integer(j.intValue());
j = new Integer(tmp);
}

public static void main(String[] args) {
Integer n = new Integer(5), m = new Integer(6);
Swap(n, m);
System.out.println("n = " + n + "; m = " + m);
}
}
Character class offers a number of useful
class (i.e., static) methods for manipulating
characters. You can create a Character object
with the Character constructor:

Character ch = new Character('a');
public static boolean isDigit(char ch)
Returns true if ch is a digit; otherwise, it returns a false
public static boolean isLetter(char ch)
Returns true if ch is a letter; otherwise, it returns a false
public static boolean isLowerCase(char ch)
Returns true if ch is a lowercase letter; otherwise, it returns a false
public static boolean isUpperCase(char ch)
Returns true if ch is a uppercase letter; otherwise, it returns a false
public static boolean isSpaceChar(char ch)
Returns true if ch is a space character; otherwise, it returns a false
public static boolean isWhiteSpace(char ch)
Returns true if ch is a Java-defined whitespace; otherwise, it returns a false
public static char toLowerCase(char ch)
Returns the lowercase equivalent of ch
public static char toUpperCase(char ch)
Returns the uppercase equivalent of ch
public static char toString(char ch)
Returns the String representation of ch





Character c1 = new Character ('A');
Character c2 = new Character ('B');
Character c3 = new Character ('A');
System.out.println ("c1.compareTo (c2): " + c1.compareTo (c2));
System.out.println ("c1.equals (c2): " + c1.equals (c2));
System.out.println ("c1.equals (c3): " + c1.equals (c3));
System.out.println (Character.isDigit ('4')); // Output: true
System.out.println (Character.isLetter (';')); // Output: false
System.out.println (Character.isUpperCase ('X')); // Output: true
System.out.println (Character.toLowerCase ('B')); // Output: b
System.out.println (Character.toUpperCase ('a')); // Output: A
class BooleanWrapper {
public static void main(String args[]) {
boolean booleanVar = 1>2;
Boolean booleanObj = new Boolean("TRue");
/* primitive to object; can also use valueOf method */
Boolean booleanObj2 = new Boolean(booleanVar);
System.out.println("booleanVar = " + booleanVar);
System.out.println("booleanObj = " + booleanObj);
System.out.println("booleanObj2 = " + booleanObj2);
System.out.println("compare 2 wrapper objects: " +
booleanObj.equals(booleanObj2));
/* object to primitive */
booleanVar = booleanObj.booleanValue();
System.out.println("booleanVar = " + booleanVar);
}
}
Sample Output
booleanVar = false
booleanObj = true
booleanObj2 = false
compare 2 wrapper objects: false
booleanVar = true
Process Class
provides methods for manipulating processes
such as killing the process, running the process
and checking the status of the process.
This class represents running programs
Runtime Class
represents the runtime environment.
Two important methods in the class are the
getRuntime and the exec method
Process Methods
public abstract void destroy()
Kills the current process.
public abstract int waitFor() throws InterruptedException
Does not exit until this process terminates.
Runtime Methods
public static Runtime getRuntime()
Returns the runtime environment associated with the current Java
application.
public Process exec(String command) throws IOException
Causes the specified command to be executed. Allows you to execute
new processes.
class RuntimeDemo {
public static void main(String args[]) {
Runtime rt = Runtime.getRuntime();
Process proc;
try {
proc = rt.exec("regedit");
proc.waitFor(); //try removing this line
} catch (Exception e) {
System.out.println("regedit is an unknown command.");
}
}
}
provides many useful fields and methods
such as the standard input, the standard
output and a utility method for fast copying
of a part of an array. Here are some
interesting methods from the class. Note that
all the class's methods are static.
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int
length)
Copies length items from the source array src starting at srcPos to dest starting at index destPos.
Faster than manually programming the code for this yourself.
public static long currentTimeMillis()
Returns the difference between the current time and January 1, 1970 UTC. Time returned is
measured in milliseconds.
public static void exit(int status)
Kills the Java Virtual Machine (JVM) running currently. A non-zero value for status by
convention indicates an abnormal exit.
public static void gc()
Runs the garbage collector, which reclaims unused memory space for recycling.
public static void setIn(InputStream in)
Changes the stream associated with System.in, which by default refers to the keyboard.
public static void setOut(PrintStream out)
Changes the stream associated with System.out, which by default refers to the console.
import java.io.*;
class SystemDemo {
public static void main(String args[]) throws IOException {
int arr1[] = new int[5000000];
int arr2[] = new int[5000000];
long startTime, endTime;
/* initialize arr1 */
for (int i = 0; i < arr1.length; i++) {
arr1[i] = i + 1;
}
/* copying manually */
startTime = System.currentTimeMillis();
for (int i = 0; i < arr1.length; i++) {
arr2[i] = arr1[i];
}
endTime = System.currentTimeMillis();
System.out.println("Time for manual copy: " +
(endTime-startTime) + " ms.");
/* using the copy utility provided by java the
arraycopy method */
startTime = System.currentTimeMillis();
System.arraycopy(arr1, 0, arr2, 0, arr1.length);
endTime = System.currentTimeMillis();
System.out.println("Time w/the use of arraycopy: " + (endTime-startTime) + " ms.");
System.gc(); //force garbage collector to work
System.setIn(new FileInputStream("temp.txt"));
/* in NetBeans, temp.txt should be locate in the project folder */
System.exit(0);
}
}
Sample Output
Time for manual copy: 32 ms.
Time w/the use of arraycopy: 31 ms.
The format Method

The format method formats multiple arguments based on a format
string. The format string consists of static text embedded with format
specifiers; except for the format specifiers, the format string is output
unchanged. All format specifiers begin with a % and end with a 1- or 2-
character conversion that specifies the kind of formatted output being
generated.

Conversion formats:
d - formats an integer value as a decimal value.
f - formats a floating point value as a decimal value.
n - outputs a platform-specific line terminator.
x - formats an integer as a hexadecimal value.
s - formats any value as a string.
tB - formats an integer as a locale-specific month name.


Code Segment:
int i = 2;
double r = Math.sqrt(i);
System.out.println("The square root of "+ i + " is "+ r);
System.out.format("The square root of %d is %.2f", i, r);
Output:
The square root of 2 is 1.4142135623730951
The square root of 2 is 1.41
Using Predefined Formats
NumberFormat Class-
an abstract base class for all number formats
provides method to format numbers, currencies, and percentages according to Locale.

To format a number for the current Locale, use one of the factory class methods:

myString = NumberFormat.getInstance().format(myNumber);

If you are formatting multiple numbers, it is more efficient to get the format and use it multiple times
so that the system doesn't have to fetch the information about the local language and country
conventions multiple times.

NumberFormat nf = NumberFormat.getInstance();
for (int i = 0; i < myNumber.length; ++i)
{ output.println(nf.format(myNumber[i]) + "; "); }

To format a number for a different Locale, specify it in the call to getInstance.

NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);

You can also use a NumberFormat to parse numbers:

myNumber = nf.parse(myString);
Currencies

If you are writing business applications, you will probably need to format and display
currencies. You format currencies in the same manner as numbers, except that you
call getCurrencyInstance to create a formatter. When you invoke the format method, it
returns a String that includes the formatted number and the appropriate currency sign.

Double currencyAmount = new Double(9876543.21);
Currency currentCurrency = Currency.getInstance(currentLocale);
NumberFormat currencyFormatter =
NumberFormat.getCurrencyInstance(currentLocale);

System.out.println(currentLocale.getDisplayName()+ ", " + currentCurrency.getDisplayName()
+ ": " + currencyFormatter.format(currencyAmount));

Use getInstance or getNumberInstance to get the normal number format.
Use getIntegerInstance to get an integer number format. Use getCurrencyInstance to get
the currency number format. And use getPercentInstance to get a format for displaying
percentages.

Integer quantity = new Integer(123456);
Double amount = new Double(345987.246);
NumberFormat numberFormatter;
String quantityOut;
String amountOut;

numberFormatter = NumberFormat.getNumberInstance(currentLocale);
quantityOut = numberFormatter.format(quantity);
amountOut = numberFormatter.format(amount);
System.out.println(quantityOut + " " + currentLocale.toString());
System.out.println(amountOut + " " + currentLocale.toString());
DecimalFormat Class
a concrete subclass of NumberFormat that formats decimal numbers.
It has a variety of features designed to make it possible to parse and
format numbers in any locale, including support for Western, Arabic,
and Indic digits. It also supports different kinds of numbers, including
integers (123), fixed-point numbers (123.4), scientific notation
(1.23E4), percentages (12%), and currency amounts ($123). All of these
can be localized.

Constructing Patterns
You specify the formatting properties of DecimalFormat with a
pattern String.


DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);

import java.text.DecimalFormat;

public class DecimalFormatExample {

public static void main(String args[]) {

//formatting numbers upto 2 decimal places in Java
DecimalFormat df = new DecimalFormat("#,###,##0.00");
System.out.println(df.format(364565.14));
System.out.println(df.format(364565.1454));

//formatting numbers upto 3 decimal places in Java
df = new DecimalFormat("#,###,##0.000");
System.out.println(df.format(364565.14));
System.out.println(df.format(364565.1454));
}

}


Output:
364,565.14
364,565.15
364,565.140
364,565.145



Date Class
A wrapper for a date.
This class lets you manipulate dates in a system independent
way.
To print today's date use:

Date d = new Date();
System.out.println("today = " + d);

To find out what day corresponds to a particular date:

Date d = new Date(63, 0, 16); // January 16, 1963
System.out.println("Day of the week: " + d.getDay());
Date()
Creates today's date/time.
Date(long date)
Date(int year, int month, int date)
Date(int year, int month, int date, int hour, int minutes)
Date(int year, int month, int date, int hour, int minutes, int seconds)
Date(String date)
Creates a date from a string according to the syntax
accepted by parse().
UTC(int, int, int, int, int, int) Calculates a
UTC value from YMDHMS.
after(Date) Checks whether this date
comes after the specified date.
before(Date) Checks whether this date
comes before the specified date.
equals(Object) Compares this object
against the specified object.
getDate() Returns the day of the month.
getDay() Returns the day of the week.
getHours()Returns the hour.
getMinutes() Returns the minute.
getMonth() Returns the month.
getSeconds() Returns the second.
getTime() Returns the time in
milliseconds since the epoch.
getTimezoneOffset() Return the time
zone offset in minutes for the current
locale that is appropriate for this time.
getYear() Returns the year after 1900.
parse(String) Given a string representing a
time, parse it and return the time value.
setDate(int) Sets the date.
setDay(int) Sets the day of the week.
setHours(int) Sets the hours.
setMinutes(int) Sets the minutes.
setMonth(int) Sets the month.
setSeconds(int) Sets the seconds.
setTime(long) Sets the time.
setYear(int) Sets the year.
toString() Converts a date to a String,
using the UNIX ctime conventions.

DateFormat
an abstract class for date/time formatting subclasses
which formats and parses dates or time in a language-
independent manner.
provides many class methods for obtaining default
date/time formatters based on the default or a given
loacle and a number of formatting styles. The
formatting styles include FULL, LONG, MEDIUM, and
SHORT.
To format a date for the current Locale, use one of the
static factory methods:

myString = DateFormat.getDateInstance().format(myDate);
Use getDateInstance to get the normal date format for
that country. There are other static factory methods
available. Use getTimeInstance to get the time format for
that country. Use getDateTimeInstance to get a date and
time format. You can pass in different options to these
factory methods to control the length of the result; from
SHORT to MEDIUM to LONG to FULL. The exact result
depends on the locale, but generally:

SHORT is completely numeric, such as 12.13.52 or 3:30pm
MEDIUM is longer, such as Jan 12, 1952
LONG is longer, such as January 12, 1952 or 3:30:32pm
FULL is pretty completely specified, such as Tuesday, April
12, 1952 AD or 3:30:42pm PST.

import java.text.DateFormat;
import java.util.Date;
public class DateFormatExample1 {

public static void main(String[] args) {
Date now = new Date();
System.out.println(" 1. " + now.toString());
System.out.println(" 2. " + DateFormat.getInstance().format(now));
System.out.println(" 3. " + DateFormat.getTimeInstance().format(now));
System.out.println(" 4. " + DateFormat.getDateTimeInstance().format(now));
System.out.println(" 5. " +
DateFormat.getTimeInstance(DateFormat.SHORT).format(now));
System.out.println(" 6. " +
DateFormat.getTimeInstance(DateFormat.MEDIUM).format(now));
System.out.println(" 7. " +
DateFormat.getTimeInstance(DateFormat.LONG).format(now));
System.out.println(" 8. " + DateFormat.getDateTimeInstance(DateFormat.SHORT,
DateFormat.SHORT).format(now));
System.out.println(" 9. " + DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
DateFormat.SHORT).format(now));
System.out.println("10. " + DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.LONG).format(now));
}}

SimpleDateFormat
a concrete class for formatting and parsing dates
in a locale-sensitive manner. It allows for
formatting (date -> text), parsing (text -> date),
and normalization.
allows you to start by choosing any user-defined
patterns for date-time formatting

public class SimpleDateFormatExample {

public static void main(String[] args) {

Date now = new Date();
String datetimeStr = now.toString();
System.out.println("1. " + datetimeStr);
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
System.out.println("2. " + format.format(now));
}

}

The output is
1. Fri Jun 27 21:28:16 EDT 2008
2. Fri Jun 27 21:28:16 EDT 2008
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {

public static void main(String args[]) {

Date today = new Date(); // This is how to get today's date in Java
System.out.println("Today is : " + today); //If you print Date, you will get un formatted output

//formatting date in Java using SimpleDateFormat
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy");
String date = DATE_FORMAT.format(today);
System.out.println("Today in dd-MM-yyyy format : " + date);

//Another Example of formatting Date in Java using SimpleDateFormat
DATE_FORMAT = new SimpleDateFormat("dd/MM/yy");
date = DATE_FORMAT.format(today);
System.out.println("Today in dd/MM/yy pattern : " + date);

//formatting Date with time information
DATE_FORMAT = new SimpleDateFormat("dd-MM-yy:HH:mm:SS");
date = DATE_FORMAT.format(today);
System.out.println("Today in dd-MM-yy:HH:mm:SS : " + date);

//SimpleDateFormat example - Date with timezone information
DATE_FORMAT = new SimpleDateFormat("dd-MM-yy:HH:mm:SS Z");
date = DATE_FORMAT.format(today);
System.out.println("Today in dd-MM-yy:HH:mm:SSZ : " + date);
} }
Calendar class is an abstract class that provides methods for converting between
a specific instant in time and a set of calendar fields such
as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating
the calendar fields, such as getting the date of the next week.

provides internationalization support.

Like other locale-sensitive classes, Calendar provides a class
method, getInstance, for getting a generally useful object of this
type. Calendar's getInstance method returns a Calendar object whose calendar
fields have been initialized with the current date and time:

Calendar.getInstance(): return a Calendar instance based on the current time in the default
time zone with the default locale.
Calendar.getInstance(TimeZone zone)
Calendar.getInstance(Locale aLocale)
Calendar.getInstance(TimeZone zone, Locale aLocale)

Calendar rightNow = Calendar.getInstance();



The most important method in Calendar is get(int calendarField), which produces
an int. The calendarField are defined as static constant and includes:

get(Calendar.DAY_OF_WEEK): returns 1 (Calendar.SUNDAY) to 7 (Calendar.SATURDAY).
get(Calendar.YEAR): year
get(Calendar.MONTH): returns 0 (Calendar.JANUARY) to 11 (Calendar.DECEMBER).
get(Calendar.DAY_OF_MONTH), get(Calendar.DATE): 1 to 31
get(Calendar.HOUR_OF_DAY): 0 to 23
get(Calendar.MINUTE): 0 to 59
get(Calendar.SECOND): 0 to 59
get(Calendar.MILLISECOND): 0 to 999
get(Calendar.HOUR): 0 to 11, to be used together with Calendar.AM_PM.
get(Calendar.AM_PM): returns 0 (Calendar.AM) or 1 (Calendar.PM).
get(Calendar.DAY_OF_WEEK_IN_MONTH): DAY_OF_MONTH 1 through 7 always
correspond to DAY_OF_WEEK_IN_MONTH 1; 8 through 14 correspond
to DAY_OF_WEEK_IN_MONTH 2, and so on.
get(Calendar.DAY_OF_YEAR): 1 to 366
get(Calendar.ZONE_OFFSET): GMT offset value of the time zone.
get(Calendar.ERA): Indicate AD (GregorianCalendar.AD), BC (GregorianCalendar.BC).

Calendar has these setters and operations:
void set(int calendarField, int value)
void set(int year, int month, int date)
void set(int year, int month, int date, int hour, int minute, int second)
void add(int field, int amount): Adds or subtracts the specified amount of time
to the given calendar field, based on the calendar's rules.
void roll(int calendarField, boolean up): Adds or subtracts (up/down) a single
unit of time on the given time field without changing larger fields.
void roll(int calendarField, int amount): Adds the specified (signed) amount to
the specified calendar field without changing larger fields.
Other frequently-used methods are:
Date getTime(): return a Date object based on this Calendar's value.
void setTime(Date date)
long getTimeInMills(): Returns this Calendar's time value in milliseconds.
void setTimeInMillis(long millis)
void setTimeZone(TimeZone value)

import java.util.Calendar;
public class GetYMDHMS {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
// You cannot use Date class to extract individual Date fields
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH); // 0 to 11
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);

System.out.printf("Now is %4d/%02d/%02d %02d:%02d:%02d\n", // Pad with
zero
year, month+1, day, hour, minute, second);
}

The calendar that we use today, called Gregorian calendar, came
into effect in October 15, 1582 in some countries and later in other
countries. It replaces the Julian calendar. 10 days were removed
from the calendar, i.e., October 4, 1582 (Julian) was followed by
October 15, 1582 (Gregorian).
The only difference between the Gregorian and the Julian calendar
is the "leap-year rule".
In Julian calendar, every four years is a leap year. In Gregorian
calendar, a leap year is a year that is divisible by 4 but not divisible
by 100, or it is divisible by 400, i.e., the Gregorian calendar omits
century years which are not divisible by 400 (removing 3 leap years
(or 3 days) for every 400 years).
Furthermore, Julian calendar considers the first day of the year as
march 25th, instead of January 1st.
java.util.Calendar is an abstract class.
Calendar.getInstance() returns an implementation
class java.util.GregorianCalendar (except locales of "th" and "jp").
In Java, thisGregorianCalendar handles both the Gregorian calendar as well as
the Julian calendar, including the cut over.

GregorianCalendar has the following constructors:
GregorianCalendar(): using the current time, with the default time zone and locale.
GregorianCalendar(int year, int month, int dayOfMonth): with the default time zone and
locale.
GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, int
second)
GregorianCalendar(TimeZone zone, Locale aLocale): using current time.
GregorianCalendar(TimeZone zone)
GregorianCalendar(Locale aLocale)
For example,
Calendar cal1 = new GregorianCalendar(); // allocate an instance and upcast to Calendar
Calendar cal2 = new GregorianCalendar(2010, 9, 26); // allocate with the specified date
cal2.get(Calendar.DAY_OF_WEEK);
The java.util.Scanner class is a simple text
scanner which can parse primitive types and
strings using regular expressions.
A Scanner breaks its input into tokens using a
delimiter pattern, which by default matches
whitespace. The resulting tokens may then be
converted into values of different types using
the various next methods.
There are two constructors that are particularly
useful: one takes an InputStream object as a
parameter and the other takes a FileReader object
as a parameter.

Scanner in = new Scanner(System.in); // System.in is an
InputStream

Scanner inFile = new Scanner(new FileReader("myFile"));
Numeric and String Methods

int nextInt()
Returns the next token as an int. If the next token is not an integer,InputMismatchException is thrown.
long nextLong()
Returns the next token as a long. If the next token is not an integer,InputMismatchException is thrown.
float nextFloat()
Returns the next token as a float. If the next token is not a float or is out of
range, InputMismatchException is thrown.
double nextDouble()
Returns the next token as a long. If the next token is not a float or is out of range, InputMismatchException is
thrown.
String next()
Finds and returns the next complete token from this scanner and returns it as a string; a token is usually
ended by whitespace such as a blank or line break. If not token exists,NoSuchElementException is thrown.
String nextLine()
Returns the rest of the current line, excluding any line separator at the end.
void close()
Closes the scanner.

For example, given the following code
segment and data

int number = in.nextInt();
float real = in.nextFloat();
long number2 = in.nextLong();
double real2 = in.nextDouble();
String string = in.next();

import java.util.Scanner;
import java.io.*; // Access System.out
public class NumericInput
{
public static void main(String[] args)
{
// Declarations
Scanner in = new Scanner(System.in);
int integer; long longInteger;
float realNumber; double doubleReal;
String string1; String string2;

// Prompts
System.out.println("Enter an integer, a long integer, + "a floating-point ");
System.out.println("number, another floating-point number, + "and a string.");
System.out.println("Separate each with a blank or return.");

// Read in values
integer = in.nextInt();
longInteger = in.nextLong();
realNumber = in.nextFloat();
doubleReal = in.nextDouble();
string1 = in.nextLine();
System.out.println("Now enter another value.");
string2 = in.next();

System.out.println("Here is what you entered: ");
System.out.println(integer + " " + longInteger + " " + realNumber + " " + doubleReal + " " + string1 + " and " + string2);
}
}

You might also like