You are on page 1of 39

E-Commerce

--------------------
Electronic Commerce -> Business thru Internet

Three Types
------------------
1. Business to Business (B2B) (Intel Corporation <-> HCL)
2. Business to Customer (B2C) (Chennaisilks.com)
3. Customer to Customer. (C2C) (Bazee.com) (Secondsales)

Web Technology
------------------------
Designing -> SGML, HTML, DHTML, Frontpage, Dreamweaver
Client side scripting -> Javascript, VBScript, JScript
Server Side scripting -> Servlets, ASP.NET, JSP
Storage DBMS(Database Management System)-> Oracle, SQL - Server, Access
RDBMS

Communication -> Socket, RPC, RMI/CORBA/DCOM, XML (Distributed Applications -


Banking, Financial, Telecom)

B2B

Intel -> Sun Microsystems (J2EE) -> Platform Independent


(XML)
HCL -> Microsoft (.NET) (Platform Dependent)

Markup Language
---------------------
1. Formatting Content
2. Describing Content

SGML -> Standard Generalized Markup Language


HTML -> Hypertext Markup Language -> Static Pages
DHTTML -> Dynamic Hypertext Markup Language
CSS -> Cascading style sheet (XML -> Extensible Markup Language)
Scripting -> VBScript, JavaScript, JScript
Java Programming
-------------------------
Java is an object oriented,multi-threaded programming language developed by
Sun Microsystems in 1991. It is designed to be simple,small and portable across
both platforms as well as Operating Systems.

Three Key elements


------------------
Powerful programming language constructs
Applets -> dynamic web program -> Instead HTML and Javascript
Significant set of object classes (Collection of variables and Function)

Java Development Environment (JDE)


----------------------------------------------
Java Compiler - generates bytecode -javac (Bulk code conversion -> Source Code to
Machine Code))
Java Interpreter - Execute the Bytecode - java (Line by Line Conversion)

Java Runtime Environment


------------------------------------
JVM -> Java Virtual Machine -> Act as a Class loader
Source Code -> javac (byte code) -> java interpreter -> JVM -> Execute

disadvantage
--------------
Execution speed is slow because of using bytecode

Java, JDBC, JFC/SWING,RMI -> jdk1.3


Java Bean -> bdk2.0
Java Servlet, Java Server Pages, EJB -> J2EE Server, Weblogic, Websphere

Architecture
------------------
Presentation layer -> Input and Output forms
Business logic -> Validations
Data layer -> Storing Data

Four types of Architecture


----------------------------------
1. Single Tier -> Foxpro (Single User)
2. Two Tier (or) Client/Server Technology-> VB and Oracle (Multi user)
3. Three Tier -> HTML, ASP, Oracle
4. Multi Tier (or) MVC Architecture (Model View Controller)
HTML
Javascript
Servlets -> Act as a controller which redirects to components and
pages
JSP -> View (Input and Output forms, Integrates HTMl and Javascript)
EJB -> Model (Business logic)
Oracle

JSP Servlets EJB

MVC - Model View Controller Architecture (JSP, Servlets, EJB)

Java Programming
--------------------------
Application (Console)
Control Statements
Arrays and Strings
Class Concepts
Inheritance
Interface and package
Exception Handling
Streams
Thread
Networking
JDBC
Applet
Graphics
AWT(Abstract Window Toolkit) Components (Heavy Weight Components)
Menu
Frame
Panel

JFC/Swing --> Java Foundation Class (Light Weight Components -> ie, the components
are developed by using Java)

Java Program Development


------------------------
Java development kit jdk

d:\>set path=%path%;c:\jdk1.3\bin;
d:\>path
d:\>notepad first.java
sample program
-------------------
class first {
public static void main(String args[]) {
System.out.println("My First Java Program");
}
}

d:\demo\DemoJava> javac first.java


d:\demo\DemoJava> java first

Note:
-----
Java program must be within a class
java class name and the filename may be same

Description of Java program


----------------------------------
public - access specifier of the method main
static - without creating object for class we can access the main method defined in
the class using class name
void - return type of main method
main - method name
String args[] - for passing arguments to main method. The argument type is String
class.

System - Class
out -Object of printStream
println - Method of printstream
System.out.println("Welcome to Java Programming");
System.out.print("Hello World");

Datatypes
---------
primitive datatypes
-------------------
char
float
long
double
int
boolean

Integer
-------
Type Size Range
---- ----- ------
byte 1 byte -128 to +127
short 2 bytes -32,768 to +32,767
int 4 bytes -2,147,483,648 to +2,147,483,647
long 8 bytes -9223372036854775808 to
+9223372036854775807

character
----------
char 2 bytes unicode characters. (Universal Code)
(ASCII+Non Ascii)
a,b,c,d some special symbols

boolean
--------
boolean 1 byte true or false

float
-----
float 4 bytes - 3.4e^38 to + 3.4e^38
double 8 bytes -1.7e^308 to +1.7e^308

Refence datatype:

String - group of characters are called string

String s1="Adroit";

userdefined datatypes
class
arrays
enums

variables
-----------
which holds some values

Three kinds of variables


------------------------
1. Instance variable
2. Local variable
3. class variable

Instance variables are used to define attributes or the state of particular object.

Local variables are used inside blocks as counters or in methods as temporary


variables.

class variables are global to a class and to all the instances of the class

Declaring variables
--------------------
datatype var_name;

Naming Conventions
----------------------------
var_name must be starting with character
special symbols are not allowed
white spaces are not allowed
only underscore allowed.
variable must be unique
int a;
int emp_no;
int emp no; //error
int e1;
int 1e; //error
char s$; //error

eg:
---
int a;
short b;
float f;
char c; (Variables)
String str; (Instance)
Eg:
----
class VarDecl
{
static void pr(String s)
{
System.out.println(s);
}
public static void main(String args[])
{
short a = 10;
float b = 3.14f;
char c = 'a';
boolean d = true;
String str = "Hello";
// VarDecl v = new VarDecl();

pr("Short Value : " + a);


pr("Floating Value : " + b);
pr("Character Value : " + c);
pr("Boolean Value : " + d);
pr("String value : " + str);
}
}

Operators
--------------
Arithmetic + - * / %
Relational >, <, >=, <=, ==, !=
Logical &&, ||, !
Increment and Decrement ++,--
Conditional ?:
Assignment =
Bitwise &, |, ^, <<, >>
Arithmetic Assignment +=, -=, *=, /=, %=

Bitwise
--------------
& And
-----------
A B C
0 0 0
0 1 0
1 0 0
1 1 1

a = 5 0101
b = 4 0100
0100 = 4

| OR
------
A B C
0 0 0
0 1 1
1 0 1
1 1 1

a = 5 0101
b = 4 0100
c = a | b 0101 = 5

^ X - OR
--------------
A B C
0 0 0
0 1 1
1 0 1
1 1 0
a = 5 0101
b = 4 0100
c = a ^ b 0001 = 1

Left Shift <<


--------------------
a = 10 << 1
00001010
00010100 = 20
a = 10 << 2
00001010
00101000 = 40
10 * 2 power 1 = 20
10 * 2 power 2 = 40

Right Shift >>


--------------------
a = 10 >> 1
00001010
00000101 = 5
a = 10 >> 2
00001010
00000010 = 2
10 / 2 power 1 = 5
10 / 2 power 2 = 2

Programming Constructs
---------------------------------
types
-------------
1. Conditional

Conditional
----------------
if statements
switch case
while loop while(true) while(1)
do while
for for(;;)

break;
continue;

if statement
---------------
if (condition)
{
statements
}

if..else
---------
if (condition)
{
true statements
}
else
{
false statements
}

if..else if
--------------
if (condition)
{
true statements
} else if(condition)
{
true statements
}
else
{
false statements;
}

nested if
-----------
if (condition) {
if (condition) {
true statements
} else
{
false statements
}
}
else
{
false statements
}
Looping
-----------
while loop
-------------
while (condition)
{
statements
}

do while
----------
do
{
statements
}while(condition);

for loop
-----------
for(initialization;condition; inc or dec)
{
statements
}

switch case
---------------
switch(expression)
{
case 1:
statements;
break;
case n:
statements;
break;
default:
statements;
}
Integer.parseInt()
Float.parseFloat()
Double.parseDouble()

Eg:
----
class CmdLine
{
public static void main(String args[])
{
if (args.length < 2)
{
System.out.println("Invalid Command Line Arguments");
System.exit(0);
}
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
Eg:
-----
class CmdLine1
{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
}
}

Factorial
Fibonacci Series
Armstrong Number
Sum of Number (123 = 1+2+3 = 6)

OOPS Concept
--------------------
Object Oriented Programming System (Simula 67)

Five Characteristics
-------------------------
1. Classes and Objects
2. Overloading
3. Inheritance
4. Polymorphism
5. Data Abstraction and Data Encapsulation.

Classes and Objects


---------------------------
Class -> Collection of member variables and member functions.

Object (or) Instance -> To access the class member variable and functions.

Syntax:
----------
class class_name
{
access_specifier datatype var_name;
access_specifier return_type function_name(arguments);
}

class_name ins_name = new class_name;

new -> Memory allocation for instance.

ins.memberfunction();

Access Specifier
-------------------
private -> With in a class
public -> Class, Subclass and main function(thru object)
protected -> Class and Subclass
no modifier -> similar to public ( Differed in package concept).

Note: By default, the variables and functions are no modifier.


Defining Class and object
Passing arguments and returning value
Passing object as arguments
Function Overloading
Static variables and functions
Constructor
this keyword
Finalizer (Destructor)
final Variable, final method and final class.
Inheritance
Abstract Class.

1. Defining class and object


----------------------------------
class Students
{
private int sno;
private String sname;

public void setstud(int no,String name)


{
sno = no;
sname = name;
}

public void dispstud()


{
System.out.println("Student No : " + sno);
System.out.println("Student Name :" + sname);
}
public static void main(String args[])
{
if(args.length < 2)
{
System.out.println("Invalid Arguments");
System.exit(0);
}
students s = new students();
int no = Integer.parseInt(args[0]);
String name = args[1];
s.setstud(no,name);
s.dispstud();
}
}

2. Passing arguments and returning values.


------------------------------------------------------
class circle
{
private int radius;

public void setradius(int r)


{
radius = r;
}

public float calculate()


{
return 3.14f * radius * radius;
}

public static void main(String args[])


{
if (args.length < 1)
{
System.out.println("Invalid Arguments");
System.exit(0);
}

circle c = new circle();


c.setradius(Integer.parseInt(args[0]));
float area = c.calculate();
System.out.println("Radius : " + args[0]);
System.out.println("Area : " + area);
}
}

3. Passing object as arguments.


-------------------------------------
return type function name(arguments)

int add(int,int);

class rect
{
int len,bre;

int totlen(rect r1,rect r2);

rect combine(rect r1,rect r2);

int add(int x,int y);


}

Eg:
-----
class rectangle
{
private int len,bre;

public void setrect(int l,int b)


{
len = l;
bre = b;
}

public int totlen(rectangle t)


{
return len + t.len;
}

public int totbre(rectangle t)


{
return bre + t.bre;
}
rectangle combine(rectangle t)
{
rectangle temp = new rectangle();
temp.len = len + t.len;
temp.bre = bre + t.bre;
return temp;
}
public void disp()
{
System.out.println("Length : " + len + "\t Breadth : " + bre);
}

public static void main(String args[]) throws Exception


{
rectangle r1 = new rectangle();
rectangle r2 = new rectangle();
rectangle r3 = new rectangle();
r1.setrect(2,3);
r2.setrect(4,5);
int tlen = r1.totlen(r2);
int tbre = r1.totbre(r2);
r3 = r1.combine(r2);
System.out.println("Total length : " + tlen);
System.out.println("Total Breadth : " + tbre);
r1.disp();
r2.disp();
r3.disp();
}
}

4. Function overloading
-------------------------------
Function name similar but passing arguments are different.

Eg:
-----
class exam
{
private int m1,m2,total;

public void setmarks(int ma1,int ma2)


{
m1 = ma1;
m2 = ma2;
}

public void setmarks()


{
m1 = 80;
m2 = 100;
}

void calculate()
{
total = m1 + m2;
}
void disp()
{
System.out.println("Mark1 : " + m1 + "\t Mark2 " + m2 + "\t Total "
+ total);
}

public static void main(String args[])


{
exam e1 = new exam();
exam e2 = new exam();
e1.setmarks();
e2.setmarks(70,80);
e1.calculate();
e2.calculate();
e1.disp();
e2.disp();
}
}
Eg:
----
class fun1
{
public void disp(char a,int n)
{
System.out.println("Character : " + a);
System.out.println("Number : " + n);
}

public void disp(int n,float f)


{
System.out.println("Number : " + n);
System.out.println("Float : " + f);
}

public static void main(String args[])


{
fun1 f = new fun1();
f.disp('a',10);
f.disp(20,3.41f);
}
}

5. Constructor
6. Finalizer
7. Static methods and variables.
8. Final keyword
9. Abstract Class.

Static Variables and Methods


-------------------------------------
Static Variable
--------------------
* Variables are not reinitialized
* Only one copy of the variable is created and shared by all objects
* By default, Initialized with zero. No other initialization is permitted.

Static Methods
-------------------
* If a method is declared as static, without creating object the method is
accessed.
* static methods are accessed only static variables
* Normal methods are access both static and normal variables.

Eg:
----
class Rect
{
int length;
int breadth;
int area;

static int count;


Rect(int a,int b)
{
length = a;
breadth = b;
count++;
}

Rect()
{
length = 0;
breadth = 0;
count++;
}

void calc()
{
area = length * breadth;
}

void display()
{
System.out.println("Length : " + length);
System.out.println("Breadth : " + breadth);
System.out.println("Area : " + area);
}
}
class Rect1
{
public static void main(String args[])
{
System.out.println("No of object : " + Rect.count);
Rect r1 = new Rect(10,20);
r1.calc();
System.out.println("No of object : " + Rect.count);
Rect r2 = new Rect();
r2.calc();
System.out.println("No of object : " + Rect.count);
r1.display();
r2.display();
}
}

Eg:
----
class Rectangle
{
int length;
int breadth;
private static int count;

static void displaycount()


{
System.out.println("No of Object : " + count);
count++;
}

Rectangle(int a,int b)
{
length = a;
breadth = b;
count++;
}

Rectangle1()
{
length = 0;
breadth = 0;
count++;
}

void display()
{
System.out.println("Length : " + length);
System.out.println("Breadth : " + breadth);
}

public static void main(String args[])


{
Rectangle.displaycount();
Rectangle r1 = new Rectangle(10,20);
Rectangle.displaycount();
Rectangle r2 = new Rectangle();
Rectangle.displaycount();
r1.display();
r2.display();
}
}

this keyword
----------------
refers current object.

Eg:
-----
class point
{
private int x,y;

void init(int x,int y)


{
this.x = x;
this.y = y;
}
void display()
{
System.out.println("x = " + x);
System.out.println("y = " + y);
}
public static void main(String args[])
{
point pp = new point();
pp.init(4,3);
pp.display();
}
}

Eg:
-----
class load
{
String firstname;
String lastname;
int age;
String profession;

load assign(String firstname,String lastname,int age,String profession)


{
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
this.profession = profession;
return this;
}

load assign(String fn,String ln)


{
firstname = fn;
lastname = ln;
return this;
}

load assign(String fn,String ln,String prof)


{
firstname = fn;
lastname = ln;
profession = prof;
return this;
}

load assign(String fn,int ag)


{
firstname = fn;
age = ag;
return this;
}

void print()
{
System.out.println(firstname + " " + lastname + " " + age + " " +
profession);
}

public static void main(String args[])


{
load fl = new load();
fl.assign("Naveen","Kumar",23,"Programmer");
fl.print();
fl.assign("Raj","Prabhu");
fl.print();
fl.assign("Chitra","Devi","Analyst");
fl.print();
fl.assign("Nithya",34);
fl.print();
}
}

Wrapper Classes
--------------------------
Integer.parseInt()
Float.parseFloat()
Double.parseDouble()
Byte.parseByte();

Constructor
----------------
To initialize the object.
Garbage Collector -> Collect or Destroy the unused object.

syntax:
-----------
class class_name
{
class_name()
{
statements;
}
}
eg
----
import java.io.*;

class Const1
{
private int sno;
private String sname;

Const1()
{
System.out.println("Constructor Called");
sno = 0;
sname = "";
}
void getdetails() throws IOException
{
DataInputStream br = new DataInputStream(System.in));
String line;
System.out.print("Enter Sno : ");
line = br.readLine();
sno = Integer.parseInt(line);
System.out.print("Enter Sname : ");
sname = br.readLine();
}

void putdetails()
{
System.out.println("Sno : " + sno);
System.out.println("Sname : " + sname);
}

public static void main(String args[]) throws IOException


{
Const1 c1 = new Const1();
c1.putdetails();
c1.getdetails();
c1.putdetails();
}
}

Overloading Constructor
---------------------------------
Constructor name are similar, but the passing arguments are different.

Default Constructor
----------------------------
classname() {}

Copy Constructor
------------------------
An object is initialized with another object.

exam(int n1,int n2)


{

exam(exam e1)
{

exam e1(10,20),e2(e1);

eg
----
import java.io.*;
class students
{
private int sno;
private String sname;
private int mark1,mark2,total;

students() throws Exception


{
DataInputStream br=new DataInputStream(System.in);
System.out.print("Enter Student No : ");
sno = Integer.parseInt(br.readLine());
System.out.print("Enter Student Name : ");
sname = br.readLine();
System.out.print("Enter mark1 and mark2 : ");
mark1 = Integer.parseInt(br.readLine());
mark2 = Integer.parseInt(br.readLine());
}

students(int no,String name,int m1,int m2)


{
sno = no;
sname = name;
mark1 = m1;
mark2 = m2;
total = mark1 + mark2;
}

void putstud()
{
System.out.println("Sno : " +
sno);
System.out.println("Sname : "
+ sname);
System.out.println("Mark1 : "
+ mark1);
System.out.println("Mark2 : "
+ mark2);
System.out.println("Total : " + total);
}

public static void main(String args[]) throws Exception


{
students s1 = new students();
students s2 = new students(100,"Kirthika",90,80);
s1.putstud();
s2.putstud();
}
}

eg
----
class marks
{
private int mark1,mark2,total;

marks() {}
marks(int m1,int m2)
{
mark1 = m1;
mark2 = m2;
}
marks(marks m1)
{
mark1 = m1.mark1;
mark2 = m1.mark2;
}

void calc()
{
total = mark1 + mark2;
}

void putdetails()
{
System.out.println("Mark1 : " + mark1);
System.out.println("Mark2 : " + mark2);
System.out.println("Total : " + total);
}
public static void main(String args[])
{
marks m1 = new marks(90,80);
marks m2 = new marks(m1);
marks m3 = new marks();
m1.calc();
m2.calc();
m1.putdetails();
m2.putdetails();
m3.putdetails();
}
}

Finalizers
------------
To destroy the unused object.

Garbage Collector -> The garbage collector will destroy the unused object
automatically. There is no need for finalizers

Arrays
-----------
Collection of like Data Types

two types
------------
1. single dimension
2. multi dimension

single dimension
-------------------------
Syntax:
------------
datatype var[] = new datatype[size];

Eg:
-----
int a[] = new int[10];

Initialization
------------------
int a[5] = {1,2,3,4,5};
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5

char c[] = new char[10]; //character Array

Eg:
-----
import java.io.*;
class Arr1
{
public static void main(String args[]) throws Exception
{
int a[] = new int[10];
int i,n;
System.out.print("Enter the value of a n : ");
DataInputStream din = new DataInputStream(System.in);
n = Integer.parseInt(din.readLine());
for(i=0;i<n;i++)
{
System.out.print("Enter a[" + i + "] : ");
a[i] = Integer.parseInt(din.readLine());
}
System.out.println("The Given Array values");
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}

Eg:
-----
import java.io.*;

class Arr1
{
public static void main(String args[]) throws Exception
{
int a[] = new int[10];
int i,n,j,temp;
System.out.print("Enter the value of a n : ");
DataInputStream din = new DataInputStream(System.in);
n = Integer.parseInt(din.readLine());
for(i=0;i<n;i++)
{
System.out.print("Enter a[" + i + "] : ");
a[i] = Integer.parseInt(din.readLine());
}

for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("The Sorted Array values");
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}

MultiDimension
-----------------------
* Java doesn't support multidimensional array.
* However an array of Array is used.
int a[] = new int[3];
a[0] = new int[3]; (a(0,0),(0,1),(0,2))
a[1] = new int[3]; (a(1,0),(1,1),(1,2))
a[2] = new int[3] (a(2,0),(2,1),(2,2))
Syntax:
---------
datatype var[][] = new datatype[row][col];

Eg:
----
int a[][] = new int[3][3];
Eg:
-----
import java.io.*;

class Matrix1
{
public static void main(String args[]) throws Exception
{
int a[][] = new int[5][5];
int i,j,row,col;
DataInputStream din = new DataInputStream(System.in);
System.out.print("Enter row and column value : ");
row = Integer.parseInt(din.readLine());
col = Integer.parseInt(din.readLine());

for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
System.out.print("Enter a[" + i + "][" + j + "] : ");
a[i][j] = Integer.parseInt(din.readLine());
}
}

System.out.println("The Given Matrix format ");


for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
}
}

String Class
---------------
Collection of characters

String constructors
-------------------
default constructor
-------------------
1. String s=new String()
char cs[]={'a','b','c'};
2. String s = new String(cs);

3. String(char chars[],int startindex,int numchars)

char cs[]={'a','b','c','d','e','f'};
String s=new String(cs,2,3); cde

Hash Table
-----------
A hash table stores information using a special calculation on the object to be
stored. A hash code is produced as a result of a calculation. The hash code is used
to choose the location in which to store the object. When the information needs to
retrieved, the same calculations is performed, the hash code is determined and a
lookup of that location in the table results in the value that was stored there
previously.

String Arithmetic
----------------
'+' - Concatenation
String toString() - convert into String
+= Operator will also work for strings.
Str1+=Str2; (str1=str1+str2)

String Class Methods


---------------------------
int length() - number of characters in String.
String s1="hello"
int len=s1.length();
len=5

char charAt(int) - The character at a location in the String


String s1="hello world"
char a = s1.charAt(2)
a=l

getChars() , getBytes() - copy chars or bytes in an external array.


String s1 = "Hello World";
char c[] = {'a','b','c'};
s1.getChars(0,s1.length,c,3);
s1.getChars(int,int,char[],int)
c[] = {'a','b','c'};

toCharArray() - produces a char[] containing the characters in the string

toByteArray() - Produces a byte[] containing the characters in the string.

boolean equals() , equalsIgnoreCase() - An equality check on the contents of the


two strings
str1="hello"
str2="Hello"

str1.equals(str2) = false
str1.equalsIgnoreCase(str2) = true

compareTo() - Result is negative,zero or positive depending on the lexiographical


ordering of the string and the argument.Uppercase and Lowercase are not equal.
str1 > str2 = +ve value
str1 < str2 = -ve value
str1 == str2 = 0

startsWith() - Boolean result indicates if the string starts with the argument
String s1="hello"
s1.startsWith("hE");=false
s1.startsWith("h"); = true

endsWith() - Boolean result indicates if the string ends with the argument
String s1="Hello";
s1.endsWith("o"); - True
s1.endsWith("h");- false

indexOf , lastIndexOf() -Returns -1 if the argument is not found within this


string, otherwise returns the index where the argument starts. lastIndexOf searches
backwards from end.

String s1="This is a sample String for indexOf Method";


s1.indexOf('s') = 3
s1.indexOf('s',5)=6
s1.lastIndexOf('s') = 10
s1.lastIndexOf('s',9) = 6

subString() - Returns a new String containing the specified character set.


subString(startindex,endindex)
String s1 = "Welcome";
s1.subString(2,4) - lc

concat() - Returns a new string object containing strings characters followed by


the characters in the argument
String s1="hello"
String s2="world"
s1.concat(s2); -> helloworld

replace() - Returns a new String object with the replacements made. uses the old
string if no matches found.
replace('Oldchar','newchar')

String s1="hello"
s1.replace('l','w') = hewwo

toLowerCase(),toUpperCase() - returns a new string object with case of all letters


changed. uses the old string if no changes to be made.
String s1 = "HELLO";
s1.toLowerCase();

String s2 = "hello";
s2.toUpperCase();

trim() - Returns a new string object with the Whitespace removed from each end.

trim(" hello ") -> hello

Eg:
----
class Arith {
String fname="Aswath";
String lname="Narayanan";
void show() {
System.out.println("The fullname is " + fname + " " + lname);
}
public static void main(String args[]) {
Arith a1=new Arith();
a1.show();
}
}

Eg:
----
class hash {
public static void main(String args[]) {
String s1="world";
String s2="Hello";
System.out.println("The hash code for " + s1 + " is " + s1.hashCode());
System.out.println("The hash code for " + s2 + " is " + s2.hashCode());
}
}

Eg:
----
class equaldemo {
public static void main(String args[]) {
String s1="Hello";
String s2="Hello";
String s3="Good bye";
String s4="HELLO";

System.out.println(s1 + " equals " + s2 + " is " + s1.equals(s2));


System.out.println(s1 + " equals " + s3 + " is " + s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " is " + s1.equals(s4));
System.out.println(s1 + " equals " + s4 + " is " + s1.equalsIgnoreCase(s4));
}
}
Eg:
----
class Strings {
int i;
String name[]={"Aswath","Aswin","Anand","Aditya","Anirudh"};
void show() {
System.out.println("My favourite names are ");
for(i=0;i<5;i++) {
System.out.println(name[i]);
}
}
public static void main(String args[]) {
Strings s=new Strings();
s.show();
}
}

Eg:
-----
class StringMeth
{
public static void main(String args[])
{
String str1 = "Hello";
String str2 = "Hello";
String str3 = "This is a sample string for indexOf method";
String str4 = " World ";
System.out.println("Length : " + str1.length());
System.out.println("charAt(4) : " + str1.charAt(4));
System.out.println("To a Character Array : ");
char c[] = new char[str1.length() + 3];
c[0] = 'a';
c[1] = 'b';
c[2] = 'c';
str1.getChars(0,str1.length(),c,3);
for(int i=0;i<c.length;i++)
System.out.print(c[i] + " ");
System.out.println();

System.out.println("To a Byte Array : ");


byte b[] = new byte[str1.length()];
str1.getBytes(0,str1.length(),b,0);
for(int i=0;i<b.length;i++)
System.out.print(b[i] + " ");
System.out.println();
System.out.println("Equals : " + str1.equals(str2));
System.out.println("EqualIgnore Case : " +
str1.equalsIgnoreCase(str2));
System.out.println("compareTo : " + str1.compareTo(str2));
System.out.println("compareTo : " + str2.compareTo(str1));
System.out.println("startsWith : " + str3.startsWith("t"));
System.out.println("endsWith : " + str3.endsWith("method"));
System.out.println("indexof : " + str3.indexOf('s'));
System.out.println("indexof : " + str3.indexOf('s',4));
System.out.println("lastIndexOf : " + str3.lastIndexOf('s'));
System.out.println("lastIndexof : " + str3.lastIndexOf('s',16));
System.out.println("substring : " + str3.substring(4,8));
System.out.println("Concatenate : " + str1.concat(str2));
System.out.println("To lower case : " + str1.toLowerCase());
System.out.println("To Upper Case : " + str1.toUpperCase());
System.out.println("str4 = " + str4);
System.out.println("Trim() = " + str4.trim());
}
}

StringBuffer
-------------
StringBuffer is a peerclass of string that provides much common use
functionality of strings. String represents fixed-length-character sequences.
Stringbuffer represents varied length character sequences. StringBuffer may have
characters and substrings inserted in the middle or appended at the end. The
compiler automatically creates a stringbuffer to evaluate certain expressions, in
particular when the overloaded operators + and += operator are used with the string
objects.

Constructor
--------------------
StringBuffer sb = new StringBuffer();

StringBuffer sb = new StringBuffer(16);

String s;
StringBuffer sb = new StringBuffer(s);
StringBuffer Methods
-----------------------
toString() - Creates a string from this stringbuffer or convert to string

length() - returns the number of character in the stringbuffer

capacity() - returns current number of spaces allocated.

boolean ensureCapacity() - makes the stringbuffer hold atleast the desired no. of
spaces.

setLength() - truncates or expand the previous character string. if expanding pads


with nulls.

charAt(int) - returns the char at that location in the buffer

setCharAt(int,char) - modifies the value of that location.


StringBuffer sb = "Hello";
sb.setCharAt(2,'w'); Hewlo;

getChars() - copy chars into an external array. There isno getBytes() as in string

append() - The argument is converted to a string and appended at the end of the
current buffer

insert() - The second arg is converted to a string and inserted into the current
buffer beginning at the offset.

reverse () - The order of the character in the buffer is reversed.

Eg:
-----
class StringBuf
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello World");
System.out.println(sb + ".capacity() = " + sb.capacity());
System.out.println(sb + ".length() = " + sb.length());
System.out.println(sb + ".insert(5,aaa) = " + sb.insert(5,"aaa"));
System.out.println(sb + ".capacity() = " + sb.capacity());
System.out.println(sb + ".length() = " + sb.length());
System.out.println(sb + ".append(bbbb) = " + sb.append("bbbb"));
System.out.println(sb + ".reverse() = " + sb.reverse());
}
}

Inheritance
--------------
* Reusability of code
* Extensibility of code.

Types of inheritance
--------------------------------
1. Single
2. Multiple -> Java Does'nt support
3. Multilevel
4. Heirarchical
5. Hybrid -> Doesn't Support

Single
----------
Base
|
Derived

Multiple
------------
Base1 Base2
| |
---------------------------
|
Derived1

Multilevel
--------------
Base1
|
Derived1
|
Derived2

Base1 -> Base class


Derived1 -> Base1 -> BaseClass
Derived2 -> Derived1 -> Immediate Class
Derived2 -> Base1 -> Indirect Base Class

Heirarchical
----------------
Base
|
-----------------------------------------
| |
Derived1 Derived2
| |
-------------------------- -------------------------------
| | | |
Derived11 Derived12 Derived21 Derived22

Hybrid
----------
Combination of Multiple and Multilevel

Base
|
Derived1 Base2
| |
| |
-------------------------------
|
Derived2

Single Inheritance
----------------------------
Base
|
Derived

Syntax:
-----------
class base
{
statements;
}
class derived extends base
{
statements;
}

Note:
---------
* Private members are not inherited
* public, protected and no modifier members are inherited
* Constructor and finalizer are not inherited.

Eg:
-----
class employee
{
private int eno;
private String ename;

public void setemp(int no,String name)


{
eno = no;
ename = name;
}

public void putemp()


{
System.out.println("Empno : " + eno);
System.out.println("Ename : " + ename);
}
}
class department extends employee
{
private int dno;
private String dname;

public void setdept(int no,String name)


{
dno = no;
dname = name;
}

public void putdept()


{
System.out.println("Deptno : " + dno);
System.out.println("Deptname : " + dname);
}
public static void main(String args[])
{
department d = new department();
d.setemp(100,"aaaa");
d.setdept(20,"Sales");
d.putemp();
d.putdept();
}
}

super () -> Keyword used to call the base constructor;

Eg:
------
class emp1
{
private int eno;
private String ename;

emp1(int no,String name)


{
System.out.println("Base Constructor");
eno = no;
ename= name;
}

public void putemp()


{
System.out.println("Empno : " + eno);
System.out.println("Empname : " + ename);
}
}

class dept1 extends emp1


{
private int dno;
private String dname;

dept1(int no,String name,int eno,String ename)


{
super(eno,ename);
System.out.println("Derived Constructor");
dno = no;
dname = name;
}

public void putdept()


{
System.out.println("Deptno : " + dno);
System.out.println("Deptname : " + dname);
}
public static void main(String args[])
{
dept1 d = new dept1(20,"Sales",100,"Kirthika");
d.putemp();
d.putdept();
}
}
Multilevel
---------------
Base
|
Derived1
|
Derived2

Derived1 -> Base -> Direct Base class


Derived2 -> Derived1 -> Direct Base class
Derived2 -> Base -> Indirect Base class

Syntax:
--------------
class base
{
statements;
}
class derived1 extends base
{
statements;
}
class derived2 extends derived1
{
statements;
}

Eg:
-----
class students
{
private int sno;
private String sname;

public void setstud(int no,String name)


{
sno = no;
sname = name;
}

public void putstud()


{
System.out.println("Student No : " + sno);
System.out.println("Student Name : " + sname);
}
}
class marks extends students
{
protected int mark1,mark2;

public void setmarks(int m1,int m2)


{
mark1 = m1;
mark2 = m2;
}

public void putmarks()


{
System.out.println("Mark1 : " + mark1);
System.out.println("Mark2 : " + mark2);
}
}

class finaltot extends marks


{
private int total;

public void calc()


{
total = mark1 + mark2;
}

public void puttotal()


{
System.out.println("Total : " + total);
}

public static void main(String args[])


{
finaltot f = new finaltot();
f.setstud(100,"Nithya");
f.setmarks(78,89);
f.calc();
f.putstud();
f.putmarks();
f.puttotal();
}
}

Eg:
-----
//multilevel with constructor
class students1
{
private int sno;
private String sname;

students1(int no,String name)


{
sno = no;
sname = name;
}

public void dispstud()


{
System.out.println("Student No : " + sno);
System.out.println("Student Name : " + sname);
}
}

class marks1 extends students1


{
protected int mark1,mark2;

marks1(int n1,int n2,int sno,String sname)


{
super(sno,sname);
mark1 = n1;
mark2 = n2;
}

public void dispmarks()


{
System.out.println("Mark1 : " + mark1);
System.out.println("Mark2 : " + mark2);
}
}

class finaltot1 extends marks1


{
private int total;

finaltot1(int n1,int n2,int no,String name)


{
super(n1,n2,no,name);
total = mark1 + mark2;
}
public void disptotal()
{
System.out.println("Total : " + total);
}

public static void main(String args[])


{
finaltot1 f = new finaltot1(90,89,100,"Kirthika");
f.dispstud();
f.dispmarks();
f.disptotal();
}
}

Abstract Class
----------------
Set of complete and Incomplete methods.

Eg:
----
abstract class baseclass
{
public void basedisp() //complete method
{
System.out.println("Base class Display method");
}
public abstract void calc(int param); //incomplete method
}

class derived1 extends baseclass


{
public void derived1disp()
{
System.out.println("Derived 1 class display method");
}

public void calc(int param)


{
System.out.println("The value of param : " + param);
}
}

class Caller extends baseclass


{
public void calc(int param)
{
System.out.println("Square value is : " + (param*param));
}

public static void main(String args[])


{
derived1 d1 = new derived1();
d1.basedisp();
d1.derived1disp();
d1.calc(10);

Caller d2 = new Caller();


d2.basedisp();
d2.calc(5);
}
}

Different between abstract and interface


-------------------------------------------------
abstract class Interface
--------------- --------------
1. set of complete and incomplete method 1. set of incomplete method

2. class and method is declared using abstract 2. interface keyword is used for
keyword declaration

Interfaces (Set of incomplete methods)


-----------------
Interface is nothing but java's Multiple Inheritance.

Interface contains the declaration of the methods, and its implementation is


made in another class.

Syntax
---------
access_specifier interface 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;
}

here access is either public or not used(no modifier).

Implementing interface
-----------------------
access class class_name[extends superclass]
[implements interface[interface...]] {
//class body
}

Eg:
-----
Callback.java
----------------------
interface Callback
{
public void call(int param);
}

Client.java
----------------
class Client implements Callback
{
public void call(int p)
{
System.out.println("Interface Method = " + p);
}
public void nonIfaceMeth()
{
System.out.println("Non Interface method is also used");
}

public static void main(String args[])


{
Callback c = new Client(); (or) Client c = new Client();
c.call(5);
// c.nonIfaceMeth();
}
}

Eg:
-----
AnotherClient.java
----------------------------
class AnotherClient implements Callback
{
public void call(int p)
{
System.out.println("Square Value is : " + (p*p));
}

public static void main(String args[])


{
Callback c = new AnotherClient();
c.call(5);
}
}

Eg:
-----
Stack-> Last In First Out
IntStack.java
--------------------
interface IntStack
{
void push(int item);
int pop();
}

FixedStack.java
-------------------------
class FixedStack implements IntStack {
private int stack[];
private int tos;

FixedStack(int size)
{
stack=new int[size];
tos=-1;
}

public void push(int item)


{
if(tos==stack.length-1)
System.out.println("stack is full");
else
stack[++tos]=item;
}

public int pop()


{
if(tos<0)
{
System.out.println("stack underflow");
return 0;
}
else
return stack[tos--];
}
public static void main(String args[]) {
FixedStack mystack1=new FixedStack(5);
FixedStack mystack2=new FixedStack(8);

for(int i=0;i<6;i++) mystack1.push(i);


for(int i=0;i<9;i++) mystack2.push(i);

System.out.println("stack in mystack1");
for(int i=0;i<6;i++)
System.out.println(mystack1.pop());

System.out.println("stack in mystack2");
for(int i=0;i<9;i++)
System.out.println(mystack2.pop());
}
}

Packages
-------------
Collection of Classes and interfaces placed under a folder.

Predefined Packages
-----------------------
import java.io.*
import java.util.Date
import java.util.Vector
import java.sql.*
import java.swing.*
import java.awt.*;

Userdefined packages
--------------------------
package package_name;

class
{
}

javac -d . filename.java

-d -> Create a new directory with the name of package_name


. -> refers current path

Private Public Protected No Modifer


-----------------------------------------------------------
----------------
Same package
Same Class Yes Yes Yes Yes

Same Package
Sub Class No Yes Yes Yes

Same Package
Non Subclass No Yes No Yes

Different Package
Subclass No Yes Yes No

Different Package
Non Subclass No Yes No No

Protection.java
----------------------
package p1;

public class Protection


{
int n=10;
private int n_pri = 20;
public int n_pub = 30;
protected int n_pro = 40;

public Protection()
{
System.out.println("Base Constructor");
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pub = " + n_pub);
System.out.println("n_pro = " + n_pro);
}
}

javac -d . Protection.java

Derived.java
-------------------
package p1;

public class Derived extends Protection


{
public Derived()
{
System.out.println("Same Package Subclass");
System.out.println("n = " + n);
System.out.println("n_pub = " + n_pub);
System.out.println("n_pro = " + n_pro);
}
}

javac -d . Derived.java

SamePackage.java
-----------------------
package p1;

public class SamePackage


{
public SamePackage()
{
Protection p1 = new Protection();
System.out.println("Same Package Non Subclass");
System.out.println("n = " + p1.n);
System.out.println("n_pub = " + p1.n_pub);
}
}

javac -d . SamePackage.java

Demo.java
---------------
import p1.Protection;
import p1.Derived;
import p1.SamePackage;

class Demo
{
public static void main(String args[])
{
Protection ob1 = new Protection();
Derived ob2 = new Derived();
SamePackage ob3 = new SamePackage();
}
}

javac Demo.java

Protection2.java
----------------------
package p2;

public class Protection2 extends p1.Protection


{
public Protection2()
{
System.out.println("Different Package Sub Class");
System.out.println("n_pub = " + n_pub);
System.out.println("n_pro = " + n_pro);
}
}

javac -d . Protection2.java

OtherPackage.java
----------------------
package p2;

public class OtherPackage


{
public OtherPackage()
{
p1.Protection ob = new p1.Protection();
System.out.println("Diffent Package Non subclass");
System.out.println("n_pub = " + ob.n_pub);
}
}

javac -d . OtherPackage.java

Demo1.java
------------------
import p2.Protection2;
import p2.OtherPackage;

class Demo1
{
public static void main(String args[])
{
Protection2 ob1 = new Protection2();
OtherPackage ob2 = new OtherPackage();
}
}

javac Demo1.java

Advantages
---------------------
1. Class Files are placed in a single directory
2. The packages are used in anywhere.

You might also like