SlideShare a Scribd company logo
1 of 102
Download to read offline
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
1
String and Stringbuffer
The java.lang package contains two string classes String and Stringbuffer
❖ String class
A combination of character is a string.
The String Constructors
1.String(); =>Empty Constructor
2.String(char chars[ ])
3.String(char chars[ ], int startIndex, int numChars)
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
This initializes s with the characters cde.
4.String(String strObj)
Here, strObj is a String object. Consider this example:
class MakeString
{
public static void main(String args[])
{
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
The output from this program is as follows:
Java
Java
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
2
String Methods
1.Length()
The length of a string is the number of characters that it contains.
int length( )
The following fragment prints “3”, since there are three characters in the string s:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
2.String Concatenation
Using + operations.
For example, the following fragment concatenates three strings:
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
This displays the string “He is 9 years old.”
3.toString( ) method
Syntax
String toString( )
The toString() method returns the string representation of the object. If you print
any object, java compiler internally invokes the toString() method on the object. So
overriding the toString() method, returns the desired output in the form of string.
class Student
{
int rollno;
String name;
Student(int r, String s)
{
rollno=r;
name=s;
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
3
}
public String toString()
{
return rollno+" "+name+;
}
public static void main(String args[])
{
Student s1=new Student(101,"vision");
System.out.println(s1);//compiler writes here s1.toString()
}
}
Character Extraction
1.charAt( )
To extract a single character from a String.
char charAt(int where)
char ch;
String s=”abc”;
ch = s.charAt(1);
assigns the value “b” to ch.
❖ String Comparison
1.equals( ) and equalsIgnoreCase( )
To compare two strings for equality, use equals( ). It
returns true if the strings contain the same characters in the same order, and false
otherwise.
It has this general form:
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
4
boolean equals(String str) => The comparison is case-sensitive.
boolean equalsIgnoreCase(String str)=> The comparison is not case-sensitive.
String s1 = "Hello";
String s2 = "HELLO";
If(s1.equals(s2))
System.out.println(“equals”);
Else
System.out.println(“not equals”);
If(s1.equalsIgnoreCase(s4))
System.out.println(“equals”);
Else
System.out.println(“not equals”);
2.startsWith( ) and endsWith( )
boolean startsWith(String str)
boolean endsWith(String str)
String s="Foobar"
s.endsWith("bar")
s.startsWith("Foo")
are both true.
3.equals( ) Versus ==
The equals( ) method compares the characters inside a String object.
The == checks to see if the 2 object names are basically references to the same
memory location.
// equals() vs = =
String s1 = "Hello";
String s2 = new String(s1);
if(s1.equals(s2))
System.out.println(“equals”);
Else
System.out.println(“not equals”);
if(s1==s2)
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
5
System.out.println(“equals”);
Else
System.out.println(“not equals”);
String obj1 = new String("xyz");
// now obj2 and obj1 reference the same place in memory
String obj2 = obj1;
if(obj1 == obj2)
System.out.printlln("TRUE");
else
System.out.println("FALSE");
4.compareTo( )
It has this general form:
int compareTo(String str)
Here, str is the String being compared with the invoking String. The result of the
comparison is returned and is interpreted as shown here:
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.
e.g String s1=”hello”
int k=s1.compareTo(“hello”)
o/p 0
Substring():It return substring
String substring(int startIndex)
String substring(int startIndex, int endIndex)
1.Concat( )
String concat(String str)
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
6
String s1 = "one";
String s2 = s1.concat("two");
puts the string “onetwo” into s2.
2.replace( )
The replace( ) method replaces all occurrences of one character in the invoking string
with another character.
String replace(char original, char replacement)
String s1=”hello”
String s = s1.replace('l', 'w');
❖ Changing the Case of Characters
The method toLowerCase( ) converts all the characters in a string from uppercase to
lowercase. The toUpperCase( ) method converts all the characters in a string from
lowercase to uppercase.
Sring toLowerCase( )
String toUpperCase( )
String s = "This is a test.";
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
7
❖ StringBuffer
• A string buffer is mutable(Once the string object is creatred,the object can be changed).
StringBuffer Constructors
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
1.append( )
The append( ) method concatenates the string representation of any other type of data
to the end of the invoking StringBuffer object. It has overloaded versions for all the
built-in types and for Object.
Here are a few of its forms:
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
int a = 42;
StringBuffer sb = new StringBuffer(40);
sb = sb.append("a = ").
sb = sb.append(a).
System.out.println(sb);
2.insert( )
The insert( ) method inserts one string into another.
These are a few of its forms:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
8
System.out.println(sb);
The output of this example is shown here:
I like Java!
3.reverse( )
You can reverse the characters within a StringBuffer object using reverse( )
StringBuffer reverse( )
StringBuffer s = new StringBuffer("abcdef");
s.reverse();
System.out.println(s);
4.delete( ) and deleteCharAt( )
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
StringBuffer sb = new StringBuffer("This is a test.");
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
The following output is produced:
After delete: This a test.
After deleteCharAt: his a test.
5.replace( )
StringBuffer replace(int startIndex, int endIndex, String str)
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
Here is the output:
After replace: This was a test.
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
9
STRING STRINGBUFFER
The length of the String object is
fixed.
The length of the StringBuffer can be increased.
String object is immutable. StringBuffer object is mutable.
It is slower during concatenation. It is faster during concatenation.
Consumes more memory. Consumes less memory.
String s=new String(“vision”) StringBuffer sb=new StringBuffer(“vision)
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
10
JAVA UTIL PACKAGE
Date
Date supports the following constructors:
Date( )
Date(long millisec)
// Show date and time using only Date methods.
import java.util.Date;
class DateDemo
{
public static void main(String args[])
{
// Instantiate a Date object
Date date = new Date();
System.out.println(date);
}
}
Sample output is shown here:
Mon Apr 22 09:51:52 CDT 2002
Random
The Random class is a generator of pseudorandom numbers. These are called
pseudorandom numbers because they are simply uniformly distributed sequences.
Random defines the following constructors:
Random( )
Random(long seed)
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
11
❖ EXCEPTION HANDLING
Error can be 2 categories
1.Compile time error:
• Missing semicolon
• Missing brackets in classes and method.
• Misspelling of identifiers and keywords
• Missing double quotes in string.
• Use of understand variable
• Incomplete types in assignments/initialization.
• Bad reference object
• Use of = in place of = = operator.
2.RunTime Errors
• Dividing an integer by zero.
• Accessing an element that is out of the bound of an array.
• Trying to store a value into an array of an incomplete class or type.
• Trying to cast an instance of a class to one of its subclass.
• Attempting to use a negative size of an array.
• Converting invalid string to a number.
class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
Or
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
12
class Exc1 {
static void subroutine() {
int d = 0;
int a = 10 / d;
}
public static void main(String args[]) {
Exc1.subroutine();
}
}
o/p
java.lang.ArithmeticException: / by zero
at Exc1.subroutine(Exc1.java:4)
at Exc1.main(Exc1.java:7)
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
13
Exception:
It is condition that is caused by run time error in the program.
The purpose of exception handling mechanism is to provide a means to detect and
report an “exception circumstance”
❖ Types Of Exception
1.Checked Exceptions
Throwable and its subclasses except Error and RuntimeException put
together are called as checked exceptions. If these exceptions are not
handled or checked by the programmer in coding, the program does not
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
14
compile. That is, compiler bothers much of this type of exceptions
because they are raised in some special cases in the code which if not
handled, the program may lead to many troubles. Common examples are
FileNotFoundException, IOException and InterruptedException etc.
2.Unchecked Exceptions
RuntimeException and its all subclasses including Error are known as
unchecked exceptions. As the name indicates, even if they are not
handled or checked by the programmer, the program simply compiles. If
at runtime, problems arise, the execution simply terminates. That is,
regarding unchecked exceptions, the compiler does not bother. Common
examples are ArithmeticException,
ArrayIndexOutOfBoundsException, NumberFormatException,
NullPointerException etc.
❖ Syntax
Java exception handling is managed via five keywords: try, catch, throw,
throws,and finally.
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
//…………….
finally
{
// block of code to be executed before try block ends
}
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
15
Using try and catch
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{
d = 0;
a = 42 / d;
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
OR
System.out.println("Error"+e);
}
}
Exception class have 2 methods
1. String getMessage();
It is method of throwable class. This methods print only the message part of the
output printed by object e.
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{
d = 0;
a = 42 / d;
}
catch (ArithmeticException e)
{
System.out.println("Error"+e.getMessage())
}
}
2. void printStackTrace();
It is method of throwable class.This method print the same message of “e” object
& line number where the exception occurred.
class Exc2
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
16
{
public static void main(String args[])
{
int d, a;
try
{
d = 0;
a = 42 / d;
}
catch (ArithmeticException e)
{
e. printStackTrace();
}
}
❖ Multiple catch Clauses
class MultiCatch
{
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);
}
}
}
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
17
Here is the output generated by running it both ways:
C:>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:>java MultiCatch TestArg
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException
After try/catch blocks.
OR
Try using exception class
class MultiCatch
{
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);
}
}
Note: The following program contains an error.A subclass must come before its
superclass in a series of catch statements. If not, unreachable code will be created
and a compile-time error will result.
class SuperSubCatch
{
public static void main(String args[])
{
try
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
18
{
int a = 0;
int b = 42 / a;
}
catch(Exception e)
{
System.out.println("error1"+e);
}
catch(ArithmeticException e)
{
System.out.println("error2"+e);
THE JAVA LANGUAGE
}
}
}
Above error solve as follow
class SuperSubCatch
{
public static void main(String args[])
{
try
{
int a = 0;
int b = 42 / a;
}
catch(ArithmeticException e)
{
System.out.println("error2"+e);
VA LANGUAGE
}
catch(Exception e)
{
System.out.println("error1"+e);
}
}
}
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
19
❖ Nested try Statements
class NestTry
{
public static void main(String args[])
{
try
{
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try
{
if(a==1)
a = a/(a-a);
if(a==2)
{
int c[] = { 1 };
c[42] = 99;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
}
}
C:>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:>java NestTry One
a = 1
Divide by 0: java.lang.ArithmeticException: / by zero
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
20
C:>java NestTry One Two
a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException
❖ Use try..catch in function
/* Try statements can be implicitly nested via
calls to methods. */
class MethNestTry
{
static void nesttry(int a)
{
try
{
if(a==1) a = a/(a-a);
if(a==2)
{
int c[] = { 1 };
c[42] = 99;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}
}
public static void main(String args[])
{
try {
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
nesttry(a);
}
catch(ArithmeticException e)
{
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
21
System.out.println("Divide by 0: " + e);
}
}
}
The output of this program is identical to that of the preceding example
❖ Finally Statement
1. Java support statement known as finally statement.
2. finally block can be used to handle any exception generated within try block.
3. When finally block is defined, that is guaranteed to execute, regardless of
whether or not an exception is thrown.
4. finally use to perform certain house-keeping operation such as closing files
and releasing resources.
5. It may be added immediately after the try block or after last catch block
shown as follow.
try
{
……………….
………..
}
finally
{
……………
……….
}
Or
try
{
……………….
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
22
………..
}
catch(…)
{
…………
……….
}
finally
{
……………
……….
}
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{
d = 0;
a = 42 / d;
}
catch (ArithmeticException e)
{
System.out.println("Error"+e);
}
Finally
{
System.out.println("finally block");
}
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
23
❖ THROW
The Java throw keyword is used to explicitly throw an exception.It can throw either
checked or uncheked exception in java by throw keyword.
Syntax
throw new throwable_subclass;
e.g
throw new NullPointerException("null exception");
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class TestExp
{
public static void main(String args[])
{
int x=5;
try
{
If (x<0)
throw new MyException(“no is negative”);
}
catch(MyException e)
{
System.out.println(e.getMessage());
}
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
24
}
}
❖ Rethrowing Exception
class ThrowDemo
{
static void demoproc()
{
try
{
T throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[])
{
try
{
demoproc();
}
catch(NullPointerException e)
{
System.out.println("Recaught: " + e);
}
}
}
throws
}
}
❖ throws
Throws keyword is used to declare that a method may throw one or some exceptions.
Thorws is used with the method signature.
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
25
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
Try
{
throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}
Here is the output generated by running this example program:
inside throwOne
caught java.lang.IllegalAccessException: demo
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
26
❖ Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible
type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an
unlocked thread.
IllegalStateException Environment or application is in incorrect state
IllegalThreadStateException Requested operation not compatible with current
thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was Encountered
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not
implement the Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or
interface.
InterruptedException One thread has been interrupted by
another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist..
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
27
Java - Collections Framework
Collection(Def):A collection allows a group of objects to be treated as a single
unit. Arbitrary objects can be stored, retrieved, and manipulated as elements
of collection.
This framework is provided in the java.util package.
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
28
Classes & Interfaces
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
29
❖ Collection Interface
SN Methods with Description
1
Boolean add(Object obj)
Adds obj to the invoking collection. Returns true if obj was added to the collection.
Returns false if obj is already a member of the collection, or if the collection does
not allow duplicates.
2
Boolean addAll(Collection c)
Adds all the elements of c to the invoking collection. Returns true if the operation
succeeded (i.e., the elements were added). Otherwise, returns false.
3
void clear( )
Removes all elements from the invoking collection.
4
Boolean contains(Object obj)
Returns true if obj is an element of the invoking collection. Otherwise, returns false.
5
Boolean containsAll(Collection c)
Returns true if the invoking collection contains all elements of c. Otherwise, returns
false.
6
Boolean equals(Object obj)
Returns true if the invoking collection and obj are equal. Otherwise, returns false.
7
Boolean isEmpty( )
Returns true if the invoking collection is empty. Otherwise, returns false.
8
Iterator iterator( )
Returns an iterator for the invoking collection.
9
Boolean remove(Object obj)
Removes one instance of obj from the invoking collection. Returns true if the
element was removed. Otherwise, returns false.
10
Boolean removeAll(Collection c)
Removes all elements of c from the invoking collection. Returns true if the
collection changed (i.e., elements were removed). Otherwise, returns false.
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
30
❖ List Interface
• It extends collection interface.
• The elements in a list are ordered. Each element, therefore, has a position in the
list.
• It can contain duplicates.
• A zero-based index can be used to access the element at the position designated
by the index value. The position of an element can change as elements are
inserted or deleted from the list.
❖ LinkedList Class
• The LinkedList implements the List interface.
• It provides a linked-list data structure.
• The elements in a linked list are ordered.
• It can contain duplicates.
Constructor
LinkedList()
import java.util.*;
class LinkedListDemo
{
public static void main(String args[])
{
LinkedList ll = new LinkedList();
ll.add("F");
ll.add("B");
ll.add("D");
System.out.println(ll);
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
31
}
}
import java.util.*;
class LinkedListDemo {
public static void main(String args[]) {
// create a linked list
LinkedList ll = new LinkedList();
// add elements to the linked list
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
// remove elements from the linked list
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: " + ll);
// remove first and last elements
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: " + ll);
// get and set a value
Object val = ll.get(2);
ll.set(2, (String) val + " Changed");
System.out.println("ll after change: " + ll);
}
}
This would produce following result:
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
32
Original contents of ll: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]
❖ ArrayList Class
• The ArrayList class implements the List interface.
• ArrayList supports dynamic arrays that can grow as needed.
• The elements in a Array list are ordered.
• It can contain duplicates.
• ArrayList gives better performance as it is non-synchronized.
• ArrayList is non-synchronized which means
• multiple threads can work on ArrayList at the same time
Constructor
ArrayList()
import java.util.*;
class ArrayListDemo
{
public static void main(String args[])
{
ArrayList al = new ArrayList();
al.add("F");
al.add("B");
al.add("D");
System.out.println(al);
}
}
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
33
ArrayList LinkedList
1) ArrayList internally uses dynamic array to
tore the elements.
LinkedList internally uses doubly linked
list to store the elements.
2) Manipulation with ArrayList is slow
because it internally uses array. If any element
is removed from the array, all the bits are
shifted in memory.
Manipulation with LinkedList is faster
than ArrayList because it uses doubly
linked list so no bit shifting is required in
memory.
3) ArrayList is better for storing and
accessing data.
LinkedList is better for manipulating
data.
4) ArrayList al = new ArrayList(); LinkedList al = new LinedList();
❖Vector class
• The class can be used to create a generic dynamic array known as vector that can
hold objects of any type and any number.(Object don’t have to be homogenous)
• The Vector class implements the List interface.
• The elements in a Vector are ordered.
• It can contain duplicates.
• Vector is synchronized. This means if one thread is working on Vector, no other
thread can get a hold of it.
• Vector operations gives poor performance as they are thread-safe
Constructor
Vector( )
Vector(int size)
Vector(int size,int incr)
import java.util.*;
class VectorDemo
{
public static void main(String args[])
{
Vector v = new Vector();
v.add("F");
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
34
v.add("B");
v.add("D");
System.out.println(v);
}
}
❖ Iterator
Need: You will want to cycle through the elements in a collection. For example, it might
want to display each element.
It can implements either the Iterator or the ListIterator interface.
Iterator is interface enables you to cycle through a collection, obtaining or removing
elements.
The Methods Declared by Iterator:
SN Methods with Description
1
boolean hasNext( )
Returns true if there are more elements. Otherwise, returns false.
2
Object next( )
Returns the next element.
3
Void remove( )
Removes the current element.
import java.util.*;
class IteratorDemo
{
public static void main(String args[])
{
ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
35
System.out.print(“Display element using iterator” );
Iterator itr = al.iterator();
while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element );
}
}
}
❖ ListIterator
ListIteratoris interface that extends Iterator to allow bidirectional traversal of a list,
and the modification of elements.
The Methods Declared by ListIterator:
SN Methods with Description
1
Void add(Object obj)
Inserts obj into the list in front of the element that will be returned by the next call to
next( ).
2
boolean hasNext( )
Returns true if there is a next element. Otherwise, returns false.
3
boolean hasPrevious( )
Returns true if there is a previous element. Otherwise, returns false.
4
Object next( )
Returns the next element. A NoSuchElementException is thrown if there is not a
next element.
5
int nextIndex( )
Returns the index of the next element. If there is not a next element, returns the size
of the list.
6
Object previous( )
Returns the previous element. A NoSuchElementException is thrown if there is not a
previous element.
7 int previousIndex( )
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
36
Returns the index of the previous element. If there is not a previous element, returns
-1.
8
Void remove( )
Removes the current element from the list. An IllegalStateException is thrown if
remove( ) is called before next( ) or previous( ) is invoked.
9
Void set(Object obj)
Assigns obj to the current element. This is the element last returned by a call to
either next( ) or previous( ).
import java.util.*;
class ListIteratorDemo
{
public static void main(String args[])
{
ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
System.out.print(“Display next element using listiterator” );
ListIterator itr = al.listIterator();
while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element );
}
System.out.print(“Display previous element using listiterator” );
while(itr.hasPrevious())
{
Object element = itr.previous();
System.out.print(element + " ");
}
}
}
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
37
ListIterator Iterator
ListIterator is interface
that extends Iterator to
allow bidirectional
traversal of a list, and the
modification of elements
Iterator is interface
enables you to cycle
through a collection,
obtaining or
removing elements
It can traverse in both the
directions (forward and
Backward).
It can traverse in
only forward
direction using
Iterator
It can use ListIterator to
traverse List only.
Iterator is used for
traversing List and
Set both.
It can add element during
traversing a list using
ListIterator.
It can not add
element during
traversing a list
using Iterator.
It can obtain indexes at
any point of time while
traversing a list using
ListIterator
It cannot obtain
indexes while using
Iterator.
Methods of ListIterator:
• add(E e)
• hasNext()
• hasPrevious()
• next()
• nextIndex()
• previous()
• previousIndex()
• remove()
• set(E e)
Methods of Iterator:
• hasNext()
• next()
• remove()
❖ Enumeration Interface
The Enumeration interface defines the methods by which you can enumerate (obtain one
at a time) the elements in a collection of objects.
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
38
boolean hasMoreElements( )
When implemented, it must return true while there are still more elements to extract, and
false when all the elements have been enumerated.
Object nextElement( )
This returns the next object in the enumeration as a generic Object reference.
import java.util.*;
class Enumeration
{
public static void main(String args[])
{
Enumeration d;
Vector v = new Vector();
v.add("C");
v.add("A");
v.add("E");
d=v.elements();
while (d.hasMoreElements())
{
System.out.println(d.nextElement());
}
}
}
❖ Set Interface
• It extends collection interface
• It does not contain duplicate
❖ SortedSet Interface
The SortedSet interface extends Set and declares the behavior of a set sorted in
ascending order.
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
39
❖ TreeSet Class
• It implements SortedSet interface that uses a tree for storage.
• Objects are stored in sorted, ascending order.
• Access and retrieval times are quite fast, which makes TreeSet an excellent choice
when storing large amounts of sorted information that must be found quickly.
Constructor
TreeSet( )
TreeSet(Comparator comp)
import java.util.*;
class TreeSetDemo {
public static void main(String args[]) {
// Create a tree set
TreeSet ts = new TreeSet();
// Add elements to the tree set
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
System.out.println(ts);
}
}
This would produce following result:
[A, B, C, D, E, F]
❖ HashSet Class
• HashSet implemets the Set interface.
• It creates a collection that uses a hash table for storage
• It does not have duplicate
• It displaying object at any order.
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
40
Constructor
HashSet( )
import java.util.*;
class HashSetDemo {
public static void main(String args[])
{
// create a hash set
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}
o/p
[A, F, E, D, C, B]
❖ Map Interface
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
41
• A Map interface defines mappings from keys to values. The <key, value> pair is
called an entry in a Map.
• A Map does not allow duplicate keys, in other words, the keys are unique.
Methods
• Object put(Object key, Object value)
• Object get(Object key)
• Object remove(Object key)
• void putAll(Map t)
• boolean containsKey(Object key)
• boolean containsValue(Object value)
• int size()
• boolean isEmpty()
• void clear()
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
42
1.TreeMap Class
• The TreeMap class implements the Map interface by using a tree.
• A TreeMap provides an efficient means of storing key/value pairs in sorted order,
and allows rapid retrieval.
• You should note that, unlike a hash map, a tree map guarantees that its elements
will be sorted in ascending key order.
• It contains only unique key.
Constructor
TreeMap()
import java.util.*;
class TreeMapDemo
{
public static void main(String args[])
{
TreeMap tm = new TreeMap();
tm.put("Amol", new Float(55.55));
tm.put("Punit", new Float(66.33));
System.out.println(tm);
}
}
2.HashMap Class
• The HashMap class uses a hash table to
implement the Map interface.
• It display object any order.
• It contains only unique key.
Constructor
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
43
HashMap( )
import java.util.*;
class HashMapDemo
{
public static void main(String args[])
{
HashMap tm = new HashMap();
tm.put("Amol", new Float(55.55));
tm.put("Punit", new Float(66.33));
System.out.println(tm);
}
}
3.Hashtable
• Hashtable contains values based on the key. It implements the Map interface.
• It contains only unique key.
• It is synchronized.
Constructor
Hashtable();
import java.util.*;
class HashDemo
{
public static void main(String args[])
{
Hashtable tm = new Hashtable();
tm.put("Amol", new Float(55.55));
tm.put("Punit", new Float(66.33));
System.out.println(tm);
}
}
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
44
APPLET
❖ What is an Applet?
Applet(java.applet.Applet) is a special type of program that is embedded in the webpage
to generate the dynamic content. It runs inside the browser and works at client side.
❖ The Basic Applet Life Cycle
Born initialization
(Load Applet)
Start()
Stop()
Display()
stopped
Paint()
Start()
Destroyed end
BORN
RUNNING
IDLE
DEAD
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
45
1. Initialization state
Applet enters the initialization state when it is first loaded. This is achieved by calling
init() method of Applet Class. The applet is born. At this stage ,It may the following, if
required.
1. Create object needed by applet.
2. Set up initial values.
3. Load images or fonts.
4. Set up colors.
The initialization occurs only once in the applet’s life cycle. To provide any of the
behaviors mentioned above, it must override the init() method.
public void init()
{
---------------
//action
}
2. Running State
This method is automatically called after the browser calls the init method. It is also
called whenever the user returns to the page containing the applet after having gone off
to other pages.
public void start()
{
---------------
//action
}
3. Idle or stopped state.
This method is automatically called when the user moves off the page on which the
applet sits. It can, therefore, be called repeatedly in the same applet.
public void stop()
{
---------------
//action
}
4.Dead state
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
46
An applet is said to be dead when it is removed from memory. This occurs
automatically by invoking the destroy() method when it quit the browser.
It override the destroy() method to clean up these resources.
public void destroy()
{
---------------
//action
}
5. Display State
Invoked immediately after the start() method, and also any time the applet needs to
repaint itself in the browser.
public void paint(Graphics g)
{
---------------
//action
}
import java.awt.*;
import java.applet.*;
public class AppletSkel extends Applet
{
// Called first.
public void init() {
// initialization
}
/* Called second, after init(). Also called whenever
the applet is restarted. */
public void start() {
// start or resume execution
}
// Called when the applet is stopped.
public void stop() {
// suspends execution
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
47
}
/* Called when applet is terminated. This is the last
method executed. */
public void destroy() {
// perform shutdown activities
}
// Called when an applet's window must be restored.
public void paint(Graphics g) {
// redisplay contents of window
}
}
❖ How to run applet
1. compile the HelloWorldApplet.java program. i.e
C:javac HelloWorldApplet.java
import java.applet.Applet;
import java.awt.*;
public class HelloWorldApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello world!", 50, 25);
}
}
2. Insert the HelloWorldApplet.class in the following HTML tag. And save HTML
file(Hello.html)
<html>
<head>
<title> hello world </title>
</head>
<body>
This is the applet:<P>
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
48
<applet code="HelloWorldApplet" width="150" height="50" name=”visionacademy”>
</applet>
</body>
</html>
3. Use appletviewer command .
C: appletviewer Hello.html
Or
/*
<applet code=" HelloWorldApplet" width=300 height=100>
</applet>
*/
import java.applet.Applet;
import java.awt.*;
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
49
public class HelloWorldApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello world!", 50, 25);
}
}
Compile
C: javac HelloWorldApplet.java
Run
C: appletviewer HelloWorldApplet.java
The HTML APPLET Tag
The APPLET tag
< APPLET
[CODEBASE = appletURL]
CODE = appletClassFile
[ALT = alternateText]
[ARCHIVE = archiveFile]
[NAME = appletInstanceName]
WIDTH = pixels
HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels]
[HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue />]
</APPLET>
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
50
What is use of PARAM tag?
Parameters are passed to applets in the form of NAME=VALUE pairs in <PARAM> tags
between the opening and closing in a APPLET tags. It can read the values passed through
the PARAM tags of applet by using method e getParameter()
import java.applet.*;
import java.awt.*;
public class DrawStringApplet extends Applet
{
String msg;
public void paint(Graphics g) {
String s = getParameter("msg");
g.drawString(s, 50, 25);
}
}
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
51
<HTML>
<BODY>
This is the applet:<P>
<APPLET code=”Myapplet" width="300" height="50">
<PARAM name="Message" value=”vision academy">
</APPLET>
</BODY>
</HTML>
❖ Simple Applet Display Methods
Use drawString( ), which is a member of the Graphics class.
It has the following general form:
void drawString(String message, int x, int y)
❖ Difference between paint(),update(),repaint() methods
repaint() –> update() –> paint()
paint():This method holds instructions to paint this component. It shouldn't call this
method directly, It should call by using repaint().
public void paint(Graphics g)
{
}
Repaint():Repaint() method calls automatically update() method and in turn update()
method calls paint() method
Update():An update method is called on calling the repaint method. The default
implementation of the update() method clears the screen and calls the paint() method.
❖ Background & Forground Color
void setBackground(Color newColor)
void setForeground(Color newColor)
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
52
Here, newColor specifies the new color. The class Color defines the constants shown
here that can be used to specify colors:
Color.black Color.magenta
Color.blue Color.orange
Color.cyan Color.pink
Color.darkGray Color.red
Color.gray Color.white
Color.green Color.yellow
Color.lightGray
For example, this sets the background color to green and the text color to red:
setBackground(Color.green);
setForeground(Color.red);
/* A simple applet that sets the foreground and
background colors and outputs a string. */
import java.awt.*;
import java.applet.*;
/*
<applet code="Appletcolor" width=300 height=100>
</applet>
*/
public class Appletcolor extends Applet
{
String msg;
// set the foreground and background colors.
public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
msg = "Inside init( ) --";
}
}
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
53
Advantage of applet
1. As applet is a small java program, so it is platform independent code which is
capable to run on any browser.
2. Applets can perform various small tasks on client-side machines. They can play
sounds, show images, get user inputs, get mouse clicks and even get user
keystrokes, etc ...
3. Applets creates and edit graphics on client-side which are different and
independent of client-side platform.
4. As compared to stand-alone application applets are small in size, the advantage of
transferring it over network makes it more usable.
5. Applets run on client browser so they provide functionality to import resources
such as images, audio clips based on Url's.
6. Applets are quite secure because of their access to resources.
7. Applets are secure and safe to use because they cannot perform any modifications
over local system.
Applets Restrictions(Disadvantages)
1. If we are running an applet from a provider who is not trustworthy than security is
important.
2. Applet itself cannot run or modify any application on the local system.
3. Applets has no access to client-side resources such as files , OS etc.
4. Applets can have special privileges. They have to be tagged as trusted applets and
they must be registered to APS (Applet Security Manager).
5. Applet has little restriction when it comes to communication. It can communicate
only with the machine from which it was loaded.
6. Applet cannot work with native methods.
7. Applet can only extract information about client-machine is its name, java
version, OS, version etc ... .
8. Applets tend to be slow on execution because all the classes and resources which
it needs have to be transported over the network.
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
54
AWT (Abstract Window toolkit)
The AWT classes are contained in the java.awt package. It is one of Java’s largest
packages. It is one of Java’s largest packages.
The AWT hierarchy
Classes:
• BorderLayout
• CardLayout
• CheckboxGroup
• Color
• Component
o Button
o Canvas
o Checkbox
o Choice
o Container
▪ Panel
▪ Window
▪ Dialog
▪ Frame
o Label
o List
o Scrollbar
o TextCompoment
▪ TextArea
▪ TextField
• Dimension
• Event
• FileDialog
• FlowLayout
• Font
• FontMetrics
• Graphics
• GridLayout
• GridBagConstraints
• GridBagLayout
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
55
• Image
• Insets
• MediaTracker
• MenuComponent
o MenuBar
o MenuItem
▪ CheckboxMenuItem
▪ Menu
• Point
• Polygon
• Rectangle
• Toolkit
Interfaces
• LayoutManager
• MenuComponent
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
56
java.lang Object
Component
java.awt
Container
Window Panel
Frame Applet
Javax.swing Jframe Japplet
Container
• A container is a component which can contain other components inside itself.
• It is also an instance of a subclass of java.awt.Container. java.awt.Container
extends java.awt.Component so containers are themselves components.
• In general components are contained in a container. containers include
applet,windows, frames, dialogs, and panels.
• Containers may contain other containers.
• Every container has a LayoutManager that determines how different
components are positioned within the container.
It is 2 kind of container
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
57
• Panel
• Window
▪ Frame
▪ Dialog
Panel
• Panels are subclasses of java.awt.Panel.
A panel is contained inside another container.
• Panels do not stand on their own.
• The Panel class is a concrete subclass of Container.
• Panel is a window that does not contain a title bar, menu bar, or border.
• Main purpose is to subdivide the drawing area into separate rectangular pieces.
Since each Panel can have its own LayoutManager
• Other components can be added to a Panel object by its add( ) method.
import java.awt.*;
import java.awt.event.*;
public class Pan extends Frame
{
public Pan()
{
setLayout(new BorderLayout());
add(new TextArea(),BorderLayout.CENTER);
Panel p = new Panel();
p.setLayout(new FlowLayout(FlowLayout.CENTER));
p.add(new Button("OK"));
p.add(new Button("CANCEL"));
add(p, BorderLayout.SOUTH);
setVisible(true);
}
public static void main(String args[])
{
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
58
new Pan();
}
}
Window
The Window class creates a top-level window.. Generally, it won’t create
Window objects directly. Instead, you will use a subclass of Window called Frame.
Frame
• Frame encapsulates what is commonly thought of as a “window.” It is a subclass
of Window .
• It has a title bar, menu bar, borders, and resizing corners.
• It can be independently moved and resized
Frame Example
import java.awt.*;
import java.awt.event.*;
public class Fr extends Frame
{
public Fr()
{
super("Vision Academy Sachin Sir 9823037693"); or setTitle(“Vision Academy
Sachin Sir 9823037693”)
setSize(250, 250);
setLocation(300,200);
setVisible(true);
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
59
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public static void main(String args[])
{
new Fr();
}
}
OR
import java.awt.*;
import java.awt.event.*;
public class Fr
{public static void main(String args[])
{
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
60
Frame f=new Frame();
f.setTitle("Vision Academy Sachin Sir 9823037693");
f.setSize(250, 250);
f.setLocation(300,200);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}
Components
Components is abstract class that encapsulated all the attribute of visual components.
Method Of Components
Component add(Component compObj)
void remove(Component obj)
removeAll( ).
Components are graphical user interface (GUI) widgets like checkboxes, menus,
windows, buttons, text fields, applets, and more.
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
61
In Java all components are subclasses of java.awt.Component. Subclasses of Component
include
• Component
o Button
o Canvas
o Checkbox
o Choice
o Container
▪ Panel
▪ W-indow
▪ Dialog
▪ Frame
o Label
o List
o Scrollbar
o TextCompoment
▪ TextArea
▪ TextField
The key thing to remember about adding components to the applet is the three
steps:
1. Declare the component
2. Initialize the component
3. Add the component to the layout.
Label
Class: java.awt.Label
import java.awt.*;
import java.awt.event.*;
public class Demo extends Frame
{
Public Demo()
{
setLayout( new FlowLayout());
Label l = new Label("Hello TY");
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
62
add(l);
setVisible(true);
}
public static void main(String args[])
{
new Demo();
}
}
Constructor
Label( )
Label(String str)
Label(String str, int how)
Where
How=>Label.LEFT, Label.RIGHT, or Label.CENTER.
Label center = new Label("This label is centered", Label.CENTER);
Label left = new Label("This label is left-aligned", Label.LEFT);
Label right = new Label("This label is right-aligned", Label.RIGHT);
Method
public int getAlignment()
public synchronized void setAlignment(int alignment)
public String getText()
public synchronized void setText(String text)
import java.awt.*;
import java.awt.event.*;
public class Demo extends Frame
{
Public Demo()
{
setLayout( new FlowLayout());
Label l= new Label("Hello TY");
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
63
l.setForeground(Color.blue);
l.setBackground(Color.yellow);
l.setFont(new Font("Arial", Font.BOLD, 24));
add(l);
setVisible(true);
}
public static void main(String args[])
{
new Demo();
}
}
Buttons
Class: java.awt.Button
Constructor
Button( )
Button(String str)
Methods
These methods are as follows:
void setLabel(String str)
String getLabel( )
Here, str becomes the new label for the button.
import java.awt.*;
import java.awt.event.*;
public class Demo extends Frame
{
public Demo()
{
setLayout( new FlowLayout());
Button b = new Button("OK");
add(b);
setVisible(true);
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
64
}
public static void main(String args[])
{
new Demo();
}
}
Button Actions
import java.awt.*;
import java.awt.event.*;
public class Demo extends Frame
{
public Demo ()
{
Button b=new Button(“ok”);
b.addActionListener(new Action());
}
public static void main(String args[])
{
new Demo();
}
}
class Action implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//logic
}
}
Or
import java.awt.*;
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
65
import java.awt.event.*;
public class Demo extends Frame
implements ActionListener
{
public Demo ()
{
Button b=new Button(“ok”);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
//logic
}
public static void main(String args[])
{
new Demo();
}
}
TextFields
Class:java.awt.TextField
Constructor
public TextField()
public TextField(String text)
public TextField(int length)
public TextField(String text, int length)
Method
String getText()
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
66
Void setText(String)
import java.awt.*;
import java.awt.event.*;
public class Demo extends Frame
{
public Demo()
{
setLayout( new FlowLayout());
TextField t = new TextField(10);
add(t);
setVisible(true);
}
public static void main(String args[])
{
new Demo();
}
}
TextArea
Class:java.awt.TextArea
Constructors:
public TextArea()
public TextArea(String text)
public TextArea(int rows, int columns)
public TextArea(String text, int rows, int columns)
public TextArea(String text, int rows, int columns, int scrollbars)
Where
TextArea.SCROLLBARS_BOTH
TextArea.SCROLLBARS_HORIZONTAL_ONLY
TextArea.SCROLLBARS_NONE
TextArea.SCROLLBARS_VERTICAL_ONLY
import java.awt.*;
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
67
import java.awt.event.*;
public class Demo extends Frame
{
public Demo()
{
setLayout( new FlowLayout());
TextArea t = new TextArea(10,20);
add(t);
setVisible(true);
}
public static void main(String args[])
{
new Demo();
}
}
TextEvents
public void textValueChanged(TextEvent te)
addTextListener() method.
Choice
Class:java.awt.Choice
Step for adding choice
1. Declare the Choice
2. Allocate the Choice
3. Add the data items to the Choice
4. Add the Choice to the layout
5. Add an ItemListener to the Choice
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
68
Methods
public int getItemCount()
public String getItem(int index)
public void add(String item)
public void addItem(String item)
public void insert(String item, int position)
public void remove(String item)
public void remove(int position)
public void removeAll()
public void removeAll()
public String getSelectedItem()
import java.awt.*;
import java.awt.event.*;
public class Demo extends Frame implements ItemListener
{
Choice ch;
TextField t;
public Demo()
{
setLayout( new FlowLayout());
ch = new Choice();
ch.addItem("BCS");
ch.addItem("BCA");
ch.addItem("BSC");
t=new TextField(20);
add(ch);
add(t);
ch.addItemListener(this);
setVisible(true);
}
public void itemStateChanged(ItemEvent ie)
{
String s=ch.getSelectedItem();
t.setText(s);
}
public static void main(String args[])
{
new Demo();
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
69
}
}
List
Class:java.awt.List
Constructor
public List()
public List(int numLines)
public List(int numLines, boolean allowMultipleSelections)
allowMultipleSelections says whether the user is allowed to select more than one item at
once (typically by Shift-clicking).
Methods
public void add(String item)
public void addItem(String item)
public void add(String item, int index)
public void addItem(String item, int index)
public void removeAll()
public void remove(String item)
public void remove(int position)
public int getItemCount()
public String getItem(int index)
public String[] getItems()
public int getSelectedIndex()
public int[] getSelectedIndexes()
public String getSelectedItem()
public String[] getSelectedItems()
public Object[] getSelectedObjects()
public boolean isMultipleMode()
public void setMultipleMode(boolean b)
import java.awt.*;
import java.awt.event.*;
public class Demo extends Frame implements ItemListener
{
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
70
List l;
TextField t;
public Demo()
{
setLayout( new FlowLayout());
l = new List();
l.addItem("BCS");
l.addItem("BCA");
l.addItem("BSC");
t=new TextField(20);
add(l);
add(t);
l.addItemListener(this);
setVisible(true);
}
public void itemStateChanged(ItemEvent ie)
{
String s=l.getSelectedItem();
t.setText(s);
}
public static void main(String args[])
{
new Demo();
}
}
CHECKBOX
Class:java.awt.CheckBox
Constructors:
Checkbox( )
Checkbox(String str)
Checkbox(String str, boolean on)
Checkbox(String str, boolean on, CheckboxGroup cbGroup)
Checkbox(String str, CheckboxGroup cbGroup, boolean on)
The first form creates a check box whose label is initially blank. The state of the check
box is unchecked.
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
71
The second form creates a check box whose label is specified by str.The state of the
check box is unchecked.
The third form allows you to set the initial state of the check box. If on is true, the check
box is initially checked; otherwise, it is cleared.
The fourth and fifth forms create a check box whose label is specified by str and whose
group is specified by cbGroup. If this check box is not part of a group, thencbGroup must
be null. (Check box groups are described in the next section.) The value of on determines
the initial state of the check box.
Methods
boolean getState( )
void setState(boolean on)
String getLabel( )
void setLabel(String str)
import java.awt.*;
import java.awt.event.*;
public class Demo extends Frame implements ItemListener
{
Checkbox chk1;
TextField t;
public Demo()
{
setLayout( new FlowLayout());
chk1= new Checkbox("BCA");
t=new TextField(20);
add(chk1);
add(t);
chk1.addItemListener(this);
setVisible(true);
}
public void itemStateChanged(ItemEvent ie)
{
if (chk1.getState()==true)
t.setText(chk1.getLabel());
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
72
else
t.setText("");
}
public static void main(String args[])
{
new Demo();
}
}
CheckboxGroup(Radio Button)
import java.awt.*;
import java.awt.event.*;
public class Demo extends Frame implements ItemListener
{
Checkbox chk1,chk2;
TextField t;
public Demo()
{
setLayout( new FlowLayout());
CheckboxGroup cbg = new CheckboxGroup();
chk1= new Checkbox("MALE",cbg,false);
chk2= new Checkbox("FEMALE",cbg,false);
t=new TextField(20);
add(chk1);
add(chk2);
add(t);
chk1.addItemListener(this);
chk2.addItemListener(this);
setVisible(true);
}
public void itemStateChanged(ItemEvent ie)
{
if (chk1.getState()==true)
t.setText(chk1.getLabel());
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
73
else
t.setText(chk2.getLabel());
}
public static void main(String args[])
{
new Demo();
}
}
❖ What is LayoutManager?
Def:The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout
managers.
Each container has a layout manager associated with it. To change the layout manager for
a container, use the setLayout() method.
Syntax
setLayout(LayoutManager obj)
The predefined managers are listed below:
1. FlowLayout
2.GridLayout
3. BoxLayout
4.CardLayout
5.GridBagLayout
1.FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow).
It is the default layout of applet or panel.
Here are the constructors for FlowLayout:
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
how are as follows:
FlowLayout.LEFT
FlowLayout.CENTER
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
74
FlowLayout.RIGHT
horz and vert follows:
specify the horizontal and vertical space left between components in
horz and vert, respectively.
e.g
setLayout(new FlowLayout(FlowLayout.LEFT));
b1=new JButton("1");
b2=new JButton("2");
add(b1);
add(b2);
2 BorderLayout
Border layout manager is the layout manager that divides the container into 5 regions
such as north,east,west,south,center..
BorderLayout( )
BorderLayout(int horz, int vert)
BorderLayout defines the following constants that specify the regions:
BorderLayout.CENTER
BorderLayout.SOUTH
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.NORTH
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
75
void add(Component compObj, Object region);
e.g
setLayout(new BorderLayout(5,5));
b1=new JButton("SOUTH");
b2=new JButton("NORTH");
b3=new JButton("EAST");
b4=new JButton("WEST");
b5=new JButton("CENTER");
3.GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
GridLayout( )
GridLayout(int numRows, int numColumns )
GridLayout(int numRows, int numColumns, int horz, int vert)
e.g
setLayout(new GridLayout(4,4));
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
76
4.GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or
along their baseline.
The components may not be of same size. Each GridBagLayout object maintains a
dynamic, rectangular grid of cells. Each component occupies one or more cells known as
its display area. Each component associates an instance of GridBagConstraints. With the
help of constraints object we arrange component's display area on the grid. The
GridBagLayout manages each component's minimum and preferred sizes in order to
determine component's size.
GridBagLayout()
e.g
setLayout(new GridBagLayout());
5.CardLayout
CardLayout is the only layout class which can hold several layouts in it.
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
77
The card layout manager generates a stack of components, one on top of the other. The
first component that you add to the container will be at the top of the stack, and therefore
visible,and the last one will be at the bottom.
Constructor as follows
CardLayout( )
CardLayout(int horz, int vert)
❖ Manually Position Components
setLayout(null);
public void setLocation(int x, int y)
public void setSize(int width, int height)
import java.awt.*;
import java.awt.event.*;
public class Demo extends Frame
{
public Demo()
{
setLayout(null);
Button b=new Button("OK");
b.setLocation(25, 50);
b.setSize(30, 40);
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
78
add(b);
setVisible(true);
}
public static void main(String args[])
{
new Demo();
}
}
EVENT
Java has two types of events:
1. Low-Level Events: Low-level events represent direct communication from
user. A low level event is a key press or a key release, a mouse click, drag, move or
release,and so on. Following are low level events.
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
79
2. High-Level Events: High-level (also called as semantic events) events encapsulate the
meaning of a user interface component. These include following events.
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
80
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
81
❖ Adapter Classes
Definition:An adapter class provides an empty implementation of all methods in an
event listener interface i.e this class itself write definition for methods which are
present in particular event listener interface.
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
82
Suppose you want to use MouseClicked Event or method from MouseListener, if you do
not use adapter class then unnecessarily you have to define all other methods from
MouseListener such as MouseReleased, MousePressed etc.
But If you use adapter class then you can only define MouseClicked method and don’t
worry about other method definition because class provides an empty implementation of
all methods in an event listener interface.
Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
Before Using Adapter Class
import java.awt.*;
import java.awt.event.*;
public class Demo extends Frame implements MouseListener
{
public Demo()
{
addMouseListener(this);
setVisible(true);
}
public void mouseClicked(MouseEvent me)
{
}
public void mouseEntered(MouseEvent me)
{
}
public void mouseExited(MouseEvent me)
{
}
public void mousePressed(MouseEvent me)
{
}
public void mouseReleased(MouseEvent me)
{
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
83
}
public static void main(String args[])
{
new Demo();
}
}
After using Adapter Class
import java.awt.*;
import java.awt.event.*;
public class Demo extends Frame
{
public Demo()
{
setVisible(true);
addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
System.out.println("mouse click");
}
});
}
public static void main(String args[])
{
new Demo();
}
}
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
84
❖ Swing
AWT SWING
AWT components are platform-
dependent.
Java swing components are platform-
independent.
AWT components are heavyweight. Swing components are lightweight.
AWT provides less components than
Swing.
Swing provides more powerful
components such as tables, lists,
scrollpanes, tabbedpane etc.
AWT doesn't support pluggable look and
feel.
Swing supports pluggable look and feel.
AWT doesn't follows MVC(Model View
Controller) where model represents data,
view represents presentation and controller
acts as an interface between model and
view.
Swing support MVC
e.g Button e.g JButton
Class Description
AbstractButton Abstract superclass for Swing buttons.
ButtonGroup Encapsulates a mutually exclusive set of
buttons.
ImageIcon Encapsulates an icon.
JApplet The Swing version of Applet.
JButton The Swing push button class.
JCheckBox The Swing check box class.
JComboBox Encapsulates a combo box (an combination
of a drop-down list and text field).
JLabel The Swing version of a label.
JRadioButton The Swing version of a radio button.
JScrollPane Encapsulates a scrollable window.
JTabbedPane Encapsulates a tabbed window.
JTable Encapsulates a table-based control.
JTextField The Swing version of a text field.
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
85
JTree Encapsulates a tree-based control.
Icons and Labels
In Swing, icons are encapsulated by the ImageIcon class, which paints an icon from an
image.
Constructor of Icons
ImageIcon(String filename)
ImageIcon(URL url)
The first form uses the image in the file named filename. The second form uses the image
in the resource identified by url.
Constructor of JLabel
JLabel(Icon i)
Label(String s)
JLabel(String s, Icon i, int align)
Here, s and i are the text and icon used for the label. The align argument is either LEFT,
RIGHT, CENTER, LEADING, or TRAILING.
METHODS
Icon getIcon( )
String getText( )
void setIcon(Icon i)
void setText(String s)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Demo extends JFrame
{
public Demo()
{
ImageIcon ic = new ImageIcon("c:wl.jpg");
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
86
JLabel l = new JLabel("Image", ic, JLabel.CENTER);
add(l);
setVisible(true);
}
public static void main(String args[])
{
new Demo();
}
}
Text Fields
Constructor
JTextField( )
JTextField(int cols)
JTextField(String s, int cols)
JTextField(String s)
Here, s is the string to be presented, and cols is the number of columns in the text field.
The following example illustrates how to create a text field. The applet begins by
getting its content pane, and then a flow layout is assigned as its layout manager. Next,
a JTextField object is created and is added to the content pane.
JPasswordField
Creates a password field.
Constructors
JPasswordField()
JPasswordField(String)
JPasswordField(String, int)
JPasswordField(int)
JPasswordField(Document, String, int)
The JButton Class
Constructor
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
87
JButton(Icon i)
JButton(String s)
JButton(String s, Icon i)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Demo extends JFrame
{
public Demo()
{
setLayout(new FlowLayout());
JTextField t = new JTextField(10);
JButton b=new JButton("OK");
add(t);
add(b);
setVisible(true);
}
public static void main(String args[])
{
new Demo();
}
}
JCheck Boxes
Constructor
JCheckBox(Icon i)
JCheckBox(Icon i, boolean state)
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
88
JCheckBox(String s)
JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i)
JCheckBox(String s, Icon i, boolean state)
Radio Buttons
Constructor
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Demo extends JFrame
{
public Demo()
{
setLayout(new FlowLayout());
JCheckBox chk1=new JCheckBox("red");
JCheckBox chk2=new JCheckBox("yellow");
JRadioButton r1=new JRadioButton("male");
JRadioButton r2=new JRadioButton("female");
add(chk1);
add(chk2);
add(r1);
add(r2);
setVisible(true);
}
public static void main(String args[])
{
new Demo();
}
}
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
89
Combo Boxes
Constructor
JComboBox( )
JComboBox(Vector v)c static void main(String args[])
{ new Demo();
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Demo extends JFrame
{
public Demo()
{
setLayout(new FlowLayout());
JComboBox cb=new JComboBox();
cb.addItem("BCS");
cb.addItem("BCA");
cb.addItem("BSC");
add(cb);
setVisible(true);
}
public static void main(String args[])
{
new Demo();
}
}
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
90
new Demo();
}
Tabbed Panes
A tabbed pane is a component that appears as a group of folders in a file cabinet. Each
folder has a title. When a user selects a folder, its contents become visible. Only one of
the folders may be selected at a time. Tabbed panes are commonly used for setting
configuration options.
The general procedure to use a tabbed pane in an applet is outlined here:
1. Create a JTabbedPane object.
2. Call addTab( ) to add a tab to the pane. (The arguments to this method define
the title of the tab and the component it contains.)
3. Repeat step 2 for each tab.
4. Add the tabbed pane in to the container.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Demo extends JFrame
{
public Demo()
{
//setLayout(new FlowLayout());
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("BCS", new BcsPanel());
jtp.addTab("BCA", new BcaPanel());
add(jtp);
setVisible(true);
}
class BcsPanel extends JPanel
{
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
91
BcsPanel()
{
add(new JButton("ok"));
add(new JButton("cancel"));
}
}
class BcaPanel extends JPanel
{
BcaPanel()
{
add(new JButton("yes"));
add(new JButton("no"));
}
}
public static void main(String args[])
{
new Demo();
}
}
DEVELOPMENT
NG JAVA
JTable
A table is a component that displays rows and columns of data.
JTable(Object data[ ][ ], Object colHeads[ ])
Here, data is a two-dimensional array of the information to be presented, and colHeads
is a one-dimensional array with the column headings.
Steps
1. Create a JTable object.
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
92
2. Create a JScrollPane object. (The arguments to the constructor specify the table
and the policies for vertical and horizontal scroll bars.)
3. Add the table to the scroll pane.
4. Add the scroll pane into the container
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Demo extends JFrame
{
public Demo()
{
String[] colHeads = { "Name", "Phone", "Fax" };
final Object[][] data = {
{ "amol", "4567", "8675" },
{ "kiran", "7566", "5555" },
{ "sagar", "5634", "5887" },
{ "punit", "7345", "9222" },
{ "umesh", "1237", "3333" },
};
JTable table = new JTable(data, colHeads);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(table, v, h);
add(jsp, BorderLayout.CENTER);
setVisible(true);
}
public static void main(String args[])
{
new Demo();
}
}
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
93
Menu
Menus are composed of three hierarchical pieces. The menu bar contains the various
menus.
Creating Menus
You should build the menus before you display them. The typical order is:
1. Create a new MenuBar.
2. Create a new Menu.
3. Add items to the Menu.
4. Add the Menu to the MenuBar.
5. If necessary repeat steps 2 through 4.
6. Add the MenuBar into the container
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Demo extends JFrame
{
public Demo()
{
JMenu fm = new JMenu("File");
fm.add(new JMenuItem("Open"));
fm.addSeparator( );
fm.add(new JMenuItem("Save"));
JMenu fe = new JMenu("Edit");
fe.add(new JMenuItem("Copy"));
fe.add(new JMenuItem("Cut"));
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
94
JMenuBar mb = new JMenuBar( );
mb.add(fm);
mb.add(fe);
setJMenuBar(mb);
setVisible(true);
}
public static void main(String args[])
{
new Demo();
}
}
Dialogs(What are different type of dialog?)
message dialog
Displays a message to the user, usually accompanied by an OK button.
confirmation dialog
Ask a question and displays answer buttons, usually Yes, No, and Cancel.
input dialog
Asks the user to type in a string.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Dialog
{
public static void main(String args[])
{
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
95
JFrame f = new JFrame("Vision Academy");
JOptionPane.showMessageDialog(f, "You have mail.");
int result = JOptionPane.showConfirmDialog(null,
"Do you want to remove Windows now?");
String name = JOptionPane.showInputDialog(null,
"Please enter your name.");
}
}
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
96
Stream classes
Stream: A stream is a sequence of data.In Java a stream is composed of bytes.
Their 2 types of stream classes
• Byte stream classes
• Character stream classes
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
97
❖ Byte Stream Classes
Byte stream classes have been designed to provide functional features for creating and
manipulating streams and files for reading and writing bytes. Java provides two kinds of
byte stream classes: input stream classes andoutput stream classes.
1.Input Stream Classes
Input stream classes that are used to read bytes include a super class known
as Inputstream and a number of subclasses for supporting various input-related
functions. The super class InputStream is an abstract class, and, therefore, we cannot
create instances of this class. Rather, we must use the subclasses that inherit from this
class.
Table InputStream Class Methods
Method Description
int read() returns the integral representation of the next available byte of
input. It returns -1 when end of file is encountered
int read (byte
buffer [])
attempts to read buffer. length bytes into the buffer and returns the
total number of bytes successfully read. It returns -1 when end of
file is encountered
int read (byte
buffer [], int loc,
int nBytes)
attempts to read 'nBytes' bytes into the buffer starting at buffer [loc]
and returns the total number of bytes successfully read. It returns -1
when end of file is encountered
int available () returns the number of bytes of the input available for reading
Void mark(int
nBytes)
marks the current position in the input stream until 'nBytes' bytes
are read
void reset () Resets the input pointer to the previously set mark
long skip (long
nBytes)
skips 'nBytes' bytes of the input stream and returns the number of
actually skippedbyte
void close () closes the input source. If an attempt is made to read even after
closing the
stream then it generates IOException
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
98
import java.io.*;
class F2
{
public static void main(String args[])
{
int ch;
char ch2;
try
{
File f1=new File("a.txt");
FileInputStream fin1=new FileInputStream(f1);
while((ch=fin1.read())!=-1)
{
System.out.println((char)ch);
}
fin1.close();
}
catch(Exception e)
{
}
}
}
2.Output Stream Classes
Output stream classes are derived from the base class Outputstream like InputStream,
the OutputStream is an abstract class and therefore we cannot instantiate it. The several
subclasses of the OutputStream can be used for performing the output operations.
TableOutputStream Class Methods
.Method Description
void write (int i) writes a single byte to the output stream
void write (byte
buffer [] )
writes an array of bytes to the output stream
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
99
Void write(bytes
buffer[],int loc, int
nBytes)
writes 'nBytes' bytes to the output stream from the buffer b
starting at buffer [loc]
void flush () Flushes the output stream and writes the waiting buffered output
bytes
void close () closes the output stream. If an attempt is made to write even after
closing the stream then it generates IOException
import java.io.*;
class F1
{
public static void main(String args[])
{
try
{
File inFile=new File("a.txt");
char ch='b';
FileOutputStream fout=new FileOutputStream(inFile);
fout.write(ch);
fout.close();
}
catch(Exception e)
{
}
}
}
2.Character Stream Classes
Character streams can be used to read and write 16-bit Unicode characters.
There are 2 types
1 reader stream classes
2.writer stream classes
1.Reader Stream Classes
Reader stream classes that are used to read characters include a super class known
as Reader and a number of subclasses for supporting various input-related functions.
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
100
Reader stream classes are functionally very similar to the input stream classes, except
input streams use bytes as their fundamental unit of information, while reader streams use
characters
import java.io.*;
class F2
{
public static void main(String args[])
{
int ch;
char ch2;
try
{
File f1=new File("a.txt");
FileReader fin1=new FileReader(f1);
while((ch=fin1.read())!=-1)
{
System.out.println((char)ch);
}
fin1.close();
}
catch(Exception e)
{
}
}
}
2.Writer Stream Classes
Like output stream classes, the writer stream classes are designed to perform all output
operations on files. Only difference is that while output stream classes are designed to
write bytes, the writer stream are designed to write character.
import java.io.*;
class F1
{
public static void main(String args[])
{
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
101
try
{
File inFile=new File("a.txt");
char ch='b';
FileWriter fout=new FilWriter(inFile);
fout.write(ch);
fout.close();
}
catch(Exception e)
{
}
}
}
java.io.File class
This class supports a platform-independent definition of file and directory names.
It also provides methods to list the files in a directory, to check the existence,
readability,writeability, type, size, and modification time of files and directories, to make
newdirectories, to rename files and directories, and to delete files and directories.
Constructors:
publicFile(String path);
publicFile(String path, String name);
publicFile(File dir, String name);
Example
File f1=new File(“/home/java/a.txt”);
Methods
1. booleancanRead()- Returns True if the file is readable.
2. booleancanWrite()- Returns True if the file is writeable.
3. String getName()- Returns the name of the File with any directory names omitted.
4. boolean exists()- Returns true if file exists
5. String getAbsolutePath()- Returns the complete filename. Otherwise, if the File isa
relative file specification, it returns the relative filename appended to the current working
directory.
6. String getParent()- Returns the directory of the File. If the File is an absolute
specification.
7. String getPath()- Returns the full name of the file, including the directory name.
Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET )
Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
102
8. Boolean isDirectory()- Returns true if File Object is a directory
9. Boolean isFile()- Returns true if File Object is a file
10. longlastModified()- Returns the modification time of the file (which should be
used for comparison with other file times only, and not interpreted as any
particular time format).
11. long length()- Return*s the length of the file.
12. boolean delete()- deletes a file or directory. Returns true after successful deletionof a
file.
13. booleanmkdir ()- Creates a directory.
14. booleanrenameTo (File dest)- Renames a file or directory. Returns true after
successful renaming
import java.io.File;
classFileTest
{
public static void main(String args[ ])
{
File f1=new File ("a.txt");
if (f1.exists())
System.out.println ("File Exists");
else
System.out.println ("File Does Not Exist");
}
}
Vision Academy Since 2005
Prof. Sachin Sir(MCS,SET)
9822506209/9823037693
Branch1:Nr Sm Joshi College,Abv Laxmi zerox,Ajikayatara Build,Malwadi Rd,Hadapsar
Branch2:Nr AM College,Aditya Gold Society,Nr Allahabad Bank ,Mahadevnager
Why Vision Academy?...
• Lectures On Projector(1 st time
in Hadapsar)
• Experienced Faculty
• Placement Assist
• Regular Guest Lectures &
Seminars
• Computer Lab Facility
• Project Guidance for
BE/MCA/MCS Students.
• Courses Sun Certification , DBA
Certification, SAP,TESTING
,AS400 Course Guidance etc
• Digital Marketing Courses

More Related Content

Similar to Java String and StringBuffer tutorial

16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02Abdul Samee
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsphanleson
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsleminhvuong
 
Java R20 - UNIT-5.docx
Java R20 - UNIT-5.docxJava R20 - UNIT-5.docx
Java R20 - UNIT-5.docxPamarthi Kumar
 
24_2-String and String Library.pptx
24_2-String and String Library.pptx24_2-String and String Library.pptx
24_2-String and String Library.pptxGandavadiVenkatesh1
 
Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and AnalysisWiwat Ruengmee
 
Mysql Functions with examples CBSE INDIA 11th class NCERT
Mysql Functions with examples CBSE INDIA 11th class NCERTMysql Functions with examples CBSE INDIA 11th class NCERT
Mysql Functions with examples CBSE INDIA 11th class NCERTHarish Gyanani
 
Introduction to structures in c lang.ppt
Introduction to structures in c lang.pptIntroduction to structures in c lang.ppt
Introduction to structures in c lang.pptshivani366010
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................suchitrapoojari984
 
The Ring programming language version 1.3 book - Part 26 of 88
The Ring programming language version 1.3 book - Part 26 of 88The Ring programming language version 1.3 book - Part 26 of 88
The Ring programming language version 1.3 book - Part 26 of 88Mahmoud Samir Fayed
 
Chapter 4 Mathematical Functions, Characters, and Strings.pptx
Chapter 4 Mathematical Functions, Characters, and Strings.pptxChapter 4 Mathematical Functions, Characters, and Strings.pptx
Chapter 4 Mathematical Functions, Characters, and Strings.pptxssusere3b1a2
 

Similar to Java String and StringBuffer tutorial (20)

Java R20 - UNIT-5.pdf
Java R20 - UNIT-5.pdfJava R20 - UNIT-5.pdf
Java R20 - UNIT-5.pdf
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
Java R20 - UNIT-5.docx
Java R20 - UNIT-5.docxJava R20 - UNIT-5.docx
Java R20 - UNIT-5.docx
 
Java
JavaJava
Java
 
24_2-String and String Library.pptx
24_2-String and String Library.pptx24_2-String and String Library.pptx
24_2-String and String Library.pptx
 
Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and Analysis
 
Unit 3 arrays and_string
Unit 3 arrays and_stringUnit 3 arrays and_string
Unit 3 arrays and_string
 
Mysql Functions with examples CBSE INDIA 11th class NCERT
Mysql Functions with examples CBSE INDIA 11th class NCERTMysql Functions with examples CBSE INDIA 11th class NCERT
Mysql Functions with examples CBSE INDIA 11th class NCERT
 
Java
JavaJava
Java
 
11slide.ppt
11slide.ppt11slide.ppt
11slide.ppt
 
structures.ppt
structures.pptstructures.ppt
structures.ppt
 
Introduction to structures in c lang.ppt
Introduction to structures in c lang.pptIntroduction to structures in c lang.ppt
Introduction to structures in c lang.ppt
 
Strings part2
Strings part2Strings part2
Strings part2
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
The Ring programming language version 1.3 book - Part 26 of 88
The Ring programming language version 1.3 book - Part 26 of 88The Ring programming language version 1.3 book - Part 26 of 88
The Ring programming language version 1.3 book - Part 26 of 88
 
Chapter 4 Mathematical Functions, Characters, and Strings.pptx
Chapter 4 Mathematical Functions, Characters, and Strings.pptxChapter 4 Mathematical Functions, Characters, and Strings.pptx
Chapter 4 Mathematical Functions, Characters, and Strings.pptx
 

Recently uploaded

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Recently uploaded (20)

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

Java String and StringBuffer tutorial

  • 1. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 1 String and Stringbuffer The java.lang package contains two string classes String and Stringbuffer ❖ String class A combination of character is a string. The String Constructors 1.String(); =>Empty Constructor 2.String(char chars[ ]) 3.String(char chars[ ], int startIndex, int numChars) char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; String s = new String(chars, 2, 3); This initializes s with the characters cde. 4.String(String strObj) Here, strObj is a String object. Consider this example: class MakeString { public static void main(String args[]) { char c[] = {'J', 'a', 'v', 'a'}; String s1 = new String(c); String s2 = new String(s1); System.out.println(s1); System.out.println(s2); } } The output from this program is as follows: Java Java
  • 2. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 2 String Methods 1.Length() The length of a string is the number of characters that it contains. int length( ) The following fragment prints “3”, since there are three characters in the string s: char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); System.out.println(s.length()); 2.String Concatenation Using + operations. For example, the following fragment concatenates three strings: String age = "9"; String s = "He is " + age + " years old."; System.out.println(s); This displays the string “He is 9 years old.” 3.toString( ) method Syntax String toString( ) The toString() method returns the string representation of the object. If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output in the form of string. class Student { int rollno; String name; Student(int r, String s) { rollno=r; name=s;
  • 3. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 3 } public String toString() { return rollno+" "+name+; } public static void main(String args[]) { Student s1=new Student(101,"vision"); System.out.println(s1);//compiler writes here s1.toString() } } Character Extraction 1.charAt( ) To extract a single character from a String. char charAt(int where) char ch; String s=”abc”; ch = s.charAt(1); assigns the value “b” to ch. ❖ String Comparison 1.equals( ) and equalsIgnoreCase( ) To compare two strings for equality, use equals( ). It returns true if the strings contain the same characters in the same order, and false otherwise. It has this general form:
  • 4. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 4 boolean equals(String str) => The comparison is case-sensitive. boolean equalsIgnoreCase(String str)=> The comparison is not case-sensitive. String s1 = "Hello"; String s2 = "HELLO"; If(s1.equals(s2)) System.out.println(“equals”); Else System.out.println(“not equals”); If(s1.equalsIgnoreCase(s4)) System.out.println(“equals”); Else System.out.println(“not equals”); 2.startsWith( ) and endsWith( ) boolean startsWith(String str) boolean endsWith(String str) String s="Foobar" s.endsWith("bar") s.startsWith("Foo") are both true. 3.equals( ) Versus == The equals( ) method compares the characters inside a String object. The == checks to see if the 2 object names are basically references to the same memory location. // equals() vs = = String s1 = "Hello"; String s2 = new String(s1); if(s1.equals(s2)) System.out.println(“equals”); Else System.out.println(“not equals”); if(s1==s2)
  • 5. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 5 System.out.println(“equals”); Else System.out.println(“not equals”); String obj1 = new String("xyz"); // now obj2 and obj1 reference the same place in memory String obj2 = obj1; if(obj1 == obj2) System.out.printlln("TRUE"); else System.out.println("FALSE"); 4.compareTo( ) It has this general form: int compareTo(String str) Here, str is the String being compared with the invoking String. The result of the comparison is returned and is interpreted as shown here: 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. e.g String s1=”hello” int k=s1.compareTo(“hello”) o/p 0 Substring():It return substring String substring(int startIndex) String substring(int startIndex, int endIndex) 1.Concat( ) String concat(String str)
  • 6. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 6 String s1 = "one"; String s2 = s1.concat("two"); puts the string “onetwo” into s2. 2.replace( ) The replace( ) method replaces all occurrences of one character in the invoking string with another character. String replace(char original, char replacement) String s1=”hello” String s = s1.replace('l', 'w'); ❖ Changing the Case of Characters The method toLowerCase( ) converts all the characters in a string from uppercase to lowercase. The toUpperCase( ) method converts all the characters in a string from lowercase to uppercase. Sring toLowerCase( ) String toUpperCase( ) String s = "This is a test."; String upper = s.toUpperCase(); String lower = s.toLowerCase(); System.out.println("Uppercase: " + upper); System.out.println("Lowercase: " + lower);
  • 7. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 7 ❖ StringBuffer • A string buffer is mutable(Once the string object is creatred,the object can be changed). StringBuffer Constructors StringBuffer( ) StringBuffer(int size) StringBuffer(String str) 1.append( ) The append( ) method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object. It has overloaded versions for all the built-in types and for Object. Here are a few of its forms: StringBuffer append(String str) StringBuffer append(int num) StringBuffer append(Object obj) int a = 42; StringBuffer sb = new StringBuffer(40); sb = sb.append("a = "). sb = sb.append(a). System.out.println(sb); 2.insert( ) The insert( ) method inserts one string into another. These are a few of its forms: StringBuffer insert(int index, String str) StringBuffer insert(int index, char ch) StringBuffer insert(int index, Object obj) StringBuffer sb = new StringBuffer("I Java!"); sb.insert(2, "like ");
  • 8. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 8 System.out.println(sb); The output of this example is shown here: I like Java! 3.reverse( ) You can reverse the characters within a StringBuffer object using reverse( ) StringBuffer reverse( ) StringBuffer s = new StringBuffer("abcdef"); s.reverse(); System.out.println(s); 4.delete( ) and deleteCharAt( ) StringBuffer delete(int startIndex, int endIndex) StringBuffer deleteCharAt(int loc) StringBuffer sb = new StringBuffer("This is a test."); sb.delete(4, 7); System.out.println("After delete: " + sb); sb.deleteCharAt(0); System.out.println("After deleteCharAt: " + sb); The following output is produced: After delete: This a test. After deleteCharAt: his a test. 5.replace( ) StringBuffer replace(int startIndex, int endIndex, String str) StringBuffer sb = new StringBuffer("This is a test."); sb.replace(5, 7, "was"); System.out.println("After replace: " + sb); Here is the output: After replace: This was a test.
  • 9. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 9 STRING STRINGBUFFER The length of the String object is fixed. The length of the StringBuffer can be increased. String object is immutable. StringBuffer object is mutable. It is slower during concatenation. It is faster during concatenation. Consumes more memory. Consumes less memory. String s=new String(“vision”) StringBuffer sb=new StringBuffer(“vision)
  • 10. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 10 JAVA UTIL PACKAGE Date Date supports the following constructors: Date( ) Date(long millisec) // Show date and time using only Date methods. import java.util.Date; class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); System.out.println(date); } } Sample output is shown here: Mon Apr 22 09:51:52 CDT 2002 Random The Random class is a generator of pseudorandom numbers. These are called pseudorandom numbers because they are simply uniformly distributed sequences. Random defines the following constructors: Random( ) Random(long seed)
  • 11. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 11 ❖ EXCEPTION HANDLING Error can be 2 categories 1.Compile time error: • Missing semicolon • Missing brackets in classes and method. • Misspelling of identifiers and keywords • Missing double quotes in string. • Use of understand variable • Incomplete types in assignments/initialization. • Bad reference object • Use of = in place of = = operator. 2.RunTime Errors • Dividing an integer by zero. • Accessing an element that is out of the bound of an array. • Trying to store a value into an array of an incomplete class or type. • Trying to cast an instance of a class to one of its subclass. • Attempting to use a negative size of an array. • Converting invalid string to a number. class Exc0 { public static void main(String args[]) { int d = 0; int a = 42 / d; } } java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4) Or
  • 12. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 12 class Exc1 { static void subroutine() { int d = 0; int a = 10 / d; } public static void main(String args[]) { Exc1.subroutine(); } } o/p java.lang.ArithmeticException: / by zero at Exc1.subroutine(Exc1.java:4) at Exc1.main(Exc1.java:7)
  • 13. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 13 Exception: It is condition that is caused by run time error in the program. The purpose of exception handling mechanism is to provide a means to detect and report an “exception circumstance” ❖ Types Of Exception 1.Checked Exceptions Throwable and its subclasses except Error and RuntimeException put together are called as checked exceptions. If these exceptions are not handled or checked by the programmer in coding, the program does not
  • 14. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 14 compile. That is, compiler bothers much of this type of exceptions because they are raised in some special cases in the code which if not handled, the program may lead to many troubles. Common examples are FileNotFoundException, IOException and InterruptedException etc. 2.Unchecked Exceptions RuntimeException and its all subclasses including Error are known as unchecked exceptions. As the name indicates, even if they are not handled or checked by the programmer, the program simply compiles. If at runtime, problems arise, the execution simply terminates. That is, regarding unchecked exceptions, the compiler does not bother. Common examples are ArithmeticException, ArrayIndexOutOfBoundsException, NumberFormatException, NullPointerException etc. ❖ Syntax Java exception handling is managed via five keywords: try, catch, throw, throws,and finally. try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } //……………. finally { // block of code to be executed before try block ends }
  • 15. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 15 Using try and catch class Exc2 { public static void main(String args[]) { int d, a; try { d = 0; a = 42 / d; } catch (ArithmeticException e) { System.out.println("Division by zero."); OR System.out.println("Error"+e); } } Exception class have 2 methods 1. String getMessage(); It is method of throwable class. This methods print only the message part of the output printed by object e. class Exc2 { public static void main(String args[]) { int d, a; try { d = 0; a = 42 / d; } catch (ArithmeticException e) { System.out.println("Error"+e.getMessage()) } } 2. void printStackTrace(); It is method of throwable class.This method print the same message of “e” object & line number where the exception occurred. class Exc2
  • 16. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 16 { public static void main(String args[]) { int d, a; try { d = 0; a = 42 / d; } catch (ArithmeticException e) { e. printStackTrace(); } } ❖ Multiple catch Clauses class MultiCatch { 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); } } }
  • 17. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 17 Here is the output generated by running it both ways: C:>java MultiCatch a = 0 Divide by 0: java.lang.ArithmeticException: / by zero After try/catch blocks. C:>java MultiCatch TestArg a = 1 Array index oob: java.lang.ArrayIndexOutOfBoundsException After try/catch blocks. OR Try using exception class class MultiCatch { 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); } } Note: The following program contains an error.A subclass must come before its superclass in a series of catch statements. If not, unreachable code will be created and a compile-time error will result. class SuperSubCatch { public static void main(String args[]) { try
  • 18. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 18 { int a = 0; int b = 42 / a; } catch(Exception e) { System.out.println("error1"+e); } catch(ArithmeticException e) { System.out.println("error2"+e); THE JAVA LANGUAGE } } } Above error solve as follow class SuperSubCatch { public static void main(String args[]) { try { int a = 0; int b = 42 / a; } catch(ArithmeticException e) { System.out.println("error2"+e); VA LANGUAGE } catch(Exception e) { System.out.println("error1"+e); } } }
  • 19. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 19 ❖ Nested try Statements class NestTry { public static void main(String args[]) { try { int a = args.length; int b = 42 / a; System.out.println("a = " + a); try { if(a==1) a = a/(a-a); if(a==2) { int c[] = { 1 }; c[42] = 99; } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); } } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } } } C:>java NestTry Divide by 0: java.lang.ArithmeticException: / by zero C:>java NestTry One a = 1 Divide by 0: java.lang.ArithmeticException: / by zero
  • 20. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 20 C:>java NestTry One Two a = 2 Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundsException ❖ Use try..catch in function /* Try statements can be implicitly nested via calls to methods. */ class MethNestTry { static void nesttry(int a) { try { if(a==1) a = a/(a-a); if(a==2) { int c[] = { 1 }; c[42] = 99; } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); } } public static void main(String args[]) { try { int a = args.length; int b = 42 / a; System.out.println("a = " + a); nesttry(a); } catch(ArithmeticException e) {
  • 21. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 21 System.out.println("Divide by 0: " + e); } } } The output of this program is identical to that of the preceding example ❖ Finally Statement 1. Java support statement known as finally statement. 2. finally block can be used to handle any exception generated within try block. 3. When finally block is defined, that is guaranteed to execute, regardless of whether or not an exception is thrown. 4. finally use to perform certain house-keeping operation such as closing files and releasing resources. 5. It may be added immediately after the try block or after last catch block shown as follow. try { ………………. ……….. } finally { …………… ………. } Or try { ……………….
  • 22. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 22 ……….. } catch(…) { ………… ………. } finally { …………… ………. } class Exc2 { public static void main(String args[]) { int d, a; try { d = 0; a = 42 / d; } catch (ArithmeticException e) { System.out.println("Error"+e); } Finally { System.out.println("finally block"); }
  • 23. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 23 ❖ THROW The Java throw keyword is used to explicitly throw an exception.It can throw either checked or uncheked exception in java by throw keyword. Syntax throw new throwable_subclass; e.g throw new NullPointerException("null exception"); class MyException extends Exception { MyException(String message) { super(message); } } class TestExp { public static void main(String args[]) { int x=5; try { If (x<0) throw new MyException(“no is negative”); } catch(MyException e) { System.out.println(e.getMessage()); }
  • 24. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 24 } } ❖ Rethrowing Exception class ThrowDemo { static void demoproc() { try { T throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside demoproc."); throw e; // rethrow the exception } } public static void main(String args[]) { try { demoproc(); } catch(NullPointerException e) { System.out.println("Recaught: " + e); } } } throws } } ❖ throws Throws keyword is used to declare that a method may throw one or some exceptions. Thorws is used with the method signature.
  • 25. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 25 type method-name(parameter-list) throws exception-list { // body of method } Here, exception-list is a comma-separated list of the exceptions that a method can throw. class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { Try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); } } } Here is the output generated by running this example program: inside throwOne caught java.lang.IllegalAccessException: demo
  • 26. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 26 ❖ Exception Meaning ArithmeticException Arithmetic error, such as divide-by-zero. ArrayIndexOutOfBoundsException Array index is out-of-bounds. ArrayStoreException Assignment to an array element of an incompatible type. ClassCastException Invalid cast. IllegalArgumentException Illegal argument used to invoke a method. IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread. IllegalStateException Environment or application is in incorrect state IllegalThreadStateException Requested operation not compatible with current thread state. IndexOutOfBoundsException Some type of index is out-of-bounds. NegativeArraySizeException Array created with a negative size. NullPointerException Invalid use of a null reference. NumberFormatException Invalid conversion of a string to a numeric format. SecurityException Attempt to violate security. StringIndexOutOfBounds Attempt to index outside the bounds of a string. UnsupportedOperationException An unsupported operation was Encountered ClassNotFoundException Class not found. CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface. IllegalAccessException Access to a class is denied. InstantiationException Attempt to create an object of an abstract class or interface. InterruptedException One thread has been interrupted by another thread. NoSuchFieldException A requested field does not exist. NoSuchMethodException A requested method does not exist..
  • 27. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 27 Java - Collections Framework Collection(Def):A collection allows a group of objects to be treated as a single unit. Arbitrary objects can be stored, retrieved, and manipulated as elements of collection. This framework is provided in the java.util package.
  • 28. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 28 Classes & Interfaces
  • 29. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 29 ❖ Collection Interface SN Methods with Description 1 Boolean add(Object obj) Adds obj to the invoking collection. Returns true if obj was added to the collection. Returns false if obj is already a member of the collection, or if the collection does not allow duplicates. 2 Boolean addAll(Collection c) Adds all the elements of c to the invoking collection. Returns true if the operation succeeded (i.e., the elements were added). Otherwise, returns false. 3 void clear( ) Removes all elements from the invoking collection. 4 Boolean contains(Object obj) Returns true if obj is an element of the invoking collection. Otherwise, returns false. 5 Boolean containsAll(Collection c) Returns true if the invoking collection contains all elements of c. Otherwise, returns false. 6 Boolean equals(Object obj) Returns true if the invoking collection and obj are equal. Otherwise, returns false. 7 Boolean isEmpty( ) Returns true if the invoking collection is empty. Otherwise, returns false. 8 Iterator iterator( ) Returns an iterator for the invoking collection. 9 Boolean remove(Object obj) Removes one instance of obj from the invoking collection. Returns true if the element was removed. Otherwise, returns false. 10 Boolean removeAll(Collection c) Removes all elements of c from the invoking collection. Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false.
  • 30. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 30 ❖ List Interface • It extends collection interface. • The elements in a list are ordered. Each element, therefore, has a position in the list. • It can contain duplicates. • A zero-based index can be used to access the element at the position designated by the index value. The position of an element can change as elements are inserted or deleted from the list. ❖ LinkedList Class • The LinkedList implements the List interface. • It provides a linked-list data structure. • The elements in a linked list are ordered. • It can contain duplicates. Constructor LinkedList() import java.util.*; class LinkedListDemo { public static void main(String args[]) { LinkedList ll = new LinkedList(); ll.add("F"); ll.add("B"); ll.add("D"); System.out.println(ll);
  • 31. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 31 } } import java.util.*; class LinkedListDemo { public static void main(String args[]) { // create a linked list LinkedList ll = new LinkedList(); // add elements to the linked list ll.add("F"); ll.add("B"); ll.add("D"); ll.add("E"); ll.add("C"); ll.addLast("Z"); ll.addFirst("A"); ll.add(1, "A2"); System.out.println("Original contents of ll: " + ll); // remove elements from the linked list ll.remove("F"); ll.remove(2); System.out.println("Contents of ll after deletion: " + ll); // remove first and last elements ll.removeFirst(); ll.removeLast(); System.out.println("ll after deleting first and last: " + ll); // get and set a value Object val = ll.get(2); ll.set(2, (String) val + " Changed"); System.out.println("ll after change: " + ll); } } This would produce following result:
  • 32. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 32 Original contents of ll: [A, A2, F, B, D, E, C, Z] Contents of ll after deletion: [A, A2, D, E, C, Z] ll after deleting first and last: [A2, D, E, C] ll after change: [A2, D, E Changed, C] ❖ ArrayList Class • The ArrayList class implements the List interface. • ArrayList supports dynamic arrays that can grow as needed. • The elements in a Array list are ordered. • It can contain duplicates. • ArrayList gives better performance as it is non-synchronized. • ArrayList is non-synchronized which means • multiple threads can work on ArrayList at the same time Constructor ArrayList() import java.util.*; class ArrayListDemo { public static void main(String args[]) { ArrayList al = new ArrayList(); al.add("F"); al.add("B"); al.add("D"); System.out.println(al); } }
  • 33. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 33 ArrayList LinkedList 1) ArrayList internally uses dynamic array to tore the elements. LinkedList internally uses doubly linked list to store the elements. 2) Manipulation with ArrayList is slow because it internally uses array. If any element is removed from the array, all the bits are shifted in memory. Manipulation with LinkedList is faster than ArrayList because it uses doubly linked list so no bit shifting is required in memory. 3) ArrayList is better for storing and accessing data. LinkedList is better for manipulating data. 4) ArrayList al = new ArrayList(); LinkedList al = new LinedList(); ❖Vector class • The class can be used to create a generic dynamic array known as vector that can hold objects of any type and any number.(Object don’t have to be homogenous) • The Vector class implements the List interface. • The elements in a Vector are ordered. • It can contain duplicates. • Vector is synchronized. This means if one thread is working on Vector, no other thread can get a hold of it. • Vector operations gives poor performance as they are thread-safe Constructor Vector( ) Vector(int size) Vector(int size,int incr) import java.util.*; class VectorDemo { public static void main(String args[]) { Vector v = new Vector(); v.add("F");
  • 34. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 34 v.add("B"); v.add("D"); System.out.println(v); } } ❖ Iterator Need: You will want to cycle through the elements in a collection. For example, it might want to display each element. It can implements either the Iterator or the ListIterator interface. Iterator is interface enables you to cycle through a collection, obtaining or removing elements. The Methods Declared by Iterator: SN Methods with Description 1 boolean hasNext( ) Returns true if there are more elements. Otherwise, returns false. 2 Object next( ) Returns the next element. 3 Void remove( ) Removes the current element. import java.util.*; class IteratorDemo { public static void main(String args[]) { ArrayList al = new ArrayList(); al.add("C"); al.add("A"); al.add("E");
  • 35. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 35 System.out.print(“Display element using iterator” ); Iterator itr = al.iterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element ); } } } ❖ ListIterator ListIteratoris interface that extends Iterator to allow bidirectional traversal of a list, and the modification of elements. The Methods Declared by ListIterator: SN Methods with Description 1 Void add(Object obj) Inserts obj into the list in front of the element that will be returned by the next call to next( ). 2 boolean hasNext( ) Returns true if there is a next element. Otherwise, returns false. 3 boolean hasPrevious( ) Returns true if there is a previous element. Otherwise, returns false. 4 Object next( ) Returns the next element. A NoSuchElementException is thrown if there is not a next element. 5 int nextIndex( ) Returns the index of the next element. If there is not a next element, returns the size of the list. 6 Object previous( ) Returns the previous element. A NoSuchElementException is thrown if there is not a previous element. 7 int previousIndex( )
  • 36. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 36 Returns the index of the previous element. If there is not a previous element, returns -1. 8 Void remove( ) Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked. 9 Void set(Object obj) Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ). import java.util.*; class ListIteratorDemo { public static void main(String args[]) { ArrayList al = new ArrayList(); al.add("C"); al.add("A"); al.add("E"); System.out.print(“Display next element using listiterator” ); ListIterator itr = al.listIterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element ); } System.out.print(“Display previous element using listiterator” ); while(itr.hasPrevious()) { Object element = itr.previous(); System.out.print(element + " "); } } }
  • 37. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 37 ListIterator Iterator ListIterator is interface that extends Iterator to allow bidirectional traversal of a list, and the modification of elements Iterator is interface enables you to cycle through a collection, obtaining or removing elements It can traverse in both the directions (forward and Backward). It can traverse in only forward direction using Iterator It can use ListIterator to traverse List only. Iterator is used for traversing List and Set both. It can add element during traversing a list using ListIterator. It can not add element during traversing a list using Iterator. It can obtain indexes at any point of time while traversing a list using ListIterator It cannot obtain indexes while using Iterator. Methods of ListIterator: • add(E e) • hasNext() • hasPrevious() • next() • nextIndex() • previous() • previousIndex() • remove() • set(E e) Methods of Iterator: • hasNext() • next() • remove() ❖ Enumeration Interface The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects.
  • 38. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 38 boolean hasMoreElements( ) When implemented, it must return true while there are still more elements to extract, and false when all the elements have been enumerated. Object nextElement( ) This returns the next object in the enumeration as a generic Object reference. import java.util.*; class Enumeration { public static void main(String args[]) { Enumeration d; Vector v = new Vector(); v.add("C"); v.add("A"); v.add("E"); d=v.elements(); while (d.hasMoreElements()) { System.out.println(d.nextElement()); } } } ❖ Set Interface • It extends collection interface • It does not contain duplicate ❖ SortedSet Interface The SortedSet interface extends Set and declares the behavior of a set sorted in ascending order.
  • 39. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 39 ❖ TreeSet Class • It implements SortedSet interface that uses a tree for storage. • Objects are stored in sorted, ascending order. • Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly. Constructor TreeSet( ) TreeSet(Comparator comp) import java.util.*; class TreeSetDemo { public static void main(String args[]) { // Create a tree set TreeSet ts = new TreeSet(); // Add elements to the tree set ts.add("C"); ts.add("A"); ts.add("B"); ts.add("E"); ts.add("F"); ts.add("D"); System.out.println(ts); } } This would produce following result: [A, B, C, D, E, F] ❖ HashSet Class • HashSet implemets the Set interface. • It creates a collection that uses a hash table for storage • It does not have duplicate • It displaying object at any order.
  • 40. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 40 Constructor HashSet( ) import java.util.*; class HashSetDemo { public static void main(String args[]) { // create a hash set HashSet hs = new HashSet(); // add elements to the hash set hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); System.out.println(hs); } } o/p [A, F, E, D, C, B] ❖ Map Interface
  • 41. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 41 • A Map interface defines mappings from keys to values. The <key, value> pair is called an entry in a Map. • A Map does not allow duplicate keys, in other words, the keys are unique. Methods • Object put(Object key, Object value) • Object get(Object key) • Object remove(Object key) • void putAll(Map t) • boolean containsKey(Object key) • boolean containsValue(Object value) • int size() • boolean isEmpty() • void clear()
  • 42. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 42 1.TreeMap Class • The TreeMap class implements the Map interface by using a tree. • A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval. • You should note that, unlike a hash map, a tree map guarantees that its elements will be sorted in ascending key order. • It contains only unique key. Constructor TreeMap() import java.util.*; class TreeMapDemo { public static void main(String args[]) { TreeMap tm = new TreeMap(); tm.put("Amol", new Float(55.55)); tm.put("Punit", new Float(66.33)); System.out.println(tm); } } 2.HashMap Class • The HashMap class uses a hash table to implement the Map interface. • It display object any order. • It contains only unique key. Constructor
  • 43. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 43 HashMap( ) import java.util.*; class HashMapDemo { public static void main(String args[]) { HashMap tm = new HashMap(); tm.put("Amol", new Float(55.55)); tm.put("Punit", new Float(66.33)); System.out.println(tm); } } 3.Hashtable • Hashtable contains values based on the key. It implements the Map interface. • It contains only unique key. • It is synchronized. Constructor Hashtable(); import java.util.*; class HashDemo { public static void main(String args[]) { Hashtable tm = new Hashtable(); tm.put("Amol", new Float(55.55)); tm.put("Punit", new Float(66.33)); System.out.println(tm); } }
  • 44. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 44 APPLET ❖ What is an Applet? Applet(java.applet.Applet) is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside the browser and works at client side. ❖ The Basic Applet Life Cycle Born initialization (Load Applet) Start() Stop() Display() stopped Paint() Start() Destroyed end BORN RUNNING IDLE DEAD
  • 45. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 45 1. Initialization state Applet enters the initialization state when it is first loaded. This is achieved by calling init() method of Applet Class. The applet is born. At this stage ,It may the following, if required. 1. Create object needed by applet. 2. Set up initial values. 3. Load images or fonts. 4. Set up colors. The initialization occurs only once in the applet’s life cycle. To provide any of the behaviors mentioned above, it must override the init() method. public void init() { --------------- //action } 2. Running State This method is automatically called after the browser calls the init method. It is also called whenever the user returns to the page containing the applet after having gone off to other pages. public void start() { --------------- //action } 3. Idle or stopped state. This method is automatically called when the user moves off the page on which the applet sits. It can, therefore, be called repeatedly in the same applet. public void stop() { --------------- //action } 4.Dead state
  • 46. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 46 An applet is said to be dead when it is removed from memory. This occurs automatically by invoking the destroy() method when it quit the browser. It override the destroy() method to clean up these resources. public void destroy() { --------------- //action } 5. Display State Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the browser. public void paint(Graphics g) { --------------- //action } import java.awt.*; import java.applet.*; public class AppletSkel extends Applet { // Called first. public void init() { // initialization } /* Called second, after init(). Also called whenever the applet is restarted. */ public void start() { // start or resume execution } // Called when the applet is stopped. public void stop() { // suspends execution
  • 47. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 47 } /* Called when applet is terminated. This is the last method executed. */ public void destroy() { // perform shutdown activities } // Called when an applet's window must be restored. public void paint(Graphics g) { // redisplay contents of window } } ❖ How to run applet 1. compile the HelloWorldApplet.java program. i.e C:javac HelloWorldApplet.java import java.applet.Applet; import java.awt.*; public class HelloWorldApplet extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } } 2. Insert the HelloWorldApplet.class in the following HTML tag. And save HTML file(Hello.html) <html> <head> <title> hello world </title> </head> <body> This is the applet:<P>
  • 48. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 48 <applet code="HelloWorldApplet" width="150" height="50" name=”visionacademy”> </applet> </body> </html> 3. Use appletviewer command . C: appletviewer Hello.html Or /* <applet code=" HelloWorldApplet" width=300 height=100> </applet> */ import java.applet.Applet; import java.awt.*;
  • 49. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 49 public class HelloWorldApplet extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } } Compile C: javac HelloWorldApplet.java Run C: appletviewer HelloWorldApplet.java The HTML APPLET Tag The APPLET tag < APPLET [CODEBASE = appletURL] CODE = appletClassFile [ALT = alternateText] [ARCHIVE = archiveFile] [NAME = appletInstanceName] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] > [< PARAM NAME = AttributeName VALUE = AttributeValue />] </APPLET>
  • 50. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 50 What is use of PARAM tag? Parameters are passed to applets in the form of NAME=VALUE pairs in <PARAM> tags between the opening and closing in a APPLET tags. It can read the values passed through the PARAM tags of applet by using method e getParameter() import java.applet.*; import java.awt.*; public class DrawStringApplet extends Applet { String msg; public void paint(Graphics g) { String s = getParameter("msg"); g.drawString(s, 50, 25); } }
  • 51. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 51 <HTML> <BODY> This is the applet:<P> <APPLET code=”Myapplet" width="300" height="50"> <PARAM name="Message" value=”vision academy"> </APPLET> </BODY> </HTML> ❖ Simple Applet Display Methods Use drawString( ), which is a member of the Graphics class. It has the following general form: void drawString(String message, int x, int y) ❖ Difference between paint(),update(),repaint() methods repaint() –> update() –> paint() paint():This method holds instructions to paint this component. It shouldn't call this method directly, It should call by using repaint(). public void paint(Graphics g) { } Repaint():Repaint() method calls automatically update() method and in turn update() method calls paint() method Update():An update method is called on calling the repaint method. The default implementation of the update() method clears the screen and calls the paint() method. ❖ Background & Forground Color void setBackground(Color newColor) void setForeground(Color newColor)
  • 52. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 52 Here, newColor specifies the new color. The class Color defines the constants shown here that can be used to specify colors: Color.black Color.magenta Color.blue Color.orange Color.cyan Color.pink Color.darkGray Color.red Color.gray Color.white Color.green Color.yellow Color.lightGray For example, this sets the background color to green and the text color to red: setBackground(Color.green); setForeground(Color.red); /* A simple applet that sets the foreground and background colors and outputs a string. */ import java.awt.*; import java.applet.*; /* <applet code="Appletcolor" width=300 height=100> </applet> */ public class Appletcolor extends Applet { String msg; // set the foreground and background colors. public void init() { setBackground(Color.cyan); setForeground(Color.red); msg = "Inside init( ) --"; } }
  • 53. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 53 Advantage of applet 1. As applet is a small java program, so it is platform independent code which is capable to run on any browser. 2. Applets can perform various small tasks on client-side machines. They can play sounds, show images, get user inputs, get mouse clicks and even get user keystrokes, etc ... 3. Applets creates and edit graphics on client-side which are different and independent of client-side platform. 4. As compared to stand-alone application applets are small in size, the advantage of transferring it over network makes it more usable. 5. Applets run on client browser so they provide functionality to import resources such as images, audio clips based on Url's. 6. Applets are quite secure because of their access to resources. 7. Applets are secure and safe to use because they cannot perform any modifications over local system. Applets Restrictions(Disadvantages) 1. If we are running an applet from a provider who is not trustworthy than security is important. 2. Applet itself cannot run or modify any application on the local system. 3. Applets has no access to client-side resources such as files , OS etc. 4. Applets can have special privileges. They have to be tagged as trusted applets and they must be registered to APS (Applet Security Manager). 5. Applet has little restriction when it comes to communication. It can communicate only with the machine from which it was loaded. 6. Applet cannot work with native methods. 7. Applet can only extract information about client-machine is its name, java version, OS, version etc ... . 8. Applets tend to be slow on execution because all the classes and resources which it needs have to be transported over the network.
  • 54. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 54 AWT (Abstract Window toolkit) The AWT classes are contained in the java.awt package. It is one of Java’s largest packages. It is one of Java’s largest packages. The AWT hierarchy Classes: • BorderLayout • CardLayout • CheckboxGroup • Color • Component o Button o Canvas o Checkbox o Choice o Container ▪ Panel ▪ Window ▪ Dialog ▪ Frame o Label o List o Scrollbar o TextCompoment ▪ TextArea ▪ TextField • Dimension • Event • FileDialog • FlowLayout • Font • FontMetrics • Graphics • GridLayout • GridBagConstraints • GridBagLayout
  • 55. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 55 • Image • Insets • MediaTracker • MenuComponent o MenuBar o MenuItem ▪ CheckboxMenuItem ▪ Menu • Point • Polygon • Rectangle • Toolkit Interfaces • LayoutManager • MenuComponent
  • 56. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 56 java.lang Object Component java.awt Container Window Panel Frame Applet Javax.swing Jframe Japplet Container • A container is a component which can contain other components inside itself. • It is also an instance of a subclass of java.awt.Container. java.awt.Container extends java.awt.Component so containers are themselves components. • In general components are contained in a container. containers include applet,windows, frames, dialogs, and panels. • Containers may contain other containers. • Every container has a LayoutManager that determines how different components are positioned within the container. It is 2 kind of container
  • 57. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 57 • Panel • Window ▪ Frame ▪ Dialog Panel • Panels are subclasses of java.awt.Panel. A panel is contained inside another container. • Panels do not stand on their own. • The Panel class is a concrete subclass of Container. • Panel is a window that does not contain a title bar, menu bar, or border. • Main purpose is to subdivide the drawing area into separate rectangular pieces. Since each Panel can have its own LayoutManager • Other components can be added to a Panel object by its add( ) method. import java.awt.*; import java.awt.event.*; public class Pan extends Frame { public Pan() { setLayout(new BorderLayout()); add(new TextArea(),BorderLayout.CENTER); Panel p = new Panel(); p.setLayout(new FlowLayout(FlowLayout.CENTER)); p.add(new Button("OK")); p.add(new Button("CANCEL")); add(p, BorderLayout.SOUTH); setVisible(true); } public static void main(String args[]) {
  • 58. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 58 new Pan(); } } Window The Window class creates a top-level window.. Generally, it won’t create Window objects directly. Instead, you will use a subclass of Window called Frame. Frame • Frame encapsulates what is commonly thought of as a “window.” It is a subclass of Window . • It has a title bar, menu bar, borders, and resizing corners. • It can be independently moved and resized Frame Example import java.awt.*; import java.awt.event.*; public class Fr extends Frame { public Fr() { super("Vision Academy Sachin Sir 9823037693"); or setTitle(“Vision Academy Sachin Sir 9823037693”) setSize(250, 250); setLocation(300,200); setVisible(true);
  • 59. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 59 addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String args[]) { new Fr(); } } OR import java.awt.*; import java.awt.event.*; public class Fr {public static void main(String args[]) {
  • 60. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 60 Frame f=new Frame(); f.setTitle("Vision Academy Sachin Sir 9823037693"); f.setSize(250, 250); f.setLocation(300,200); f.setVisible(true); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } } Components Components is abstract class that encapsulated all the attribute of visual components. Method Of Components Component add(Component compObj) void remove(Component obj) removeAll( ). Components are graphical user interface (GUI) widgets like checkboxes, menus, windows, buttons, text fields, applets, and more.
  • 61. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 61 In Java all components are subclasses of java.awt.Component. Subclasses of Component include • Component o Button o Canvas o Checkbox o Choice o Container ▪ Panel ▪ W-indow ▪ Dialog ▪ Frame o Label o List o Scrollbar o TextCompoment ▪ TextArea ▪ TextField The key thing to remember about adding components to the applet is the three steps: 1. Declare the component 2. Initialize the component 3. Add the component to the layout. Label Class: java.awt.Label import java.awt.*; import java.awt.event.*; public class Demo extends Frame { Public Demo() { setLayout( new FlowLayout()); Label l = new Label("Hello TY");
  • 62. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 62 add(l); setVisible(true); } public static void main(String args[]) { new Demo(); } } Constructor Label( ) Label(String str) Label(String str, int how) Where How=>Label.LEFT, Label.RIGHT, or Label.CENTER. Label center = new Label("This label is centered", Label.CENTER); Label left = new Label("This label is left-aligned", Label.LEFT); Label right = new Label("This label is right-aligned", Label.RIGHT); Method public int getAlignment() public synchronized void setAlignment(int alignment) public String getText() public synchronized void setText(String text) import java.awt.*; import java.awt.event.*; public class Demo extends Frame { Public Demo() { setLayout( new FlowLayout()); Label l= new Label("Hello TY");
  • 63. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 63 l.setForeground(Color.blue); l.setBackground(Color.yellow); l.setFont(new Font("Arial", Font.BOLD, 24)); add(l); setVisible(true); } public static void main(String args[]) { new Demo(); } } Buttons Class: java.awt.Button Constructor Button( ) Button(String str) Methods These methods are as follows: void setLabel(String str) String getLabel( ) Here, str becomes the new label for the button. import java.awt.*; import java.awt.event.*; public class Demo extends Frame { public Demo() { setLayout( new FlowLayout()); Button b = new Button("OK"); add(b); setVisible(true);
  • 64. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 64 } public static void main(String args[]) { new Demo(); } } Button Actions import java.awt.*; import java.awt.event.*; public class Demo extends Frame { public Demo () { Button b=new Button(“ok”); b.addActionListener(new Action()); } public static void main(String args[]) { new Demo(); } } class Action implements ActionListener { public void actionPerformed(ActionEvent e) { //logic } } Or import java.awt.*;
  • 65. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 65 import java.awt.event.*; public class Demo extends Frame implements ActionListener { public Demo () { Button b=new Button(“ok”); b.addActionListener(this); } public void actionPerformed(ActionEvent e) { //logic } public static void main(String args[]) { new Demo(); } } TextFields Class:java.awt.TextField Constructor public TextField() public TextField(String text) public TextField(int length) public TextField(String text, int length) Method String getText()
  • 66. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 66 Void setText(String) import java.awt.*; import java.awt.event.*; public class Demo extends Frame { public Demo() { setLayout( new FlowLayout()); TextField t = new TextField(10); add(t); setVisible(true); } public static void main(String args[]) { new Demo(); } } TextArea Class:java.awt.TextArea Constructors: public TextArea() public TextArea(String text) public TextArea(int rows, int columns) public TextArea(String text, int rows, int columns) public TextArea(String text, int rows, int columns, int scrollbars) Where TextArea.SCROLLBARS_BOTH TextArea.SCROLLBARS_HORIZONTAL_ONLY TextArea.SCROLLBARS_NONE TextArea.SCROLLBARS_VERTICAL_ONLY import java.awt.*;
  • 67. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 67 import java.awt.event.*; public class Demo extends Frame { public Demo() { setLayout( new FlowLayout()); TextArea t = new TextArea(10,20); add(t); setVisible(true); } public static void main(String args[]) { new Demo(); } } TextEvents public void textValueChanged(TextEvent te) addTextListener() method. Choice Class:java.awt.Choice Step for adding choice 1. Declare the Choice 2. Allocate the Choice 3. Add the data items to the Choice 4. Add the Choice to the layout 5. Add an ItemListener to the Choice
  • 68. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 68 Methods public int getItemCount() public String getItem(int index) public void add(String item) public void addItem(String item) public void insert(String item, int position) public void remove(String item) public void remove(int position) public void removeAll() public void removeAll() public String getSelectedItem() import java.awt.*; import java.awt.event.*; public class Demo extends Frame implements ItemListener { Choice ch; TextField t; public Demo() { setLayout( new FlowLayout()); ch = new Choice(); ch.addItem("BCS"); ch.addItem("BCA"); ch.addItem("BSC"); t=new TextField(20); add(ch); add(t); ch.addItemListener(this); setVisible(true); } public void itemStateChanged(ItemEvent ie) { String s=ch.getSelectedItem(); t.setText(s); } public static void main(String args[]) { new Demo();
  • 69. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 69 } } List Class:java.awt.List Constructor public List() public List(int numLines) public List(int numLines, boolean allowMultipleSelections) allowMultipleSelections says whether the user is allowed to select more than one item at once (typically by Shift-clicking). Methods public void add(String item) public void addItem(String item) public void add(String item, int index) public void addItem(String item, int index) public void removeAll() public void remove(String item) public void remove(int position) public int getItemCount() public String getItem(int index) public String[] getItems() public int getSelectedIndex() public int[] getSelectedIndexes() public String getSelectedItem() public String[] getSelectedItems() public Object[] getSelectedObjects() public boolean isMultipleMode() public void setMultipleMode(boolean b) import java.awt.*; import java.awt.event.*; public class Demo extends Frame implements ItemListener {
  • 70. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 70 List l; TextField t; public Demo() { setLayout( new FlowLayout()); l = new List(); l.addItem("BCS"); l.addItem("BCA"); l.addItem("BSC"); t=new TextField(20); add(l); add(t); l.addItemListener(this); setVisible(true); } public void itemStateChanged(ItemEvent ie) { String s=l.getSelectedItem(); t.setText(s); } public static void main(String args[]) { new Demo(); } } CHECKBOX Class:java.awt.CheckBox Constructors: Checkbox( ) Checkbox(String str) Checkbox(String str, boolean on) Checkbox(String str, boolean on, CheckboxGroup cbGroup) Checkbox(String str, CheckboxGroup cbGroup, boolean on) The first form creates a check box whose label is initially blank. The state of the check box is unchecked.
  • 71. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 71 The second form creates a check box whose label is specified by str.The state of the check box is unchecked. The third form allows you to set the initial state of the check box. If on is true, the check box is initially checked; otherwise, it is cleared. The fourth and fifth forms create a check box whose label is specified by str and whose group is specified by cbGroup. If this check box is not part of a group, thencbGroup must be null. (Check box groups are described in the next section.) The value of on determines the initial state of the check box. Methods boolean getState( ) void setState(boolean on) String getLabel( ) void setLabel(String str) import java.awt.*; import java.awt.event.*; public class Demo extends Frame implements ItemListener { Checkbox chk1; TextField t; public Demo() { setLayout( new FlowLayout()); chk1= new Checkbox("BCA"); t=new TextField(20); add(chk1); add(t); chk1.addItemListener(this); setVisible(true); } public void itemStateChanged(ItemEvent ie) { if (chk1.getState()==true) t.setText(chk1.getLabel());
  • 72. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 72 else t.setText(""); } public static void main(String args[]) { new Demo(); } } CheckboxGroup(Radio Button) import java.awt.*; import java.awt.event.*; public class Demo extends Frame implements ItemListener { Checkbox chk1,chk2; TextField t; public Demo() { setLayout( new FlowLayout()); CheckboxGroup cbg = new CheckboxGroup(); chk1= new Checkbox("MALE",cbg,false); chk2= new Checkbox("FEMALE",cbg,false); t=new TextField(20); add(chk1); add(chk2); add(t); chk1.addItemListener(this); chk2.addItemListener(this); setVisible(true); } public void itemStateChanged(ItemEvent ie) { if (chk1.getState()==true) t.setText(chk1.getLabel());
  • 73. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 73 else t.setText(chk2.getLabel()); } public static void main(String args[]) { new Demo(); } } ❖ What is LayoutManager? Def:The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is implemented by all the classes of layout managers. Each container has a layout manager associated with it. To change the layout manager for a container, use the setLayout() method. Syntax setLayout(LayoutManager obj) The predefined managers are listed below: 1. FlowLayout 2.GridLayout 3. BoxLayout 4.CardLayout 5.GridBagLayout 1.FlowLayout The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of applet or panel. Here are the constructors for FlowLayout: FlowLayout( ) FlowLayout(int how) FlowLayout(int how, int horz, int vert) how are as follows: FlowLayout.LEFT FlowLayout.CENTER
  • 74. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 74 FlowLayout.RIGHT horz and vert follows: specify the horizontal and vertical space left between components in horz and vert, respectively. e.g setLayout(new FlowLayout(FlowLayout.LEFT)); b1=new JButton("1"); b2=new JButton("2"); add(b1); add(b2); 2 BorderLayout Border layout manager is the layout manager that divides the container into 5 regions such as north,east,west,south,center.. BorderLayout( ) BorderLayout(int horz, int vert) BorderLayout defines the following constants that specify the regions: BorderLayout.CENTER BorderLayout.SOUTH BorderLayout.EAST BorderLayout.WEST BorderLayout.NORTH
  • 75. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 75 void add(Component compObj, Object region); e.g setLayout(new BorderLayout(5,5)); b1=new JButton("SOUTH"); b2=new JButton("NORTH"); b3=new JButton("EAST"); b4=new JButton("WEST"); b5=new JButton("CENTER"); 3.GridLayout The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle. GridLayout( ) GridLayout(int numRows, int numColumns ) GridLayout(int numRows, int numColumns, int horz, int vert) e.g setLayout(new GridLayout(4,4));
  • 76. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 76 4.GridBagLayout The Java GridBagLayout class is used to align components vertically, horizontally or along their baseline. The components may not be of same size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells. Each component occupies one or more cells known as its display area. Each component associates an instance of GridBagConstraints. With the help of constraints object we arrange component's display area on the grid. The GridBagLayout manages each component's minimum and preferred sizes in order to determine component's size. GridBagLayout() e.g setLayout(new GridBagLayout()); 5.CardLayout CardLayout is the only layout class which can hold several layouts in it.
  • 77. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 77 The card layout manager generates a stack of components, one on top of the other. The first component that you add to the container will be at the top of the stack, and therefore visible,and the last one will be at the bottom. Constructor as follows CardLayout( ) CardLayout(int horz, int vert) ❖ Manually Position Components setLayout(null); public void setLocation(int x, int y) public void setSize(int width, int height) import java.awt.*; import java.awt.event.*; public class Demo extends Frame { public Demo() { setLayout(null); Button b=new Button("OK"); b.setLocation(25, 50); b.setSize(30, 40);
  • 78. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 78 add(b); setVisible(true); } public static void main(String args[]) { new Demo(); } } EVENT Java has two types of events: 1. Low-Level Events: Low-level events represent direct communication from user. A low level event is a key press or a key release, a mouse click, drag, move or release,and so on. Following are low level events.
  • 79. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 79 2. High-Level Events: High-level (also called as semantic events) events encapsulate the meaning of a user interface component. These include following events.
  • 80. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 80
  • 81. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 81 ❖ Adapter Classes Definition:An adapter class provides an empty implementation of all methods in an event listener interface i.e this class itself write definition for methods which are present in particular event listener interface.
  • 82. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 82 Suppose you want to use MouseClicked Event or method from MouseListener, if you do not use adapter class then unnecessarily you have to define all other methods from MouseListener such as MouseReleased, MousePressed etc. But If you use adapter class then you can only define MouseClicked method and don’t worry about other method definition because class provides an empty implementation of all methods in an event listener interface. Adapter Class Listener Interface ComponentAdapter ComponentListener ContainerAdapter ContainerListener FocusAdapter FocusListener KeyAdapter KeyListener MouseAdapter MouseListener MouseMotionAdapter MouseMotionListener WindowAdapter WindowListener Before Using Adapter Class import java.awt.*; import java.awt.event.*; public class Demo extends Frame implements MouseListener { public Demo() { addMouseListener(this); setVisible(true); } public void mouseClicked(MouseEvent me) { } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } public void mousePressed(MouseEvent me) { } public void mouseReleased(MouseEvent me) {
  • 83. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 83 } public static void main(String args[]) { new Demo(); } } After using Adapter Class import java.awt.*; import java.awt.event.*; public class Demo extends Frame { public Demo() { setVisible(true); addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { System.out.println("mouse click"); } }); } public static void main(String args[]) { new Demo(); } }
  • 84. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 84 ❖ Swing AWT SWING AWT components are platform- dependent. Java swing components are platform- independent. AWT components are heavyweight. Swing components are lightweight. AWT provides less components than Swing. Swing provides more powerful components such as tables, lists, scrollpanes, tabbedpane etc. AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel. AWT doesn't follows MVC(Model View Controller) where model represents data, view represents presentation and controller acts as an interface between model and view. Swing support MVC e.g Button e.g JButton Class Description AbstractButton Abstract superclass for Swing buttons. ButtonGroup Encapsulates a mutually exclusive set of buttons. ImageIcon Encapsulates an icon. JApplet The Swing version of Applet. JButton The Swing push button class. JCheckBox The Swing check box class. JComboBox Encapsulates a combo box (an combination of a drop-down list and text field). JLabel The Swing version of a label. JRadioButton The Swing version of a radio button. JScrollPane Encapsulates a scrollable window. JTabbedPane Encapsulates a tabbed window. JTable Encapsulates a table-based control. JTextField The Swing version of a text field.
  • 85. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 85 JTree Encapsulates a tree-based control. Icons and Labels In Swing, icons are encapsulated by the ImageIcon class, which paints an icon from an image. Constructor of Icons ImageIcon(String filename) ImageIcon(URL url) The first form uses the image in the file named filename. The second form uses the image in the resource identified by url. Constructor of JLabel JLabel(Icon i) Label(String s) JLabel(String s, Icon i, int align) Here, s and i are the text and icon used for the label. The align argument is either LEFT, RIGHT, CENTER, LEADING, or TRAILING. METHODS Icon getIcon( ) String getText( ) void setIcon(Icon i) void setText(String s) import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Demo extends JFrame { public Demo() { ImageIcon ic = new ImageIcon("c:wl.jpg");
  • 86. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 86 JLabel l = new JLabel("Image", ic, JLabel.CENTER); add(l); setVisible(true); } public static void main(String args[]) { new Demo(); } } Text Fields Constructor JTextField( ) JTextField(int cols) JTextField(String s, int cols) JTextField(String s) Here, s is the string to be presented, and cols is the number of columns in the text field. The following example illustrates how to create a text field. The applet begins by getting its content pane, and then a flow layout is assigned as its layout manager. Next, a JTextField object is created and is added to the content pane. JPasswordField Creates a password field. Constructors JPasswordField() JPasswordField(String) JPasswordField(String, int) JPasswordField(int) JPasswordField(Document, String, int) The JButton Class Constructor
  • 87. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 87 JButton(Icon i) JButton(String s) JButton(String s, Icon i) import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Demo extends JFrame { public Demo() { setLayout(new FlowLayout()); JTextField t = new JTextField(10); JButton b=new JButton("OK"); add(t); add(b); setVisible(true); } public static void main(String args[]) { new Demo(); } } JCheck Boxes Constructor JCheckBox(Icon i) JCheckBox(Icon i, boolean state)
  • 88. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 88 JCheckBox(String s) JCheckBox(String s, boolean state) JCheckBox(String s, Icon i) JCheckBox(String s, Icon i, boolean state) Radio Buttons Constructor JRadioButton(Icon i) JRadioButton(Icon i, boolean state) JRadioButton(String s) JRadioButton(String s, boolean state) JRadioButton(String s, Icon i) JRadioButton(String s, Icon i, boolean state) import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Demo extends JFrame { public Demo() { setLayout(new FlowLayout()); JCheckBox chk1=new JCheckBox("red"); JCheckBox chk2=new JCheckBox("yellow"); JRadioButton r1=new JRadioButton("male"); JRadioButton r2=new JRadioButton("female"); add(chk1); add(chk2); add(r1); add(r2); setVisible(true); } public static void main(String args[]) { new Demo(); } }
  • 89. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 89 Combo Boxes Constructor JComboBox( ) JComboBox(Vector v)c static void main(String args[]) { new Demo(); } import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Demo extends JFrame { public Demo() { setLayout(new FlowLayout()); JComboBox cb=new JComboBox(); cb.addItem("BCS"); cb.addItem("BCA"); cb.addItem("BSC"); add(cb); setVisible(true); } public static void main(String args[]) { new Demo(); } }
  • 90. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 90 new Demo(); } Tabbed Panes A tabbed pane is a component that appears as a group of folders in a file cabinet. Each folder has a title. When a user selects a folder, its contents become visible. Only one of the folders may be selected at a time. Tabbed panes are commonly used for setting configuration options. The general procedure to use a tabbed pane in an applet is outlined here: 1. Create a JTabbedPane object. 2. Call addTab( ) to add a tab to the pane. (The arguments to this method define the title of the tab and the component it contains.) 3. Repeat step 2 for each tab. 4. Add the tabbed pane in to the container. import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Demo extends JFrame { public Demo() { //setLayout(new FlowLayout()); JTabbedPane jtp = new JTabbedPane(); jtp.addTab("BCS", new BcsPanel()); jtp.addTab("BCA", new BcaPanel()); add(jtp); setVisible(true); } class BcsPanel extends JPanel {
  • 91. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 91 BcsPanel() { add(new JButton("ok")); add(new JButton("cancel")); } } class BcaPanel extends JPanel { BcaPanel() { add(new JButton("yes")); add(new JButton("no")); } } public static void main(String args[]) { new Demo(); } } DEVELOPMENT NG JAVA JTable A table is a component that displays rows and columns of data. JTable(Object data[ ][ ], Object colHeads[ ]) Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-dimensional array with the column headings. Steps 1. Create a JTable object.
  • 92. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 92 2. Create a JScrollPane object. (The arguments to the constructor specify the table and the policies for vertical and horizontal scroll bars.) 3. Add the table to the scroll pane. 4. Add the scroll pane into the container import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Demo extends JFrame { public Demo() { String[] colHeads = { "Name", "Phone", "Fax" }; final Object[][] data = { { "amol", "4567", "8675" }, { "kiran", "7566", "5555" }, { "sagar", "5634", "5887" }, { "punit", "7345", "9222" }, { "umesh", "1237", "3333" }, }; JTable table = new JTable(data, colHeads); int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp = new JScrollPane(table, v, h); add(jsp, BorderLayout.CENTER); setVisible(true); } public static void main(String args[]) { new Demo(); } }
  • 93. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 93 Menu Menus are composed of three hierarchical pieces. The menu bar contains the various menus. Creating Menus You should build the menus before you display them. The typical order is: 1. Create a new MenuBar. 2. Create a new Menu. 3. Add items to the Menu. 4. Add the Menu to the MenuBar. 5. If necessary repeat steps 2 through 4. 6. Add the MenuBar into the container import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Demo extends JFrame { public Demo() { JMenu fm = new JMenu("File"); fm.add(new JMenuItem("Open")); fm.addSeparator( ); fm.add(new JMenuItem("Save")); JMenu fe = new JMenu("Edit"); fe.add(new JMenuItem("Copy")); fe.add(new JMenuItem("Cut"));
  • 94. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 94 JMenuBar mb = new JMenuBar( ); mb.add(fm); mb.add(fe); setJMenuBar(mb); setVisible(true); } public static void main(String args[]) { new Demo(); } } Dialogs(What are different type of dialog?) message dialog Displays a message to the user, usually accompanied by an OK button. confirmation dialog Ask a question and displays answer buttons, usually Yes, No, and Cancel. input dialog Asks the user to type in a string. import java.awt.*; import java.awt.event.*; import javax.swing.*; class Dialog { public static void main(String args[]) {
  • 95. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 95 JFrame f = new JFrame("Vision Academy"); JOptionPane.showMessageDialog(f, "You have mail."); int result = JOptionPane.showConfirmDialog(null, "Do you want to remove Windows now?"); String name = JOptionPane.showInputDialog(null, "Please enter your name."); } }
  • 96. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 96 Stream classes Stream: A stream is a sequence of data.In Java a stream is composed of bytes. Their 2 types of stream classes • Byte stream classes • Character stream classes
  • 97. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 97 ❖ Byte Stream Classes Byte stream classes have been designed to provide functional features for creating and manipulating streams and files for reading and writing bytes. Java provides two kinds of byte stream classes: input stream classes andoutput stream classes. 1.Input Stream Classes Input stream classes that are used to read bytes include a super class known as Inputstream and a number of subclasses for supporting various input-related functions. The super class InputStream is an abstract class, and, therefore, we cannot create instances of this class. Rather, we must use the subclasses that inherit from this class. Table InputStream Class Methods Method Description int read() returns the integral representation of the next available byte of input. It returns -1 when end of file is encountered int read (byte buffer []) attempts to read buffer. length bytes into the buffer and returns the total number of bytes successfully read. It returns -1 when end of file is encountered int read (byte buffer [], int loc, int nBytes) attempts to read 'nBytes' bytes into the buffer starting at buffer [loc] and returns the total number of bytes successfully read. It returns -1 when end of file is encountered int available () returns the number of bytes of the input available for reading Void mark(int nBytes) marks the current position in the input stream until 'nBytes' bytes are read void reset () Resets the input pointer to the previously set mark long skip (long nBytes) skips 'nBytes' bytes of the input stream and returns the number of actually skippedbyte void close () closes the input source. If an attempt is made to read even after closing the stream then it generates IOException
  • 98. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 98 import java.io.*; class F2 { public static void main(String args[]) { int ch; char ch2; try { File f1=new File("a.txt"); FileInputStream fin1=new FileInputStream(f1); while((ch=fin1.read())!=-1) { System.out.println((char)ch); } fin1.close(); } catch(Exception e) { } } } 2.Output Stream Classes Output stream classes are derived from the base class Outputstream like InputStream, the OutputStream is an abstract class and therefore we cannot instantiate it. The several subclasses of the OutputStream can be used for performing the output operations. TableOutputStream Class Methods .Method Description void write (int i) writes a single byte to the output stream void write (byte buffer [] ) writes an array of bytes to the output stream
  • 99. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 99 Void write(bytes buffer[],int loc, int nBytes) writes 'nBytes' bytes to the output stream from the buffer b starting at buffer [loc] void flush () Flushes the output stream and writes the waiting buffered output bytes void close () closes the output stream. If an attempt is made to write even after closing the stream then it generates IOException import java.io.*; class F1 { public static void main(String args[]) { try { File inFile=new File("a.txt"); char ch='b'; FileOutputStream fout=new FileOutputStream(inFile); fout.write(ch); fout.close(); } catch(Exception e) { } } } 2.Character Stream Classes Character streams can be used to read and write 16-bit Unicode characters. There are 2 types 1 reader stream classes 2.writer stream classes 1.Reader Stream Classes Reader stream classes that are used to read characters include a super class known as Reader and a number of subclasses for supporting various input-related functions.
  • 100. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 100 Reader stream classes are functionally very similar to the input stream classes, except input streams use bytes as their fundamental unit of information, while reader streams use characters import java.io.*; class F2 { public static void main(String args[]) { int ch; char ch2; try { File f1=new File("a.txt"); FileReader fin1=new FileReader(f1); while((ch=fin1.read())!=-1) { System.out.println((char)ch); } fin1.close(); } catch(Exception e) { } } } 2.Writer Stream Classes Like output stream classes, the writer stream classes are designed to perform all output operations on files. Only difference is that while output stream classes are designed to write bytes, the writer stream are designed to write character. import java.io.*; class F1 { public static void main(String args[]) {
  • 101. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 101 try { File inFile=new File("a.txt"); char ch='b'; FileWriter fout=new FilWriter(inFile); fout.write(ch); fout.close(); } catch(Exception e) { } } } java.io.File class This class supports a platform-independent definition of file and directory names. It also provides methods to list the files in a directory, to check the existence, readability,writeability, type, size, and modification time of files and directories, to make newdirectories, to rename files and directories, and to delete files and directories. Constructors: publicFile(String path); publicFile(String path, String name); publicFile(File dir, String name); Example File f1=new File(“/home/java/a.txt”); Methods 1. booleancanRead()- Returns True if the file is readable. 2. booleancanWrite()- Returns True if the file is writeable. 3. String getName()- Returns the name of the File with any directory names omitted. 4. boolean exists()- Returns true if file exists 5. String getAbsolutePath()- Returns the complete filename. Otherwise, if the File isa relative file specification, it returns the relative filename appended to the current working directory. 6. String getParent()- Returns the directory of the File. If the File is an absolute specification. 7. String getPath()- Returns the full name of the file, including the directory name.
  • 102. Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP,SET ) Classes For BBA(CA)/`BCA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 102 8. Boolean isDirectory()- Returns true if File Object is a directory 9. Boolean isFile()- Returns true if File Object is a file 10. longlastModified()- Returns the modification time of the file (which should be used for comparison with other file times only, and not interpreted as any particular time format). 11. long length()- Return*s the length of the file. 12. boolean delete()- deletes a file or directory. Returns true after successful deletionof a file. 13. booleanmkdir ()- Creates a directory. 14. booleanrenameTo (File dest)- Renames a file or directory. Returns true after successful renaming import java.io.File; classFileTest { public static void main(String args[ ]) { File f1=new File ("a.txt"); if (f1.exists()) System.out.println ("File Exists"); else System.out.println ("File Does Not Exist"); } } Vision Academy Since 2005 Prof. Sachin Sir(MCS,SET) 9822506209/9823037693 Branch1:Nr Sm Joshi College,Abv Laxmi zerox,Ajikayatara Build,Malwadi Rd,Hadapsar Branch2:Nr AM College,Aditya Gold Society,Nr Allahabad Bank ,Mahadevnager Why Vision Academy?... • Lectures On Projector(1 st time in Hadapsar) • Experienced Faculty • Placement Assist • Regular Guest Lectures & Seminars • Computer Lab Facility • Project Guidance for BE/MCA/MCS Students. • Courses Sun Certification , DBA Certification, SAP,TESTING ,AS400 Course Guidance etc • Digital Marketing Courses