Top Banner
JAVA INTRODUCTION Java SE : It deals with developing stand alone applications and Networking applications and also exploring library. Java EE : It deals with developing Enterprise (business) solutions for a network. Java ME : (Micro edition or Mobile edition) It deals with developing embedded systems and wireless applications. Digital signal : When we press any character on key board then it generates a 8 bit code it is passed to the processor as Digital signal. Network : Inter Connection of Computers is called Network. If we connect one computer to another, following are the requirements for setting up a network of computers. 1) Hardware : Computer Systems, Network interface cards, cables, modems, hubs, satellites etc.., 2) Software:- Any software which supports networking features like UNIX, LINUX, WindowsNT etc.., So that data can be sent or received. 3) Protocol:- It is a specification of Rules to be followed by every computer on the Network. It can follow two rules. 1. When to send/receive data. 2. How to send/receive data.
123
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java

JAVAINTRODUCTION

Java SE:It deals with developing stand alone applications and Networking applications and also exploring library.

Java EE:It deals with developing Enterprise (business) solutions for a network.

Java ME: (Micro edition or Mobile edition)It deals with developing embedded systems and wireless applications.

Digital signal:When we press any character on key board then it generates a 8 bit code it is passed to the processor as Digital signal.

Network:Inter Connection of Computers is called Network.

If we connect one computer to another, following are the requirements for settingup a network of computers.1) Hardware: Computer Systems, Network interface cards, cables, modems, hubs, satellites etc..,2) Software:- Any software which supports networking features like UNIX, LINUX, WindowsNT etc.., So that data can be sent or received.3) Protocol:- It is a specification of Rules to be followed by every computer on the Network.

It can follow two rules.1. When to send/receive data.2. How to send/receive data.

URI:- uniform resource indicator (for internet files)URL:- uniform resource locator (for source files)

Handshaking Mechanism:Two computers establishing a connection, communicating with each other and finally

disconnecting from each other.

packet: It represents group of bytes of data. Each packet is inserted into a cover(frames).Frame: It contains packet+To address+from address+packet length+checksum digits.

Page 2: Java

IIQ) What is IP address?Ans It is a unique identification number allotted to every computer on a network.

TCP/IP : (Transmission control protocol/Internet protocol)This is also known as protocol suit. It is used in Networks.

Client: It is a Machine that receives services from other computers in the network.

Server: It is a Machine that provides services to the clients.

==> Network uses client-server architecture.

Advantage:Resource sharing is the Main advantage of the network. That meansa) sharing datab) sharing memoryc) sharing hardwared) sharing softwaree) sharing the processor

Internet: It is a network of computers existing on the various locations on the earth.

(or) It is a Global network of networks.

Intranet: It is a network of computers in an Organisation.

Extranet:It is an external network that connects a companies network with the network of another company.

Dial-up connection:ISP:- (internet service provider) It is a person(or) Organization who provides a connection into Internet.

It has a server Machine (a high memory multi processing system)It will give Bandwidth: 64kbps( kilo bytes per second)

Internic.com: It provides physical connection to ISP.dial-up connection advantage:- It is very cheap and effortable.

dis-advantage: There is no security for data.

Page 3: Java

==> To avoid this we use Leased-line connection. It is directly connected into Internet without ISP.Advantage when we use leased-line : Complete security for data.Disadvantage: Highly expensive.

Requirements for Internet:1. Hardware:2. Software: a) web browser is s/w needed by Internet client. Popular web browsers are :

a)IE (Internet Explorer)b)Mogilla firefoxc)Mosaic etc...,

b) web server is s/w needed by Internet server. Popular web servers are:

a)IIS (Internet Information Service)b)Weblogicc)Apached)Webspheree)Jboss etc...,

3. Protocol:Mostly used protocol on internet is HTTP.HTTP: (HyperText Transfer Protocol) It transfer web pagesFTP : (file transfer protocol) To download/upload filesSMTP: (Simple mail transfer protocol) It is used to sending mails.POP : (post office protocol) It is used for receiving mails.

==> Internet also used client-server architecture.Machine language:

This means instructions are represented by 0's and 1's.Translator:It is a program that converts any program into Machine code. There are 3 types of translators.1.Interpreter: It takes more time to convert program into Machine code.2.Compiler: It takes less time to convert program into Machine code and 10 times more faster than Interpreter.3.Assembler: It converts assembly language program into machine code.

Execution of a C program:

diagram:-

IIQ) What is Object code?Ans Object code is equivalent Machine code of the source code.

Page 4: Java

What is .exe file?It contains also Machine code.

What is the difference between .obj and .exe?The only difference is the header file machine code is not included in .obj. therefore .exe = .obj + header file code.First Microprocessor is 4004.

Execution of a Java program:

diagram:Java soft people created 200 instructions.Each instruction takes 1 byte(8 bits).By using

these instructions each java source code is declared into "bytecode" instructions. This type of file is .class file. So .class file contains byte code.

JVM:- (java virtual Machine)It is a program that understands all byte code instructions and converts into Machine code

which is understandable to the processor.--> Java programs are system independent because they can be executed on any other System.There fore java is suitable for internet.

Note:- 1).class file is System independent.2)JVM is System dependent Why because it is written in C.

Main Security problems on Internet:1.Evesdropping:

Reading others data illegally. This is the major problem on internet. To avoid this,Encription/decription is used in Java. Encription:- Converting the original data into unreadable format. Decription:- Getting back the original data from the encripted format.

2.Tampering : Not only reading others data and also modifying the data.The solution for this also encription and decription.

3.Impersonation:A person acting as another person on internet.The solution for this problem is digital

signature.Digital signature:- It is a file with personal information in encripted format.It is created by java. 4.virus:

It is a computer program that damages the data,software and hardware of a computer system.

Page 5: Java

-->the first person who developed the virus is Pakistanies. --> .exe,.doc,images(.gif,.jpeg),audio,video files can spread virus. --> a text file (i.e .txt of notepad) can not spread virus. --> .class files,which are simillar to .txt files and hence there is no chance of virus affecting these files.

Note:Even if somebody intentionally tries to incorporate the virus codeinto .class file,Jvm can

verify its presence before running the program and if found,can abort the .class file's execution.

IIQ) why java is suitable for internet?Ans Because of two reasons

1)It is system independent 2)It eliminates a lot of security problems for data on internet.

History of java:In 1990,Sun Microsystems Inc.(US) has conceived a project to develop software for

consumer electronic devices that could be controlled by remote.In 1991 Bill Joy,James Gosling, Mike sheradin and several others met and discuss about

this project. Finally they developed new Language in 1993 called Oak. But this name was registered by some other company. Later it was changed to Java.

In 1994,They developed a web browser called "HotJava".It is the first web-browser, having the capabilities of executing applets, which are programs designed to run dynamically on Internet.

In 1995, They announced Java and HotJava at Sunworld conference. After that on 1996 January 23 JDK1.0 version was released.

Features of Java1.Simple:

Java is a simple programming language. Because of 2 reasons.1)Java Soft people maintained the same syntax of C and C++ in Java.2)Pointers are eliminated in Java.

IIQ) Why pointers are eliminated from Java?1)Pointers can crash program very easily.2)Using pointers, it is possible to develop harmful programs like virus and haking programs. So Pointers are security threat for java.Because of these reasons pointers are eliminated from java.

2) Object-Oriented:Java programs use Objects and classes.

Object: An object is anything that exists physically in this world. An object will have properties(variables) and actions(methods). variable: It represents memory location to store data. Class: It is a group name that specifies properties and actions of objects. ==> Class also contains variables and methods.

Page 6: Java

==> Class is only specification but object exist physically. ==> Class is a model for creating Objects.

3)Distributed:Information is distributed on various computers on a network.Using java, we can write programs which capture information and distribute it to the clients.

4)Robust:Robust means strong. Java programs are strong and they don't crash easily like c and C++.There are 2 reasons for this.1)Java has got excellent exception handling features.2)Memory management features.

Here memory allocation is done by JVM's Class loader subsystem. Memory deallocation is done by JVM's garbage collector.

5)Secure:Security problems are eliminated by using java on Internet.

6)System Independence: (or) Architecture neutralJava's byte code is not machine dependent. It can be run on any machine with any processor.

7)portable:If a program yields the same result on every machine, then that program is called portable. This is the result of java's system independence nature.

8)Interpreted:In any other language, only one interpreter or compiler is used to execute the program. But in java, we use both compiler and interpreter for the execution.

9)Multi-threaded:Executing statements are called thread. Each thread can execute no of statements. This is essential feature to server side programs.

10)High performance:The problem with interpreter inside the jvm is that it is slow. Because of this, Java programs used to run slow. To overcome this problem, along with the interpreter javasoft people introduced JIT(Just in time)compiler, which enhances the speed of execution.

Page 7: Java

JVM ArchitectureClass loader sub system does the following tasks.1)It loads .class files into memory(i.e.,RAM).2)It verifies byte code instructions.3)It allots necessary memory needed by the program.The memory allotted by class loader sub system is divided into 5 parts called Run-time areas. They are

1)Method area:The class code and methods code is stored on method area.

2)Heap:Objects will be created by the JVM on heap memory.

3)Java stacks:These are the places where Java methods are executed.

4)PC (program counter) registers:They are provide memory address of the next instruction to be executed by the Micro-processor.

5)Native method stacks:These are the places where native methods(c,c++ programs) are executed.

Note:Native method interface is a program that copies native method libraries(c,c++ header files) into JVM. since,Jvm can run c,c++ programs also.

Execute engine:It contains interpreter and JIT(Just in Time) compiler which converts byte code into mechine code.So that the processor executes it and displays the result.

Hotspot:It is a block of code executed by JIT compiler. So Jvm is known as Hotspot JVM.

The following steps to be taken when you writing a java program:Comment: It represents description about all the features of a program. (or)

Un executable lines in a program.There are 3 types of comments in Java.1. //single line comment2. /* multiple line--

---comments------ ------------------*/

3./**--java documentation ---comments----- -------------------*/ they are useful to create API document from a .java program.

API: (application programming interface)

Page 8: Java

IIQ) What is API document?Ans It is a .html file that contains description of all the features of a software,a product or a

technology.Note: javadoc compiler is used to create API document

importing classes:java library-->packages-->classes/interfaces-->methods

package:It is a sub directory which contains classes and interfaces.

ex:- import java.lang.System; import java.lang.String;-->If you want to import several classes of same package then we write import java.lang.*;

IIQ) what is the difference between #include and import?Ans #include makes a c (or) c++ compiler to copy entire header file code into the program.

Thus the program size increases unnecessarily and it wastes memory and processor time. Import statement makes JVM to go to the Java library, and execute the code there and copy the result into the java program. So import is better mechanism than #include.

IIQ) what is JRE (Java Runtime Environment)?Ans jre = jvm + java library.ex:class First{

public static void main(String args[]){System.out.print("Welcome to java");

}}

==>Jvm starts execution of a java program from main() method.==>Values passed to method are called arguments.

Calling a method in java in 2 ways.1.create an object to the class to which the method belongs. classname objectname = new classname(); calling the method like this: objectname.methodname();

2. classname.methodname(); The second method for static methods only.

static method: Static method is a method that can be called and executed without using any object.

==> print method belongs to PrintStream class.

Page 9: Java

There is a shortcut available to create the object of PrintStream class.That is System.out (i.e: monitor).

Here out is a variable (or) field in System class. field is nothing but static variable.

How to compile and execute a java program:d:\>javac First.java === This is saved file.d:\>java First === this is .class file.

IIQ) what is the difference between print() and println()?print() method displays the result and keep the cursor in the same line.println() method displays the result and then throws the cursor to the next line.

Backslash code meaning ============== ========

\n next line \t Horizontal tab space

\r enter key\b Back space\\ displays \ \" displays " \' displays '

ex: System.out.println("Hello");System.out.println("\\Hello");System.out.println("\"Hello\"");

o/p:- Hello \Hello "Hello"

important points:-> Java is case sensitive language.-> Every statement should end with semicolen.

In java we should follow naming convensions(rules):Naming Convensions:1)Package names in java are written in all small letters. ex:- java.awt java.io java.swing

2) Each word of class names and interfaces start with a capital. ex:- String,DataInputStream,ActionListener

3) Method names start with small letter,then each word start with a capital.

Page 10: Java

ex:- println(),readLine(),getNumberInstance(),etc..

4)Variable names also follow the above rule. ex:- age , empName, employee_Net_Sal

5)Constants should be written using all capital letters. ex:- PI , MAX_VALUE , Font.BOLD (Here Font is class)

6)All keywords should be written in all small letters. ex:- public , void , import

java lang is the default package that is imported in to every program

Important packages of core java:1.java.lang :

This package got primary classes and interfaces essential for java program it consists of wrapper classes (useful to convert ordinary data in to objects),strings,threads.

2.java.util: This package contains useful classes and interfaces

like Stacks,LinkedList,HashTable,Arrays3.java.io:

This package handles files and input output related tasks.4.java.awt(abstract window tool kit):

This package helps to develop GUI.it consists of an important sub package is java.awt.event.

java.awt.event is providing actions to components.5.javax.swing(extended package): This is also helps to develop GUI like java.awt

==>difference between 4 and 5 is a lot of new feauters are available in swing6.java.net:

client server programing can be done using this package7.java.applet:

applet means programs .They are stored in server on internetApplets are programes which come from a server in to client and get executed on the client machine

8.java.sql:This package helps to connect to data bases like oracle and utilize them in java.

Data type:It represents the type of data stored into variable(or)memory.

Datatypes and literals:

Page 11: Java

1.Integer datatypes:These data types store integer numbers like 125,100000,-10,... int is divided into 4 types.Datatype Memory size Rangebyte 8 bits(1 byte) -128 to +127short 2 bytes -32,768 to +32,767int 4 bytes -2147483648 to +2147483647long 8 bytes -9223372036854775808 to

+9223372036854775807

=>Literal:- It is the value stored into variable directly in the program.ex:- byte rno=10; here 10 is literal. long x = 150L;Here 8 bytes memory will be alloted.If there is no L then jvm allocates memory 2 bytes only.

2.float datatypes: (single precision floating number)These data types represents numbers with decimal points like 125.36,0.0034,-1.0,etc....

These are again classified into float and double. double means double precision floating point. precision ==> accuracy.

Data type Memory size range float 4 bytes 1.4*10p-45 to 3.4*10p38

double 8 bytes 4.9*10p-324 to 1.8*10p308 ex: float PI=3.142F; here 4 bytes memory alloted by JVM.

Here there is no F,Jvm alloted 8 bytes.

IIQ) What is the difference between float and double?Ans Float can represent upto 7 digits after decimal point accurately. double can represent upto 15 digits after decimal point.

3)character datatype:This datatype represents a single character like A,a,9,*,etc..,

datatype memory size range char 2 bytes 0 to 65,535

ex:- char ch='x';

IIQ)what is UNICODE system? It is an encoding standard to include the alphabet from all human languages into the character set of java.UNICODE systed used 2 bytes to represent each character.

4)String datatype:It represents a group of characters.

Page 12: Java

ex:- 1.String name="Vijayawada";2.String str = new String("Name");

5)boolean datatype:Boolean means two.These can handle either true (or) false.Jvm uses 1 bit to represent a

boolean value internally. ex:- boolean response = true;

OPERATORSoperator:

It is a symbol that performs an operation. => An operator acts on some variables called operands to get the desired resuls.

ex:- a + bhere a,b are operands and + is operator.

Unary operator: If an operator acts on a single variable it is called unary operator.

Binary operator:If an operator acts on two variables it is called Binary operator.

Ternary operator:If an operator acts on three variables it is called Ternary operator.

Various Types of Operators used in JAVA:1) Arithmetical operators: ( +,-,*,/,% )2) Unary operators: a) unary minus operator(-) b) Increment operator ( ++ ) c) Decrement operator ( -- )3) Assignment operator: ( = , += , -= , *= , %= , /= )4) Relational operators:

a)greater than ( > )b)greater than or equal to ( >= )c)less than ( < )d)less than or equal to ( <= )e)equal to ( == )f)not equal to ( != )

5) Logical operators:a) Logical AND ( && )b) Logical OR ( || )c) Logical NOT ( ! )

6) Boolean operators:a) Boolean AND ( & )b) Boolean OR ( | )c) Boolean NOT ( ! )

7) Bitwise operators:

Page 13: Java

a) bit-wise complement operator ( ~ )a) bit-wise AND operator ( & )a) bit-wise OR operator ( | )a) bit-wise XOR operator ( ^ )a) bit-wise Left shift operator ( << )a) bit-wise Right shift operator ( >> )a) bit-wise zero fill right shit operator ( >>> )

8) Ternary operator (or) Condition operator ( ?: )9) Member operator ( . ) (or) dot operator10) Instanceof operator11) new operator12) cast operator

Bit-wise zero fill right shift operator( >>> ):This operator also shift the bits towards right.But it does not protect the sign bit.

'>>>' operator always fills the sign bit with '0'.

IIQ)what is the difference between >> and >>> ?Both bitwise right shift(>>) and bitwise zero fill right shift(>>>) operators are used to

shift the bits towards right.The only difference is that >> will protect the sign bit whereas the >>> operator will not protect the sign bit.It always fills 0 in the sign bit.

Priority of operators:Certain rules of operator precedence are followed:

1)The content inside the braces: () and [] will be executed.2)Next ++ and --3)Next *,/,and % will execute.4)+ and - will come next.5)Relational operators are executed next.6)Boolean operators and bitwise operators.7)Logical operators will come afterwords.8)then ternary operator.9)Assignment operators are executed at the last.

sequential execution:Executing the statements one by one sequentially is called sequential execution. It is

useful to write simple programs.

Random execution:Executing the statements randomly and repeatedly is called Random execution.

The following are the statements which change the flow of execution.The following are control statements in JAVA.1) if --- else statement2) do --- while loop

Page 14: Java

3) while loop4) for loop5) foreach loop6) switch statement7) break statement8) continue statement9) return statement

if-else statement:This statement executes a task depending upon a condition is true (or) not.Syn:-if(condition)

Statements-1; [else statements-2;]

do-while loop:This loop executes a group of statements repeatedly as long as a condition is true.syn:-

do{

statements;}while(condition);

while loop:It is same as do while.It is executes a group of statements repeatedly as long as a

condition is true.syn:-

while(condition){

statements;}

for loop:This loop executes a group of statements repeatedly as long as a condition is true.Syn:-

for(exp1;exp2;exp3){

statements;}

here exp1 = initializationexp2 = conditionexp3 = updation=>we can write a for loop without using exp1 (or) exp2 (or) exp3 (or) any two expressions (or) all the three expressions.=> A loop that executes forever is called Infinite loop.=> Infinite loops are drawbacks(mistakes) in ur program. ctrl+c to terminate from program.

Note:we can write loop inside another loop.They are called nested loops.

Page 15: Java

Infinite loops :for(;;){

statments;}

while(true){ statements;}

do{

statements;}while(true);

foreach loop:This loop executes a group of statements for each element of a collection(group of

elements). collection: Any array,any class of java.util

syn:- for(var:collection)

{statements;

}ex:- (program)

class Demo{p s v m(String args[]){

int arr[] = {10,20,40,50};for(int x:arr){

System.out.print(x + "\t");//System.out.println(x);

}}

}

IIQ) Why goto statement is not available in java?Ans 1.goto statements lead to confusion for a programmer.

2.goto's form infinite loops easily.3.goto's make documentation difficult.4.goto statements are not part of structural programming.

Page 16: Java

break:It is used in 3 ways.1.It is used to comeout of loop.2.It is used to comeout from switch statement3.It is used in nested blocks to goto end of a block.

return:There are 2 uses.1.return statement is used to comeout of a method block to the calling method.2.return statement can be used to return some value to the calling method.

Note:Return statement in main() will terminate the program(or) application.

IIQ) what is the difference between System.exit(0) and System.exit(1)?Ans Sys.exit(0) represents normal termination.

sys.exit(1) represents termination due to error.

switch statement:It is useful to execute a particular task from available tasks depending upon the value of

variable.syn:-

switch(option){ case value-1:

statements-1; case value-2:

statements-2; -------------- -------------- case value-n: statements-n; [default:

default statements;]}

H.W:1)print odd numbers upto 1002)Test whether the no is even (or) odd3)Test whether the number is prime (or) not4)display a multiplication table.5)display the stars in the form *

Page 17: Java

* * * * * * * * *

INPUT AND OUTPUT

Accepting input from the keyboard:Stream:

It represents flow of data from one place to another place.There are 2 types of streams.1.InputStream:- It reads (or) receive data2.OutputStream:- It send (or) store(write) data to some other place.

=>All streams are represented as classes in java.io package (more than 50 classes).

diagram:

3 steps to be follow:1).connect your keyboard to InputStreamReader InputStreamReader is a class. InputStreamReader obj = new InputStreamReader(); To connect stream to keyboard is: InputStreamReader obj = new InputStreamReader(System.in);2). connect InputStreamReader to BufferedReader.

BufferedReader br = new BufferedReader(obj);3).Now read data from BufferedReader object using read() (or) readLine() methods.

Note:To create BufferedReader object in single step is:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); exception:

A run time error.

*read():- The read() method reads a single character from the keyboard but it returns its ASCII number,which is an integer.So we have to convert into character.This is called typecasting (or) casting.

Accepting String from keyboard:

Page 18: Java

String ch = br.readLine();Accepting int value from keyboard:

String str = br.readLine();int n = Integer.parseInt(str);

(or)int n = Integer.parseInt(br.readLine());

Accepting float number from keyboard:float f = Float.parseFloat(br.readLine());

Accepting double value from keyboard:double d = Double.parseDouble(br.readLine());

H.W)1.Accept 2 numbers from keyboard and findout result of their addition,sub,mul,div.2.print even numbers between m and n.3.print fibonacci series up to given number.4.print prime number series.

ARRAYSIt represents a group of elements of same data type.use: Arrays are useful to handle a group of elements easily.Threre are 2 types of arrays.1.single dimensional arrays(1D)2.multi dimensional arrays(2D,3D,...)

Single-Dimensional arrays:It represents a single row (or) a single column of elements.

ex: Marks obtained by a student in 5 subjects.

50,51,52,53,54

To create 1D arrays in java:There are 2 ways.1.We can declare a 1D array and directly initialize it at the time of declaration. ex: int marks[]={50,51,52,53,54};

index: position number of the element in the array.ex: marks[i];

2.We can allot memory for a 1D array and later store the elements into it. int marks[] = new int[5];

Note:arrayname.length property returns size of the array.

ex: 2D arrays:

They represents several rows and columns of elements.

Page 19: Java

ex: Marks obtained by a group of students in 5 subjects.50,51,52,53,5460,61,62,63,6470,71,72,73,7480,81,82,83,8490,91,92,93,94

Creating a 2D array:We can declare as well as initialize a 2D array.

1.int marks[][]={{50,51,52,53,54},{60,61,62,63,64},{70,71,72,73,74}}; A 2D array will have 2 indexes that represents row position number and column

position number of an element. A 2D array is the combination of several 1D arrays. A 3D array is the combination of several 2D arrays.

2.We can allot memory for 2D array using new operator and store the elements into the element later.

ex: int marks[][] = new int[3][5];ex: W.a.p to accept a 2D array and display.

method parameter is a variable that receives data from outside into method. arguments represents values passed to a method.

IIQ) what are the commandline arguments?Ans The values passed to main() method at command prompt.

ex:- c:\java Arr 10 20 30 It represents run command + arguments size of array = no of arguments.

H.W:1.To find sum of two matrices.2.To find transpose of a matrix.3.Take a 2D array and display all its elements using one loop.

String:A String represents a group of characters.ex: name,address,creditcard no,etc..,In java,Any string is object of String class.->String is not a character array.

create String object:1.We can declare a String type variable and initialize it directly witha group of characters.

ex:- String st = "Hello";

Page 20: Java

2.We can create a String object using new operator and pass a group of characters to the object.ex:- String s1 = new String("BDPS");

3.We can create a character array into a string by passing it to the String object.ex:- char arr[] = {'c','h','a','i','r','s'};

String s2 = new String(arr);ex:- String s3 = new String(arr,1,4);

o/p: hair

String class methods:String class belongs to java.lang package.

1.String concat(String str):concatenates the calling string with str.

Note: '+' will also do the same.ex: String s1="hydera"; String s2 = "bad"; String s3 = s1.concat(s2); o/p: hyderabad

2.int length():Returns the length of the string.String s1 = "Vijayawada";int n = s1.length();

3.char charAt(int i):It extracts only one character from given String.That character at the same it h

place.4.int compareTo(String str): (case sensitive)

(or) int compareToIgnoreCase(String str): (case insensitive)

They are used to compare two strings.5.boolean equals(String str): (case sensitive)

(or) boolean equalsIgnoreCase(String str): (case insensitive)

It returns true if the calling string equals to str.6.boolean startsWith(String prefix):

It returns true if the calling string starts with prefix(begins)prefix - sub string (or) not.

7.boolean endsWith(String suffix):It returns true if the invoking string ends with suffix.

Note:The above two methods use case sensitive comparison.

8.int indexOf(String str):It returns the position number of substring in the main String.So we have to pass

substring.It returns the first occurance of str in the string.EX: "This is a book"

int n = str.indexOf("is");

Page 21: Java

o/p :- n = 29.int lastIndexOf(String str):

It returns last Occurance in the string.10.String replace(char oldchar,char newchar):

It returns a new String that is obtained by replacing all characters of 'oldchar' in string with 'newchar'.

11.String substring(int beginIndex):It ruturns a new String consisting of all characters from beginindex until the end of the

String.

12.String substring(int beginIndex,int endIndex):It returns a new String consisting all characters from beginindex until

endindex(exclusive).

13.String toLowerCase():It converts all characters into lowercase and returns.

14.String toUpperCase():IT converts all characters into uppercase and returns.

15.String trim():It eleminates all leading and trailing spaces.

IIQ) What is hashCode?Ans Hash code is a unique id number given to every object by the JVM.#code is also called as reference number.

ex:- To compare two strings. String s1 = new String("Hello"); String s2 = "Hello";Now JVM follow:if( s1 == s2 ) returns not same.because it compares reference of Object.if( s1.equals(s2)) returns same.

IIQ) what is the difference between == and equals() method?Ans while comparing the strings, == operator compares references of string objects.So it gives un-reliable result.equals() method compares content of string objects.So it gives correct results.

IIQ) What is String constant pool?Ans It is a block of memory where string objects are stored by JVM here if(s1==s2) then it gives same.when s1 = "hello" s2 = "hello".

Types of Obejcts:There are 2 types.

Page 22: Java

1.Mutable2.Immutable

1.Mutable:A mutable object is an object where content can be modified.

2.Immutable:An immutable object is an object whose content can not be modified.

String objects are immutable.

ex:Test whether the string class objects are immutable or not.diagram:

StringBuffer Objects are mutable.

Creating StringBuffer objects:1.StringBuffer sb = new StringBuffer("hello");2.StringBuffer sb = new StringBuffer(50);3.StringBuffer sb = new StringBuffer();

java.lang.StringBuffer methods:1)StringBuffer append(x):

x may be int,float,double,char,String (or) StringBuffer.It will be appended to the calling StringBuffer.2)StringBuffer insert(int offset,x):

x may be int,float,double,char,String (or) StringBuffer.It will be inserted into the StringBuffer at offset.3)StringBuffer delete(int start,int end):

Removes the characters from start to end position.4)StringBuffer reverse():

It reverses the all characters in the StringBuffer.5)String toString():

Converts the StringBuffer into the String.purpose: Converts StringBuffer to string class.

6)int length():returns the length of the StringBuffer.

7)int indexOf(String str):It returns the first position of subString 'str' in the StringBuffer object.

8)int lastIndexOf(String str):It returns the last Occurance of substring 'str' in the StringBuffer object.

StringBuilder:This class has been added in jdk1.5.0 which has same features like StringBuffer

class.These objects are also mutable as are the StringBuffer objects.

IIQ) What is the difference between the StringBuffer and StringBuilder classes?

Page 23: Java

Ans StringBuffer class is synchronized and StringBuilder is not.When the programmer wants to use several threads,he should use StringBuffer as it gives reliable results.If only one thread is used,StringBuilder is prefered,as it improves execution time.

H.W:1)sort a given group of strings into alphabetical order.2)find the position of substring in a given main string.3)Test whether a given string is palindrome or not.

OOPS(Object Oriented Programming System)

Languages like c,pascal,fortran,cobol etc.. are called procedure oriented languages.Because they follow procedure oriented approach.Languages like c++,java are called object oriented languages.Because they follow object oriented approach.

IIQ) what is SRS(software requirements specification)?Ans SRS is report that contains client requirements and strategies to fulfill those requirements.

IIQ) What is SDS(software design specification)?Ans It is a report that contains IO streams(input/output),TSUODO code(logic to convert i/p to o/p),DFD's(data flow diagram),Database description etc..,

In procedure oriented approach programmer concentrates only on the problem and its solution.We need another approach where the entire behaviour of the system is studied and then only the software is developed.

Prodcedure oriented approach is suitable for handling small projects(less than 1,00,000 lines).We need another approach where the programmer will have better control even though lacks of lines of code is there.

programming in procedure oriented approach is un natural.We need another approach where programming reflects human beings life.

Because of the above reasons a new approach (or) methodology is created or developed it is calld OOPS.

Object:It is any thing that exists physically in this world.

An object has properties and actions. Properties are represented by variables. Actions are represented by methods. An object contains variables and methods.

Page 24: Java

Class:A class is a group name that specifies properties and actions of objects.

class also contains properties and actions.It means a class also contains variables and methods.

class does not exist physically.=>An object is an instance(physically happining) of a class. A class is an idea (blue print or model) for creating objects. An object does not exist without a class. But a class can exist with out any object( ex:=

dynocerous)

Encapsulation:Taking data and code as a single unit is called encapsulation.ex:- class.The members of one class is isolated from the members of another class.So the

programmer can use same names for the members of two different classes.

Abstraction: (hiding)Un necessary data is hiding from the user.It is implemented using the keywords like private, public etc.., They are called access

specifiers.

Inheritance:Producing new classes based on existing classes is called inheritance.

Advantage of inheritance is re-usability.

Polymorphism:This word coming from two Greek words.poly = many and morphos=forms.The ability to exist various forms is nothing but polymorphism.

if a variable (or) object (or) method performs different tasks is called polymorphism.

IIQ) what is difference between object oriented programming and object based programming?Ans OOP languages follow all the features of OOPS.

ex:- c++,java,simula67,smalltalk etc..Object based programming languages follow all the features of OOPS except inheritance.ex:- javascript,vbscript.

Page 25: Java

Classes And ObjectsWhen the instance variables are not initialized,Java compiler adds some code to the class

to initialize instance variables with the following default values. Datatype Default value

int 0float 0.0double 0.0char a spaceString nullany class nullboolean false

Initializing instance variables:Type 1:

We can initialize the instance variables of one class in another class with the help of reference variables.ex: Access specifer:

It is a keyword that represents how to access (or) read the members of a class (or) a class itself.

These are 4 types1.private 2.public 3.protected 4.default

Private members are not accessible out side the class.public,protected and default members are available out side the class.Note: If no access specifier is used java compiler internally uses "default access specifier".

in this type,if instance variables are declared as private.they are not available to any other class.

Type 2:We can initialize the instance variables directly at the time of declaring them in the class.

defect: In this type every object is initialized with same data.So this type is suitable for

initializing constants. ex:- final double PI=3.14;

'final' is a keyword used to declare constants.

ex:Type 3:

Page 26: Java

We can initialize instance variables using a constructor.

Constructors: A constructor is similar to a method that is used to initialize the instance variables. A constructor's name and class name should be same. A constructor may or may not have parameters. A constructor with out any parameters called default constructor (or) zero parameterized

constructor. A constructor with one (or) more parameters is called parameterized constructor. A constructor is called only once at the time of creating the objects. At the time of creating an object, we pass parameters to the parameterized constructor. A constructor doesn't return any value, not even 'void'.

IIQ) what is the difference between default constructor and parameterized constructor?Ans Default constructor is used to initialize every object with same data. But parameterized constructor is used to initialize each object with different data.

Constructor overloading:Writing two (or) more constructors with the same name but with difference in parameters

is called constructor overloading.

Note:If no constructor is written by the programmer then the JAVA compiler internally adds

default constructor with default values in the class.ex:

A method represents a group of statements that performs a task.A method contains two parts.

1.Method header (or) prototype:This part contains method name,parameters and return type.syn:- returntype methodname(para-1,para-2,...)ex:- void sum() void sum(double s1,double s2)

2.Method body:It represents a group of statements written in {} to perform the task.syn:

{statements;

}Note:

If a method returns some value, we should use return statement in the method body.

Ex: return k;Instance method:

It is a method that acts upon instance variables of a class.ex:

Page 27: Java

static method:A static method is a method that does not act upon instance variables of a class. static

methods are declared by using 'static' keyword. All static methods can be called by using Objectname.methodname();

(or) classname.methodname();Ex:

*** Instance variables are not available to static methods. Because JVM executes static methods first and creates objects later.

Jvm executes in below order.1. Static blocks.2. Staic methods.3. Instance methods.

*** static variables are available to static methods directly. static variables are also declared as static.

ex:- static int i=100;Ex:

IIQ) what is the difference between an instance variable and static variable?Ans Instance variable is a variable whose separate copy is available to every object. Any modifications to the instance variables in one object will not affect other objects.A static variable is a variable whose single copy in memory is shared by all the objects of the class. So any modification to the static variable will also modify all the objects.

Instance variables are created in heap memory.Static variables are stored on method area.

Note1:Any thing static stored on method area.

Note2:A static block represents a block of statements declared as static.

Ex:static{

statements;}

Note: With out main method any class will be compile and run.

this:It represents the present class object. it means this represents all the members of the

present class. This --> present class instance variables.

--> present class methods. --> present class constructors.

Page 28: Java

ex:

Instance Methods:There are two types of instance methods.1. Accessor methods2. Mutator methods.

Accessor methods:These are simply access or read the instance variables. They do not modify the instance

variables.

Mutator methods:These are not only access the instance variables but also modify them.

Ex: write a program to create Person class object

IIQ) How objects are passed to the methods in JAVA?Ans primitive datatypes, objects, even object references-every thing is passed to methods using 'pass by value' (or) 'call by value' concept. This means bit by bit copy is passed to the methods.

Ex:

Factory methods:Factory methods are static methods only. But their intension is to create an object

depending on the user choice. A factory method is a method that returns an object to the class, to which it belongs. Ex: getNumberInstance() is a Factory method. Because it belongs to NumberFormat class and returns an object to NumberFormat class.

IIQ) What are factory methods?Ans A factory method is a method that creates and returns an object to the class to which it belongs. A single factory method replaces several constructors in the class by accepting different options from the user, while creating the object.

some NumberFormat methods are:setMaximumIntegerDigits();setMinimumIntegerDigits();setMaximumFractionDigits();setMinimumFractionDigits();

Apply the format to the required statement using format() method. This method returns a string that contains formatted area value.

//creating NumberFormat class object:NumberFormat obj = NumberFormat.getNumberInstance();

Page 29: Java

There is another way of using getNumberInstance() method as:getNumberInstance(Locale constant);

Here,the parameter represents a constant that represents the name of a country(locality) as Locale.CANADA,Locale.CHINA,Locale.FRANCE,...

ex: w.a.p to calculate the area of a circle.

IIQ) In how many ways can you create an object?Ans There ae four ways of creating objects in java.

1. Using new operator. ex: Employee obj = new Employee();

2. Using factory methods. ex:- NumberFormat obj = NumberFormat.getNumberInstance();

3. Using newInstance() method. Here, we should follow two Steps, as First,store the class name 'Employee' as a string into an object.For this purpose,factory

method forName() of the class 'Class' will be useful. Class c = Class.forName("Employee"); here Class is a class in java.lang package.

Next,create another object to the class whose name is in the object c,for this purpose,we need newInstance() method of the class 'Class' as:

Employee obj = (Employee)c.newInstance();

4. By cloning an already available object, we can create another object. Creating exact copy of an existing object is called "cloning".

Employee obj1 = new Employee();Employee obj2 = (Employee)obj1.clone();

Relationship between objects:There are 3 ways to relate objects in java:1. Using references2. Using Inner Class concept3. Using Inheritance.

IIQ) what is Object graph?Ans Object graph is a graph showing relationship between objects in memory.ex:- //w.a.p to relate two objects using reference.

Inner class:A class within another class.

Page 30: Java

Only inner classes are declared as private. Use: For security mechanism

Outer class acts like firewall between inner class and other program

firewall: It is a software that allows only authorised people to access system resources.

Imp. points on Inner class:1. An inner class is a class within another class.2. Inner class is a safety machanism.3. Inner class is hidden from other classes in the outer class.4. An object to inner class cannot be created in any other class.5. An object to inner class can be created only in its outerclass.6. Only inner class is declared as 'private'.7. Outer class object and inner class object are created in different locations in memory.8. All the outer class members are directly available to inner class.9. Inner class contains an additional invisible field 'this$0' that stores reference of outer class object in memory.10. If same names (class) are used then outer class members are referred as:outerclassname.this.member and inner class refered as: this.member

INHERITANCEIIQ) What is inheritance?Ans Deriving new classes from existing classes such that the new classes acquire all the features of existing classes is called inheritance.The syntax of inheritance is:

class subclass extends superclass

IIQ) why super class members are available to sub class?Ans Because, the sub class objects contains a copy of super class object.

IIQ) What is the advantage of inheritance?Ans In inheritance, a programmer reuses the super class code without rewriting it, in creation of sub classes. So, developing the classes becomes very easy. Hence, the programmer's productivity is increased.

ex:- (program)

super: (keyword)Actually we create sub class object. Because by using this object we can access both sub

class members and super class members.

Page 31: Java

But some times, the super class members and sub class members are same names. In that case, by default only subclass members are accessible. In such case; 'super' keyword has been invented. 'super' refers to super class members from a sub class.Ex:

1. super can be used to refer to super class variables, as:super.variable;

2. super can be used to refer to super class methods are:super.method();

3. super can be used to refer to super class constructor.

We need not call the default constructor of the super class, as it is by default available to sub class.To call the parameterized constructor, we can write:

super(values);ex:(program)

Protected specifier:The private members of super class are not available to sub classes directly. But some

times, there may be a need to access the data of super class in the sub class. For this purpose, 'protected' specifier is used.Protected is commonly used in super class to make the members of super class available directly in its sub classes.We can think that the protected specifier works like public with respect to sub classes.

Ex:

Types of inheritance:There are two types of inheritance:

1. Single inheritance2. Multiple inheritance.

1.single inheritance:Producing sub classes from single super class is called single inheritance.

In this, a single super class will be there. There can be one or more sub classes.

Diagram: 2. Multiple inheritance:

Producing sub classes from multiple super classes is called multiple inheritance.In this, there will be more than one super class and there can be one or more sub classes.Diagram: Only single inheritance is available in JAVA. There is no multiple inheritance in java.

The following are the reasons:1. Multiple inheritance leads to confusion for the programmer.

Page 32: Java

Ex: class A has got a member x, and class B also got a member x. When another class C extends both the classes, then there is confusion regarding which copy of x is available in C.

2. Multiple inheritance is available in C++, which is not available in Java. This leads to disappointment in Java programmers. A java programmer wishes to use multiple inheritance in some cases. Fortunately, Java Soft people have provided interface concept, expecting the programmers to achieve multiple inheritance by using multiple interfaces.

ex: we can write, class Myclass implements interface1,interface2,.... *achieving multiple inhertance by using interfaces is not useful.

3. The programmer feels achieving multiple inheritance by using classes would be practically useful to him. The way to achieve multiple inheritance is by repeating the use of single inheritace.ex: class B extends A

class C extends B

H.W:1) create Rectangle class from square class and display the area of both the Rectangle and square class.

Polymorphism:The ability to exist in various forms called Polymorphism.

If a variable or an object or a method performs different tasks. Then it is called polymorphism.

There are two types of polymorphisms.1. Dynamic polymorphism 2. Static polymorphism.

Dynamic Polymorphism:This is the polymorphism exhibited at Run time. In this a method call is bound(linked) to

a method body. At the time of running the program. It is also called Run-time polymorphism (or) Dynamic binding.

Method signature:Method name along with method parameters is called method signature.

Method overloading:Writing two (or) more methods with same name but with a difference in the method

signature.

ex:

Page 33: Java

In method overloading, JVM decides which method to be executed depending upon the difference in the method signatures. The difference may be as shown below.

1. There is a difference in the no of parameters in the both the methods.ex:- void add(int a,int b); void add(int a,int b,int c);

2. There is difference in the data types of parameters.ex:- void add(int a,float b); void add(float a,double b);

3. There is difference in the sequence of parameters.ex:- int swap(int a,char b); int swap(char a,int b);

Any one difference in above will make JVM recognize the methods differently.Method overloading using instance methods is an example for dynamic polymorphism.

Method Overriding:Writing two or more methods with the same name and same signature is called method

overriding.

Using instance methods is an example for dynamic polymorphism.

In method overriding JVM executes a particular method depending upon the class for which the object is created.

Ex: (method overriding)

Static polymorphism:The polymorphism exhibited at compilation time is called static polymorphism. Here the

compiler knows which method is called and it binds the method call with method body at the time of compilation. It is also called static binding or compile time polymorphism.

Method overloading and method overriding using static methods, private methods and final methods are example for static polymorphism.

Ex:

Final methods are the methods written in a final class.

final class:- It is a class declared as final.ex:- final class Myclass.

final keyword before a class prevents Inheritance. That is you can't create sub class from final class. ex:- final class A;

class B extends A // invalid

Note: final methods can not be overridden.

Page 34: Java

|MOL MOR --------|-------| ------- static | true | true

--------|-------|-------- private | true | false

--------|-------|-------- final | true | false

H.w:W.a.p to show how to override the calculateBill() method of Commercial class inside the Domestic class.hint:- take name as instance variable pass units as parameter to calculateBitt() method.

TYPE CASTINGType casting:

Converting a data type into another data type is called Type casting(or)casting.

Datatype:- A data type represents the type of data stored into a variable.

There are two types of datatypes.1.primitive (or) fundamental data types:

These represents single values.Methods are not available to act upon them.ex:- byte, short, char, int, long, float, double etc..,

2.Advance(or) reference datatypes:They represents a group of values.methods are also available to act upon them.ex:- array,class (ex:- String,Employee,....)

IIQ) What is the difference between primitive and advanced datatypes?Ans see above.

limitations:1. We can convert a primitive type into another primitive type.2. We can convert an advanced type into another advanced type using casting.3. We can not use casting to convert a primitive data type into an advanced data type.(or) vice versa. For this purpose, Wrapper class methods should be used.casting primitive datatypes:1)Widening: Converting a Lower data type into higher type is called widening. byte, short, char, int, long, float, double lower<.......................>higher

ex: char ch = 'A'; int n = (int) ch;

ex: int n = 12;

Page 35: Java

float x = (float)n;* Widening is safe operation.*Widening is also called implicit casting.

2)Narrowing: Converting a higher datatype into lower type is calledNarrowing.In narrowing, Some times we loose digits.Therefore Narrowing is unsafe operation.ex:- int num=66; char ch = (char)num;ex:- double d = 12.9877; int n = (int)d;

Narrowing is also called explicit casting.

casting advanced datatypes:We can convert one class type into another class type using casting. If those classes are

related by inheritance.

Ex: (program)

Abstract Classesconcrete method:

It is a method with body. When all the objects want to perform same task. We should write a concrete method in the class.

Abstract method:A method with out body is called abstract method. When the same method should be

implemented differently for different objects. Then we should write it as an abstract method.

Abstract class:A class that contains abstract methods is called abstract class. Both the abstract class and

abstract methods should be declared using the keyword 'abstract'.

Note: We cannot create object for Abstract class.

Diagram:

ex: w.a.p in which abstract class Car contains an instance variable, one concrete method and two abstract methods, And write two sub classes to implement Car abstract class. And write a program to use all features of abstract class by creating a reference to it.

Imp points:1. An abstract class is a class with 0 (or) more abstract methods.2. An abstract class may have instance variables and concrete methods in addition to abstract methods.

Page 36: Java

3. We can not create an object to an abstract class.4. We can create a reference of abstract class.5. All the abstract methods of abstract class should be implemented in its sub classes.6. If any abstract method is not implemented, then the sub class should also be declared as 'abstract'.7. Abstract class reference can be used to refer to all objects of its sub classes.8. A class can not be declared as both 'abstract' and 'final'. ex:- final abstract class A // invalid

H.W:Create abstract class 'Parent' with property details and an abstract method

'calculate()'.Now derive 'Son' class from 'Parent' class and calculate the son's property by implementing 'calculate()' method.

INTERFACESDefinition:

An interface is a specification of method prototypes.

Diagram:

Summary on interfaces:1. An interface is a specification of method prototypes.2. An interface contains only abstract methods.3. An interface contains 0 (or) more abstract methods.4. All the methods of the interface are public and abstract by default.5. An interface can contain variables which are public, static and final by default.6. We cannot create an object to interface.7. We can create a reference of interface type.8. All the methods of the interface should be implemented in its implementation class.9. If any method is not implemented, then that implementation class should be declared as 'abstract'.10. Interface reference can be used to refer to objects of its implementation classes.11. An interface can not implement another interface.12. An interface can extend another interface.13. We can write a class within an interface.14. A class can implement multiple interfaces.

IIQ) what is the difference between abstract class and interface?Ans

Page 37: Java

1) A programmer carets an abstract class when there are some common features shared by all the objects. A programmer writes an interface when every feature should be implemented differently for different objects.2) When an abstract class is written, it is the duty of the programmer to provide sub classes to it. When an interface is written, the programmer can leave implementation for the third party vendors.

Ex:

MIIQ) Why multiple inheritance is not available in java?Ans1) Multiple inheritance leads to confusion for a programmer.2)A programmer can achieve multiple inheritance using multiple interfaces.3)The programmer can achieve multiple inheritance by repeated use of single inheritance.

ex:- class B extends A class C extends B Because of the above reasons multiple inheritances is not directly available in java.

Ex: Multiple inheritance using interfaces.

H.W: Create an interface 'shape' with PI value as 3.14153 and a method 'volume (float a, float b)'.Implement this interface individually in 'sphere' and 'cylinder' classes to find their volumes.

HINT:- volume of sphere = 4*PI*(r*r*r)/3; volume of cylinder = PI*r*r*h;

PACKAGESDefinition:

A package is a sub directory that stores a group of classes and interfaces.

Advantages:1. They protect classes and interfaces. So that accidental deletion is not possible.2. Packages provide reusability.3. The classes of one package are isolated from the classes of another package. So, same names can be used in two different packages.4. Using package concept we can also create our own packages and extend already available packages.

Ex: creating our own package.Ex: adding another class to the same package.

compilation of packages: javac -d . savedclassname.java

Page 38: Java

here d -> define/create sub directory. (Destination folder/directory) . -> Current directoryex: (Package Usage class)

Execution process of a package use class:1. Java compiler searches for .class files in the current directory.2. Java compiler searches for packages in the current directory3. finally java compiler searches for the package in the present class path.

CLASSPATH: It is an operating system's environment variable which stores the active directory path.

That is all files in those directories are available to any programs in the system.

To see the class path in our system:c:\>echo %CLASSPATH%

To set the permanent class path:mycomputer -> properties -> advanced -> environmentvariables->uservariables -> click new ->

variable Name: CLASSPATHvariable value: package path;. (d:\;.)

To set the temporary path and compile and run the main program:

main prog dir:\>javac -cp packagepath;. mainprog.javaex:- e:\work\>javac -cp d:\;. Use.java

main prog dir:\>java -cp packagepath;. mainprogclassfile ex:- e:\work\>java -cp d:\;. Use

THE JAR FILES:IIQ) What is JAR file?Ans A Java Archive file(JAR) is a file that contains compressed version of several .class files, audio files, image files or directories.JAR file is useful to bundle up several files related to a project and use them easily.

To create a Jar file:jar cf jarfilename inputfiles

here cf : create file.ex:- c:\>jar -cf pack.jar pack

now pack.jar is created.

To view the contents of a jar file: jar tf jarfilename here tf : table view of file.

Page 39: Java

ex:- c:\>jar -tf pak.jar

To extract files from .jar file:jar xf jarfilenamehere xf : extract files from jar file

ex:- c:\>jar -xf pack.jar

Interfaces in packages:It is possible to write interfaces in a package.

ex:- //write a program to create an interface with a single method to display system date and time.

IIQ) which statement is first executable statement in java program?Ans Package statement should be the first executable statement in java.

Access specifiers in JAVA:Access specifier is a keyword that represents how to access or read the members of a

class (or) the class itself.There are 4 access specifiers in java.

1. private 2. public 3. protected 4. default

Diagram:

private members of a class are not accessible in any other class either in the same package (or) in another package. The scope of private specifier is 'class scope'.

public members of a class are available in other classes of the same package (or) another package. The scope of public specifier is 'global'.

protected members are available in the classes of same package. They are not available in the classes of the another package. So protected access specifier is acts as public with respect to sub classes.

Default members are available to the classes of the same package. But not in the classes of another package.The scope of default specifier is 'package scope'.

NOTE: Protected members are always available in the subclasses of same package (or)

another package also.

API document: (Application Programming Interface)It has contains the description of all features of a software (or) product (or) technologies.

To create API:

Page 40: Java

we should use c:\>javadoc *.java

H.W:Create Figure class with 2 instance variables x,y in a package called 'geopack'.Then

import that package into Rectangle class,to find the area of the Rectanle(your Rectanle class extends Figure) simillarlly,derive Triangle class and Circle classes and display thier areas.-

Exception Handling

The error in a program is called 'Bug'. Removing the errors is called 'debugging'.

There are 3 types of errors.1.compile-time errors:

These are the errors in the syntax (or) grammar of the language. These errors are detected by java compiler at the time of compilation.2.Run-time errors:

These errors happen due to inefficiency of the computer system to execute a statement. These errors are detected by JVM at run-time.3.Logical errors:

These are the errors in the logic of the program. They are not detected by java compiler (or) by JVM.

Logical errors are detected by comparing program o/p with manually calculated results.

Exception:An Exception is a run-time error. All exceptions are represented by classes in java.

Diagram:

IIQ) what are the checked exceptions?Ans The exceptions detected by java compiler at compilation time are called checked exceptions.IIQ) What are unchecked exceptions?

The exceptions detected by JVM at Run time are called Unchecked exceptions. Exception is the super class of all the Exceptions. Throw able is a class that represents all errors and exceptions.

ex: When an exception occurs in a program JVM terminates the program abnormally and

entire user data may be lost. SO, the programmer should perform the following 3 tasks.step 1:The programmer should write statements in a try block to raise the exception.

syn:try{

Page 41: Java

statements;}

When there is an exception in try block, jvm will not terminate the program abnormally. It will store exception details in an "Exception stack" and then jumps into "catch" block.

step 2:The programmer should display exception details and any messages to the user in catch block.

syn: catch(Exceptionclass obj){

statements;}

We can display the exception details using any one of the following ways:1.print() (or) println() methods.such as System.out.println(obj);2.printStackTrace() method of Throwable class,which fetches exception details

from the exception stack and display them.

step 3:close all files and databases in finally block.

syn: finally{

Statements;}

Finally block is executed even if there is an exception (or)not. Performing the above tasks is called "Exceptin Handling".

ex:- (ArrayIndexOutOfBoundsException example)

Multiple Exceptions:summary:1. Multiple Exceptions can be handled by writing multiple catch blocks.2. A single try block can be followed by multiple catch blocks.3. Catch block does not exist with out a try block.4. But a try exist without a catch.

IIQ) What is the difference between Exception and error?Ans

Exception: An exception is an error and it can be handled. Error:- But an error can not be handled.

Throws Clause:1. Throws statement is useful to throw an exception out of a method without handling it.2. Throws exception is useful to throw any type of exception without handling it.Ex:

Page 42: Java

Throw:This statement is useful to throw an exception object and also handle it.

IIQ) What is the difference between throws and throw?Ans Throws statement is useful to throw an exception without handling it. Throw statement is useful to throw an exception object and handle it explicitly.

Uses of throw:1. Throw is used in software testing to test whether a java program is handling all the exceptions as claimed by the user.2. Throw is useful to create user-defined exceptions and handle them.

Ex:

Types of exceptions:1.Built-in Exceptions:The exceptions which are already available in java.

Ex: 1. IOException

2. ArrayIndexOutOfBoundsException3. StringIndexOutOfBoundsException4. ArithmeticException5. FileNotFoundException6. ClassNotFoundException7. NoSuchMethodException8. NullPointerException9. RuntimeException10. InterruptedException11. NumberFormatException

2.User-defined Exceptions:The exceptions created by the user's of the language are called user-defined exceptions.

creating user-defined Exceptions:1.create user-exception class as a sub class to Exception class.

ex:- class MyException extends Exception2.Write a default constructor in user-exception class

ex:-MyException(){}3.Write a constructor with a string parameter and from there call super class constructor.

ex:-MyException(String str){

Page 43: Java

super(str);}

4.To raise the exception throw exception class object out of try block using throw Statement.ex:- MyException me = new MyException();

throw me;

ex:- How to create our own exception and raise it.

H.W:-1.create a program that accepts 2 numbers as input from command line. Your program should throw RuntimeException if exactly two numbers are not given.2.create a student class with some students names and their marks in maths. Raise your own exception like unreasonable marks if any student gets more than 100 marks in maths.

WRAPPER CLASSESWrapper class:

A wrapper class is a class whose object wraps(contains) primitive data type within it.

Primitive data type wrapper class1. char Character2. byte Byte3. int Integer4. float Float5. double Double6. long Long

All these wrapper classes are available in java.lang package.

Character class:The Character class wraps a value of the primitive type 'char' in an object. Character class

object contains a single field whose type is char. In this, we can store a primitive 'char'.

constructors: 1)Character(char ch) creating character object:

Character obj = new Character('A'); --->this is called boxing (or) ch

char ch = 'A';Methods:1)char charValue():

It returns the char value of the invoking object.

Page 44: Java

ex:- char x = obj.charValue(); --->THis is called unboxing.2)int compareTo(Character obj):

This method compares two character objects.It returns 0 if both the objects are equal.If the calling object is less than obj.Then it returns -ve, else +ve value.

ex:- int n = c1.compareTo(c2);if(c1 == c2) then n = 0;if(c1>c2) then n = +ve;if(c1<c2) then n = -ve;

3)String toString():Converts character object into String object and returns that String object.

4)static boolean isDigit(char ch):It return true if ch is a digit(0 to 9) otherwise returns false.

ex:- Character.isDigit('9'); it is true.

5)static boolean isLetter(char ch): It returns true if ch is letter(A to Z (or) a to z).

6)static boolean isUpperCase(char ch):It returns true if ch is an uppercase letter(A to Z).

7)static boolean isLowerCase(char ch):It returns true if ch is lower case letter(a to z).

8)static boolean isSpaceChar(char ch):It returns true if ch is comming from 'spacebar'.

9)static boolean isWhitespace(char ch):It returns true if ch is comming from TAB,ENTER,BACKSPACE.

10)static char toUpperCase(char ch):It converts ch into upper case.

11)static char toLowerCase(char ch):It converts ch into lower case.

Ex: W.a.p to test the type of a character.

H.w:- Modify the above program to execute repeatedly till enter button is pressed using while loop.

Byte class:The Byte class wraps a value of primitive type 'byte' in an object. An object of type Byte

contains a single field whose type is byte.

Page 45: Java

Constructors:1. Byte(byte num)2. Byte(String str)

Creating Byte class object:byte b = 99;Byte obj = new Byte(b); //Ist constructorString s = "99";Byte obj = new Byte(s); // IInd constructor

IIQ) Which of the wrapper classes does not contain a constructor with String parameter?. (or)Which of the wrapper classes contains only one constructor?

Ans) Character.

Methods of Byte class:1)byte byteValue():

It returns the value of invoking object as a byte.

2)int compareTo(Byte b):Compares the numerical value of invoking object with that of 'b'. Returns 0 if the values

are equal. Returns a negative value if the invoking object has a lower value. Returns a positive value if the invoking object has a greater value. Ex: int n=b1.compareTo(b2);

if b1 == b2, n=0 if b1 > b2, n = +ve;

if b1 < b2, n = -ve;

3)static byte parseByte(String str):It returns the byte equivalent of the number contained in the string specified by 'str'.

4)String toString():Returns a String that contains the decimal equivalent of the invoking object.

5)static Byte valueOf(String str):Returns a Byte object that contains the value specified by the String str.

ex:- //creating and comparing Byte objects.

Integer Class:The Integer Class wraps a value of the primitive type 'int' in an Object.An object of type

Integer contains a single field whose type is int.constructors:

Page 46: Java

1)Integer(int num);2)Integer(String str);

Methods in Integer Class:1)int intValue():

Returns the value of the invoking object as an 'int'.

2)int compareTo(Integer obj):compares the numerical value of the invoking object with that of 'obj'.Returns 0,-ve value

(or) +ve value.

3)static int parseInt(String str):returns int equivalent of the String str.

4)String toString():Returns a String form of the invoking object.

5)static Integer valueOf(String str):Returns Integer object that contains the value shown by str.

6)static String toBinaryString(int i):returns a string representation of the integer argument in base 2.

7)static String toHexString(int i):returns a string representation of the integer argument in base 16.

8)static String to0ctalString(int i):returns a String representation of the integer argument in base 8.

ex:- // converting into other systems.

Float class:The Float class wraps a value of primitive type 'float' in an object. An object of type

Float contains a single field whose type is float.

constructors:1)Float(float num);2)Float(String str);

Methods in Float class:1)float floatValue():2)double doubleValue():3)int compareTo(Float f):4)static float parseFloat(String str):5)String toString()6)static Float valueOf(String str):

Page 47: Java

Double class:The Double class wraps a value of primitive type 'double' in an object. An object of type

Double contains a single field whose type is double.

constructors:1)Double(double num);2)Double(String str);

Methods in Double class:1)double doubleValue():2)float floatValue():3)int compareTo(Double f):4)static Double parseDouble(String str):5)String toString();6)static Double valueOf(String str): Math class:

The class Math contains methods for performing mathematical operations.All these methods are 'static' and 'public'.Methods:1.static double sin(double arg):

returns the sine value of the arg.arg is in radians.

2.static double cos(double arg):returns the cosine value of the arg.arg is in radians.

3.static double tan(duoble arg):returns the tangent value of the arg.arg is in radians.

4.static double log(double arg):returns the natural logrithm value of arg.

5.static double pow(double x,double n):returns x to the power of n value.

6.static double sqrt(double arg):returns the square root of arg.

7.static double abs(double arg):returns the absolute value of arg.

8.static double ceil(double arg):returns the smallest integer which is greater than or equal to arg.

Page 48: Java

ex:- Math.ceil(4.5) is 5.0

9.static double floor(double arg):returns the greatest integer which is lower than or equal to arg.ex:- Math.floor(4.5) is 4.

10.static double min(arg1,arg2):returns the minimum of arg1 and arg2.

11.static double max(arg1,arg2):returns the maximum of arg1 and arg2.

12.static long round(arg):returns the rounded value of arg.ex:- Math.round(4.6) is 5.

13.static double random():returns a random number between 0 and 1.

14.static double toRadians(double angle):converts the angle in degrees into radians.

15.static double toDegrees(double angle):converts angle in radians into degrees.

ex:- generate random numbers between 0 and 10.

H.w:- create a class 'Calculate' with static methods to find:factorial value,power value,squareroot value,sine value.

IOSTREAMSStream:

A Stream represents flow of data from one place to another.There are two types of streams.

1. Input Streams: They read (or) accept data2. Output Streams: They send (or) write data to some other place.

Here another 2 classifications are also there.1. byte streams: They transport data in the form of bits and bytes.2. text streams: They transport data in the form of characters.All streams are represented by classes in java.io package.

Byte streams:These classes are derived from the abstract classes:

Page 49: Java

InputStream and OutputStreamEx:ByteArrayInputStream: It uses a buffer to read bytes.(or)read bytes from array.

ByteArrayOutputStream: It writes data into byte array.

FileInputStream : Reads data from file.

FileOutputStream: Write data into file.

FilterInputStream: Reads data from another inputStream.

FilterOutputStream: Sends data to another outputStream.

PipedInputStream: This should be connected to piped output stream.It reads data that is send to PipedOutputStream.

PipedOutputStream: Sends data from one program to another program.

ObjectInputStream: Reads objects from a file.

ObjectOutputStream: Writes objects into a file.

BufferedInputStream: Reads a buffer full of data from another inputStream.

BufferedOutputStream:Writes a buffer full of data(bytes) into another outputStream.

DataInputStream: Reads primitive data types from another inputStream.

DataOutputStream: writes primitive datatypes to another outputStream.

PrintStream: Sends bytes to another Stream.

TextStreams:These classes are derived from the abstract classes:Reader and Writer.

Ex:BufferedReader: Reads a buffer full of characters from another inputStream.

BufferedWriter: Writes a buffer full of characters into another outputStream.

CharArrayReader: Reads a character array.

CharArrayWriter: Writes a character array.

InputStreamReader: It reads bytes and decodes them into character.

Page 50: Java

InputStreamWriter: It converts characters into bytes and writes them to another stream.

FileReader: Reads characters from a file.

FileWriter: Writes characters into a file.

PrintWriter: Sends text to another Stream.

File:Organized collection of data and stored permanently in the Hard-Disk (or) Flopy (or) CD.

Uses:1. Data stored permanently in the secondary memory.2. Same file data can be shared by different programs.

Diagram:ex:- //To create a file.

ex:- //To read data from a file.

Diagram:ex:- // create a text file using FileWriter.

ex:- //Reading data from the text file.

To Zip -->DeflaterOutputStreamTo unZip -->InflaterInputStream

These two classes are in java.util.zip package.

ex:- // zipping a file contents

ex:- //unzipping a file contents.

serialization:Storing Object data into a file is called serialization.

Deserialization:Reading back object data from a file is called deserialization.

IIQ) Which type of variables can not be serialized?Ans static and transient variables can not be serialized.

Ex:

File class:

Page 51: Java

File class of java.io package provides some methods to know the properties of a file or a directory.

create a File class object:File obj = new File(filename);File obj = new File(directoryName);File obj = new File("path",filename);File obj = new File("path",directoryname);

File class methods:1.boolean isFile():

This method returns true if the File object contains a file name, other wise false.

2.boolean isDirectory():This method returns true if the File Objects contains a directory name.

3.boolean canRead():This method returns true if the File object contains a file which is readable.

4.boolean canWrite():This method returns true if the file is writable.

5.boolean canExecute():This method returns true if the file executable.

6.boolean exists():This method returns true when the File object contains a file or directory which

physically exists in the computer.

7.String getParent():This method returns the name of the parent directory of a file or directory.

8.String getPath():This method returns the name of the directory path of a file or a directory.

9.String getAbsolutePath():This method gives the absolute directory path of a file or directory location. Absolute

path is mentioned starting from the root directory.

10.long length():This method returns a number that represents the size of the file in bytes.

11.boolean delete():This method deletes the file or directory Whose name is given in File Object.

Page 52: Java

12.boolean createNewFile():This method automatically creates a new,empty file indicated by File object, if and only

if a file with this name does not yet exist.

13.boolean mkdir():This method creates the directory whose name is given in File object.

14.boolean renameTo(File newname):This method changes the name of the file as new name.

15.String[] list():This method returns an array of strings naming the files and directories in the directory.

ex:- //w.a.p that accepts a file or directory from commandline arg.To get the file properties.

H.W:-1)copy a file content into another file(new file).2)Append the contents of one file to another file(existing).3)count the no of characters,words and lines in a text file.

THREADSDefinition:

A Thread represents a process (or) execution of group of statements.

ex:// which is currently running Thread?class MyClass{

public static void main(String args[]){System.out.println("This is first line");Thread t = Thread.currentThread();System.out.println("Current Thread:" + t);System.out.println("Its name:" + t.getName());

}}

O/P:- This is first line current Thread:Thread[main,5,main] Its name :main

Main thread is default Thread that executes the statements in a java program.

5 is the default priority number.

Page 53: Java

Execution of statements is of Two types:1.Single Tasking:

Executing only one task at a time by the Micro-Processor is called single tasking..Much of the processor time is wasted in single tasking.

2.Multi-tasking:time slice: It represents a unit of time alloted for a task.

Round Robin:Executing the first task after the last task in cyclic manner is called round robin

method.Executing Multiple tasks simultaneously by the processor is called Multi-tasking.

Advantage:Here processor time is not wasted.i.e the processor time is utilized in an optimum(better) way.

There are two ways of multi-tasking:1.Process based Multi-tasking:

In this Multiple processes (or) programs are executed by the processor at a time.2.Thread based Multi-tasking:

In this several parts of same program are executed by the processor at a time using threads.Diagram:

IIQ) What is the difference between process and Thread?Ans A thread is a light weight process. It uses less resources of the system.

(light weight -> less memory,less time)A process is a heavy weight process.It uses high resources of the system.

Uses of Threads: Threads are used in server side programs to provide services to several clients at a time. Threads are used in animations and games.

Creating a Thread:1. Create a class as a sub class to Thread class (or) create a class as an implementaion class

of 'Runnable' interface.ex:- class Myclass extends Thread class Myclass implements Runnable

2. write public void run() in the class.

Page 54: Java

Note:- A thread will recognise and execute only run() method.

3. create an object to the classex:- Myclass obj = new Myclass();

4. create a Thread and attatch it to the object.ex:- Thread t = new Thread(obj);

5. Now run the Thread.ex:- t.start();

IIQ) How can you stop a thread in the middle?Ans 1.create a boolean type variable and store false in it.

ex:- boolean stop = false;

2.If the variable value is true,return from public void run() method.ex: if(stop) return;

3.When the user wants to stop the thread,store true into the variable.ex:- //stop thread when Enter pressed

System.in.read();obj.stop = true;

ex:- //creating a thread and running it.

*class Theatre extends Thread*class Theatre implements Runnable

IIQ) What is the difference between extends Thread and Implements Runnable?Ans Functionally both are same.When we extends Thread class there is no scope to extend

another class. ex:- class Myclass extends Thread,class1 //invalid

When we implement Runnable interface.there is still scope to extend another class.ex:- class Myclass extends class1 implements Runnable //valid

So,implements Runnable is more advantageous than extends Thread.

Multi-tasking with two threads:In multi-tasking, several tasks are executed at a time. For this purpose, we need more

than one thread. For example, to perform 2 tasks, we can take 2 threads and attach them to the 2 tasks. Then those tasks are simultaneously executed by the two threads.Using more than one thread is called 'multi threading'.

Ex:

Multiple Threads acting on one object:

Page 55: Java

But in this case, sometimes we get unreliable results.

Ex:

Thread Synchronization:When a Thread acts on an object, any other Threads are not allowed to act upon the same

object simultaneously this is called Thread Synchronization.The object on which the Threads are synchronized is called Mutex(mutually exclusive lock).

Thread synchronization (or) Thread Safe is done in 2 ways1.We can synchronize a block of statements using synchronized block. ex:- synchronized(obj){

Statments;}

2.We can use Synchronized keyword before a method to Synchronize the entire method.ex:- synchronized return type method(){

method body;}

IIQ) What is the difference between sysnchronized block and synchronized key word?Ans synchronized block is useful to synchronize a block of statements. synchronized key word is useful to synchronize an entire method.

Threads:A Thread represents a process (or) execution of a group of statements.

Creating a Thread:Thread t1 = new Thread();//Thread is created without any name.Thread t2 = new Thread(obj);//Here , obj is target object of the ThreadlThread t3 = new Thread(obj,"Thread-name");//target Object and Thread name are given

Thread class methods:1.To know the currently running Thread:

Thread t = Thread.currentThread();

2.To start a Thread:t.start();

3.To stop execution of a Thread for a specified time:Thread.sleep(milliseconds);

4.To get the name of a Thread:String name = t.getName();

Page 56: Java

5.To set a new Name to Thread:t.setName("new name");

6.To get the priority of a Thread:int priority_no = t.getPriority();

7.To set the priority of a Thread:t.setPriority(int priority_no);

Note: Thread priorities can change from 1 to 10.We can also use the following constants to represents priorities.Thread.MAX_PRIORITY value is 10Thread.MIN_PRIORITY value is 1Thread.NORM_PRIORITY value is 5

8.To test if a Thread is still alive:t.isAlive() returns true/false.

9.To wait till a Thread dies:t.join();

Thread DeadLock:When a Thread wants to act upon an object which is locked by another thread, and the

second thread wants to act upon the object which is already locked by the first thread, both the threads will continue in waiting state forever. Which is called 'Thread DeadLock'.

when deadlock occurs further processing of the program is halted.

ex:- //To cancle a Ticket.

ex:- //To book a ticket.

ex:- //cancle and book a tickets.

IIQ) What is the solution for Thread DeadLock?Ans There is no solution for Thread deadLock.The programmer should design the logic in such a way that it will not involve the Thread DeadLock.

Ex:

Thread communication:In some cases,two or more threads should communicate with each other.

ex:-

Page 57: Java

A Consumer thread is waiting for a Producer to produce the data(or some goods). when he Producer thread completes production of data,then the Consumer thread should take that data and use it.

Diagram: ex:- // write a program such that the consumer thread is informed immediately when the data production is over.

Object class methods:1.To send a notification to a waiting thread:

obj.notify();

2.To send notification to all waiting Threads:obj.notifyAll();

3.To wait till the obj is released(till notification is received) obj.wait();Note:-Microsoft peope announced that notify() and wait() methods should be used with in Synchronized block.

IIQ) What is the difference between the sleep() and wait() methods?Ans1. Both the sleep() and wait() methods are used to suspend a thread execution for a specified time.2.When sleep() method is executed inside a synchronized block, the object is still under lock.3.When wait() method is executed inside a synchronized block, It breaks that block, so that the object lock is removed and it is available.

generally,sleep() is used for making a thread to wait for some time. But wait() method is used in Connection with notify() or notifyAll() methods in thread communication.

Thread Priorities:ex:// w.a.p to understand the thread priorities.The thread with higher priority number will complete its execution first.

Thread Group:A Thread group represents several threads as a single group.The main advantage of

taking several threads as a group is that by using a single method, we will be able to control all the threads in the group.

To create a Thread group:ThreadGroup tg = new ThreadGroup("groupname");

here tg is thread group object,and groupname is its name.

To add a thread to this group(tg):

Page 58: Java

Thread t1 = new Thread(tg,targetobj,"threadname");Here t1 is child thread,This thread acts on target object

To add another thread group to the group 'tg':ThreadGroup tg1 = new ThreadGroup(tg,"groupname");

To know the parent of a thread (or) A thread group:tg1.getParent(); //output:tg

To know the parent thread group of a thread:t1.getThreadGroup();

To know the no of Threads actively running in a thread group:tg.activeCount();

To change the maximum priority of a thread group tg:tg.setMaxPriority();

ex://W.a.p to demonstrate the creation of thread groups and some // methods which act on thread groups.

Daemon Threads:Some times,A Thread has to continuously execute without any interruption to provide

services to other threads.Such threads are called daemon threads.

IIQ) what is daemon thread?Ans A daemon thread is a thread that executes continuously.Daemon threads are service providers for other threads (or) objects.It generally provides a background processing.

To make a thread t as daemon thread:t.setDaemon(true);

To know if a Thread is daemon thread or not:boolean x = t.isDaemon();

Thread LifeCycle:

Diagram:

IIQ) What is Thread LifeCycle?Ans A Thread is created using new Thread() statement and is executed by start() method. The thread enters 'runnable' state and when sleep() (or) wait() methods are used (or) when the Thread is blocked on I/O, it then goes into 'not runnable' state. From 'not runnable' state, The Thread comes back to the 'runnable' state and continues running the statements. The Thread dies when it comes out of run() method. These state transitions are called 'life cycle of a thread'

Page 59: Java

COLLECTION FRAME WORK

(java.util package)Container Object (or) Collection Object:

It is an Object that contains a group of other objects.Collection class (or) Container class:

It is a class whose object can store a group of other objects. All collection classes are available in java.util package.

IIQ) What is collection frame work?Ans It is a class library to handle group of Objects. It is implemented in java.util package.

All the classes in Collection frame work have been divided into 3groups. 1.sets :

HashSet, LinkedHashSet, TreeSet. 2.Lists:

It is also similar to a set.It also stores a group of elements like an array.ex:- LinkedList, ArrayList, Vector.

Difference between (1) and (2) :Sets will not allow duplicate elements,But Lists will allow duplicates.

3.Maps: It stores elements in Key,value pairs.ex:- HashMap,Hashtable.

Collection object stores only references of other objects.

Collection object do not store primitive data types.They store only objects.

ex:

Diagram:

stack:A stack represents a group of elements(objects) arranged in LIFO structure.

LIFO --- Last In First Out order.

Diagram: inserting the elements into stack is called Push operation.

deleting the elements from the stack is called Pop operation.

Page 60: Java

push and pop operations are done at only one side of the stack, called 'top' of the stack.

searching for an element in the stack is called peep operation.ex:

1.pile of plates in a coffee trae.2.bangles of hand3.shunting the coaches to railway engine.

To create a stack:Stack st = new Stack();

stack class methods:1)boolean empty():

Returns true if the stack is empty, other wise false.

2)element peek(): it returns top-most Object from the stack with out removing it.

3)element pop():This method pops the top-most object from the stack and returns it.

4)element push(element obj):pushes an element obj onto the top of the stack and returns that element.

5)int search(Object obj):This method returns the position of an element obj from the top of the stack.If the

element(Object) is not found in the stack then it returns -1.

ex: To create stack and perform some operations with the help of menu

To retrieve element by element from a collection object we can use one of the following interfaces.

1.Iterator 2.ListIterator 3.Enumeration

LinkedList:A linked list represents a set of nodes such that each node contains 3 fields. One data

field contains data and 2 link fields which stores references to previous node and next node.

Page 61: Java

node: | link | data | link |

Diagram:

References is useful to traverse in linked list from one node to another node.

It is most useful to storing and retrieving data.

LinkedList methods:1)To create a LinkedList:

LinkedList ll = new LinkedList();

2)To add elements(objects) to a linkedList.ll.add(element);

To add elements in the 2nd position. ll.add(2,element);

3)To remove first element from the LinkedList:ll.removeFirst();

To remove last element from the LinkedList.ll.removeLast();

To remove 2nd element.ll.remove(2);

4)To change the 2nd element with a new element:ll.set(2,NEWelement);

ex:- //a linked list with String elements

ARRAYS:Arrays class contains methods to handle any array. All the methods of this is public and

static.

1)static void sort(array):This method sorts all the elements of an array into ascending order. This method

internally uses Quick Sort algorithm.

2)static void sort(array,int start,int end):

Page 62: Java

This method sorts the elements in the range from 'start' to 'end' within an array into ascending order.

3)static int binarySerach(array,element):This method searches for an element in the array and returns its position number. If

element not found, it returns a negative value. This method acts only on an array sorted into ascending order. This method internally uses Binary Search algorithm.

4)static boolean equals(array1,array2):This method returns true if two arrays are equal, otherwise false.

ex:- //Sorting an array and searching in it.

H.w:1)create an array with strings. Accept a string from the keyboard, and find its position in the array.

2)Build a linked list of double values.

3)create a stack with a group of strings.

ArrayList:An ArrayList is like an array which can grow in memory dynamically. ArrayList is not

synchronized.Creating ArrayList:

ArrayList<E> arl = new ArrayList<E>();ArrayList<E> arl = new ArrayList<E>(int capacity);

here E means Element type.

ArrayList methods:1.boolean add(element obj):

Appends the specified element to the end of the ArrayList.If the element is added successfully it returns true.

2.void add(int position,element obj):Insert the specified element at the specified position in the ArrayList.

3.element remove(int position):Removes the element at the specified position in the ArrayList. It returns the removed

element.

4.boolean remove(Object obj):Removes the first occurrence of the specified element obj from the ArrayList.

5.void clear():Removes all the elements from the ArrayList.

Page 63: Java

6.element set(int position,element obj):Replaces an element at the specified position in the ArrayList with new element obj.

7.boolean contains(int position):This method returns true if the ArrayList contains the specified element obj.

8.element get(int position):Returns the element available at the specified position in the ArrayList.

9.int size():Returns the number of elements present in the ArrayList.

ex:- // An ArrayList with Strings

Vector:It is also similar to ArrayList.It also stores elements But Vector is synchronized.(it allow

one thread act upon Object)

Creating Vector obj:Vector<E> v = new Vector<E>();Vector<E> v = new Vector<E>(int capacity);

Vector class methods:1.boolean add(element obj):2.void add(int position,element obj):3.element remove(int position):4.boolean remove(Object obj):5.void clear():6.element set(int position,element obj):7.boolean contains(Object obj):8.element get(int position):9.int size():

ex:- // a vector with integer objects.

HashMap:HashMap is a Collection that stores elements in the form of Key-value pairs. Keys should

be unique. It is not synchronized.

Creating HashMap:HashMap<K,v> hm = new HashMap<k,v>();HashMap<k,v> hm = new HashMap<k,v>(int capacity);

Page 64: Java

HashMap class methods:1.value put(key,value):2.value get(Obejct key):3.Set<k> keySet();4.collection<v> value():5.value remove(Object key):6.void clear():7.int size():

ex://hashmap to create telephone book.

Hashtable: (Maps)Hashtable can store elements in the form of key-value pairs.Hashtable is synchronized.

Creating Hashtable:Hashtable<K,V> hm = new Hashtable<K,V>();Hashtable<K,V> hm = new Hashtable<K,V>(int capacity);here capacity = How many pairs.

Hashtable class methods:1.value put(key,value):

This method stores key-value pair into the Hashtable.

2.value get(Object key): This method returns the corresponding value when key is given. If the key doesnot have a value associated with it,then it returns null.

3.Set<K> keySet():This method,when applied on a Hashtable converts it into a Set where only keys will be

stored.

4.Collection<V> values():This method returns all the values of the Hashtable into Collection object.

5.value remove(Object key):This method removes the key and corresponding value from the Hashtable.

6.void clear():removes all the key-value pairs from the Hashtable.

7.int size():Returns number of key-value pairs in the Hashtable.

//Hashtable with cricket players and scores.

Page 65: Java

IIQ) What is the difference between ArrayList and Vector?Ans1.ArrayList object is not synchronized by default.Vector object is synchronized by default.2.In case of a single thread,using ArrayList is faster than the Vector.In case of multiple threads using Vector is advisable.3.ArrayList increases its size every time by 50%(half).Vector increases its size every time by doubling it.

IIQ) What is the difference between HashMap and Hashtable?Ans1.HashMap object is not synchronized by default. But Hashtable object is Synchronized by default.2.In case of a single thread, using HashMap is faster than Hashtable. In case of Multiple threads using Hashtable is advisable.3.HashMap allows null keys and null values to be stored.Hashtable does not support null keys and values.4.Iterator in the HashMap is fail-fast.This means Iterator will produce exception of concurrent updates are made of the HashMap. Enumeration for the Hashtable is not fail-fast.

StringTokenizer:This class is useful to break into pieces, called Tokens. These tokens are then stored in

the StringTokenizer Object from where they can be retrieved.

Creating StringTokenizer Object:StringTokenizer st = new StringTokenizer(str,"delimiter");here delimiter is Seperator character.

StringTokenizer class methods:1.int countTokens():

Returns the number of tokens available in a StringTokenizer object.

2.boolean hasMoreTokens():Tests if there are more tokens available in the StringTokenizer object or not.If next token

is there then it returns true.

3.String nextToken():Returns the next token from the StringTokenizer.

ex:- //braking a String

Calendar:Calendar class is useful in two ways:

1.It is useful to know the system date and time.2.It is also useful to store a date and time value. So that it can be transported to some other application.

Page 66: Java

creating Calendar object:Calendar cl = Calendar.getInstance(); //factory methodHere cl stores the current system date and time by default.

Calendar class methods:1.int get(int field):

This method returns the value of the given Calendar field. for example.

Calendar.DATE : gives the date (number from 1 to 31)Calendar.MONTH : gives the month (number from 0 to 11)Calendar.YEAR : gives the year Calendar.HOUR : gives the hour (number from 0 to 11)Calendar.MINUTE : gives the minute (number from 0 to 59)Calendar.SECOND : gives the second (number from 0 to 59)Calendar.AM_PM : gives 0 if it is AM.Gives 1 if it is PM.

2.void set(int field,int value):This method sets the given field in Calendar object to the given value.

For example,we can set a date like 15th March 2007 to Calendar object as:cl.set(Calendar.DATE,15);cl.set(Calendar.MONTH,2);cl.set(Calendar.YEAR,2007);

3.String toString():Returns the String representation of the Calendar Object.

4.boolean equals(Object obj):compares the Calendar object with another object 'obj' and returns true if they are same,

otherwise false.

ex:- // to display system date and time using Calendar class.

Date:Date is a class it is useful to display the date and time at a particular moment. Date class

contains the system date and time by default.

Creating Date class object:Date d = new Date();

Now, d contains the System date and time.Once you create Date object, it should be formatted using the methods of DateFormat class of java.text package.They are:

1.DateFormat fmt =DateFormat.getDateInstance(formatConst(date),region(country));This method formats date only.

Page 67: Java

2.DateFormat fmt =DateFormat.getTimeInstance(formatConst(time),region(country));This method formats time only.

3.DateFormat fmt = DateFormat.getDateTimeInstance(formatConst(date),formatConst(time),region(country));

This method formats date and time.

Finally, apply format information in fmt to Date class object d.String str = fmt.format(d);

Format constants are:DateFormat.FULLDateFormat.LONGDateFormat.MEDIUMDateFormat.SHORT

Region constants are:Locale.USLocale.UKLocale.CHINALocale.CANADALocale.ITALYLocale.JAPANLocale.KOREALocale.TAIWANLocale.FRANCELocale.GERMANY

ex:- // display System date and time.

H.w:1)create an employee class with an Employee's id, name and address. Store some objects of this class in an ArrayList. When an employee's id is given display his name and address.

2)create a Vector with a group of Strings. Sort them and display them in ascending order. display them in reverse order.

3)create a Hashtable with some students hall ticket numbers and their results. Type a hall ticket no and display his result.

4)cut the following into pairs of pieces. "India=>Delhi,America=>Washington,Briton=>London,France=>paris" Now display the tokens as given below. ------------------------------------

Page 68: Java

CITY CAPITAL FOR ------------------------------------ Delhi India Washington America London Briton Paris France ------------------------------------

CLONINGcloning:

It is a technology to create exact copy of a plant, a bird, an animal or a human being.

cloning in JAVA:creating bit-wise exact copy of an object is called cloning.

Bit-wise exact copy:deto (Bit to Bit) object.

//cloning examplecode: (CloneDemo.java)

class Employee implements Cloneable{int id;String name;Employee(int i,String n){

id = i;name = n;

}void display(){

System.out.println("Id =" + id);System.out.println("Name=" + name);

}Object myClone() throws CloneNotSupportedException{

return super.clone();}

}class CloneDemo{

public static void main(String args[])throws CloneNotSupportedException{

Employee e1 = new Employee(10,"Gouse");e1.display();Object o = e1.myClone();Employee e2 = (Employee)o;//Employee e2 = (Employee)e1.myClone();e2.display();

Page 69: Java

}}

There are two types of cloning:1)shallow cloning:

In this,any modifications to the cloned object will also modify the original object and vice versa.

2)deep cloning:In this,any modifications to the cloned object will not effect to the original object.

Cloneable is a Interface which is without members and without methods.

IIQ) can you write an Interface without any methods and members?Ans yes

IIQ) what is that interface called?Ans An interface without any members (or) methods is called Tagged interface (or) marker interface.

IIQ) What is the pupose of such an Interface?Ans A marker interface specifies some information about the class objects.

IIQ) can you give me 2 examples for Tagged interface?Ans

1.cloneable :- It indicates that class objects are cloneable. 2.serializable: It indicates that class objects will be serialized.

Graphics programming using AWTAWT: (Abstract Window ToolKit)

Any user can work with application in 2 ways.

1.CUI: (Character User Interface)This is not user friendly. Why because the user should Know the syntax and correct

commands. Since user has to use characters(or) commands to interact with the application. This is call CUI.

Page 70: Java

2.GUI: (Grphics User Interface)In this way the user need not remember any commands but interacts with any application

by clicking on some image or graphics.This is called GUI.

Main Advantages of GUI:1.It is user friendly.2.It adds attraction and beauty to any application by adding pictures, colors, menus, animation etc...,3.It is possible to simulate the real life objects using GUI.

ex:- calculater etc...,4.GUI helps to create graphical components like push buttons, radio buttons, check buttons, etc..., and use them efficiently in our programs.

AWT: It represents a class library to develop applications using GUI.

The java.awt package got classes and interfaces to develop GUI and let the users interact in a more friendly way with the applications.

Classes of AWT:Diagram:

components:A component represents an object which is displayed pictorially on the screen. ex:- creating an object of Button class as

Button b = new Button();

IIQ) What is the difference between a window and a frame?Ans A window is a frame without any borders and title. Whereas a frame contains borders and title.

Diagram:

Creating a Frame:A Frame becomes the basic component in AWT.

The frame has to be created before any other component because all other components can be desplayed in a frame.

There are 3 ways to create a frame.1.create a frame class object:

Frame f = new Frame();

2.create a Frame class object and pass its title also:Frame f = new Frame("My Frame");

Page 71: Java

3.To create a sub class MyFrame to the Frame class and create an object to the sub class:class MyFrame extends FrameMyFrame f = new MyFrame();

Since, the size of our frame would be 0px width and 0px height,It is not visible and hence we should increase its size. This is done by setSize() method.

ex:- f.setSize(400,350);

To visible the frame:f.setVisible(true);

ex://w.a.p to create a frame by creating an object to frame class.

ex://w.a.p to create a frame by creating an object to subclass of Frame class.

Event Delegation Model:

Diagram:

IIQ) What is event delegation model?Ans Event Delegation Model represents that when an event is generated by the user on a component, it is delegated to a listener interface and listener calls a method in response to the event. Finally, the event is handled by the method.

IIQ) Which model is used to provide to AWT components?Ans Even delegation model.

The following steps are involved in Event Delegation Model:1.We should attach an appropriate listener to a component. This is done using addXxxListener() method.Simillarly, to remove a Listener from a component, we can use removeXxxListener() method.

2.Implement the methods of listener, especially the method which handles event. 3.When an event is generated on the component, then the method in step2 will be executed and the event is handled.

Adapter class:An Adapter class is an implementation class of a Listener class where all the methods

contain empty body.

Page 72: Java

WindowAdapter class:It is a Adapter class for WindowListener Interface.

ex: class Myclass extends WindowAdapter{

public void windowClosing(WindowEvent e){System.exit(0);

}}

IIQ) What is Anonymous Inner Class?Ans It is an inner class whose name is not mentioned but for which only one object is created.

ex:- f.addWindowListener(new WindowAdapter(){public void WindowClosing(WindowEvent e){

System.exit(0);}

});

Once the frame is created, we can use the frame to display the following:1.To display text/Strings2.To display images/photos3.To display components like push button, radio buttons, check boxes, etc..

Displaying the Strings in the frame:For this, we should use drawString() method of Grphics class.ex:- g.drawString(String,x,y);here x,y are color coordinates in pixels.

Note: public void paint(Graphics g)This method is used to refresh the frame contents and display updated contents.

To specify colors in awt packaage:1.we can directly mentioned the name of the color as a constant in color class.

ex:- Color.RED,Color.WHITE,etc...,

2.By combining r,g,b values we can get any other values(colors).ex:- Color c = new Color(r,g,b);

// here r,g,b values from 0 to 255.

To specify Text in the frame:ex: Component class methods:

A Component is a graphical representation of an object on the screen. ex:

push buttons, radio buttons, menus etc.., are all components.1.Font getFont():

Page 73: Java

This method returns the font of the component.

2.void setFont(Font f):This method sets a particular font f for the text of the component.

3.Color getForeground():This method gives the foreground color of the component.

4.Color setForeground(Color c):This method sets a foreground color c to the component.

5.Color getBackground():Gets the back ground color of the component.

6.void setBackground(Color c):It sets the background color c for the component.

7.int getHeight():Returns the height of the component in pixels as an integer.

8.int getWidth():Returns the width of the component in pixels as an integer.

9.int getX(): and int getY():Returns the current x, y coordinates of the component's location.

10.void setSize(int width,int height):Resizes the component so that it has new width and height as passed to setSize() method.

11.void setVisible(boolean b):Shows or hides the components.

12.void setEnabled(boolean b):Enables or disables the component.

13.void setBounds(int x,int y,int w,int h):-This method allots a rectangular area starting at (x,y) coordinates and with width w and

height h. The component is displayed in thid area.

Listener:A Listener is an interface that listens to an event from a component. Listeners are in

java.awt.event package.

Component Listener Listener methodsButton ActionListener actionPerformed(ActionEvent e)

Page 74: Java

Checkbox ItemListener itemStateChanged(ItemEvent e)

CheckboxGroup ItemListener itemStateChanged(ItemEvent e) (RadioButton)

TextField ActionListener focusGained(FocusEvent e)(or)FocusListener focusLost(FocusEvent e)

Label ItemListener itemStateChanged(ItemEvent e)

TextArea ActionListener focusGained(FocusEvent e)(or)FocusListener focusLost(FocusEvent e)

Choice ItemListener itemStateChanged(ItemEvent e)(or)ActionListener actionPerformed(ActionEvent e)

List ItemListener itemStateChanged(ItemEvent e)(or)ActionListener actionPerformed(ActionEvent e)

AdjustmentListener adjustmentValueChanged(AdjustmentEvent e)Scrollbar

(or)MouseMotionListener mouseMoved(MouseEvent e) mouseDragged(MouseEvent e)

Note 1:The above Listener methods are all 'public void' methods.

Note 2:A listener can be added to a component using addXxxListener method.ex:- addActionListener();

Note 3:A Listener can be removed from a component using removeXxxListener()

method.ex:- removeActionListener();

Note 4:A Listener method takes an object of XxxEvent class.ex:- actionPerformed(ActionEvent e);

Displaying Images in the frame:To display Images (or) graphics we should use drawImage() method of Graphics class.ex:- g.drawImage(Image obj,x,y,ImageObserver obj(or null));

Page 75: Java

It stores history of imageTo display the image in frames title bar we should use setIconImage() method of Frame

class.ex:- f.setIconImage();

ex:- //displaying Image in the frame

Push Buttons:Button class is useful to create push buttons.A push button performs a particular action.

1.To create a push button,we can create an object to Button class, as:Button b = new Button();Button b = new Button("label");

2.To get the label of the button, use getLabel():String l = b.getLabel();

3.To set the label of the button:b.setLabel("label");

4.When,there are several buttons, to know the label of the button clicked by the user:String s = ae.getActionCommand();here ae is ActionEvent class Object.

5.To know the source object which has been clicked by the user:Object obj = ae.getSource();

ex:- //push buttons

Checkboxes:A Checkbox is a square shaped box which displays an option to the user. The user can

select any one or more options from a group of Checkboxes.

1.To create a Checkbox, we can create an object to Checkbox class as:Checkbox cb = new Checkbox();Checkbox cb = new Checkbox("Label");Checkbox cb = new Checkbox("label",state);

2.To get the state of the Checkbox:boolean b = cb.getState();

3.To set the state of the Checkbox:cb.setState(true);

Page 76: Java

4.To get the label of checkbox:String s = cb.getLabel();

5.To set the new label to the Checkbox:void setLabel(String label);

ex:- //check boxes

RadioButtons:A RadioButton represents a round shaped button, such that only one can be selected

from a group. RadioButton can be created using CheckboxGroup class and Checkbox classes.

1.TO create a radio button:CheckboxGroup cbg = new CheckboxGroup();Checkbox cb = new Checkbox("Label",cbg,true);

2.To know the selected Checkbox:Checkbox cb = cbg.getSelectedCheckbox();

3.TO know the selected Checkbox label:String label = cbg.getSelectedCheckbox().getLabel();

ex:- //RadioButtons

Choice:Choice class is useful to display a choice menu.It is a popup list of items and the user can

select only one item from the available items.

1.To create a Choice menu:Choice ch = new Choice() // create empty Choice menu

2.Once a Choice menu is created,we should add items as:ch.add("item");

3.To know the name of the item selected from the Choice menu:String s = ch.getSelectedItem();

4.TO know the index of the currently selected item:int i = ch.getSelectedIndex();This method returns -1 if nothing is selected.

5.To get the item String,given the item index number.String item = ch.getItem(int index);

6.TO know the number of items in the Choice menu:int n = ch.getItemCount();

Page 77: Java

7.TO remove an item from the Choice menu:ch.remove(int position);ch.remove(String item);

8.To remove all items from the Choice menu:ch.removeAll();

ex:- //A Choice menu

ListBox:List class is useful to create a list box which is similar to choice menu where the user can

select one (or) more items.

1.To create a List box, we can create an object to List class:List lst = new List();Here, the user can select only one item.

List lst = new List(3);This statement creates a list box which displays initially 3 rows.

List lst = new List(3,true);This list box initially displays 3 items,'true' represents multiple selection is enabled.

2.To add items to the list box:lst.add("item");

3.To get all the selected items from the list box:String x[] = lst.getSelectedItems();

4.To get a single selected item from the list box:String x = lst.getSelectedItem();

5.To get the selected items position numbers:int x[] = lst.getSelectedIndexes();

6.To get a single selected item position number:int x = lst.getSelectedIndex();

ex:- //list box

Label:A label is a constant text that is generally display along with a textField to text area.

1.To create a Label:Label l = new Label(); //create an empty labelLabel l = new Label("text",alignmentConstant);

Page 78: Java

Here the alignmentConstant may be on of the following:Label.RIGHT,Label.LEFT,Label.CENTER.

Textfield:A textfield represent a long rectangular box where the user can type a single line of

text.We can also display a line of text in the text field.

1.To create a Textfield:TextField tf = new TextField();TextField tf = new TextField(25);TextField tf = new TextField("defaulttext",25);

2.TO retrieve the text from a textfield:String s = tf.getText();

3.To set the text to a textfield:tf.setText("text");

4.To hide the text being typed into the textfield by a character ‘char':tf.setEchoChar('char');

TextArea:It is simillar to TextField,but it can accomudate several lines of text.

1.To create TextArea:TextArea ta = new TextArea();TextArea ta = new TextArea(rows,cols);TextArea ta = new TextArea("string");

2.To retrieve the text from a TextArea:String s = ta.getText();

3.To set the text to a TextArea:ta.setText("Text");

4.To append the given text to the TextArea's current text:ta.append("text");

5.To insert the specified text at the specified position in the TextArea:ta.insert("text",position);

ex:- //labels and textfields

Page 79: Java

Multi Frames:ex:

H.w:-1)Create Two textfields to enter two nos when the push button is clicked, display their sum in the third text field.

enter first no: ......Enter second no : ------The sum is : ........

_________|find sum||________|

2) Create a Frame and enter employee name and salary.Calculate incomtax based on the salary and display it in a second Frame.

SWINGS

1.When awt components is created, It calls a native method(c function) which creates a 'peer' component(peer = equivalent). A copy of this peer component is given back to awt. So awt components are dependent on c functions. Hence it is also called peer component based model.

2.The look and feel of awt component change depending upon the operating system.look = appearancefeel = user interaction with component

3.awt components are heavy weight components.heavy weight means they take more system resources(memory,time)

Because of the above problem all the classes of java.awt package are Re-Written in java. These classes are called JFC(Java foundation classes).

JFC: It is an extension of the Original awt.It contains libraries that are developed in java and hence completely portable.

1.JFC components are light-weight. They take less memory and time.

Page 80: Java

2.JFC components will have same look and feel on all platforms.

3.The programmer can change the look and feel as suited for a platform(PLAF -> pluggable look and feel).

4.JFC offers a rich set of components with lots of features.5.JFC does not replace awt.JFC is an extension to awt.Major Packages in JFC:1.javax.swing:- To develop components like buttons,menus.

2.javax.swing.plaf:- To provide a native look and feel to swing components.It is pluggable. 3.java.awt.dnd:- To drag and drop the components and data from one place to another.

4.javax.accessibility:- To provide accessibility of applications to disabled persons.

5.java.awt.geom:- To draw 2D graphics,filling,rotating the shapes etc..,

MVC:All the swing components follow a model-view-controller architecture.

'model' represents the data that represents the state of a component. 'view' represents visual appearance of the component based on the model data. 'controller' deals with user interaction with the components and modifies the model or the view in response to use action.

Advantage:MVC separates the model and view of a component. Hence, multiple views for the same

model is possible. Also the programmer can modify view (or) model without affecting the other.

window panes:A window pane represents a free area of a window. Where some text(or) components can

be displayed. There are 4 types of window panes.

Diagram:

JFrame class methods:1.getContentPane():

Returns an object of container class.

2.getLayeredPane():Returns an object of JLayeredPane class.

3.getRootPane():Returns an object of JRootPane class.

Page 81: Java

4.getGlassPane():Returns an object of Component class.

ex: JFrame jf = new JFrame();Container c = jf.getContentPane();

c.add(but);HIERARCHY OF CLASSES IN SWING:Diagram://creating a frame:-ex:

To Close the Jframe:To close the frame we have to use setDefaultCloseOperation(constant);here constants are 4 types:1)JFrame.EXIT_ON_CLOSE2)JFrame.DISPOSE_ON_CLOSE3)JFrame.DO_NOTHING_ON_CLOSE4)JFrame.HIDE_ON_CLOSE

Displaying Text in JFrame:Swing package provides two ways to display text in the frame.

1.paintComponent(Graphics g) method of JPanel class is used to paint the portion of a component in swing.

ex: class MyPanel extends Jpanel{public void paintComponent(Graphics g){

super.paintComponent(g);g.setColor(Color.red);

g.setFont(new Font("Arial",Font.BOLD,34));g.drawString("Hello learners!",50,100);}

}

2.Second way to display text in swing frame is by using a label.A label represents some constant text to be displayed in the frame. We can use JLabel class to create a label as:

JLabel lbl = new JLabel("text");

ex:-

JComponent class methods:1.To set some background color to the component:

Component.setBackground(Color.YELLOW);

2.TO set the foreground color:Component.setForeground(Color.RED);

Page 82: Java

3.TO set some font for the text displayed on/in the component:Component.setFont(Font obj);

4. Tool tip text is the text that is displayed automatically when the mouse is placed on the component.

To set the tool tip text:Component.setToolTipText("This is a swing component");

5.To set the shortcut key to the component:Component.setMnemonic('C');

6.TO enable or disable a component:Component.setEnabled(true);

7.TO make a component to be visible or invisible:Component.setVisible(true);

8.TO get the current x and y coordinates of the component in pixels:Component.getX();Component.getY();

Borders:BorderFactory class has got methods to set different borders for the component. These

methods return Border interface(of javax.swing.border package) object.

Border Object should be passed to setBorder() method as:Component.setBorder(Border obj);

BorderFactory methods:1.To set bevel border:

BorderFactory.createBevelBorder(BevelBorder.RAISED);BorderFactory.createBevelBorder(BevelBorder.LOWERED,Color.RED,

Color.GREEN);

This method uses lowered bevel border with red color for high lightening and green for shading purpose.

2.To set etched border:BorderFactory.createEtchedBorder();BorderFactory.createEtchedBorder(Color.RED,Color.GREEN);

3.TO set a line border:BorderFactory.createLineBorder(Color.RED);BorderFactory.createLineBorder(Color.RED,5);

Page 83: Java

4.TO set matte border:BorderFactory.createMatteBorder(5,10,15,20,Color.RED);

Here thickness 5,10,15,20 px at top,left,bottom and right of the component.

5.To set compound border:-BorderFactory.createCompoundBorder(Border out,Border in);

This method creates a compound border with 'out' at outside edge of the component and 'in' at inside edge of the component.

//A push button with all features:-ex:

To create Labels:1.JLabel lbl = new JLabel();

lbl.setText(); // to display text on labellbl.setImage(); // to display image on label

2.JLabel lbl = new JLabel("Text",ImageIcon ii);

3.JLabel lbl = new JLabel("Text",alignment);JLabel.RIGHTJLabel.LEFTJLabel.CENTER are constants.

To create a Check box:1.JCheckBox cb = new JCheckBox("label",true);

TO create a RadioButton:1.JRadioButton rb = new JRadioButton("label",true);

Note:TO specify several Radio Buttons as belonging to same group. We should add them to

same button group. ButtonGroup bg = new ButtonGroup();

bg.add(rb1);bg.add(rb2);

To create a TextField:1.JTextField tf = new JTextField(20);

To create a Text Area:1.JTextArea ta = new JTextArea(5,20);

Page 84: Java

//checkboxes and radio buttonsex:

JTable:JTable class is useful to create a table.

JTable tab = new JTable(data,columnnames);Here, data represents a two dimensional array and column names represents a one-dimensional array. Alternately, we can also use a Vector class object to represent data and another Vector object to represent column names.

To create a row for the table using a Vector:Vector row = new Vector();

Now add column data to the above row as:row.add(Columndata);

Now this row should be added to the tables data part as:Vector data = new Vector();data.add(row);

1.To know the index of the first selected column:int n = tab.getSelectedColumn();This method returns -1 if no column is selected.

2.To know the indexes of all selected columns:int x[] = tab.getSelectedColumns();

3.To know the index of the first selected row:int n = tab.getSelectedRow();This method returns -1 if no row is selected.

4.To know the indexes of all selected Rows:int x[] = tab.getSelectedRows();

5.To know Which object is there in the table at particular row and column position:Object x = tab.getValueAt(int row,int column);

6.To return the table header used by the table:JTableHeader head = tab.getTableHeader();JTableHeader class is defined in javax.swing.table package.

//a table with employee dataex:

Page 85: Java

JTabbedPane:Pane represents a Frame Area.But A TabbedPane represents a frame with tabs attatched

to it. JTabbedPane is useful to create a tabbed pane,such that on each tab sheet a group of components can be added.

To create an empty tabbed pane:JTabbedPane jtp = new JTabbedPane();

1.To add the tab sheets to the tabbed pane:jtp.add("title",Object);jtp.addTab("title",Object);Here Object is represents group of components that are being added in sheet.

2.To remove a tab and its components from the tabbed pane:jtp.removeTabAt(int index);

3.TO remove all tabs and their corrensponding components:jtp.removeAll();

4.To get the currently selected component Object in the tabbed pane:Component c = jtp.getSelectedComponent();

5.To get the selected components position number:int x = jtp.getSelectedIndex();

//a TabbedPaneex:

Menu:A menu represents a group of Items (or) Options for a the user to select.

Diagram:

Create a Menu:1.Create a Menu Bar.2.Add menu bar to the content pane.3.create menus.4.Add menus to Menu Bar.5.Create Menu Items6.Add Menu Items in the Menu.

Page 86: Java

Creating a Sub Menu:A sub menu is a Menu inside another Menu.

1.Create a Menu.2.Add this Menu inside another Menu.3.Create Menu items.4.Add Menu items to the sub Menu.

To create a Menu:1.Create a menu bar using JMenuBar:

JMenuBar mb = new JMenuBar();

2.Attatch this menu bar to the container:c.add(mb);

3.Create a separate menu using JMenu:-JMenu file = new JMenu("File");

4.Attatch this menu to the main menu:-mb.add(file);

5.Create Menu Items using JMenuItem , JCheckBoxMenuItem (or) JRadioButtonMenuItem :

JMenuItem op = new JMenuItem("Open");JCheckBoxMenuItem pr = new JCheckBoxMenuItem("Print");

6.Attatch the menu item to the menu:-file.add(op);

Creating a sub menu:1.Create menu:-

JMenu font = new JMenu("Font");

2.Now attatch it to another menu:-file.add(font);

3.Create a menu item:-JMenuItem f1 = new JMenuItem("Arial");

4.Attatch menu item to the sub menu:-

Page 87: Java

font.add(f1);

//creating a Menu:ex:

H.w:-1.create a calculator using a textfield and pushbuttons. Also add the functionality to it.

2.Take a student class with halticket no,name and marks it physics,maths and chemistry.Create the following screen,which accepts hno and display the rest of details in text fields.

Enter HallTicketNumber:______________

| RETRIEVE |Marks in Physics : _________

Marks in Maths : _________

Marks in Chemistry: _________

LAYOUT MANAGERS

Definition:A Layout Manager is a class that is useful to arrange components in a particular manner

in a frame (or) container.

The following classes represents the Layout Managers:1.GridLayout :

GridLayout divides the container into a two dimensional grid that contains rows and cols. GridLayout obj = new GridLayout(); GridLayout obj = new GridLayout(int rows,int cols); GridLayout obj = new GridLayout(int rows,int cols,int hgap,int vgap);

//gridlayout demo:ex:-

2.CardLayout:CardLayout manager treats each component as a card. Only one card is visible at a time,

and the container acts as a stack of cards.CardLayout obj = new CardLayout();

CardLayout obj = new CardLayout(int hgap,int vgap);

Page 88: Java

While adding components to the container,we can use add() method as:c.add("cardname",Component);

To retrieve the cards one by one, the following methods can be used:void first(container) : to retrieve the first card.void last(container) : to retrieve the last card.void next(container) : to go to the next card.void previous(container): to go back to previous card.void show(container,"cardname") : To see a particular card

whose name is given.

//CardLayout Demoex:-

3.GridBagLayout:GridBagLayout arranges the components in rows and columns. In this layout,

components can span more than one row (or) column and the size of components can be adjusted to fit the display area.

GridBagLayout obj = new GridBagLayout();To apply some constraints on the components:GridBagConstraints cons = new GridBagConstraints();

GridBagConstraints are:gridx, gridy:-

They represents the row and column positions of the component at upper left corner of the component.

Diagram:

gridwidth,gridheight:-specify the no of columns(for gridwidth) or rows(for gridheight) in the

components display area. The default value is 1.

weightx,weighty:-When the frame is resized, the components inside the container should also be

resized or not is determined by weight x and weighty constraints. valid values are from 0.0 to 1.0default value is 0.0 (not resized)

anchor:When the display area is larger than the component, anchor constraint will determine

where to place the component in the display area. The default value is GridBagConstraints.CENTER.

Page 89: Java

anchor values are: FIRST_LINE_START PAGE_START FIRST_LINE_END

LINE_START CENTER LINE_END

LAST_LINE_START PAGE_END LAST_LINE_END fill:

If the display area is larger than the component, then the component should stretch and occupy the display area horizontally or vertically is decided by the fill constraint. fill can be NONE (default) , HORIZONTAL, VERTICAL , BOTH

insets:This is to leave some space around the component(external padding). Insets insets = new Insets(5,10,15,20);//0,0,0,0 is default

ipadx,ipady:ipadx and ipady are useful to leave space horizontally and vertically within the

component (internal padding).default value is 0.

//GridBagLayout Demo:ex:

APPLETS

Applet:An Applet represents java Bytecode embeded in a Web page.

Uses of Applet:1.Applets are used to provide the dynamic nature to the web pages.2.Applets are used in Animations and games development.

TO CREATE AN APPLET:The following methods should be used: These methods are available in java.applet.Applet and javax.swing.JApplet classes.1.public void init(): (To Initialize)

Page 90: Java

This method is executed only once, immediately after the applet is loaded into memory. We write code to initialize the variables, parameters, to create the components etc...,

2.public void start():This method is executed after init method.It is executed as long as applet receives focus.

We write code to connect to data bases, retrieve data process the data and display the results. therefore start() method is heart of applet.

3.public void stop():This method is executed when an applet loses its focus.We write code to disconnect from the data bases, stop the running threads and perform

cleanup operations.

Note:- start() and stop() methods can be executed repeatedly.

4.public void destroy():This method is executed when the applet is terminated from the memory.We write code related to the task after terminating the applet should be written in this

method.

Note: stop() method is always executed just before destroy() method

IIQ) What is applet lifecycle?Ans see above.

Note: public void paint(Graphics g) method can also be used in applets.Note: There is no public static void main(String args[]) method available in applets.

IIQ) Where applets are executed?Ans Applets are executed by applet engine(JVM) present in the web browser on the client Machine.

//a sample appletex:

Html is a text formatting language.It uses tags to formate the text.

Tag:- A tag is a string constant that formats the text.

<applet> : To embed an applet into webpage.

Page 91: Java

Networking in JAVA

Definition:Inter connection of computers is called Network.

client:A client is a Machine that sends a request for some service.

Server:-A server is a Machine that provides the services to the client.

Protocol:It is a standard specification.

Internet:requirements:- I)H/W

II)S/W III)protocol

Browser:The software which is installed in a client Machine.

Webserver:The Software which is to be installed on an Internet server Machine.ex:- webdynamics, websphere, apache, etc..,

protocol: TCP/IP and UDP TCP/IP:- it is a connection oriented reliable protocol

UDP is connection less unreliable protocol. It is used to sending (or) receiving the movies, photos etc,,

On Internet several protocols are used:1.HTTP:- It is mostly used protocol on Internet.It is used to transmitting the webpages.2.FTP:-(file Transfer protocol)Used for uploading and down loading the files.3.SMTP:-(Simple mail transfer protocol) Used for sending mails.4.POP:- (post office protocol)Used for receiving the mails.

Socket:

Page 92: Java

A socket is a point of connection between a server and the client. It does not exist physically. It exist logically.port number:

It is a unique Id number given to every Socket.IIQ) When you will change the socket port number?Ans 1.If the service is changed you can provide new port number.

2.If you create new socket you can provide new port number.

socket programming:Establishing communication between a server and client through a socket is called socket

programming. It is oldest networking technology.

there are 2 classes provided in socket programming.To create serverside socket:

We should use ServerSocket.To create clientside socket:

We should use Socket class.

ServerSocket and Socket classes are available in java.net package.

ex:- // a server that sends messages to client.

ex:- // a client that receives the strings from server

IP address: It is a unique id number given to every computer on the network.

currently IP address uses 16 bytes(version-6) old version i.e v4 ------- 4 bytes

ex:- 120.33.78.01

DNS: (Domain naming service)Maps website names with corresponding IP addresses.

In DOS,IPCONFIG used to see IP address of computer.

It is possible to run several JVMs at a time in the same system.

RMI: (Remote Method Invocation)Calling methods of remote object(in some other JVM) through a reference is called RMI.

ex:-//Two way communication between client and server.H.w:-1)Develop a server that sends System date and time to the client. Display the date and time at client side.

Page 93: Java

2)write client-server program,so that the client sends the name of a file to the server and the server sends that file content to the client.Display the file contents at client side.[The file should present in the server].