Core Java - Unit 4
Core Java - Unit 4
class Exc2 {
public static void main(String args[]) {
int d, a;
Output:
Division by zero.
After catch statement.
import java.util.Random;
class HandleError {
public static void main(String args[]) {
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<32000; i++) {
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
}
catch (ArithmeticException e) {
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}
}
3) // Demonstrate multiple catch statements.
class MultipleCatches {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
Output 1:
C:\>java MultipleCatches
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
5) Throw :
Syntax : throw ThrowableInstance.
// Demonstrate throw.
class ThrowDemo {
7) finally Example :
// Demonstrate finally.
class FinallyDemo {
// Throw an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
}
finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.
procB();
procC();
}
}
Output :
inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procC's finally
Multy Threading
class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
class ThreadDemo {
public static void main(String args[ ] ) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
class MultiThreadDemo {
public static void main(String args[]) {
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try {
// wait for other threads to end
Thread.sleep(10000);
}
catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
4) Thread Priorities :
final void setPriority(int level)
final int getPriority( )
The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10,
respectively. To return a thread to default priority, specify NORM_PRIORITY, which is currently 5.
5) Write about thread synchronization:
When two or more threads access to a shared( common) resource, they need some way to ensure that the resource will be used
by only one thread at a time. The process by which this is achieved is called synchronization. We can synchronize our code in two ways.
Both involve the use of ―synchronized‖ keyword
a) synchronized methods
b) synchronized code blocks
a) synchronized methods :
We can serialize the access to the methods to only one thread at a time. To do this you simply need to precede the method’s
definition with the keyword synchronized.
synchronized void meth( )
{
Some thread work;
}
When we declare a method synchronized, java creates a ―monitor‖ and hands it over the thread that calls method first time. As
long as the thread holds the monitor, no other thread can enter the synchronized section of code.
wait():
The method tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and
calls notify( ).
Syntax: final void wait( ) throws InterruptedException
notify():
Wakes up the first thread that called wait( ) on the same object. The Object class declaration of this method is:
Syntax: final void notify( )
notifyAll():
Strings
Ex :
Ex :
Output : ABCDEF
CDE
String Operations :
1) String Length
Synt : int length( )
The following fragment prints "3", since there are three characters in the string s:
Ex: char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
2) String Literals
char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars);
String s2 = "abc"; // use string literal
Note : System.out.println("abc".length());
3) String Concatenation :
Ex:
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
Output : "He is 9 years old."
Output : four: 22
Character Extraction :
1) charAt( )
Ex : char ch;
ch = "abc".charAt(1);
2) getChars( )
Syntax : void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
Ex :
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
Output :
Demo
3) getBytes( )
Syntax : byte[ ] getBytes( )
4) toCharArray()
String Comparison :
2) regionMatches( ) :
Syn : i) boolean regionMatches(int startIndex, String str2,int str2StartIndex, int numChars)
ii) boolean regionMatches(boolean ignoreCase,int startIndex, String str2,int str2StartIndex, int numChars)
4) equals( ) Versus == :
Ex : class EqualsNotEqualTo {
public static void main(String args[]) {
II String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
Output : Hello equals Hello -> true
Hello == Hello -> false
5) compareTo( ) :
Synt : int compareTo(String str)
Value Meaning
Less than zero The invoking string is less than str.
Greater than zero The invoking string is greater than str.
Zero The two strings are equal.
Searching Strings :
Ex :
// Demonstrate indexOf() and lastIndexOf().
class indexOfDemo {
public static void main(String args[]) {
String s = "Now is the time for all good men " +
"to come to the aid of their country.";
System.out.println(s);
System.out.println("indexOf(t) = " +
s.indexOf('t'));
System.out.println("lastIndexOf(t) = " +
s.lastIndexOf('t'));
System.out.println("indexOf(the) = " +
s.indexOf("the"));
System.out.println("lastIndexOf(the) = " +
s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " +
s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " +
s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " +
s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " +
s.lastIndexOf("the", 60));
}
}
1) substring( ) :
Sysntax : String substring(int startIndex);
String substring(int startIndex, int endIndex)
Ex :
// Substring replacement.
class StringReplace {
public static void main(String args[]) {
String org = "This is a test. This is, too.";
String search = "is";
String sub = "was";
String result = "";
int i;
do { // replace all matching substrings
System.out.println(org);
i = org.indexOf(search);
if(i != -1) {
result = org.substring(0, i);
result = result + sub;
result = result + org.substring(i + search.length());
org = result;
}
} while(i != -1);
}
}
Output :
This is a test. This is, too.
Thwas is a test. This is, too.
Thwas was a test. This is, too.
Thwas was a test. Thwas is, too.
Thwas was a test. Thwas was, too.
2) concat( ) :
Syn: String concat(String str)
Ex : String s1 = "one";
String s2 = s1.concat("two");
3) replace( ) :
Syn: String replace(char original, char replacement)
Ex: String s = "Hello".replace('l', 'w');
4) trim( ) :
Syn: String trim( )
Ex: String s = " Hello World ".trim();
Vector class :
Ex:
// Demonstrate various Vector operations.
import java.util.*;
class VectorDemo {
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector<Integer> v = new Vector<Integer>(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +
v.capacity());
v.addElement(1);
v.addElement(2);
v.addElement(3);
v.addElement(4);
System.out.println("Capacity after four additions: " +
v.capacity());
v.addElement(5);
CORE JAVA EXAMPLES PGK
System.out.println("Current capacity: " +
v.capacity());
v.addElement(6);
v.addElement(7);
System.out.println("Current capacity: " +
v.capacity());
v.addElement(9);
v.addElement(10);
System.out.println("Current capacity: " +
v.capacity());
v.addElement(11);
v.addElement(12);
System.out.println("First element: " + v.firstElement());
System.out.println("Last element: " + v.lastElement());
if(v.contains(3))
System.out.println("Vector contains 3.");
// Enumerate the elements in the vector.
Enumeration<Integer> vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
Output:
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5 6 7 9 10 11 12