Professional Documents
Culture Documents
Core Java Programming
Core Java Programming
Hours
Topic
Day
1.
2.
3.
4.
Basic Operators
Loop Control
Decision Making
5.
Numbers Methods
Characters Methods
Strings Methods
6.
Arrays
Date & Time
7.
Methods
8.
Exceptions
9.
Inheritance
10.
Polymorphism
11.
Interfaces
12.
Packages
13.
14.
15.
Window Forms
Features of Java
Object Oriented
Platform independent
Simple
Secure
Architectural-neutral
Portable
Robust
Multithreaded
Interpreted
High Performance
Distributed
Dynamic
Java Versions
Release
Year
JDK Beta
1995
JDK 1.0
1996
JDK 1.1
1997
J2SE 1.2
1998
J2SE 1.3
2000
J2SE 1.4
2002
J2SE 5.0
2004
Java SE 6
2006
Java SE 7
2011
Java SE 8
2014
JRE is used to provide runtime environment.It is the implementation of JVM.It physically exists.
JRE = JVM + Required Library to run Application.
JDK Java Development Kit
JDK = JRE + Required Library to develop Java Application
Class - A class can be defined as a template/ blue print that describe the behaviors/states that
object of its type support.
Methods - A method is basically a behavior. A class can contain many methods. It is in methods
where the logics are written, data is manipulated and all the actions are executed.
Instance Variables - Each object has its unique set of instance variables. An object's state is
created by the values assigned to these instance variables.
Simple Java program
Sample program
class Student{
}}
Data Type
Default Value
Default size
boolean
false
1 bit
char
'\u0000'
2 byte
byte
1 byte
short
2 byte
int
4 byte
long
0L
8 byte
float
0.0f
4 byte
double
0.0d
8 byte
4. Operators
Operators
Precedence
postfix
expr++ expr--
unary
multiplicative
*/%
additive
+-
shift
relational
equality
== !=
bitwise AND
&
bitwise exclusive OR
bitwise inclusive OR
logical AND
&&
logical OR
||
ternary
?:
assignment
Variables Types
A class can contain any of the following variable types.
Local variables: Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable
will be destroyed when the method has completed.
Instance variables: Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance variables
can be accessed from inside any method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared with in a class, outside any
method, with the static keyword.
Keywords
abstract
default
if
private
this
boolean
do
implements
protected
throw
extends
null
break
double
import
public
throws
byte
else
instanceof
return
transient
case
int
false
short
try
catch
final
interface
static
void
char
finally
long
strictfp
volatile
true
class
float
native
super
while
const
for
new
switch
continue
goto
package
synchronized
Statement
Description
if statement
if...else statement
nested if statements
switch statement
Loop Statements
Loop Type
Description
while loop
for loop
do...while loop
Number Methods
SN
xxxValue() - Converts the value of this Number object to the xxx data type and returned it.
valueOf() - Returns an Integer object holding the value of the specified primitive.
toString() - Returns a String object representing the value of specified int or Integer.
parseInt() - This method is used to get the primitive data type of a certain String.
ceil() - Returns the smallest integer that is greater than or equal to the argument. Returned as
a double.
floor() - Returns the largest integer that is less than or equal to the argument. Returned as a
double.
10
rint() - Returns the integer that is closest in value to the argument. Returned as a double.
11
round() - Returns the closest long or int, as indicated by the method's return type, to the
argument.
14 exp() - Returns the base of the natural logarithms, e, to the power of the argument.
16 pow() - Returns the value of the first argument raised to the power of the second argument.
24
atan2() - Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns
theta.
Character Methods
SN
toString() - Returns a String object representing the specified character valuethat is, a one-character
string.
String Methods:
SN
String concat(String str) Concatenates the specified string to the end of this string.
boolean contentEquals(StringBuffer sb) Returns true if and only if this String represents the
same sequence of characters as the specified StringBuffer.
static String copyValueOf(char[] data) Returns a String that represents the character
sequence in the array specified.
static String copyValueOf(char[] data, int offset, int count) Returns a String that represents
the character sequence in the array specified.
boolean endsWith(String suffix) Tests if this string ends with the specified suffix.
byte getBytes() Encodes this String into a sequence of bytes using the platform's default
byte[] getBytes(String charsetName)Encodes this String into a sequence of bytes using the
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) Copies characters from this
int indexOf(int ch) Returns the index within this string of the first occurrence of the specified
16 character.
int indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence
int indexOf(String str) Returns the index within this string of the first occurrence of the
18 specified substring.
int indexOf(String str, int fromIndex) Returns the index within this string of the first
int lastIndexOf(int ch) Returns the index within this string of the last occurrence of the
21 specified character.
int lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last
22 occurrence of the specified character, searching backward starting at the specified index.
int lastIndexOf(String str) Returns the index within this string of the rightmost occurrence of
int lastIndexOf(String str, int fromIndex) Returns the index within this string of the last
24 occurrence of the specified substring, searching backward starting at the specified index.
25 int length() Returns the length of this string.
boolean matches(String regex) Tells whether or not this string matches the given regular
26 expression.
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
boolean regionMatches(int toffset, String other, int ooffset, int len) Tests if two string regions
28 are equal
String replace(char oldChar, char newChar) Returns a new string resulting from replacing all
String replaceAll(String regex, String replacement Replaces each substring of this string that
String replaceFirst(String regex, String replacement) Replaces the first substring of this
31 string that matches the given regular expression with the given replacement.
32 String[] split(String regex) Splits this string around matches of the given regular expression.
String[] split(String regex, int limit) Splits this string around matches of the given regular
33 expression.
34 boolean startsWith(String prefix) Tests if this string starts with the specified prefix.
boolean startsWith(String prefix, int toffset) Tests if this string starts with the specified prefix
37 String substring(int beginIndex) Returns a new string that is a substring of this string.
String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this
38 string.
String toLowerCase() Converts all of the characters in this String to lower case using the
String toLowerCase(Locale locale) Converts all of the characters in this String to lower case
String toUpperCase() Converts all of the characters in this String to upper case using the
String toUpperCase(Locale locale) Converts all of the characters in this String to upper case
45 String trim() Returns a copy of the string, with leading and trailing whitespace omitted.
static String valueOf(primitive data type x) Returns the string representation of the passed
Syntax :
Date class
Java provides the Date class available in java.util package, this class encapsulates the current
date and time.
The Date class supports two constructors as shown below.
Date()
Date(long millisec)
To specify the time format, use a time pattern string. In this pattern, all ASCII letters are reserved
as pattern letters, which are defined as the following:
Character
Description
Example
Era designator
AD
2001
Month in year
July or 07
Day in month
10
12
22
Minute in hour
30
Second in minute
55
Millisecond
234
Day in week
Tuesday
Day in year
360
Week in year
40
Week in month
A.M./P.M. marker
PM
24
10
Time zone
'
Delimiter
"
Single quote
Sample
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.printf("%1$s %2$tB %2$td, %2$tY",
"Due date:", date);
}
}
Output
Due date: February 22, 2016
GregorianCalendar Class:
Description
Example
2004-02-09
02/09/2004
24-hour time
18:05:19
12-hour time
06:05:19 pm
18:05
2004
04
20
February
Feb
02
03
Monday
Mon
069
18
05
19
047
047000000
PM
pm
-0800
Time zone
PST
1078884319
1078884319047
06
7. Methods
A Java method is a collection of statements that are grouped together to perform an operation. When
you call the System.out.println() method, for example, the system actually executes several statements
in order to display a message on the console.
Method Overloading
A class may define multiple methods with the same name---this is called method
overloading
usually perform the same task on different data types
Example: The PrintStream class defines multiple println methods, i.e., println is
overloaded:
println (String s)
println (int i)
println (double d)
The following lines use the System.out.print method for different data types:
System.out.println ("The total is:");
double total = 0;
System.out.println (total);
8. EXCEPTION HANDLING
An exception is a problem that arises during the execution of a program. An exception can occur
for many different reasons, including the following:
A network connection has been lost in the middle of communications, or the JVM has run
out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
Categories of exceptions:
Runtime exceptions: A runtime exception is an exception that occurs that probably could
have been avoided by the programmer. As opposed to checked exceptions, runtime
exceptions are ignored at the time of compliation.
Errors: These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer. Errors are typically ignored in your code because you can rarely do
anything about an error. For example, if a stack overflow occurs, an error will arise. They
are also ignored at the time of compilation.
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally happen in
case of severe failures, which are not handled by the java programs. Errors are generated to
indicate errors generated by the runtime environment.
Example : JVM is out of Memory. Normally programs cannot recover from errors.
The Exception class has two main subclasses : IOException class and RuntimeException Class.
Exceptions Methods
Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords.
A try/catch block is placed around the code that might generate an exception.
Code within a try/catch block is referred to as protected code, and the syntax for using
try/catch looks like the following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
A catch statement involves declaring the type of exception you are trying to catch.
If an exception occurs in protected code, the catch block (or blocks) that follow the try is
checked.
If the type of exception that occurred is listed in a catch block, the exception is passed to
the catch block much as an argument is passed into a method parameter.
Uncaught Exceptions
It is useful to see what happens when you dont handle them. This small program includes an
expression that intentionally
int a = 42 / d;
}
}
Multiple catch Blocks (try, Catch):
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks
like the following:
try
{
//Protected code
}catch(ExceptionType1
e1)
{
//Catch block
}catch(ExceptionType2
e2)
{
//Catch block
}catch(ExceptionType3
e3)
{
//Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of
them after a single try.
If an exception occurs in the protected code, the exception is thrown to the first catch
block in the list. If the data type of the exception thrown matches ExceptionType1, it gets
caught there.
The try statement can be nested. That is, a try statement can be inside the block of another
try.
Each time a try statement is entered, the context of that exception is pushed on the stack.
If an inner try statement does not have a catch handler for a particular exception, the
stack is unwound and the next try statements catch handlers are inspected for a match.
If a method does not handle a checked exception, the method must declare it using the
throws keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just
caught, by using the throw keyword. Try to understand the different in throws and throw
keywords.
import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
The finally keyword is used to create a block of code that follows a try block. A finally
block of code always executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanup-type statements that you want to
execute, no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
The try statement can be nested. That is, a try statement can be inside the block of another
try.
Each time a try statement is entered, the context of that exception is pushed on the stack.
If an inner try statement does not have a catch handler for a particular exception, the stack is
unwound and the next try statements catch handlers are inspected for a match.
9. Inheritance
Types:
Simple Inheritance
Multilevel Inheritance
Simple Inheritance
When a subclass is derived simply from its parent class then this mechanism is
known as simple inheritance. In case of simple inheritance there is only a sub class
and it's parent class. It is also called single inheritance or one level inheritance.
class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
eg
}
}
class B extends A{
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
void display(){
System.out.println("B");
}
}
Multilevel Inheritance
It is the enhancement of the concept of inheritance. When a subclass is derived
from a derived class then this mechanism is known as the multilevel inheritance.
The derived class is called the subclass or child class for it's parent class and this
parent class works as the child class for it's just above ( parent ) class. Multilevel
inheritance can go up to any number of level.
e.g.
class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
void Showb(){
System.out.println("B");
}
}
class C extends B{
void display(){
System.out.println("C");
}
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}}
super keyword
The super is java keyword. As the name suggest super is used to access the members of the super
class.It is used for two purposes in java.
The first use of keyword super is to access the hidden data variables of the super class hidden by
the sub class.
e.g. Suppose class A is the super class that has two instance variables as int a and float b. class B
is the subclass that also contains its own data members named a and b. then we can access the
super class (class A) variables a and b inside the subclass class B just by calling the following
command.
super.member;
Here member can either be an instance variable or a method. This form of super most useful to
handle situations where the local member of a subclass hides the members of a super class
having the same name. The following examples clarify all the confusions.
class A{
int a;
float b;
void Show(){
System.out.println("b in super class: " + b);
}
}
class B extends A{
int a;
float b;
B( int p, float q){
a = p;
super.b = q;
}
void Show(){
super.Show();
System.out.println("b in super class: " + super.b);
System.out.println("a in sub class: " + a);
}
public static void main(String[] args){
We have also discussed has a relationships in which a class has objects of other classes as
memberssuch relationships create new classes by composition of existing classes.
For example, given the classes Employee, BirthDate and TelephoneNumber, it is
improper to say that an Employee is a BirthDate or that an Employee is a
TelephoneNumber.
But it is certainly appropriate to say that an Employee has a BirthDate and that an
Employee has a TelephoneNumber.
10. POLYMORPHISM
METHOD OVERRIDING
If a class inherits a method from its super class, then there is a chance to override the method
provided that it is not marked final.
The benefit of overriding is: ability to define a behavior that's specific to the sub class type.
Which means a subclass can implement a parent calss method based on its requirement.
In object oriented terms, overriding means to override the functionality of any existing method.
Calling a Method:
In creating a method, you give a definition of what the method is to do. To use a method, you
have to call or invoke it. There are two ways to call a method; the choice is based on whether
the method returns a value or not.
When a program calls a method, program control is transferred to the called method. A called
method returns control to the caller when its return statement is executed or when its methodending closing brace is reached.
If the method returns a value, a call to the method is usually treated as a value. For example:
int larger = max(30, 40);
Passing Parameters by Values:
When calling a method, you need to provide arguments, which must be given in the same order
as their respective parameters in the method specification. This is known as parameter order
association.
Rules for method overriding:
The argument list should be exactly the same as that of the overridden method.
The return type should be the same or a subtype of the return type declared in the
original overridden method in the super class.
The access level cannot be more restrictive than the overridden method's access level.
For example: if the super class method is declared public then the overridding method
in the sub class cannot be either private or public. However the access level can be less
restrictive than the overridden method's access level.
Instance methods can be overridden only if they are inherited by the subclass.
A method declared final cannot be overridden.
A method declared static cannot be overridden but can be re-declared.
If a method cannot be inherited then it cannot be overridden.
A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
A subclass in a different package can only override the non-final methods declared
public or protected.
An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However the overriding method should
not throw checked exceptions that are new or broader than the ones declared by the
overridden method. The overriding method can throw narrower or fewer exceptions
than the overridden method.
Constructors cannot be overridden.
Using the super keyword:
When invoking a superclass version of an overridden method the super keyword is
used.
In object oriented terms, overriding means to override the functionality of any existing method.
Example:
Let us look at an example.
class Animal{
Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class
object.
Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java,
all Java objects are polymorphic since any object will pass the IS-A test for their own type and
for the class Object.
It is important to know that the only possible way to access an object is through a reference
variable. A reference variable can be of only one type. Once declared, the type of a reference
variable cannot be changed.
The reference variable can be reassigned to other objects provided that it is not declared final.
The type of the reference variable would determine the methods that it can invoke on the
object.
A reference variable can refer to any object of its declared type or any subtype of its declared
type. A reference variable can be declared as a class or interface type.
11.INTERFACES
An interface is not a class. Writing an interface is similar to writing a class, but they are
two different concepts. A class describes the attributes and behaviors of an object. An interface
contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface
need to be defined in the class.
An interface is similar to a class in the following ways:
An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
Defining an Interface
Using the keyword interface, you can fully abstract a class interface from its
implementation.
An interface declaration consists of modifiers, the keyword interface, the interface name,
a comma-separated list of parent interfaces (if any), and the interface body.
Interfaces are syntactically similar to classes, but they lack instance variables, and their
methods are declared without any body.
Interfaces add most of the functionality that is required for many applications that would
normally resort to using multiple inheritance in a language such as C++.
For example:
An interface is defined much like a class. This is the general form of an interface:
access interface name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
The public access specifier indicates that the interface can be used by any class in any
package.
An interface can extend other interfaces, just as a class can extend or subclass another
class. However, whereas a class can extend only one other class,
An interface can extend any number of interfaces. The interface declaration includes a
comma-separated list of all the interfaces that it extends.
Example of an interface definition
It declares a simple interface that contains one method called callback( ) that takes a single
integer parameter.
interface Callback {
void callback(int param);
}
The interface body contains method declarations for all the methods included in the
interface.
A method declaration within an interface is followed by a semicolon, but no braces,
because an interface does not provide implementations for the methods declared within it.
All methods declared in an interface are implicitly public, so the public modifier can be
omitted.
Once an interface has been defined, one or more classes can implement that interface.
To implement an interface, include the implements clause in a class definition, and then
create the methods defined by the interface.
The general form of a class that includes the implements clause looks like this:
If a class implements more than one interface, the interfaces are separated with a comma.
If a class implements two interfaces that declare the same method, then the same method
will be used by clients of either interface.
Also, the type signature of the implementing method must match exactly the type
signature specified in the interface definition.
Here is a small example class that implements the Callback interface shown earlier.
Partial Implementations
If a class includes an interface but does not fully implement the methods defined by that
interface, then that class must be declared as abstract.
For example:
abstract class Incomplete implements Callback
{
int a, b;
void show() {
System.out.println(a + " " + b);
}
// ...
}
Here, the class Incomplete does not implement callback( ) and must be declared as
abstract.
Any class that inherits Incomplete must implement callback( ) or be declared abstract
itself.
Following is an example:
// One interface can extend another.
interface A {
void meth1();
void meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A {
void meth3();
}
// This class must implement all of A and B
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
A Java class can only extend one parent class. Multiple inheritance is not allowed.
Interfaces are not classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a commaseparated list.
For example, if the Hockey interface extended both Sports and Event, it would be declared as:
Tagging Interfaces:
The most common use of extending interfaces occurs when the parent interface does not
contain any methods. For example, the MouseListener interface in the java.awt.event package
extended java.util.EventListener, which is defined as:
package java.util;
public interface EventListener
{}
An interface with no methods in it is referred to as a tagging interface.
Abstract Class
A class which contains the abstract keyword in its declaration is known as abstract class.
Abstract classes may or may not contain abstract methods ie., methods with out body
( public void get(); )
But, if a class have at least one abstract method, then the class must be declared abstract.
To use an abstract class you have to inherit it from another class, provide
implementations to the abstract methods in it.
If you inherit an abstract class you have to provide implementations to all the abstract
methods in it.
12.PACKAGES
A package is a grouping of related types providing access protection and name space
management.
Note that types refer to classes, interfaces, enumerations, and annotation types.
Enumerations and annotation types are special kinds of classes and interfaces,
respectively, so types are often referred to in this lesson simply as classes and interfaces
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a package
called MyPackage.
package MyPackage;
Java uses file system directories to store packages. For example, the .class files for any
classes you declare to be part of MyPackage must be stored in a directory called MyPackage.
Remember that case is significant, and the directory name must match the package name
exactly.
More than one file can include the same package statement. The package statement
simply specifies to which package the classes defined in a file belong. It does not exclude other
classes in other files from being part of that same package. Most real-world packages are
spread across many files.
the
CLASSPATH environmental variable. the -classpath option with java and javac to specify
package MyPack
In order for a program to find MyPack, one of three things must be true. Either the program
can be executed from a directory immediately above MyPack,
The CLASSPATH must be set to include the path to MyPack, or the -classpath option must
specify the path to MyPack when the program is run via java.
When the second two options are used, the class path must not include MyPack, itself.
It must simply specify the path to MyPack. For example, in a Windows environment, if the
path to MyPack is
C:\MyPrograms\Java\MyPack
C:\MyPrograms\Java
The easiest way to try the examples shown in this book is to simply create the package
directories below your current development directory, put the .class files into the appropriate
directories, and then execute the programs from the development directory.
ACCESS PROTECTION
Classes and packages are both means of encapsulating and containing the name space and
scope of variables and methods. Packages act as containers for classes and other subordinate
packages.
Classes act as containers for data and code. The class is Javas smallest unit of
abstraction.
Because of the interplay between classes and packages, Java addresses four categories of
visibility for class members:
The three access specifiers: private, public, and protected, provide a variety of ways to produce
the many levels of access required by these categories.
IMPORTING PACKAGES
The import statement is a convenience to the programmer and is not technically needed to
write a complete Java program.
In a Java source file, import statements occur immediately following the package
statement (if it exists) and before any class definitions. This is the general form of the import
statement:
import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate
package inside the outer package separated by a dot (.)
There is no practical limit on the depth of a package hierarchy, except that imposed by
the file system. Finally, you specifyeither an explicit classname or a star (*), which indicates
that the Java compiler should import the entire package. This code fragment shows both forms
in use:
import java.util.Date; import java.io.*;
The File class does not specify how information is retrieved from or stored in files; it
describes the properties of a file itself.
A File object - used to obtain or manipulate the information associated with a disk
file, such as the permissions, time, date, and directory path, and to navigate
subdirectory hierarchies.
Files are a primary source and destination for data within many programs.
File(String directoryPath)
File(URI uriObj)
Sample
Example program
import java.io.File;
class FileDemo {
static void p(String s) {
System.out.println(s);
}
public static void main(String args[]) {
File f1 = new File("/java/COPYRIGHT");
p("File Name: " + f1.getName());
p("Path: " + f1.getPath());
p("Abs Path: " + f1.getAbsolutePath());
p("Parent: " + f1.getParent());
p(f1.exists() ? "exists" : "does not exist");
Output:
Directories
A directory is a File that contains a list of other files and directories. When you
create a File object and it is a directory, the isDirectory( ) method will return true.
import java.io.File;
class DirList {
public static void main(String args[]) {
String dirname = "/java";
File f1 = new File(dirname);
if (f1.isDirectory()) {
System.out.println("Directory of " + dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++) {
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory()) {
System.out.println(s[i] + " is a directory");
} else {
System.out.println(s[i] + " is a file");
}
}
} else {
System.out.println(dirname + " is not a directory");
}
}
}
Using FilenameFilter
String[ ] list(FilenameFilter FFObj)
FilenameFilter defines only a single method, accept( ), which is called once for each file in a
list.
General form
The listFiles( )
The signatures for listFiles( ) are shown here:
File[ ] listFiles( )
File[ ] listFiles(FilenameFilter FFObj)
File[ ] listFiles(FileFilter FObj)
Closeable
void close( ) throws IOException
Flushable
void flush( ) throws IOException
Javas stream-based I/O is built upon four abstract classes: InputStream,
OutputStream,Reader, and Writer.
InputStream is an abstract class that defines Javas model of streaming byte input.
It implements the AutoCloseable and Closeable interfaces
OutputStream
OutputStream is an abstract class that defines streaming byte output. It implements the
AutoCloseable, Closeable, and Flushable interfaces.
Input/Output related classes are defined in java.io package.
Input/Output in Java is defined in terms of streams.
A stream is a sequence of data, of no particular length.
Java classes can be categorised into two groups based on the data type one which they
operate:
Byte streams
Character Streams
PushbackInputStream Example
import java.io.*;
import java.text.SimpleDateFormat;
class PushbackInputStreamDemo
{
public static void main(String args[]) throws IOException
{ final long start = System.nanoTime();
String s = "if (a == 4) a=0;\\n";
byte buf[] = s.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(buf);
PushbackInputStream f = new PushbackInputStream(in);
int c;
while ((c = f.read()) != -1)
{
switch(c)
{
case '=':
if ((c = f.read()) == '=')
System.out.print(".eq.");
else
{
System.out.print("<-");
f.unread(c);
}
break;
default:
System.out.print((char) c);
break;
}//end of Switch
}//end of While
}//end of class
PushBackReader Example
import java.io.*;
public class PRDemo {
public static void main(String args[]) throws IOException
{ char carray[] = { 'q', 'u', 'a', 'l', 'i', 't', 'y' };
CharArrayReader careader = new CharArrayReader(carray);
PushbackReader preader = new PushbackReader(careader);
int temp; // read first character and print
temp = preader.read();
System.out.println("The first character: " + (char) temp); // read the second character and print
temp = preader.read();
System.out.println("The second character: " + (char) temp); // read the third character and print
temp = preader.read(); System.out.println("The third character: " + (char) temp);
java.awt.Component class:
The Component class provides 1 life cycle method of applet. public void paint(Graphics g): is
used to paint the Applet. It provides Graphics class object that can be used for drawing oval,
rectangle, arc etc.
How to run an Applet?
There are two ways to run an applet
By html file.
By appletViewer tool (for testing purpose).
Lets begin with the simple applet shown here:
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleApplet" width=200 height=60>
</applet>
*/
public class SimpleApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("A Simple Applet", 20, 20);
}
}
To execute the applet by appletviewer tool, write in
command prompt:
c:\>javac SimpleApplet.java
c:\>appletviewer SimpleApplet.java
16.
FrameTest.java
import java.awt.*;
As with the other AWT components, the appearance of a frame depends on the platform.
ButtonTest.java
import java.awt.*;
// Driver class
public class ButtonTest {
public static void main(String[] args) {
Frame f = new ButtonTestFrame("Button Test");
f.setSize(150, 100);
f.setVisible(true);
}
}
// Frame class
class ButtonTestFrame extends Frame {
public ButtonTestFrame(String title) {
super(title);
setLayout(new FlowLayout());
Button b = new Button("Testing");
add(b);
}
}
Event
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.They are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. 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.
This model defines the standard mechanism to generate and handle the events.Let's have a
brief introduction to this model.
The Delegation Event Model has the following key participants namely:
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.
Now the object of concerned event class is created automatically and information
about the source and the event get populated with in same object.
It is the root event class for all AWT events. This class and its subclasses supercede the
original java.awt.Event class.
ActionEvent
The ActionEvent is generated when button is clicked or the item of a list is double
clicked.
InputEvent
The InputEvent class is root event class for all component-level input events.
KeyEvent
4
The object of this class represents the adjustment event emitted by Adjustable objects.
ComponentEvent
10
11
12
Sr. No.
ActionListener
10
11
ComponentListener
This interface is used for receiving the component events.
ItemListener
This interface is used for receiving the item events.
KeyListener
This interface is used for receiving the key events.
MouseListener
This interface is used for receiving the mouse events.
TextListener
This interface is used for receiving the text events.
WindowListener
This interface is used for receiving the window events.
AdjustmentListener
This interface is used for receiving the adjusmtent events.
ContainerListener
This interface is used for receiving the container events.
MouseMotionListener
This interface is used for receiving the mouse motion events.
FocusListener
This interface is used for receiving the focus events.
References
1. Herbert Schildt, Java -Complete Reference, 8th edition Tata McGraw Hill, 2013.
2. Kathy sierra and Bert Bates Head First Java second edition, Oreilly, 2013
3. Harvey M. Deitel and Paul J. Deitel, Java How to Program, Prentice Hall of India,
2012
4. Gary Cornell and Cay S.Horstmann, Core Java Vol.1 and Vol.2, Sun Microsystems
Press, 2010
5. Herbert Schildt, Java(R) 7, A Beginners Guide, Tata McGraw Hill, 2012
http://www.tutorialspoint.com/java/
www.javatpoint.com/java-tutorial
javabeginnerstutorial.com/core-java/