Unit 3 &4
Unit 3 &4
1.Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object. ...
The idea behind inheritance in Java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of the parent class.
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the
syntax of extends keyword.
Syntax
class Super
{
.....
}
class Sub extends Super
{
.....
.....
}
Super Class: The class whose features are inherited is known as super class(or a
base class or a parent class).
Sub Class: The class that inherits the other class is known as sub class(or a derived
class, extended class, or child class). The subclass can add its own fields and
methods in addition to the superclass fields and methods.
1
Single Inheritance :(One base ,One sub class):
Single Inheritance :
Syntax
class Super-class name
{
}
class Sub-classname extends Super-class name
{
}
Example
class aaa
{
}
class bbb extends aaa
{
}
Multilevel Inheritance-(One base One sub one or more than one intermediate)
2
Example
class aaa
3
Example
class aaa
In Multiple inheritance ,one class can have more than one superclass and inherit
features from all parent classes. Please note that Java does not support multiple
inheritance with classes
4
Hybrid Inheritance-More than one type of Inheritance
Example Program-1
class Teacher
void aaa()
System.out.println("Teaching");
5
{
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.aaa()
}}
Example Program-2
Import java.io.*;
class Animal
{
public void eat()
{
System.out.println("I can eat");
}
public void sleep()
{
System.out.println("I can sleep");
}
}
class Dog extends Animal
{
public void bark()
{
System.out.println("I can bark");
}}
class Main
{
public static void main(String[] args)
{
Dog dog1 = new Dog();
dog1.eat();
6
dog1.sleep();
dog1.bark();
}}
2.Interface
An interface is a completely "abstract class" that is used to group related methods
with empty bodies.
Example:
interface Animal
}
Relationship between class and Interface
Multiple Interfaces:
Multiple Interface
interface aaa
{
}
interface bbb
7
{
}
interface ccc implements aaa,bbb
{
}
Example Program
interface Animal
{
public void animalSound();
public void sleep();
}
class Pig implements Animal
{
public void animalSound()
{
System.out.println("The pig says: wee wee");
}
public void sleep()
{
System.out.println("Zzz");
}
}
class MyMainClass
{
public static void main(String[] args)
{
Pig myPig = new Pig();
myPig.animalSound();
myPig.sleep();
}
}
Out put
The pig says: wee wee
Zzz
3.Package in java .
Package in Java is a mechanism to encapsulate a group of classes, sub packages
and interfaces
Package in java can be categorized in two form, built-in package and user-defined
package.
8
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
Types of packages:
Predefine Package
a.Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of
the commonly used built-in packages are:
java.lang:
Contains language support classes(e.g classed which defines primitive data types,
math operations). This package is automatically imported.
java.io:
9
Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
java.applet:
Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc).
java.net:
b.User-definedpackages
These are the packages that are defined by the user. First we create a package using
package keyword. While creating a package, programmers must choose a name for the
package and include a package statement program that contains the classes, interfaces,
enumerations, and annotation types that you want to include in the package.
Creating a Package
To create a package, you choose a name for the package (and put
a package statement with that name at the top of every source file that contains the types
(classes, interfaces, enumerations, and annotation types) that you want to include in
the package.
Syntax
package nameOfPackage;
class class-name
{----}
Example
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
Importing package
Using packagename.*
package pack;
10
public class A
{
public void msg(){System.out.println("Hello");}
}
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Using packagename.classname
package pack;
public class A
{
public void msg(){System.out.println("Hello");}
}
import pack.A;
class B
{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Sub package
Package inside the package is known as subpackage. Thepackages that come lower
in the naming hierarchy are called "sub package" of the corresponding package higher in
the hierarchy i.e. the package that we are putting into another package is called "sub
package"
Example program
package mypack;
String name;
double bal;
11
name=n;
bal=b;
if(bal>0) {
System.out.print(“”);
System.out.println(name+”$”+bal);
else
System.out.println(“negative value”);
import mypack.*;
class testBalance
test.show();
}
OUTPUT:
j.j.jaspers $ 99.88
Unit -4
1.Exception handling
Exception
Exception handling?
Exception is the place where a problem has occurred, Handling is the place for the
solution to the specific exception.
12
Use try block to write code that may disrupts the normal program flow Use catch block to
handle it
Try
{
// Block of code to try
}
catch(Exception e)
{
// Block of code to handle errors
}
Types of Exception
Error
Example Program-1
13
System.out.println(myNumbers[1]);
System.out.println(myNumbers[2]);
System.out.println(myNumbers[10]);
// error!
}
}
Example Program-3
public class MyClass
{
public static void main(String[ ] args)
{
try
{
int myNumbers[] = {1, 2, 3};
System.out.println(myNumbers[10]);
}
catch (Exception e)
{
System.out.println("Something went wrong.");
}}
}
RuntimeException or Unchecked Exception
These type of exception can be easily validated during code
development. A developer can avoid this exception completely in their application by
writing good validation. Exception that are subclass of RuntimeException are called as
Unchecked Exception
Example
ArithmeticException
NumberFormatException
NullpointerException
CompileTimeException or checked Exception
Exception that cannot be validated during development are called checked
Exception, the compiler will force you to use try catch block or to throws the
exception.
Example
FileNotFoundException
SQLException
14
InterruptedException
Error
An Error is a subclass of Throwable that indicates serious problems that a
reasonable application should not try to catch. Most such errors are abnormal
conditions. That is, Error and its subclasses are regarded as unchecked exceptions for
the purposes of compile-time checking of exceptions.
Example
IOError
LinkageError
VirtualMachineError
Try block
The try block contains set of statements where an exception can occur. A try block is
always followed by a catch block, which handles the exception that occurs in
associated try block. A try block must be followed by catch blocks or finally block or
both.
Syntax:
try
{
//statements that may cause an exception
}
Catch block
15
A catch block is where you handle the exceptions, this block must follow the try
block. A single try block can have several catch blocks associated with it. You can
catch different exceptions in different catch blocks. When an exception occurs in try
block, the corresponding catch block that handles that particular exception executes.
Syntax
try
{
//statements that may cause an exception
} catch (exception(type) e(object))
{
//error handling code
}
Multiple catch blocks
A try block can be followed by one or more catch blocks. Each catch block must
contain a different exception handler. So, if you have to perform different tasks at the
occurrence of different exceptions, use java multi-catch block.
At a time only one exception occurs and at a time only one catch block is executed.
All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception
Finally block
A finally block contains all the crucial statements that must be executed whether
exception occurs or not.
try
{
//Statements that may cause an exception
}
Catch
{
//Handling exception
}
finally
{
//Statements to be executed
}
Throw and Throws
16
17
InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it
is interrupted.
InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it
is interrupted.
NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
NoSuchMethodException
It is thrown when accessing a method which is not found.
NullPointerException
This exception is raised when referring to the members of a null object. Null
represents nothing
NumberFormatException
This exception is raised when a method could not convert a string into a numeric
format.
RuntimeException
This represents any exception which occurs during runtime.
StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than
the size of the string
2.Thread
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking
to utilize the CPU. Multitasking can be achieved in two ways:
Process-based Multitasking (Multiprocessing)
Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
Each process has an address in memory. In other words, each process allocates a
separate memory area.
A process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
Threads share the same address space.
A thread is lightweight.
Cost of communication between the thread is low.
Thread
A thread is a lightweight sub process, the smallest unit of processing. It is a
separate path of execution.
18
Threads are independent. If there occurs exception in one thread, it doesn't affect
other threads. It uses a shared memory area.
Multithread
Multithreading
Multithreading in Java is a process of executing multiple threads
simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a
shared memory area. They don't allocate separate memory area so saves
memory, and context-switching between the threads takes less time than
process.
Advantages of Java Multithreading
19
1) It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception
occurs in a single thread.
Thread Life Cycle
New
When we create a new Thread object using new operator, thread state is New
Thread. At this point, thread is not alive and it’s a state internal to Java
programming.
Runnable
When we call start() function on Thread object, it’s state is changed to
Runnable. The control is given to Thread scheduler to finish it’s execution. Whether
to run this thread instantly or keep it in runnable thread pool before running,
depends on the OS implementation of thread scheduler.
Example
MyThread t1 = new MyThread();
t1.start();
Running
When thread is executing, it’s state is changed to Running. Thread scheduler
picks one of the thread from the runnable thread pool and change it’s state to
Running.
20
Then CPU starts executing this thread. A thread can change state to
Runnable, Dead or Blocked from running state depends on time slicing,
thread completion of run() method or waiting for some resources.
Schedule()
yield(()
Blocked/Waiting state:
When a thread is temporarily inactive, then it’s in one of the following states.
Blocked
Waiting
For example, when a thread is waiting for I/O to complete, it lies in the
blocked state. It’s the responsibility of the thread scheduler to reactivate and
schedule a blocked/waiting thread.
suspend()
wait()
sleep(t)
notify()
notifyAll()
resume()
A thread in this state cannot continue its execution any further until it is
moved to runnable state.
Terminated (Dead)
A runnable thread enters the terminated state when it completes its task or otherwise
terminates.
Dead state means that a thread has finished its execution or its run() method and
when the stop() method is invoke. The stop() method kills the thread and
the thread doesn't work further
Example
t1.stop();
Thread Methods
public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run()
method on the thread.
public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
21
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public Thread currentThread(): returns the reference of currently executing
thread.
public int getId(): returns the id of the thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended thread(depricated).
public void stop(): is used to stop the thread(depricated)
Create a Thread
There are two ways to create a thread:
By extending Thread class
By implementing Runnable interface.
Thread class
Thread class provide constructors and methods to create and perform
operations on a thread. Thread class extends Object class and implements Runnable
interface.
Commonly used Constructors of Thread class:
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
By extending the Thread class
We create a class that extends the java.lang.Thread class. This class
overrides the run() method available in the Thread class. A thread begins its
life inside run() method.
We create an object of our new class and call start() method to start the
execution of a thread. Start() invokes the run() method on the Thread object
Example
class class_name extends Thread
Example Program-extends thread
class MultithreadingDemo extends Thread
{
22
public void run()
{
System.out.println("My thread is in running state.");
}
public static void main(String args[])
{
MultithreadingDemo obj=new MultithreadingDemo();
obj.start();
}}
By implementing the Runnable interface.
We create a new class which implements java.lang.Runnable interface and
override run() method.
Then we instantiate a Thread object and call start() method on this object.
Runnable is a interface name .
Example
class class_name implements Runnable
Example Program-implements Runnable
class Multi3 implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Priority of a Thread (Thread Priority):
Each thread have a priority. Priorities are represented by a number between 1
and 10. In most cases, thread scheduler schedules the threads according to
23
their priority (known as pre-emptive scheduling). But it is not guaranteed
because it depends on JVM specification that which scheduling it chooses.
Thread Priority
public static int MIN_PRIORITY(1)
public static int NORM_PRIORITY(5)
public static int MAX_PRIORITY(10)
Get and Set methods in Thread priority
getPriority()
setPriority(intnewPriority)
Example Program(1) –Thread Priority
class TestMultiPriority1 extends Thread
{
public void run()
{
System.out.println("running thread name
is:"+Thread.currentThread().getName());
System.out.println("running thread priority
is:"+Thread.currentThread().getPriority());
}
public static void main(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}}
OUTPUT
running thread name is:Thread-0
24
running thread priority is:10
running thread name is:Thread-1
Java provides a way of creating threads and synchronizing their task by using
synchronized blocks. Synchronized blocks in Java are marked with the
synchronized keyword. A synchronized block in Java is synchronized on
some object.
All synchronized blocks synchronized on the same object can only have one
thread executing inside them at a time. All other threads attempting to enter
the synchronized block are blocked until the thread inside the synchronized
block exits the block.
25
To prevent thread interference.
Types of Synchronization
Process Synchronization
Thread Synchronization
Mutual Exclusive
Synchronized method.
Synchronized block.
static synchronization.
Synchronization block
26
Example Program
class Table
{
synchronized void printTable(int n)
{
//synchronized method
for(int i=1;i<=5;i++)
{
27
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e){System.out.println(e);
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
public class TestSynchronization2
28
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output
5
10
15
20
25
100
200
300
400
500
3.Applet
An applet is a Java program that runs in a Web browser. ... An applet is
a Java class that extends the java. applet. Applet class. A main() method is
not invoked on an applet, and an applet class will not define main().
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.
Advantage
It works at client side so less response time.
Secured
It can be executed by browsers running under many plateforms, including
Linux, Windows, Mac Os etc.
29
All applets are sub-classes (either directly or indirectly)
of java.applet.Applet class.
Applets are not stand-alone programs. Instead, they run within either a web
browser or an applet viewer. JDK provides a standard applet viewer tool
called applet viewer.
In general, execution of an applet does not begin at main() method.
Output of an applet window is not performed by System.out.println(). Rather
it is handled with various AWT methods, such as drawString().
Difference between Applet and Application
Java Applications can execute codes from the local Java Applets Applications
system cannot do so
Example Program
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome",150,150);
}}
Html Program
<html>
<body>
<applet code="First.class" width="300" height="300">
30
</applet>
</body>
</html>
Applet Life Cycle
Applet Methods
init( ) : The init( ) method is the first method to be called. This is where you should
initialize variables. This method is called only once during the run time of your
applet.
start( ) : The start( ) method is called after init( ). It is also called to restart an
applet after it has been stopped. Note that init( ) is called .
paint( ) is also called when the applet begins execution. Whatever the cause,
whenever the applet must redraw its output, paint( ) is called.
stop( ) : The stop( ) method is called when a web browser leaves the HTML
document containing the applet—when it goes to another page. You should
use stop( ) to suspend threads that don’t need to run when the applet is not visible.
You can restart them when start( ) is called if the user returns to the page.
destroy( ) : The destroy( ) method is called when the environment determines that
your applet needs to be removed completely from memory. At this point, you
should free up any resources the applet may be using. The stop( ) method is always
called before destroy( ).
Applet Hierarchy in Java
class java.lang.Object
class java.awt.Component
class java.awt.Container
class java.awt.Panel
class java.applet.Applet
31
Example Program-1
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
int height, width;
public void init()
{
height = getSize().height;
width = getSize().width;
setName("MyApplet");
}
public void paint(Graphics g)
{
g.drawRoundRect(10, 30, 120, 120, 2, 3);
}}
<html>
<body>
<applet code=“MyApplet.class" width="300" height="">
</applet>
</body>
</html>
32
Example Program-2
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo1 extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.black);
g.drawString("Welcome to studytonight",50, 50); g.setColor(Color.blue);
g.fillOval(170,200,30,30); g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
g.drawLine(21,31,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
}}
<html>
<body>
<applet code="GraphicsDemo1.class" width="300" height="300">
</applet>
</body>
</html>
OutPut
33
Passing Parameter in Applet
We can get any information from the HTML file as a parameter. For this
purpose, Applet class provides a method named getParameter().
Syntax
public String getParameter(String parameterName)
Steps
To pass the parameters to the Applet we need to use the param attribute
of <applet> tag.
To retrieve a parameter's value, we need to use
the getParameter() method of Applet class.
Example
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet
{
public void paint(Graphics g)
{
String str=getParameter("msg");
g.drawString(str,50, 50);
34
}
}
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
Output:
Welcome to Applet
Unit 5
Java Byte streams are used to perform input and output of 8-bit bytes,
whereas Java Character streams are used to perform input and output for 16-bit unicode.
Though there are many classes related to character streams but the most frequently
used classes are, FileReader and FileWriter.
Java Byte streams are used to perform input and output of 8-bit bytes. Byte stream
is defined by using two abstract class at the top of hierarchy, they are InputStream and
OutputStream. For example FileInputStream is used to read from source and
FileOutputStream to write to the destination.
35
BufferedInputStream -Used for Buffered Input Stream.
BufferedOutputStream -Used for Buffered Output Stream.
DataInputStream - Contains method for reading java standard datatype
DataOutputStream- - An output stream that contain method for writing java
standard data type
FileInputStream- Input stream that reads from a file
FileOutputStream - Output stream that write to a file.
InputStream - Abstract class that describe stream input.
OutputStream -Abstract class that describe stream output.
PrintStream - Output Stream that contain print() and println() method
Read Console input in java
36
Input streams - for reading data from streams
Input Stream Class in Java. InputStream class is the superclass of all the io classes i.e.
representing an input stream of bytes. It represents input stream of bytes. Applications that
are defining subclass of InputStream must provide method, returning the next byte of
input
Input stream Constructor :
37
Output Stream
void close() : Closes this output stream and releases any system resources associated with
this stream
void flush() : Flushes this output stream and forces any buffered output bytes to be
written output
void write(byte[] b) : Writes b.length bytes from the specified byte array to this output
stream
void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array
starting at offset off to this output stream.
abstract void write(int b) : Writes the specified byte to this output stream
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java
Character streams are used to perform input and output for 16-bit unicode. Though there
are many classes related to character streams but the most frequently used classes are,
FileReader and FileWriter.
38
PrintWriter -Output Stream that contain print() and println() method.
Reader -Abstract class that define character stream input
Writer -Abstract class that define character stream output
Reader class
Reader classes are used to read 16-bit unicode characters from the input stream.
The Reader class is the superclass for all character-oriented input stream classes. All the
methods of this class throw an IOException. Being an abstract class, the Reader class
cannot be instantiated hence its subclasses are used.
close() It closes the stream and releases any system resources associated with it.
mark(int readAheadLimit) It marks the present position in the stream.
read() It reads a single character.
read(char[] cbuf) It reads characters into an array.
ready() It tells whethe
reset()It resets the stream.r this stream is ready to be read.
Writer class
39
Writer classes are used to write 16-bit Unicode characters onto an outputstream.
The Writer class is the superclass for all character-oriented output stream classes .All the
methods of this class throw an IOException. Being an abstract class, the Writer class
cannot be instantiated hence, its subclasses are used
Constructor in Writer class
Writer() It creates a new character-stream writer whose critical sections will synchronize
on the writer itself.
Writer(Object lock) It creates a new character-stream writer whose critical sections will
synchronize on the given object.
Date class
The class Date represents a specific instant in time, with millisecond precision. The
Date class of java.util package implements Serializable, Cloneable and Comparable
interface. It provides constructors and methods to deal with date and time with java.
40
long getTime() : Returns the number of milliseconds since January 1, 1970,
00:00:00 GMT represented by this Date object.
void setTime(long time) : Changes the current date and time to given time.
Example Program:
import java.util.Date;
class DateDemo
System.out.println (date);
OUTPUT:
Calendar class
Calendar class in Java is an abstract class that provides methods for converting date
between a specific instant in time and a set of calendar fields such as MONTH, YEAR,
HOUR, etc. It inherits Object class and implements the Comparable, Serializable,
Cloneable interfaces.
As it is an Abstract class, so we cannot use a constructor to create an instance.
Instead, we will have to use the static method Calendar.getInstance() to instantiate and
implement a sub-class.
Methods used in Calender class.
Calendar.getInstance(): return a Calendar instance based on the current time in
the default time zone with the default locale.
Calendar.getInstance(TimeZone zone)
Calendar.getInstance(Locale aLocale)
Calendar.getInstance(TimeZone zone, Locale aLocale)
Example program
import java.util.*;
class GregorianCalendarDemo
String months[ ] = {"Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug", "Sep", "Oct",
"Nov", "Dec"};
int year;
System.out.print("Date: ");
System.out.print(months[gcalendar.get(Calendar.MONTH)]);
System.out.println(year = gcalendar.get(Calendar.YEAR));
System.out.print("Time: ");
System.out.print(gcalendar.get(Calendar.HOUR) + ":");
System.out.print(gcalendar.get(Calendar.MINUTE) + ":");
System.out.println(gcalendar.get(Calendar.SECOND));
if(gcalendar.isLeapYear(year)) {
else
}}}
OUTPUT:
Time: 8:17:42
Random class
42
java.util.Random.doubles(): Returns an effectively unlimited stream of pseudo
random double values,
java.util.Random.ints(): Returns an effectively unlimited stream of pseudo random
int values
java.util.Random.longs(): Returns an effectively unlimited stream of pseudo
random long values.
Scanner class
The Scanner class is used to get user input, and it is found in the java.util package.
To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class documentation. In our example, we will use
the nextLine() method, which is used to read Strings
Example Program
import java.io.*;
import java.util.Scanner;
num1 = sc.nextInt();
43
System.out.println("Enter Second Number: ");
num2 = sc.nextInt();
sc.close();
String Tokenizer class in Java is used to break a string into tokens. Example:
A String Tokenizer object internally maintains a current position within the string to be
tokenized .A token is returned by taking a substring of the string that was used to create
the String Tokenizer object.
import java.util.StringTokenizer;
public class Simple
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
44
}
}
}
Output:
my
name
is
khan
3. FILES IN JAVA
1. Create file
2. Delete file
3. Open file
4. Close file
5. Read file
6. Write file
7. Change files permissions.
8. Check file permission
9. Rename of file
10. Getting the name of file
11. Getting the size of file
Create File
We can use File class createNewFile() method to create new file. This method returns true
if file is successfully created, otherwise it returns false. Once creating file following steps
should be follow:
Delete File
Read File
There are many ways to read a file in java. We can use BufferedReader, FileReader or
Files class
FileReader
45
FileReader is meant for reading streams of characters. For reading streams of raw
bytes, consider using a FileInputStream.
Constructors:
Methods:
public int read () throws IOException – Reads a single character. This method
will block until a character is available
public int read(char[] cbuff) throws IOException – Reads characters into an
array. This method will block until some input is available
Write File
FileWriter
Constructors:
Methods:
46
public void write (char [] stir) throws IOException – Writes an array of
characters.
public void write(String str)throws IOException – Writes a string.
File Permissions
File class provide methods to get file permission details as well as change them.
Java provides a number of method calls to check and change the permission of a file, such
as a read-only file can be changed to have permissions to write.
File permissions are required to be changed when the user want to restrict the
operations permissible on a file. For example, a file permission can be changed from write
to read-only because the user no longer want to edit the file.
Executable:
Tests whether the application can execute the file denoted by this abstract path
name.
Syntax
Readable:
Tests whether the application can read the file denoted by this abstract path name.
Syntax
Writable:
Tests whether the application can modify the file denoted by this abstract path
name.
Syntax
setExecutable
A convenience method to set the owner’s execute permission for this abstract path
name
Syntax
47
setReadable:
A convenience method to set the owner’s read permission for this abstract path name
Syntax
setWritable:
A convenience method to set the owner’s write permission for this abstract path
name.
Syntax
4. Event in java
Change in the state of an object is known as event i.e. event describes the change
in state of source. Events are generated as result of user interaction with the graphical
user interface components.
For example, clicking on a button, moving the mouse, entering a character through
keyboard, selecting an item from list, scrolling the page are the activities that causes an
event to happen.
Types of Event
Foreground Events - Those events which require the direct interaction of user.
For example, clicking on a button, moving the mouse, entering a character through
keyboard, selecting an item from list, scrolling the page etc.
Background Events - Those events that require the interaction of end user are
known as background events. Operating system interrupts, hardware or software
failure, timer expires, an operation completion are the example of background
events.
Event Handling
Event Handling is the mechanism that controls the event and decides what should
happen if an event occurs. This mechanism has the code which is known as event handler
that is executed when an event occurs. Java Uses the Delegation Event Model to handle
the events.
Event Source
The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source
object.
Event Listener
It is also known as event handler. Listener is responsible for generating response to
an event. From java implementation point of view the listener is also an object. Listener
waits until it receives an event. Once the event is received , the listener process the event
an then returns.
48
Event classes
Event Classes in Java are the classes defined for almost all the components that may
generate events
Event Adapters:
Event Adapters classes are abstract class that provides some methods used for
avoiding the heavy coding. Adapter class is defined for the listener that has more than one
abstract method.
Event and Listener (Java Event Handling)
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
The component with the Listener, many classes provide the registration methods. For example:
Button
◦MenuItem
◦TextField
49
public void addActionListener(ActionListener a){}
◦TextArea
◦Checkbox
◦Choice
◦List
Example Program
import java.awt.*;
import java.awt.event.*;
TextField tf;
AEvent(){ .
create components
tf=new TextField();
tf.setBounds(60,50,170,20);
b.setBounds(100,120,80,30);
register listener
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
tf.setText("Welcome");
50
}
new AEvent();
} }
Output
Legacy Classes - Java Collections. ... It only defined several classes and
interfaces that provide methods for storing objects. When Collections framework
were added in J2SE 1.2, the original classes were reengineered to support the
collection interface. These classes are also known as Legacy classes.
Dictionary
HashTable
Properties
Stack
Vector
There is only one legacy interface called Enumeration
Enumeration interface
Enumeration interface defines method to enumerate(obtain one at a time) through
collection of objects.
51
However, some legacy classes such as Vector and Properties defines several
method in which Enumeration interface is used.
To create an enum, use the enum keyword (instead of class or interface), and
separate the constants with a comma.
Vector class
Vector is similar to ArrayList which represents a dynamic array.
There are two differences between Vector and ArrayList. First, Vector is
synchronized while ArrayList is not, and Second, it contains many legacy methods
that are not part of the Collections Framework.
With the release of JDK 5, Vector also implements Iterable. This means that Vector
is fully compatible with collections, and a Vector can have its contents iterated by
the for-each loop.
Vector Constructor
Vector()
Vector(int size)
This creates a vector whose initial capacity is specified by size and whose
increment is specified by incr. Vector(Collection c)
Vector Methods
Method Description
52
The Vector class implements a growable array of objects. Vectors basically fall in
legacy classes but now it is fully compatible with collections. It is found in the java.util
package and implements the List interface, so we can use all the methods of List interface
here.
Example Program
import java.io.*;
import java.util.*;
class VectorExample {
int n = 5;
v.add(i);
System.out.println(v);
v.remove(3);
System.out.println(v);
}}
Output
53
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
123
Stack class
If you want to put an object on the top of the stack, call push() method. If you want
to remove and return the top element, call pop() method. An EmptyStackException is
thrown if you call pop() method when the invoking stack is empty.
boolean empty()
Tests if this stack is empty. Returns true if the stack is empty, and returns false if the
stack contains elements.
Object peek( )
Returns the element on the top of the stack, but does not remove it.
Object pop( )
Returns the element on the top of the stack, removing it in the process.
Example Program
import java.util.Stack;
class Main
54
{
animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
}}
55