Anda di halaman 1dari 55

C++ : CUI GUI (Graphics) - Expensive Drawbacks : C++ suports Real World Programm

ing. Means one program can be used in another computer. But with in the Geograph
ical Area. C++ doesn't support for Web and Enterprise Level Applications SOLUTIO
N J A V A 1990 James Ghosling, Peter Smith Project Name : Elctronic Consumers or
Project Name : Project Green Idea : Communicate with other systems in d. Design
ing using C++ Language 1991 Introduced a new Language called "OAK" OAK - Greek L
atin word "Everything" 1993 1994 1995 First time GUI based WWW appeared onto the
computers through APPLETS New Java Web Browser, to support for execution of APP
LETS. Called as HotJava Renamed to JAVA Java is a country name. Located between
North Korea and South Korea. JAva location is famous for exporting other parts o
f the world 1997 1998 Advanced Networking Concepts are Advanced GUI applications
to make java Coffee Beans to improved Portable. and JSP' the worl
2000 Advanced Web Applications called Servlets s are introduced 2002 2003 Advanc
ed Reusable Components called EJB's are introduced. Struts
2009
Android
Java Applications : CUI GUI Web Character User Interface Graphical User Interfac
e Web applications
Mobile Mobile Devices Applications AI Artificial Intelligense
Java characterstics : 1. 2. 3. 4. 5. 6. 7. 8. 9. Simple Platform Independent Por
table Robust or Faster Distributed Reliable and Scalable Multi Threaded Secured
Compiler and Interpreter
Java Architecture : 1. Java File 2. Class File .java -> Compiler -> .class -> In
terpreter -> Hardware Byte Code Byte Code = ASCII + UNICODE ENGLISH + Asian Lang
uages 3. Java Virtual Machine (JVM) Components of JVM : 1. 2. 3. 4. Class Loader
Starts the Execution engine Just In time Compiler Garbage Collection i. Referen
ce Collectors ii. Tracing Collectors iii. Compacting Collectors
4. Application Programming Interface (API) .class Byte Code JVM API Java API
Harware Machine Code (0,1) Java Security Levels :
1. Compiler Level Security 2. Class Loader Security 3. Byte code Verifier Byte C
ode Verifier : 1. Checks for the Structure of the Programs 2. Checks for the val
idity of the Variables, Methods and es. Java Programming Constructs : 1. Variabl
es Is a name, which holds a values Which can be changed during the Program execu
tions. Every variable in Java, occupies into its respected memory x = 100; Types
: a. Class Variables class a { var; } b. Instance Variables class A { for(a=0;
{ } } c. Local Variables class A { method() { var; } } d. Static Variables a = 1
00; a = 200 static a = 100; a = 100 2. Data Types : Defines the Type of data is
being used. location Classnam
Types : i. Primitive or Fundamental Integer Group : byte short int long 1 2 4 8
Byte Bytes Bytes Bytes 0 0 0 0
Floating Point Group : float 4 Bytes .123456 double 8 bytes .123456 123456 Boole
an Group : boolean 1 bit Character Group : char 2 Bytes null 0/1
ii. Abstract or Derived String 8 Bytes 3. Operators Operates on Operands Values
of Variables
Operand : a + b i. UNARY a. unary
Operates on 1 - and ! a = 10 -a = 0-10= -10 a = true; !a = FALSE
b. increment c. decrement PRE int a = 10; ++a; 1. 2. 3. Faster a = 10 + 1; a = 1
1;
++ -POST int a = 10; a++; a = 10; a = 10 + 1; a = 11 Slower
Known ii. BINARY a. Arithmetic b. Assignment
Unknown Operates on >1 +, -, *, / and % = a = 10; b = a; c. ArithmeticAssignment
+=, -=, *=, /=, %= a+=5 a-=5; a*=5; a/=5; a%=5; d. relational a a a a a = = = =
= a a a a a + * / % 5 5; 5; 5; 5;
<, >, <=, >=
e. comparision == and != f. Logical && || ! g. Bit-Wise h. Shift i. Ternary &&,
|| and ! Both If any one Inversion or Reverse &, |, ^ and ~ <<, >>, >>> ?, :
(cond)?T-Stmts:F-Stmts; 4. Conditional Statements i. If Statements a. b. c. d. S
imple If If ... Else Else If Ladder Nested If
ii. SWITCH .. CASE Statements Meu Driven with integers or rs 5. Looping Statemen
ts Loop : Repetition Depicts " REUSABILITY" i. WHILE ii. DO .. WHILE iii. FOR ch
aracte
6. Arrays Collection of Similar or Homogeneous elements under the same Data Type
, referred by a common NAME. int a; 1 variable int a..z; 26 variables; int aa..a
z, ba..bx; 50 Variables int a1,a2...a50; int a[50]; i. Single Dimensional data-t
ype var[size]; int a[10], b; data-type[size] var; int[10] a,b; data-type var[siz
e] = {Elements}; int a[3] = {1,2}; int a[3] = {1,2,3}; int a[3] = {1,2,3,4}; dat
a-type var[] = {Elements}; int a[] = {1,2}; 2 int a[] = {1,2,3}; 3 int a[] = {1,
2,3,4}; 4 ii. Multi Dimensional data-type var[R][C]; int a[3][3], b; data-type[R
][C] var; int[3][3] a,b; data-type var[R][C] = {Elements}; int a[3][2] = {1,2};
int a[3][3] = {1,2,3}; int a[3][2] = {1,2,3,4}; data-type var[][C] = {Elements};
int a[][2] = {1,2}; 2 int a[][3] = {1,2,3}; 3 int a[][2] = {1,2,3,4}; 4 Importa
nce : [2^32] -> 2 GB - 4 GB [2^64] -> 20 GB - 40 GB [2^64][2^64][2^64] Ranges :
int float chars 7. Functions or Methods Set of instructions to execute a specifi
c task of the given program. Syntax : <Access> return-type Method-name() 0 to n-
1 0 to n-1 0 to n-1, n (/0) 50 Variables
{ code; } Types : i. Non Parameterized <Access> return-type Method-name() { code
; } ii. Parameterized <Access> return-type Method-name(param) { code; } Paramete
rs can be called : a. By Value a 10 0x101 x 20 0x103 b. By Reference a 20 0x101
x 20 0x101 Method Overloading : Same Method name with different es in the same c
lass. Signatures : 1. 2. 3. 4. Example : add(int , int) add(int, float) add(floa
t, int) Name of the Methods Type of Paramters No of Parameters Order of the Para
meters Signatur b 10 0x102 y 10 0x102 b 20 0x102 y 10 0x104
add(float, float) Method Overriding : Same method name with same parammeters in
different classes while inheritance. class A { void Display() { S.o.p("Hi"); } }
class B extends A { void Display() { S.o.p("Welcome"); } } 8. Accesses Permissi
ons for acceptance or denying. Types : i. Specifiers Used on CLASSES
public Can be access all the properties to other classes. Open to alkl with in a
ll FOLDERS private Only to that class. protected Only to the sub classes.
default Open to all with in the FOLDER Level ii. Modifiers Used on VARIABLES and
METHODS
public Can be access all the properties to other classes. Open to alkl with in a
ll FOLDERS private Only to that class. protected Only to the sub classes.
default Open to all with in the FOLDER Level static Constant, never changes the
values even after the program successfully completed final Stop overriding. To m
akes the variables static in the calling classes. Contains only the definition.
No Implementation methods(); methods() { code; } Definition Implementation
abstract
native To call the other language like C, C++ methods into the current JRE. sync
hronized Sharing the same resource to the multiple, but allowing only one to acc
ess at a time. 9. Classes and Objects Class Collection of Objects class ClassNam
e { } Rules : Every Ist character of each word should be in CAPITAL Letters Stud
entDetails Follows by all the Rules of Variables. Object Is an instance of a cla
ss, which exhibits a well defined behaviour of that class Object contains both v
ariables and Methods. Calling Objects : ClassName ob = new ClassName(); new -> A
llocates memory to the Objects
ClassName() -> Constructor, used for invoking the objects and initializing the m
ember variables with the default
values obj.variables; obj.methods(); 10. Principles of OOPs : i. Encapsulation H
ides the data and code for providing the security Hides only the unessentials. C
an be done by using Accesses i.i. Abstraction Shows the essentials perspective o
f the viewer Can be done by using Methods and Objects ii. Inheritance Aquiring t
he properties from one to another One Super / Base / Parent class Which gives th
e properties Another Sub / Derived / Child class Which accepts the properties. T
ypes : i. Single Inheritance a. Single Level A | B b. Multi Level A | B | C c. H
eirarchical Level A | B C ii. Multiple Inheritance a. Multipath A | B
C
| D b. Hybrid A | B | D Properties can be derived into the Sub class by using ke
yword "extends" iii. Polymorphism Many Forms
C
Same fom exists more than one wither physically or Programmatically. Types : i.
Static Physically Done by using Overloading Programmatically Done by using Objec
ts
ii. Dynamic
11. Interfaces and Abstract classes : Abstract Classes : If a class contains one
or more abstract methods or a class is declared as an abstract. Syntax : class
A { abstract class A { abstract method1(); method1(); abstract method2(); method
2(); method3() } { code; } class B extends A { method1() { code; } method2() { }
}
} class B extends A { method1() { code; } method2() { } }
Drwabacks of abstract Classes :
i. Always it should be a PARENT CLASS. ii. Need to be written multiple times for
multiple Sub Classes Interfaces : Prototype to the classes. Syntax : interface
InterfaceName extends Interface { public return-type method(param); public retur
n-type method(param); } To implement the abstract methods of an interface into a
ny of the classes, we use a keyword "implements" class ClassName extends SuperCl
assName implements InterfaceName1, Interf aceName2..... { abstract methods() { I
mplementation; } } interface A { public void Disp1(); } interface B { public voi
d Disp2(); } class C implements A, B C.java { public void Disp() { S.o.p("Ok");
} p s v m(String args[]) { C c = new C(); c.Disp(); } } 12. Exception Handling :
Programs Compile Syntax Errors Execute Run time Errors or Exceptions. A.java
B.java
Exception : normal flow of execution
Is an abnormal termination of the program, which disturbs the
Heirarchy of Exceptions : Object | Throwable Exception | User defined Checked (K
nown) Checked Exceptions : i. ClassNotFoundException class ADD { } Add.java ADD.
class Error Pre Defined | Unchecked (Unknonw)
class CALC { Add a = new Add(); } ii. MethodNotFoundException Display(); iii. In
validArgumentException int add(int , int) int add('a',10.45); iv. IllegalAccessE
xception private methods(); a.methods(); Unchecked Exceptions : i. ArithmeticExc
eption / 0 B.java A.java display();
ii. ArrayIndexOutOfBoundsException int a[3] = {1,2}; int a[3] = {1,2,3}; int a[3
] = {1,2,4,5,6,7}; iii. ArrayStoreException int a[3] = {1, 'a'}; iv. NegativeArr
ayException int a[-3] = {1};
v. NullPointerException String s=""; S.o.p("this is String : "+s); ClassName obj
; obj.method(); vi. NumberFormatException int add(int, int) int add("a","b"); To
handle all the above or any other exceptions, we need Exception Handlers . Stat
ements to Handle the Exceptions : i. TRY ii. CATCH iii. FINALLY Contains erroren
eous code Handles the exceptions of TRY Whether an exception is rainsed or not i
n TRY, to do some statements Can Throw a single Exceptional Object. Used for Use
r defined Exceptions Can Throw Multiple Exceptional Objects. Alternate for the T
RY .. CATCH in methods
iv. THROW
v. THROWS
Syntax : try { try { code; finally stmts;
code; } } catch(ExceptionType obj) { { stmnts; } } try { code; } catch(Exception
Type obj) { stmnts; } finally { stmts; } Multiple Catch Blocks to TRY :
try { code; } catch(ExceptionType obj) { stmnts; } catch(ExeptionType obj) { } c
atch(ExceptionType obj) { } catch(Exception e) { } If the Exception in catch blo
ck at first catch, it shown a compile time error, UNREACHABLE CODE ERROR Nested
Try .. Catch : try { code; try { code; } catch(ExceptionType e) { } } catch(Exce
ption obj) { stmnts; } THROWS : Alternate for TRY .. CATCH. method-name() { try
{ code; } catch(ExceptionType obj) { } catch(ExceptionType obj) { } } or
method-name() throws ExceptionType, ExceptionType { code; } THROW : Used for Use
r Defined Exceptions
class AgeException extends Exception { public String getMessage() { return "Inva
lid Age"; } } class MainAgeDemo { public void setAge(int age) { if(age < 13 || a
ge > 30) throw new AgeException(); S.o.p("Age is : "+age); } p s v m(String args
[]) { MainAgeDeme mad = new MainAgeDemo(); mad.setAge(20); mad.setAge(-20); } }
13. Conversions and Castings : Data type to Data Type conversion Conversion : Wh
en converting from one data type another data type which was compatible each oth
er Types : i. Implicit or Widening Conversion : From LOW to HIGH priority data t
ype. These are default process int a = 10; double d = a; 10.00
ii. Explicit or Narrowing Conversion : From HIGH to LOW priority data type. doub
le d = 15.25; int i = d; Error
(type)var; int i = (int)d; Valid Castings : When converting from one data type a
nother data type which are incompatible each other int i = 10; String s = i; "10
"
String s = "10"; int i = s; Error int i = Integer.parseInt(s); 14. Super and Thi
s Keywords : Super : Refers the parent class Objects class SuperClassName { supe
r-var; super-constructors() { } super-methods() { } } class SubClassName extends
SuperClassName { super(); Constructor super.var; Variables super.methods(); Met
hods } This : Refers the Current class Objects class CurrentClassName { cur-var;
int a, b; Class CurrentClassName() { this(params); } CurrentClassName(param) {
} int add(int a, int b) Instance { this.a = a; this.b = b; } int mul(int x, int
y) {
a = x; b = y; } } 15. Multi Threading : Software Application Program Instruction
program Task Thread Coll of Application Coll of Programs sequence of instructio
ns Small executable task of a given
In the system, the applications can be controlled in two ways : i. Process Based
ii. Thread Based Processor takes care Programming thru
i. Single Processed ii. Multi Processed Advantages with the threads : i. Improve
d the performance ii. Simultaneous access on the resources. iii. Program structu
re simplification Pitfalls of threads : i. Race Condition ii. Lock Starvation ii
i. Deadlocks To create Multi Threading in JAVA, we take a support from the Paren
t class, java.lang.Thread class Syntax of Thread class : Thread t = new Thread()
; Thread t = new Thread(String name); Thread t = new Thread(String, int priority
); Thread t = new Thread(String, int, ThreadGroup tg); Methods : i. setName(Stri
ng) Sets a name to the Thread
t.setName("Name"); ii. getName() Returns the name of the Thread
S.o.p(t.getName()); iii. setPriority(int priority) Specifies new priorities prio
rities : Default Thread.HIGH_PRIORITY Thread.NORM_PRIORITY Thread.LOW_PRIORITY T
hread.HIGH_PRIORITY+10 Thread.HIGH_PRIORITY+15 A thread with HIGH priority alway
s execute first. iv. getPriority() Returns the priority of the Thread v. start()
; To start the execution of the given Thread object 10 5 0
t1.start(); t2.start(); t3.start(); t4.start(); vi. wait() To make the thread to
be wait until the previous thread finishes its execution
t1.wait(); vii. notify() Which notifies the waiting threads for their executions
t1.notify() If the threads are N, notify() should be used for (N-1) times viii.
notifyAll() Notifies all the Threads,n but the execution will be done on the bas
es of priority notifyAll(); ix. sleep(long ms) Makes the thread to be wait for a
certain amount of duration t2.sleep(10*60*1000); After the specified amount of
time finished, the Thread starts its execution by putting the previous thread in
the Dead stage Life Cycle of threads :
i. New Stage : When the Thread is created for the Ist time, the Threads are in N
ew Stage How to create Threads : a. By extending parent class "Thread" b. By imp
lementing interface "Runnable" ii. Runnable Stage : Every created should be star
ted for their execution by using start(). Then the Threads are in Runnable Stage
. iii. Not Runnable : If the Threads are : a. Waiting for another thread to comp
lete by using wait() method b. Waiting for another thread for a particular durat
ion of time by using sleep() c. If the Thread blocked by another iv. Dead or Ter
minated Stage : If the Threads completed their execution normally or stopped by
using stop() method. How to make Multi threads : i. isAlive() Returns the state
of the Thread, means either DEAD or ALIVE
t1.start(); if(t1.isAlive() == false) { t2.start(); } if(t2.isAlive() == false)
{ t3.start(); } ii. join() another ChildThread : t1 Joins one thread object to
MainThreadClass c1 c2 c3 c1.t1.join();
c2.t1.join(); c3.t1.join(); How to create Threads : a. By extending parent class
"Thread" class ChildThread1 extends Thread { ChildThread1() { super("Child-1");
start(); } public void run() { Running code; } } class ChildThread2 extends Thr
ead { ChildThread2() { super("Child-2"); start(); } public void run() { Running
code; } } class MainThreadClass { p s v m(String args[]) { ChildThread1 c1 = new
Child1() ChildThread1 c2 = new Child1() } } b. By implementing interface "Runna
ble" class ChildThread implements Runnable { Thread t1, t2, t3; ChildThread() {
t1 = new Thread("Child-1"); t2 = new Thread("Child-2"); t3 = new Thread("Child-3
"); t1.start(); t2.start(); t3.start(); } public void run() { Running code; } }
class MainThreadClass
{ p s v m(String args[]) { ChildThread c1 = new ChildThread(); } } 16. Packages
Folder, which contains collection of classes and interfaces which are organized
in a format. Steps to Create a Package : i. Create a program which contains the
package definition. include "package" keyword in the beginning of the program pa
ckage Package_Name; or package Package_Name.SubPackage; <access> class ClassName
{ code; } ii. Save and Compile the Program iii. Create the folders on the names
of Package_Name and SubPackage iv. Copy .class files into the respected Folders
. v. Execute the Sub Programs by creating Main Program in the parent Folder mean
s starting folder or i. Create a program which contains the package definition.
include "package" keyword in the beginning of the program package Package_Name;
or package Package_Name.SubPackage; <access> class ClassName { code; } ii. Save
these files in the parent folder. iii. Compile the programs by using following c
ommand javac -d . ClassName.java
or javac -d . *.java -d Create a directory on the name of Package_Name or SubPac
kage Identifies the Packages and Sub Packages
.
iv. Execute the Sub Programs by creating Main Program in the parent Folder means
starting folder How to call packaged programs into Other programs : To call the
programs of one package into another package, Ist of all the access should be P
UBLIC To call them, we use "import" keyword. import Packa_Name.SubPack.ClassName
; or import Packa_Name.SubPack.*; * calls all the ClassName.class files to the O
ther program In user defined packages, * can't work. To work explicitly, we shou
ld add these .class files to the CLASSPATH set CLASSPATH=%classpath%;Driver:\Fol
der\Fold; Pre Defined Packages : Types : i. java lang Before 1997 Contains all t
he necessary elements and classes supported to create Basic Java Programs Defaul
t package for all Java Programs. No need to import awt Supports to create GUI ap
plications.
applet Support to create java enabled web applications called APPLETs util Suppo
rts for Java based Data Structures and All the Utilities programs Supports for r
ead and write operations
io
net sql rmi
Supports for Networking applications Supoprts for Database applications Supports
advance Netwokring applications called Remote Method Invocation After 1997 (x -
eXtended) Supports for Advanced GUI and portable applications
ii. javax swing
servlet Supoprts for Advanced Web Applications and server side applications serv
let.jsp Supports for creating Java Server Pages applications, an alternate to Se
rvlets 17. java.lang package : Supports all the basic java programming elements.
Classes : Object Is a parent for all other classes of Java. Making java as pure
object oriented. Class Manages the classes and Objects created inside of a prog
ram
System Provides the system devices information like input, output and error devi
ces System.in System.out System.err Math Input Output Error
Contains all the Mathmatical and Trignometric Methods or Operations Math.abs(-10
) 10 Math.ceil(10.25) 11.00 Math.floor(10.25); 10.00 Math.round(12.49); 12.00 Ma
th.max(1,2); 2 Math.min(1,2); 1 Math.pow(2,3); 8 Math.random(); 0.0 - 1.0
Wrapper Are the super classes for all the data types of Java int float double In
teger Float Double
char
Character
String Handles the String operations length() String indexOf(char) Index of spec
ified character inside the String Length of the given
lastIndexOf(char) Index of the character inside the String which located at last
position equals(str) Checks the equality
equalsIgnoreCase(Str) Checks the equality by ignoring the cases toUpperCase() to
LowerCase() trim() Convert to Upper case Converts to Lower case Removes the whit
e spaces before and after the string
replace(old, new) Replaces the Character(s) with in the String substring(start,
end) Finds the String in another String getChars(start, end) Returns the Charact
er of a given String in char array hashCode() Converts into hash code
Exception Provides all the exceptional statements to handle the Runtime Errors T
hread Support for multi Threading applications using java 19. Java.awt package :
AWT Abstract Abstract Window Toolkit Only the definition with out any code
Window Support for GUI based Desktop apps Toolkit Tools support to design and de
velop GUI
apps Heirarchy of AWT : java.lang.Object | java.awt.Component | Containers | Pan
els | Applet Frame Component : Self contained software device, which can be plug
ged into any target applications
Components Levels : i. High Level or Containers Applet Are java enabled web appl
ications, which execute only in java web browsers Frame Supports to create and d
esign GUI based Window or Desktop applications
Dialog Are part of the Frame applications to display the messages. ii. Mid Level
or Mid Containers : Panel To add the Low LEvel to High Level
iii. Low Level or Control Components : Label Used for displaying captions
TextField Used to accept an input from the end user in the format of Text Box Te
xtArea Used to accept an input if it is in more than one line
Choice Accepts one item from given group of items Example : Select Country List
Accepts one or multiple items from the given group of items Example : Education
Qualifi Technical Skills
Checkbox
Used to accept one or more items from the given Example : Select Hobbies Select
Gender To make checkbox items as a single unit.
CheckboxGroup
Menu
USed for designing Menus for GUI appls
MenuBar Place which contains multiple menus, and can be placed at top of the GUI
applications MenuItem Items of each Menu.
Button Submitting the data to the database, or another applciations or to the fi
le 19. javax.swing package : Differences between AWT and SWINGS : AWT SWING ----
--------------------------------------------------------------------------------
---1. Components are heavy weight 1. Components are Light Weight during the load
and execute durng the load and execute 2. LEssa No. of Components 3. No Pluggab
le Look And Feel (PLAF) 4. Sharp edges 2. Huge no of components 3. Contains PLAF
4. Rounded Edges
5. No images to all components 5. Images can be used for reliable components.] H
eirarchy of Swings : java.lang.Object | javax.swing.JComponent | JContainers | J
Panels | JApplet JFrame JComponent : Self contained software device, which can b
e plugged into any target applications
Components Levels :
i. High Level or Containers JApplet Are java enabled web applications, which exe
cute only in java web browsers JFrame Supports to create and design GUI based Wi
ndow or Desktop applications ii. Mid Level or Mid Containers : JPanel To add the
Low LEvel to High Level JTabbedPane Container which can have their own sub cont
ainers called TABS, where each tab can contain many Components iii. Low Level or
Control Components : JLabel Used for displaying captions JTextField Used to acc
ept an input from the end user in the format of Text Box JTextArea Used to accep
t an input if it is in more than one line JComboBox Accepts one item from given
group of items Example : Select Country JList Accepts one or multiple items from
the given group of items Example : Education Qualifi Technical Skills
JCheckBox Used to accept multiple items from the given Example : Select Hobbies
Select Gender JRadioButton Used to accept a single item from the given group of
items ButtonGroup To make Button related items as a single unit. JMenu JMenuBar
USed for designing Menus for GUI appls Place which contains multiple menus, and
can be placed at top of the GUI applications
JMenuItem
Items of each Menu.
JButton Submitting the data to the database, or another applciations or to the f
ile Extra Components of SWINGs : JPasswordField Represents for Passwords JFileCh
ooser JColorChooser JOptionPane JScrollPane JTree JTable JSlider 20. java.util p
ackage : Util package contains all the utilities which are not necessary for bas
ic programming. Data Structure : organized format of data in memory Drawbacks of
an Arrays : i. Fixed size elements int a[3] = {1,2,3}; ii. Not easier for Data
insertions, deletions and updations Insertions Deletions Queues Updation Maintai
n Linked Lists, Queues and Stacks Hashing Searching Techniques Sorting Technique
s Classes : Linked Lists, Queues and Stacks Double Linked List, Stacks and Used
for Open and Save As options Used for colors. Used for displaying Messages. It i
s an alternate for Dialogs Adds the Scroll bars to the GUI basing on kind of App
lications Prepares the data in Tree format Foir Tabular format representation US
ed for sliding (Volume)
i. BitSet
Growable array of elements which contains the data in bit format
BitSet bs = new BitSet(); bs.add(10); i0000 1010 bs.add('a'); c0110 0001 ii. Str
ingBuffer Advanced class to the Strings.
String s = "GIET "; s = s.trim() + ", Gunupur"; StringBuffer sb = new StringBuff
er(s); sb.length(); 4 sb.capacity(); 4+16 sb.append(string) Adds the data at end
sb.reverse(); s1 = MADAM I AM ADAM s2 = sb.reverse(s1); iii. StringTokenizer De
vides the huge string into small parts called Tokens. String s = "This is an Exa
mple for String Tokenizer"; StringTokenizer st = new StringTokenizer(s, " "); in
t n = st.countTokens(); 7-1 while(st.hasMoreTokens()) { S.o.p(st.nextToken()); }
iv. Arrays Super class for representing the arrays created inside the the Data
Structure
int a[10] = {2,5,1,6,4,9}; Arrays.sort(a); Arrays.find(array, ele); v. ArrayList
Maintains the collection of elements in Array format. which can contains duplic
ate values
ArrayList al = new ArrayList(); ArrayList<Type> al = new ArrayList<Type>(); al.a
dd(elements); vi. HashSet Maintains the elements in the order of KEY and VALUE p
air
HashSet hs = new HashSet(); hs.put(key, value)
hs.get(key); vii. Date Performs the current system date operations.
Date d = new Date(); S.o.p(d); IST d.getTime(); 23-07-2011 01-01-1970 ----------
----22-06-0041 12:30 PM 00:00 AM --------------12:30 Hours Sat July 2011 23 12:2
0:24 PM
41 * 365 * 24 * 60 * 60 * 1000 + 06 * 30 * 24 * 60 *60 *1000 + 22 * 24 * 60 * 60
*1000 + 12 * 60 *60 *1000 + 30 * 60 *1000 viii. Calendar Is an abstract class w
hich contains the Date and Timing of the Local Zones Calendar cal = null; cal.ge
tInstance(); YEAR MONTH MONTH_OF_YEAR DAY_OF_YEAR DAY_OF_WEEK S.o.p(cal.YEAR); 1
6+1 204 7
ix. GregorianCalendar Maintains the world wide dates and timings India USA Miami
23-07-2011 23-07-2011 22-07-2011 12:25:25 PM 01:55:25 AM 02:00:00 PM
GregorianCalendar gcal = new GregorianCalendar(); gcal.get(cal.YEAR); gcal.isLea
pYear(cal.YEAR); Interfaces : i. Set Maintains the data with out duplicates ii.
List Maintains the data with duplicates The above 2 interfaces are part of Colle
ction Framework Framework : Coll of Classes and interface which use among them 2
011 false
Collection | List Set | | ArrayList BitSet LinkedList SortedSet TreeSet HashSet
Legacy Classes and Interfaces : The classes which are introduced from jdk 1.4 ve
rsion onwards, called as Legacy Classes Vector Class Growable array which was re
placement for max of classes of java.util package
Vector v = new Vector(); Vector v = new Vector(size, increment); Vector v = new
Vector(10, 10); Methods : v.addElement(Object ele); v.insertElementAt(int index,
Object ele); v.replaceElementAt(int index, Object ele); v.removeElementAt(int i
ndex); v.removeAll(); Enumeration Interface Generates the series of information
Enumeration en = v.elements(); while(en.hasMoreElements()) { S.o.p(en.nextElemen
t()); } java.io packages : IO Input and Output
How the data can be saved into the memory and then how this can maintained and m
anipulated. In C, C++ In C : FILE *fp;
In C++ fstream ifstream and ofstream Max supporting formats are .dat or .txt In
Java.io packages Data can : File Used to create the files and Directories
inside the java File File File File Methods : i. exists() Returns the avaialabil
ity of the file for the later operations ii. isReadOnly() iii. size() iv. length
() Returns true or false basing on the permissions of the file Returns the size
of the file within the memory Returns the length of the content within the file
Returs the last access date and f f f f = = = = new new new new File(); File("St
ring filename.ext"); File("path\filename.ext"); File(directoryObject);
v. lastAccessed() time
vi. lastModified() Returns the last modified content date and time vii. createdO
n() viii. getParent() file ix. getPath() Returns the date of creation. Returns t
he parent folder to the
Returns the complete Path of the file Returns the complete data of the
x. String[] list() File RandomAccessFile
Is a class which allows the users to perform write operations into the Files Ran
domAccessFile raf = new RandomAccessFile(); RandomAccessFile raf = new RandomAcc
essFile("String filename.ext", "mode"); File f = new File("path\filename.ext");
RandomAccessFile raf = new RandomAccessFile(f, "mode"); Modes : C C++ Java -----
-------------------------------------------------------------read r ios::in r wr
ite w ios::out w append a ios:app rw read+write r+ write+read w+
append+read truncate create
a+ ios::trunc ios::ate
Methods : i. writeBytes(string) Which wirtes the string data to the file in Byte
s format raf.writeBytes("abcd"); ii. int length() raf.length(); iii. void seek(i
nt) Setting and Finding out the specified location with in the file raf.seek(raf
.length()); iv. getFilePointer() Returns the current file pointer with in the Fi
le raf.getFilePointer(); int SNo 1 2 21 3 4 File Operations : i. Byte format Str
eams Stream Flow of data between Source to Destination Types : a. InputStream Re
ad the data from Common Methods : int read() Check the file pointer is reached t
o EOF string SName A B E C D int 16 SMarks 56 89 74 78 59 Returns the length of
the file
while(is.read() != -1) { length++; } read(byte b[]) Reads the data from the file
and keeps it into the Byte format byte b[] = new byte(10000);
System.in.read(b); String s = new String(b); S.o.p(s); read(byte b[], int offset
, int length) Reads the data in byte format, from the specified location with th
e given length is.read(b, 0, 16); int mark(int nbyte) Sets the cursor in the spe
cified location for the next read void reset() Resets the marked pointer locatio
n. So that the cursor positions will be set to beginning of the file (0) Close t
he opened file.
void close()
InputStream Classes : a. FileInputStream Reads the data from Specified File Loca
tion FileInputStream fis = new FileInputStream("filename.ext"); b. BufferedInput
Stream Reads the data from the File or any other input device, can be stored the
dat inside the Buffer BufferedInputStream bis = new BufferedInputStream(new Fil
eInputStream("filename.ext")); BufferedInputStream bis = new BufferedInputStream
(System.in); c. DataInputStream Reads the exact data type data from the Specifie
d File Streams or any i/p devices DataInputStream dis = new DataInputStream(new
FileInputStream(Filename.ext)); DataInputStream dis = new DataInputStream(System
.in);
Methods : readInt() readDouble(); readFloat() readUTF() Reads int data Reads dou
ble Read Float Reads String
b. OutputStream Writes the data to Common Methods : i. write(byte b[]) Writes te
h byte formatted content to the file ii. write(byte b[], int offset, int length)
Write the byte data to the file with the specified length and position iii. flu
sh() write iv. close() Clears the buffer b4 the new to close the opened file
Ouput Stream Class : FileOutputStream BufferedOutputStream DataOutputStream ii.
Binary Format Binary : Types : a. Readers Common Methods : int read() Check the
file pointer is reached to EOF Reads the data from Character 0 or 1. Low level p
rogramming
while(is.read() != -1) { length++; } read(char b[]) Reads the data from the file
and keeps it into the binary format char b[] = new char(10000);
System.in.read(b); String s = new String(b); S.o.p(s); read(char b[], int offset
, int length) Reads the data in char format, from the specified location with th
e given length is.read(b, 0, 16); int mark(int nchar) Sets the cursor in the spe
cified location for the next read void reset() Resets the marked pointer locatio
n. So that the cursor positions will be set to beginning of the file (0) Close t
he opened file.
void close()
Readers classes : FileReader BufferedReader b. Writers Common Methods : i. write
(char b[]) Writes teh binary formatted content to the file ii. write(char b[], i
nt offset, int length) Write the binary data to the file with the specified leng
th and position iii. flush() write iv. close() Writer classes : FileWriter Buffe
redWriter PrintWriter Servlets Clears the buffer b4 the new to close the opened
file Writes the data to
Serialization
Process of converting from Byte to Object and vice versa This is only in the cas
e of providing the security to the data while transferring over the internet To
implement this we use an interface 'Serializable'.
class A implements Serializable { } java.net packages : Networking Benefits : Gr
oup of computers interconnected together Sort of sharing the information
Sort of communication Java programming language by defaulted with networking fea
tures to make the data to be travelled over the network. 1997, advanced networki
ng features are added to make java internet programming language Communicational
Architectures : 1. 1-Tier or Traditional Approach : 1 - System Presentation Inp
ut and Output Business Logic Main Code Database Data Drawbacks : i. No communica
tion ii. No data share iii. If any change in 1, need other two tho change 2. 2-T
ier or Client/Server Approach : 1-System Client Presentation Business Logic Busi
ness Logic + Presentation Business Logic + Database => FAT CLIENT => FAT SERVER
2-System Server Database
To creaet client and server applications using java, we use a package java.net p
ackage How the Client and Server applications can be created: 1. IP Address Inte
rnet Protocol Address. To identify the systems opver the network. 32-bit(IPv4) o
r 64-bit (IPv6) 2^8 256 0-255 Govt Private Public Public Future Class A 0-127 N
Class B 128-191 N Class C 192-223 N Class D 224-247 N Class E 248-255 2^8 256 0-
255 H N N N 2^8 256 0-255 H H N N 2^8 256 0-255 H H H H
2. Port Numbers Service point of an Application Port Numbers Range : 0 - 65535 V
alid Port Numbers : 0 - 9999 80 8080 23 25 69 21 1433 1521 3306 3. Protocols HTT
P Web Servers Telnet - LINUX SMTP Telnet - UNIX FTP Ms SQL Oracle My SQL Set of
Rules and Regulations for making better communication
HTTP Dynamic to Static SMTP FTP TCP/IP SNTP POP PPP WTP UDP ITP
4. DNS Domain Naming Service In network computers can be represented either nume
rically or names wise. 202.48.125.106 google.com Classes of java.net Package : I
netAddress Used to retrive the IP Addresses
InetAddress inet = null; Methods : getLocalHost() Return local system IP Address
getByName(name) Returns the IP Address of the specified name system getAllByNam
e(name) available IP Addresses of the specified name system ii. Sockets Conneciv
ity point. Returns all the
a. Client Socket Establisgh a connectivity to the Client Socket s = new Socket("
Ip Address of Server", int port-number); Socket s = new Socket("172.24.1.1", 808
0); b. Server ServerSocket Server side connectivity
ServerSocket ss = new ServerSocket(int port-number); ServerSocket ss = new Serve
rSocket(8080); Socket s = ss.accept(); ObjectInputStream getInputStream() Object
OutputStream
getOutputStream(); URL Makes a communication to the system which are loated in s
ome other geographical areas URL u = new URL("site-name"); URL u = new URL("http
://www.google.com"); Methods : getPort() getProtocol() URLConnection Makes the U
RL connection to open and gets some information
URL u = new URL("site-name"); URLConnection uc = u.openConnection(); Methods : g
etPort() getProtocol() getLastAccessed(); getModified() getLength() toExternalFo
rm(); who.is whois.net ADVANCED JAVA : JDBC database programs Java JDBC Software
s : Win XP Win 7 ----------------------------------JDK 1.6 JDK 1.6 Netbeans 6.5
Netbeans 6.5 MS SQL 2000 SQL 2005 Oracle XE Oracle XE My SQL My SQL Class.forNam
e("driver-class"); MS SQL sun.jdbc.odbc.JdbcOdbcDriver MS Access -> Data -> Data
base
Java Database Connectivity
Oracle oracle.jdbc.driver.OracleDriver classes12.jar and ojdbc6.jar/ojdbc14.jar
My SQL com.mysql.jdbc.Driver mysql-connector-java-5.1.6-bin.jar set classpath=%c
lasspath%;C:\mysql-connector-java-5.1.6\mysql-connector-java-5.1 .6-bin.jar;. tr
y { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManage
r.getConnection("jdbc:odbc:CSEB"); -> Acces s or Connection con = DriverManager.
getConnection("jdbc:odbc:CSEB1", "sa", "p ass"); -> MS SQL Server or Connection
con = DriverManager.getConnection("jdbc:oracle:thin:@SYSNAME/ localhost/IPAddres
s:1521:XE", "cseb", "cseb"); -> Oracle or Connection con = DriverManager.getConn
ection("jdbc:mysql://SYSNAME or lo calhost:3306/database", "root", "root"); -> M
y SQL } catch(Exception e) { } DSN : Datasource Name MS Control Panel
Control Panel -> Administrative Tools -> Datasources (ODBC) -> Add Access : Micr
osoft Access Driver (*.mdb) Name Description Select Button Select the location o
f Ms Access Databse located. SQL Server SQL Server -> Finish Name Description Se
rver CSEB1 Optional SERVER_NAME or CURR_SYS_NAME or CSEB Optional
. NExt Authentication Type O windows NT v SQL Server Login Id Password Next Sele
ct default database Master -> ComboBox Next -> Finish SQL statements : DDL Data
Definition Language CREATE Create a Structure ALTER Modifies the Structure DROP
Remove the Structure frm Memory TRUNCATE Clears the Structure DML Data Manipulat
ion Language UPDATE Modifiying the Data of Table DELETE Removes the data from th
e Table INSERT Adds the data to the Table DCL Data Control Language GRANT Permit
s the Permissions of Access REVOKE Denying the Permissions DQL Data Query Langua
ge SELECT Retrieves the data from the Table TCL Transaction Controlling Language
COMMIT Makes permanent settings ROLLBACK Takes the cursor to recent original po
sitions JDBC - SQL Statements L SQL Statements Methods Return Type -------------
--------------------------sa pass
DDL DML DQL
execute()
boolean
executeUpdate() int executeQuery() ResultSet
if table created successfully -> false if table created unsuccessfully -> true J
DBC SQL Statements : i. Statement Executes Simple SQL statements Class.forName()
Connection con Statement st = con.createStatement(); DDL create table Students(
Sno int, SName varchar(20), SMarks int) DML DQL insert into Students values(101,
'A', 99); select * from Students;
boolean b = st.execute("DDL") or int n = st.executeUpdate("DML"); or ResultSet r
s = st.executeQuery("DQL"); ii. PreparedStatement Execute Prepared SQL Statement
s (pre defined) with place holders (?) Methods : prepareStatement(query); ps.set
XXXX(int ?, Object val) int ? Number Object Values Example : PreparedStatement p
s = con.prepareStatement(""insert into Studen ts values(?,?,?)); ps.setInt(1, no
); ps.setString(2, name); ps.setInt(3, marks); int n = ps.executeUpdate(); iii.
CallableStatement Execute Stored Procedures
Stored Procedures : Are part of server which maintain and maipulate the data of
a table thru T-SQL Statements. Types : i. Without Parameters create procedure Pr
oc_Name As SQL stmts i. With Parameters create procedure Proc_Name @sno int, @sn
ame varchar(20) output as @sname = select sname from Students where sno=@s no; S
yntax : CallableStatement cs = con.prepareCall("{call proc_name(?,?)}"); Output
Parameters : cs.registerOutParameters(2, java.Types.DOUBLE); cs.setXXXX(int inde
x, Object val); cs.getXXXX(int index); 1. 2. 3. 4. "" "{}" "{call proc_name}" "{
call proc_name(?,?)}"
o/p update Students set smarks = smarks + 10 where smarks < @smarks; i/p cond i/
p iv. ResultSet Interface : Used Retrieves the data of the tables. Used when the
suer is using "select" query. Syntax : ResultSet rs = st.executeQuery("select q
uery"); Methods : rs.next() Finds the next record availability the details in
specified
rs.getXXXX(int) Returns column
specified format
XXXX data
type
rs.getMetaData() Returns the complete information related to the table v. Result
SetMetaData Retrieves the details about the Tables. Syntax : ResultSetMetaData r
smd = rs.getMetaData(); Methods : rsmd.getColumnCount() Returns the Count of col
umns from the Table rsmd.getColumnName(int) Returns the Column Names of the Tabl
e CLASSPATH c:\Program Files\Java\jdk1.6.0_12\lib;C:\mysql-connector-java-5.1.6\
mysql-connec tor-java-5.1.6-bin.jar;C:\OracleJARs\classes12.jar;C:\OracleJARs\oj
dbc6.jar;C:\O racleJARs\ojdbc14.jar;. RMI : Remote Method Invocation Remote Othe
r than Current systems Method Methodology to access the applications Invocation
Calling or Invoking 1-Tier : Presentation Business Logic Database 2-Tier : Clien
t Pres B.L B.L + Pres B.L + D.B B.L + Pres FAT CLIENT FAT SERVER FAT SERVER Serv
er D.B
3-Tier or Component Based Approach : Client Pres HTML JSP ASP PHP Client Student
s Fund Application Server B.L Common Server D.B Orac MS SQL My SQL DB2 server Ch
airman Funds
A.S Dean RMI Registry
Server Socket Programming : Client Socket(s) 9 fields 1000 RMI Components : 1. R
MI Server 2. RMI Client RMI Architecture : 1. Stub / Skeleton Layer 2. R.R.L 3.
T.L Packages : 1. java.rmi Remote Interface Naming class RMISecurityManager 2. j
ava.rmi.registry Registry Interface RegistryHandler Interface 3. java.rmi.server
RemoteObject class RemoteServer class RemoteStub class UnicastRemoteObject clas
s RemoteCall interface Skeleton interface Unreferenced interface 4. java.rmi.dgc
Lease dirty() clean() Server ServerSocket 9 fields 1
Marshalling : Converting from the Known to Unknown format Unmarshalling : Conver
tes from Unknown to Known format. OSI : Appl Pres Sess Trans Net DL Phy Client 7
2 85 Naming Class : bind() Registers the objects for single time usage SERVER re
bind()Registers the objects for Multi time usage unbind()unRegisters the objects
from the server list() Displays the registered Objects CLIENT lookup() Makes a
communication between the registered objects of the server and client Applicatio
ns 2 create RMI Applications : 1. Remote Interface Abstract Methods import java.
rmi.*; public interface InterfaceName extends Remote { public return-type method
-name(params) throws RemoteException; } 2. Implmentation for Interface : Impleme
ntation for Abstract methods import java.rmi.*; import java.rmi.server.*; public
class ImplClassName extends UnicastRemoteObject implements Interf Low level (0,
1) Request Object1 Object2 High Level (A, B)
aceName { ImplClassName() throws RemoteException { super(); } public return-type
method-name(params) throws RemoteException { Implement - code; } } 3. RMI Serve
r Rergisters the objects by using bind(), rebind() import java.rmi.*; import jav
a.rmi.server.*; public class RMIServer { p s v m(String args[]) { InterfaceName
obj = new ImplClassName(); } } 4. RMI client : Makes the reference to the server
by using lookup() or 1. Remote Interface Abstract Methods import java.rmi.*; pu
blic interface InterfaceName extends Remote { public return-type method-name(par
ams) throws RemoteException; } 2. Implmentation and RMI Server : Implementation
for Abstract methods Rergisters the objects by using bind(), rebind() import jav
a.rmi.*; import java.rmi.server.*; public class ImplClassName extends UnicastRem
oteObject implements Interf aceName { ImplClassName() throws RemoteException { s
uper(); } public return-type method-name(params) throws RemoteException { Implem
ent - code;
} p s v m(String args[]) { ImplClassName obj = new ImplClassName(); Naming.rebin
d("InstanceName", obj); System.setSecurityManager(new RMISecurityManager()); } 3
. RMI client : Makes the reference to the server by using lookup() import java.r
mi.*; import java.rmi.server.*; { p s v m(String args[]) { InterfaceName obj = (
InterfaceName)Naming.lookup("rmi:// System_IP/InstanceName"); obj.methods(); } }
4. Policytool : Start -> Run -> cmd type policytool -> Press Enter Click on Add
Policy Entry Click on Add Permission Select All Permission -> Click on Ok -> Cl
ick on Done To save : Win XP
C:\Documents and Settings\CurrentUser Fist -> Save As -> locate filename : To sa
ve : .java.policy
Win 7
C:\Users\CurrentUser Fist -> Save As -> locate filename : .java.policy
5. Generate Stub and Skeleton files : rmic ImplClassName v 1.4 ImplClassName_stu
b.class ImplClassName_skel.class
6. Start RMI Registry start rmiregistry port-no start rmiregistry 1099 (Default)
start rmiregistry 1234 (Userdef) 7. Start and Run RMI Server : start java RMISe
rver 8. Start and Run RMI Client : start java RMIClient Programs needed for clie
nt and server systems : CLIENT SERVER --------------------------------JVM JVM Re
moteInterface RemoteInterface Client Server Impl_stub Impl_stub SERVLETS : Chair
man Dean HOD Students JRE | Application Server | Web Container | Servlets JSP H
TML Web components Servlet Interface : 1. GenericServlet Supports other than HTT
P Protocols like FTP javax.servlet 2. HttpServlet Supports only the HTTP Protoco
l javax.servlet.http ServletConfig interface : Contains the confirgurational inf
ormation about the type of servlets. ServletConfig cfg = getServeltConfig(); Cla
ssName extends HttpServlet HttpServlet extends GenericServlet Server side progra
ms
ClassName extends GenericServlet or ClassName extends Servlet Web Application <-
Web Browsers Web Life Cycle IDE GUI main()
Integrated Development Environment Designing Developing Testing Deploying Netbea
ns 6.5 Eclipse My Eclipse Web Shpere JBoss
Life Cycle : public void init() { code; } GenerticServlets : public void service
(ServletRequest req, ServletResponse res) { code; } HttpServlet : public void do
Get(HttpServletRequest req, HttpServletResponse res) { code; } public void doPos
t(HttpServletRequest req, HttpServletResponse res) { code; } Client server -----
uid String u=req.getParameter("uid"); & pwd String p=req.getParameter("pwd"); if
(u and p are in DB) { }
skills Select Tech Skills C, C++, Java, Oracle, DB2, MS SQL, My SQL String skil[
] = req.getParameterValues("skills"); <select name="skills"> <option>C <option>C
++ </select> <select name="skills" multiple> <option>C <option>C++ </select> Enu
meration en = req.getParameterNames(); while(en.hasMoreElements()) { req.getPara
meter(en.nextElement()); } Sys Name IP Addr req.getRemoteHost()l; req.getRemoteA
ddr() PrintWriter out = res.getWriter(); out.println(); out.print(); res.setCont
entType("text/plain"); res.setContentType("text/html"); res.setContentType("imag
e/jpeg"); Context : Security, Session Management and Instance Persistance Servle
tConfig cfg = getServletConfig(); ServletContext ctx = cfg.getServletContext();
ctx.setAttribute("name", value); ctx.getAttribute("name"); Cricinfo : req.getHea
der("refresh"); res.setHeader("refresh", "5; url=./Page.ext"); res.addHeader("re
fresh", "1; url=./Adv.ext"); Validation : if(u and p are in DB) { res.sendRedire
ct("HomePage.ext"); } else
{ res.sendRedirect("Login.html"); } session.setAttribute("name", value); session
.getAttribute("name"); Diff B/w Ctx and Session : 1 ctx.setAttribute("1", "ok");
2 ctx.getAttribute("1"); ctx.setAttribute("1", "ok"); 3 ctx.getAttribute("1");
ctx.setAttribute("1", "ok"); 1 session.setAttribute("1", "ok"); 2 session.getAtt
ribute("1"); 3 session.getAttribute("1"); 4 session.getAttribute("1"); MIME Mult
i Interchange Mail Extension

Anda mungkin juga menyukai