Académique Documents
Professionnel Documents
Culture Documents
In procedural program:
Programming logic follows certain procedures
class class2{
class obj_comparison{
ote: Values enclosed in <> are required values, while those values in [] are optional.
VARIABLES
Primitive Variables:
Variables with primitive data types such as int
or long. Stores data in the actual memory
location of where the variable is present
X1 X2 Result
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE
LOGICAL OPERATORS
|| (logical) and | (boolean logical)
The basic difference between || and | operators is
same as && and &
X1 X2 Result
! ( log ical NOT)
X1 X2
TRUE FALSE
FALSE TRUE
BITWISE OPERATORS
Java provides Bit wise operators to manipulate the contents of variables at the bit
level. These variables must be of numeric data type ( char, short, int, or long).
Java provides seven bitwise operators. They are AND, OR, Exclusive-OR,
Complement, Left-shift, Signed Right-shift, and Unsigned Right-shift.
A B ~A A&B A|B A^B
Primitive Wrapper
boolean AtomicBoolean
int AtomicInteger
long AtomicLong
V AtomicReference<V>
Wrapper class
}
}
Control Structures & Loops
If loop
If-else loop
Muliple if loop
Switch case
While loop
For loop
Do-while loop
Methods
Syntax
returnType methodName( /* argument list */ ) {
/* Method body */
}
Ne ste d c lasse s that are de c lare d static are simply calle d static
ne ste d c lasse s.
No nstatic ne ste d c lasse s are c alle d inne r c lasse s.
No nstatic ne ste d c lasse s (inne r c lasse s) have acc e ss to o the r
me mbe rs o f the e nc lo sing c lass, e ve n if the y are de clare d
private
Static nested classes do not have access to other members of the enclosing class.
Why Nested Class
Lo gic al gro uping o f c lasse s
If a c lass is use ful to o nly o ne o the r c lass, the n it is lo gic al
to e mbe d it in that c lass and ke e p the two to ge the r.
Ne sting suc h "he lpe r c lasse s" make s the ir pac kage mo re
stre amline d.
Inc re ase d e nc apsulatio n
class InnerClass{
void printdata(){
System.out.println(Message+"in inner");}}
If the re is no c o nstruc to rs fo r yo ur c lass, the c o mpile r will supply
a de fault c o nstruc to r(no arg c o nstruc to r).
A c o nstruc to r is use d to c o nstruc t an o bje c t.
A c o nstruc to r may have ze ro argume nt, in whic h c ase it is c alle d
a no argume nt c o nstruc to r.
Co nstructo r argume nts c an be use d to initialize the fie lds in the
o bje c t.
Example 1
class Rock {
Rock() { System.out.println("Creating Rock");
}}
public class SimpleConstructor {
public static void main(String[] args) {
for (int i = 0; i < 10; i++)
new Rock();
}}
Constructor
Example 2
class Rock2 {
Rock2(int i) {
System.out.println("Creating Rock number " + i);
}}
// Class constructor
MainClass(double theRadius) {
radius = theRadius;
}
}
Polymorphism
As we know that a method has its own signature which is
known by method's name and the parameter types.
Java has a powerful feature which is known as method
overloading. With the help of this feature we can
define two methods of same name with different
parameters.
class overload{
public static void main(String args[]) {
over a=new over();
double result;
a.test();
a.test(10);
a.test(10,20);
result=a.test(12.6);
System.out.println("result of a.test(12.6) is:"+result);
}
}
Access Modifiers
You can define the scope of a variable or
method or class by using access modifiers.
Public
Protected
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();
}
}
Inheritance
super keyword
As the name suggest super is used to access the
members of the super class. It is used for two
purposes in java.
First: To access the hidden data variables of the
}
}
R.Jerome, Technical Consultant, CalydonTech, jerome@caly
Interfaces
R.Jerome, Technical Consultant, CalydonTech, jerome@caly
Abstract Classes
Exceptions
Exception, that means exceptional errors. Actually
exceptions are used for handling errors in
programs that occurs during the program
execution
Exceptions in java are any abnormal,
try{
//Protected code
}
catch(ExceptionName e1){
//Catch block
}
Catching Exceptions
Ex1:
public static void main(String[] args) {
int i, j, numer1 = 5, denom1 = 5, denom2 = 0;
try {
i = numer1/denom1;
System.out.println("numer1/denom1 = " + i);
}
catch(Exception e){
System.out.println("Exception : "+ e.getMessage());
}
finally{
if(quotient != -1){
System.out.println("Finally Block Executes");
System.out.println("Result : "+ quotient);
}else{
System.out.println("Finally Block Executes. Exception Occurred");
return quotient;
}
}
return quotient;
}
}
Rules for try, catch and finally Blocks
import java.io.*;
public class className{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException {
// Method implementation
}
//Remainder of class definition}
Declaring you own Exception
Keep the following points in mind when writing
your own exception classes
All exceptions must be a child of Throwable.
int available()
Returns the number of bytes that can be read (or skipped over) from this input stream without blocking by the
Method Summary
void close()
Closes this output stream and releases any system resources associated with this
stream.
void flush()
Ex1:
import java.io.*;
public class TrivialApplication {
public static void main ( String args[] ) throws IOException {
else{
FileInputStream finp=new FileInputStream(f);
byte b;
do{
b=(byte)finp.read();
System.out.print((char)b);
} while(b!=-1);
finp.close();
}
}
}
Files
Ex5:
import java.io.*;
if(f.exists()){
String str="How are you babe?";
fop.write(str.getBytes());
fop.flush();
fop.close();
System.out.println("The data has been written");
}
else
System.out.println("This file is not exist");
}
}
String Class
String class objects work with complete strings
instead of treating them as character arrays as
some languages do.
String class objects are immutable (ie. read only).
When a change is made to a string, a new object is created
StringDemo3
Ex3:
StringBuffer Class
The StringBuffer class is used to represent characters that
can be modified.
This is simply used for concatenation or manipulation of the
strings.
StringBuffer is mainly used for the dynamic string
concatenation which enhances the performance.
//append()
strbuf.append("Hello");
strbuf.append("World"); //print HelloWorld
System.out.println(strbuf);
StringBuffer Examples
Ex1:
//insert()
strbuf.insert(5,"_Java ");
System.out.println(strbuf);
//reverse()
strbuf.reverse();
//charAt()
System.out.print("Character at 6th position : ");
System.out.println(strbuf.charAt(6)); //print J
//substring()
System.out.print("Substring from position 3 to 6 : ");
System.out.println(strbuf.substring(3,7));
StringBuffer Examples
Ex1:
//deleteCharAt()
strbuf.deleteCharAt(3);
System.out.println(strbuf);
//capacity()
System.out.print("Capacity of StringBuffer object : ");
6 char StringBuilder nulString=new StringBuilder(6); // explicitly sets size StringBuilde
StringTokenizer Class
StringTokenizer class objects may be created by one of three
constructor methods depending on the parameters used.
The first parameter string is the source text to be broken at
the default set of whitespace delimiters (space, tab,
newline, cr, formfeed).
If a second parameter is passed, that string is assumed to
Collection Map
Sorted Map
Sorted Set
perations are all there, but you work with a key-value pair instead of an isolated element. Map i
Hierarchical Relationships
vThe Collection interface is a group of objects, with
duplicates allowed.
nterface returns an Iterator. An Iterator is similar to the Enumeration interface witch has the
Group Operations
boolean containsAll(Collection collection)
boolean addAll(Collection collection)
void clear()
void removeAll(Collection collection)
All() method allows you to discover if the current collection contains all the elements of another
method ensures all elements from another collection are added to the current collection
ü Implements all optional list operations, and permits all elements, including null.
ü An ArrayList capacity is the size of the array used to store the elements in the list.
As elements are added to an ArrayList, its capacity grows automatically. It is an
Array based implementation where elements of the List can be accessed directly
through get() method.
Example :ArrayListDemo.java
Java Linked List
ü A LinkedList is used to store an “ordered” group of elements where
duplicates are allowed.
ü A LinkedList is based on a double linked list where elements of the List are
typically accessed through add() and remove() methods
Example :LinkedListExample.java
Java Vector
The Vector class implements a growable array of objects where the size of
the vector can grow or shrink as needed dynamically.
Like an array, it contains components that can be accessed using an integer
index.
Example :VectorDemo.java
Java Hash Set
The HashSet class implements the Set interface.
It makes no guarantee that the order of elements will remain constant over time.
This class is not synchronized and permits a null element.
This class offers constant time performance for the basic operations (add,
remove, contains and size), assuming the hash function disperses the
Example :HashSetExample.java
Java Hash Table
HashTable is synchronized.
Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t.
Hashtable doesn’t allow nulls
Example :TreeSetExample.java
Map Interface
The Map interface is not an extension of the Collection
interface. Instead, the interface starts off its own interface
Allow you to add and remove key-value pairs from the map. Both the key and value can be null. However, you should not
add a Map to itself as a key or value.
o Object put(Object key, Object value)
o Object remove(Object key)
o void putAll(Map mapping)
o void clear()
Query Operations
import java.util.*;
public class MapExample {
public static void main(String args[]) {
Map map = new HashMap();
Integer ONE = new Integer(1);
Annotation
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.RUNTIME)
public @interface Override{
}
Override Annotations
Employee.java
public class Employee {
protected void startWork() {
Manager.java
// Code
public class that willextends
Manager start toEmployee
do some work.
{
}@Override
@SuppressWarnings(value={"deprecation"}
)
Class
enum
User-defined Annotations
AnnotatedClass.java (Using Annotation Author)
public class AnnotatedClass{
@Author(name = "Author1")
public void annotatedMethod1(){
}
Class.forName(String driver)
This method is static. It attempts to load the class and returns class
instance and takes string type value (driver) after that matches class
with given string.
DriverManager
It is a class of java.sql package that controls a set of JDBC drivers.
Each driver has to be register with this class.
Description of code
getConnection(String url, String userName, String
password)
This method establishes a connection to specified database url.
It takes three string types of arguments like:
con.close()
This method is used for disconnecting the connection. It frees
all the resources occupied by the database.
JDBC API
DriverManager
"Driver Manger" Manages all the Drivers found in JDBC environment, load the most
appropriate driver for connectivity.
Connection :-
Connection class creates objects which represents connection and it's object also helps in
creating object of Statement, PreparedStatement and CallableStatement classes.
Statement
JDBC Examples
MSAccess
JdbcMSAccess.java