Java
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.
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. 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.
Advantage:
Resource sharing is the Main advantage of the network. That means a) sharing data b) sharing memory c) sharing hardware d) sharing software e) 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)
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.
--> .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.
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. ==> 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.
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.
JVM Architecture
Class 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.
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 comment 2. /* multiple line----comments-----------------------*/ 3./**--java documentation ---comments-----------------------*/ they are useful to create API document from a .java program. API: (application programming interface)
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) Ans what is the difference between #include and import? #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. 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.
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 ============== \n \t \r \b \\ \" \' meaning ======== next line Horizontal tab space enter key Back space displays \ displays " displays '
ex:
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. 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
Data type:
It represents the type of data stored into variable(or)memory. Datatypes and literals:
1.Integer datatypes:
These data types store integer numbers like 125,100000,-10,... int is divided into 4 types.
=>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.
float PI=3.142F; here 4 bytes memory alloted by JVM. Here there is no F,Jvm alloted 8 bytes.
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:
ex:It represents a group of characters. 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;
OPERATORS
operator:
It is a symbol that performs an operation. => An operator acts on some variables called operands to get the desired resuls. ex:- a + b here 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.
9) Member operator ( . ) (or) dot operator 10) Instanceof operator 11) new operator 12) 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 statement 2) do --- while loop 3) while loop 4) for loop 5) foreach loop 6) switch statement 7) break statement 8) continue statement 9) 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 = initialization exp2 = condition exp3 = 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.
Infinite loops :
for(;;) { statments; }
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.
break:
It is used in 3 ways. 1.It is used to comeout of loop. 2.It is used to comeout from switch statement 3.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) Ans what is the difference between System.exit(0) and System.exit(1)? 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 100 2)Test whether the no is even (or) odd 3)Test whether the number is prime (or) not 4)display a multiplication table. 5)display the stars in the form * * * * * * * * * *
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.
double d = Double.parseDouble(br.readLine()); H.W) 1.Accept 2 numbers from keyboard and findout result of their 2.print even numbers between m and n. 3.print fibonacci series up to given number. 4.print prime number series. addition,sub,mul,div.
ARRAYS
It 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
2D arrays:
They represents several rows and columns of elements. ex: Marks obtained by a group of students in 5 subjects. 50,51,52,53,54 60,61,62,63,64 70,71,72,73,74 80,81,82,83,84 90,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.
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.
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 unreliable 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. 1.Mutable 2.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:
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? 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.
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) Ans what is SRS(software requirements specification)? 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.
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 Advantage of inheritance is re-usability. inheritance.
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) Ans what is difference between object oriented programming and object based programming? 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.
Datatype
int float double char String any class boolean
Default value
0 0.0 0.0 a space null null false
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 types 1.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:
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.
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:
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. ex:
Instance Methods:
There are two types of instance methods. 1. Accessor methods 2. 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.
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();
Inner class:
A class within another class. 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
INHERITANCE
IIQ) 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) Ans why super class members are available to sub class? 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. 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 inheritance 2. 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.
ex:
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: 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. |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 CASTING
Type 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) Ans What is the difference between primitive and advanced datatypes? 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.
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.
Ex: (program)
Abstract Classes
concrete 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. 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.
INTERFACES
Definition:
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 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? Ans 1) 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;
PACKAGES
Definition:
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 here d -> define/create sub directory. (Destination folder/directory) . -> Current directory ex: (Package Usage class)
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 set the temporary path and compile and run the main program:
main prog dir:\>javac -cp packagepath;. mainprog.java ex:- e:\work\>javac -cp d:\;. Use.java main prog dir:\>java -cp packagepath;. mainprogclassfile ex:- e:\work\>java -cp d:\;. Use
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) Ans which statement is first executable statement in java program? Package statement should be the first executable statement in java.
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 package also. same package (or) another
To create API:
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{ 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)
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:
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:
3. StringIndexOutOfBoundsException 4. ArithmeticException 5. FileNotFoundException 6. ClassNotFoundException 7. NoSuchMethodException 8. NullPointerException 9. RuntimeException 10. InterruptedException 11. NumberFormatException
2.User-defined Exceptions:
The exceptions created by the user's of the language are called user-defined exceptions.
WRAPPER CLASSES
Wrapper class:
A wrapper class is a class whose object wraps(contains) primitive data type within it.
wrapper class
Character Byte Integer Float Double Long
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. 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.
Constructors:
1. Byte(byte num) 2. Byte(String str)
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:
1)Integer(int num); 2)Integer(String str);
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);
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);
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. 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 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. arg.
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.
IOSTREAMS
Stream:
A Stream represents flow of data from one place to another. There are two types of streams. 1. Input Streams: They read (or) accept data 2. 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: InputStream and OutputStream Ex: ByteArrayInputStream: ByteArrayOutputStream: FileInputStream : FileOutputStream: FilterInputStream: FilterOutputStream: PipedInputStream: PipedOutputStream: ObjectInputStream: It uses a buffer to read bytes.(or)read bytes from array. It writes data into byte array.
Reads data from file. Write data into file. Reads data from another inputStream. Sends data to another outputStream. This should be connected to piped output stream.It reads data that is send to PipedOutputStream. Sends data from one program to another program. Reads objects from a file.
BufferedInputStream: Reads a buffer full of data from another inputStream. BufferedOutputStream:Writes a buffer full of data(bytes) into another outputStream. DataInputStream: DataOutputStream: PrintStream: Reads primitive data types from another inputStream. writes primitive datatypes to another outputStream.
TextStreams:
These classes are derived from the abstract classes: Reader and Writer. Ex: BufferedReader: BufferedWriter: CharArrayReader: CharArrayWriter: InputStreamReader: InputStreamWriter: FileReader: FileWriter: PrintWriter: Reads a buffer full of characters from another inputStream. Writes a buffer full of characters into another outputStream. Reads a character array. Writes a character array. It reads bytes and decodes them into character. It converts characters into bytes and writes them to another stream. Reads characters from a file. Writes characters into a file. 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 -->DeflaterOutputStream To 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) Ans Ex: Which type of variables can not be serialized? static and transient variables can not be serialized.
File class:
File class of java.io package provides some methods to know the properties of a file or a directory.
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. 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.
THREADS
Definition:
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.
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.
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) Ans What is the difference between process and Thread? 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. Note:- A thread will recognise and execute only run() method. 3. create an object to the class ex:- 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) Ans What is the difference between extends Thread and Implements Runnable? 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.
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 ways 1.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 ex:- synchronized return type method(){ method body; }
entire method.
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:
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 Threadl Thread t3 = new Thread(obj,"Thread-name"); //target Object and Thread name are given
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: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.
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 complete its execution first. priority number will
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): 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'
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. 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 hand 3.shunting the coaches to railway engine.
To create a stack:
Stack st = new Stack();
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. 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): 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. 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)
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);
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.
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. IIQ) What is the difference between ArrayList and Vector? Ans 1.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? Ans 1.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.
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.
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.
Locale.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. -----------------------------------CITY CAPITAL FOR -----------------------------------Delhi India Washington America London Briton Paris France ------------------------------------
CLONING
cloning:
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.
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(); } }
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 IIQ) Ans can you write an Interface without any methods and members? yes methods.
IIQ) what is that interface called? Ans An interface without any members (or) methods is called Tagged interface (or) marker interface. IIQ) Ans What is the pupose of such an Interface? A marker interface specifies some information about the class objects.
IIQ) Ans
can you give me 2 examples for Tagged interface? 1.cloneable :- It indicates that class objects are cloneable. 2.serializable: It indicates that class objects will be serialized.
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 title.
A window is a frame without any borders and title. Whereas a frame contains borders and
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.
Adapter class:
An Adapter class is an implementation class of a Listener class where all the methods contain empty body.
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/Strings 2.To display images/photos 3.To display components like push button, radio buttons, check boxes, etc..
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.
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
Button Checkbox CheckboxGroup (RadioButton) TextField Label TextArea Choice List
Listener
ActionListener ItemListener ItemListener ActionListener (or)FocusListener ItemListener ActionListener (or)FocusListener ItemListener (or)ActionListener ItemListener (or)ActionListener
Listener methods
actionPerformed(ActionEvent e) itemStateChanged(ItemEvent e) itemStateChanged(ItemEvent e) focusGained(FocusEvent e) focusLost(FocusEvent e) itemStateChanged(ItemEvent e) focusGained(FocusEvent e) focusLost(FocusEvent e) itemStateChanged(ItemEvent e) actionPerformed(ActionEvent e) itemStateChanged(ItemEvent e) actionPerformed(ActionEvent 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 ex:- removeActionListener(); Note 4: A Listener method takes an object of XxxEvent class. ex:- actionPerformed(ActionEvent e); removeXxxListener() method.
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); 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(); 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 label Label l = new Label("text",alignmentConstant); 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
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 = appearance feel = 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. 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.
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:
} 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:-
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); 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 label lbl.setImage(); // to display image on label 2.JLabel lbl = new JLabel("Text",ImageIcon ii); 3.JLabel lbl = new JLabel("Text",alignment); JLabel.RIGHT JLabel.LEFT JLabel.CENTER are constants.
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);
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 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 data ex: column position:
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 TabbedPane ex:
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 Items 6.Add Menu Items in the 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);
LAYOUT MANAGERS
Definition:
A Layout Manager is a class that is useful to arrange components in a particular manner in a frame (or) container.
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); 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 Demo ex: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.0 default 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_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) 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) Ans What is applet lifecycle? 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 applet ex:
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.
Networking in JAVA
Definition:
Inter connection of computers is called Network.
client:
A client is a Machine that sends a request for some service.
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,,
Socket:
A socket is a point of connection between a server and the client. It does not exist physically. It exist logically.
port number:
IIQ) Ans It is a unique Id number given to every Socket. When you will change the socket port number? 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