Sie sind auf Seite 1von 56

Core Java

Through out history of programming, the increasing complexity of programs has driven the need for better ways to manage complexity. Computer Languages evolve for two reasons to adapt the changes in environment and to implement advances in the art of programming. OOP is a programming methodology that helps to organize complex programs through the use of Inheritance, Encapsulation and Polymorphism. Java developed at Sun Microsystems in 1995.Java is simply the Internet version of c++. The output of a java compiler is not executable code. Rather it is Byte code generated (executed) by a Java Virtual Machine i.e. Java run-time system is an interpreter for bytecode Features Simple To learn java requires little effort since inherits the c/c++ syntax and OOPs features of c++. Object-Oriented Java is simple and easy to extend. In Object Oriented Languages controls data and achieves several benefits ( i.e Programming around its data, who is being affected). Java is 100% OOP language. Everything is an object and must call throw object Java -> j2se -> standard edition (core, adv java) J2ee enterprise edition J2me message edition J2ee, j2me is collection of services, which are platforms not a language. J2se is java compiler programme and java supports all language features. java

Page No 1

Object based language It does not support inheritance, dynamic binding Ex: java script, vb script OOPs Principles Encapsulation It is a mechanism that binds code and the data together. It manipulates and keeps safe from outside interference. I.e Data security Class : Defines the structure (data) and behavior (code) that will be shared by a set of objects. i.e. Each object of a given class contains the structure and behavior defined by the class. And objects referred as instances of class. Thus class is logical and object is physical construct. The data defined by the class are referred to as member variables or instance variables. The code that operates on that data is referred to as member methods. i.e. methods operate on instance data. Public represents that external users of the class need to know and private methods and data can only be accessed by code that is member of the class. Inheritance It is process by which one object acquires the properties of another object. i.e Reusability of code & no wastage of memory. Without inheritances each object need to define all of its characteristics explicitly. A subclass inherits all of the attributes of all of its ancestors. Polymorphism In a non-object oriented language allows different sets of routines with different names But in Object oriented language the polymorphism feature allows different sets of routines that all share the same names i.e. one interface, multiple methods The compilers select the specific action applies to each situation depending on the type of data being passed

Page No 1

Abstraction Complexity is managed through abstraction. Hiding complex data from external resources to reduce complexity. Robust Java is Robust language for the two main reasons Memory Management : Java automatically eliminates managing memory allocation and deallocation (Garbage Collection) Exception Handling :In c++ exceptions (divide by zero and file not found) managed with clumsy and hard. But in java all run-time errors can be managed by program itself. Multithreaded Allows to write programs that do many things at once Ex:In the requirements of multi process synchronization, networked programs. Execution of different parts of program at a time, utilizes cpu maximum time.In vc++ using MFC classes, in c/c++ posix1.0, Distributed As java handles TCP/IP protocols it was designed for distributed applications of internet very efficiently using socket programming. i.e inter process communication In unix using fifo and sema phores,pipe

Page No 1

Architecture Neutral Java language goal was write once; run anywhere, any time, forever i.e even Operating system upgrades, processor upgrades. means different OS and machine, .exe is dependent of platform Using JVM (java virtual machine) the source .java file converts to byte code file (.class), which does not have information of operation system. Java interpreter converts byte code to binary code, to execute java application must contain JVM s/w Java performs following features class loader, byte code verifier,security manager,garbage collector, JIT compiler .class occupies less memory compare to .exe file, command line arguments & environment variables occupies high order memory, local variables in stack area, dynamic memory manager in heap area, static variables in static area, program instructions in text area memory. Java interpreter converts from byte code to binary code and submits to processor, interpreter executes line by line and compiler execute file at a time. JIT compile improves performance of the application. Garbage collector is to clear the unused object, security manager instruct processor to stop the application. Difference between java and c++ Java does not support Pointers, friend functions (no access from outside), destructors, operator overloading, generic templates, no interaction with kernel. Sample Programme /* This is a simple java program Class Example { public static void main (String args[]) { System.out.println( This is my first JAVA prog ); } } Page No 1

The name of the class (Example) should match the name of the file (Example.java) that holds the program. To compile the program C:>javac Example.java Javac compiler creates a file called Example.class that contains bytecode of the program. And it is not the code that can be directly executed. To execute or run the program C:>java Example O/p This is my first JAVA prog While executing java interpreter requires class name and automatically search for a file that has .class extension and interprets code in the class. Explanation /* */ are comments :

The contents of a comment are ignored by compiler, which explains the operation of the program. Java supports three styles of comments Single-line comment: // (for line by line descriptions) Multi-line comment: /* */ Documentation comment: /** */ (is used to produce HTML file that documents the program). Class Example {: Class is a keyword to declare a new class is being defined. Example is an identifier that is the name of the class. { is a opening brace, i.e. entire class definition including class members must be with in opening brace and closing brace }. public static void main(String args[]) { main() : all java applications begin execution by calling main method. But applications in browsers (applets) wont

Page No 1

use main(), since browser uses a starting the execution of applets.

different

means

of

public : it is a keyword and access specifier, the main must be declared public since it must be called by the code outside of its class. static : allows main() to be called without instantiating the class, since main() is called by java interpreter before any objects are made. void : tells to the compiler that main() does not return a value. Main() is different from main(),since java is case sensitive. If program does not having main() the class compiles but java interpreter report error because unable to find main() as program execution starts from main(). String args[] : declares a parameter args, which is an array of instances of the class String, args receives any command line arguments when program is executed System.out.println( This is my first JAVA prog ); System is predefined class that provides access to system. Out is the output stream that connects to console Println() : displays the string on the screen follwed by a newline. All statements in java ends with a semicolon. Class Example2 { public static void main(String args[]) { int num; // this declares a variable num num =100; // assigns num the value 100 System.out.println( this is num :+ num); num = num *2; Systm.out.println( value num *2 is + num); } } o/p this is num 100 value num *2 is 200 Name of the program file should be same as the class name in which main method is defined.

Page No 1

Command line arguments are used to pass information into a program, when it is executed and passed as string. Setting java environment After jdk installation it generates the following folders C:\jdk1.4\bin,lib,doc,example folders Bin directory contains .exe files Javac - java compiler, java - interpreter, rmic rmi compiler, jar to create jar file. Lib directory contains tools Setting path In autoexec.bat file C:> set path = c:\jdk1.4\bin;.;%path% . refers to current working directory c:>set classpath = c:\jdk1.4\lib\tools.jar;.;%classpath%; setting environment for window server system start- setting- control panel system icon advanced environment system variable variable name value Variable name Value path c:\jdk1.4\bin;.; classpath c:\jdk1.4\lib\tools.jar;.;

Java data types


User defined or abstract type or compiler type Primitive data type Boolean Numeric type Integral type (byte, short, int,long) Floating type (float, double) Size of data type byte-1, short-2, int-4, long-8, char-2, float-4, double-8, Boolean 1 bit not byte. Variable: is a named memory location that may be assigned a value by the program, which may be changed during the execution of the program int num;

Page No 1

this line declares an integer variable called num. variables must be declared before they are used. To declare more than one variable use comma-separated list. num=100; assigns to num value 100. + (plus) sign in println statement is used to append the string with the value in the variable num. print() is similar to println() except that it does not output a newline character after each call. Introduction Java is a collection of whitespace, identifiers, comments, literals, operators, separators and keywords. Whitespace: it is a space, tab or newline. Identifier:used for clasnames, method names, identifiers. Consists of uppercase and lowercase letters, numbers, underscore and dollar-sign characters. Identifiers must not begin with number and java is case-sensitive. Ex: TempAvg, a123 // valid identifiers 4abc, be*in // invalid identifiers Literals: it is a constant value Ex: 400, 78.5, b (character constant), prem (string) Comments: single, multiline and documentation comment Single // Multilane /* */ Documentation /** */ Separators: ; semicolon , comma . period terminates statements separates consecutive identifiers in declaration and inside a for statement. used to separate package names from subpackages and classes. And method from reference variable.

() parenthesis used to contain list of parameters in method definition, expression in control statements, casting of types. {} braces defines a block of code, for classes, methods, local scopes, initialized arrays [] brackets used to declare array types

Page No 1

Keywords: Keywords are predefines values. Currently 49 keywords are defined in java language, keywords cannot be used as names of variable, class, or method.

Data Types
Java defines eight simple(elemental) types of data: byte, short, int, long, float, double, and boolean. Simple types are very efficient and atomic types represent single values. Making simple types into objects degrades performance. Because of portability All data types are defined range ex: int always 32 bits regardless of the platform. Integers: This group includes byte, short, int and long which are whole valued signed numbers. C/c++ supports both signed and unsigned integers. but java does not allows, since unsigned was used mostly to specify the behavior of the high order bit. byte : occupies 8 bits (1 Byte) and ranges from 128 to 127 useful when working with a stream of data from a file, a network, or binary data. Short: Occupies 16 bits (2 Bytes) and Ranges from 32,768 to 32,767. short is Least-used java type and stores in big-endian format. i.e. most significant byte is first followed by least significant one. While intelx86 is little-endian. Int: Occupies 32 bits (4 Bytes) and ranges from -2,147,483,648 to 2,147,483,647 int type commonly used in control loops, index arrays. Before any calculation is done, expression involving bytes, shorts, ints and literal numbers promoted to int. long: Occupies 64 bits (8 bytes) and ranges from -9,223,372, 036,854,775,808 to 9,223,372,036,854,775,807. Ex: for scientific applications and to hold large value (19 digits) value

Floating-Point Types
It is also known as real numbers, are when evaluating expressions that requires fractional precision. Ex: square root, sin, cos.

Page No 1

There are two kinds of floating-point types float:It is a single-precision uses 32 bits (4 Bytes) ranges from 1.7e-308 to 1.7e+308 double:Uses 64 bits (8 Bytes) used when to maintain accuracy over many iterative calculations or manipulating large numbers

Characters
Char : is used to store characters in 16 bits (0,65536). In c/c++ char is a integer occupies 8 bits, but in java char uses Unicode to represent all of the characters found in all human languages. Use of Unicode(universal code) is inefficient for languages such as English, German, French since these characters can easily be contained within 8 bits, but for global portability char data type uses 16 bits. Ex: char ch1,ch2,ch3; Ch1=95; ch2=b; ch3=b; Ch3++; System.out.println( ch1 + ch2 + O/p a b c Unicode represent in single quote. Octal \ddd 0-7 Hexa \uddd 0-f Char ch =a; Ch2=\141 ch1=\u061 ( a in hexa format) ( a in octal format )

ch3);

Boolean :Boolean data type can hava only one of two values true or false. It is used in all relational operators, boolean expression of control statements such as if and for . Boolean values true and false do not convert into any numerical representation, java does not equal 1 for true. Ex: boolean ch =true; If(ch) Sytem.out.println( true block); O/p true block Integer Literals Any whole number is an integer ex: 1,34,567 which are decimal values i.e. base of 10.Octal values are denoted

Page No 1

in java by a leading 0. normal decimal number cannot have a leading zero. Hexa decimal with a leading 0x and range is 0 to 15 (a to f for 10 to 15) To specify long literal explicitly tell the compiler by appending letter L to the literal. Floating Point Literals Floating point numbers can be expressed either standard or scientific notation. Standard notation : consists of a whole number followed by a decimal point followed by fractional component. Ex: 2.4, 3.14 Scientific notation: uses standard notation, floating point number plus a suffix that specifies a power of 10 by which number is to be multiplied Ex: 6.22e21, 314e-05 To specify a float literal must append F or f to the constant and double literal by appending D or d Ex : double a = 4567.23d; Character Literals Characters are represented in Unicode which occupies 16 bits (2 Bytes). A literal character is represented in single quote such a, *. Use backslash followed by the three digit number for octal representation ex:\141 is a. use \u followed by 4 hexadecimal digits for hex representation ex: \u061 is the ISO-latin a. Ex : char ch=a; String Literals String literals are specified by enclosing a sequence of characters between a pair of double quotes. Ex: String s1 = Prem Prakash String s2 = \Prem Prakash\ ( to store within double quotes) Java strings must begin and end on the same line. There is no line-continuation escape sequence. Variable A variable is unit of storage with scope, which defines visibility and lifetime. All variables must be declared before they can be used. The identifier is the name of the variable. Page No 1

To declare more than one variable use a comma-separated list. To initialize a variable specify a equal sign and a value. Variables declared within a method will lose its value when the block is left.

Casting
When one type of data is assigned to another data type variable, an automatic type conversion will take place if the two types are compatible (or) the destination type is larger than source type upcasting : small size to big size byte b=10; int I; I=b // valid implicit casting Downcasting : big to small Byte b; int I=10; B=I; // invalid compiler error B= (byte) I // explicit / narrow casting.

Operators
Arithmetic Operators : + - * / % (modulo, remainder), ++, --, +=, *=, /= Bit wise Operators Operates on individual bits of their operands Java uses 2s compliment to store negative numbers 42 00101010 -42 11010101 + 1 = a b 0 0 1 1 0 1 0 1 11010110

a&&b a||b a^b 0 0 0 0 0 1 1 1 0 1 1 0

&& both must be true to get true || any one must be true ^ exactly one must be true but not both Relational Operators Determines relationship between one operand and another

Page No 1

Ex: < > <= >= ==(equal to) != (not equal) boolean a = true In java true and false do not relate to 0 and 1

Assignment operator Int x,y,z allows chain of assignment X = y =z =100 ? operator (ternary) exp = exp1 ? exp2 : exp3 ex: c = a>b ? a: b; if exp1 is true the exp2 assigns to exp if exp1 is false the exp3 assigns to exp Control Statements Selection : Iteration : Jump : allows to choose different paths repeat one (or) more statements allows to execute in non-linear fashion

Selection Statements
Simple If: Only if block contains. If-else used to route program execution different paths if(condition) st1; else st2; Nested if statement If(condi) { if(cond) { st1; st2; st3; }} if-else-if Ladder : sequence of nested ifs if(cond) st1; else if(cond) st2; else if(cond) st3; :If statement contains another if-else through two

Page No 1

if cond is true associated statement is executed and rest of ladder is bypassed.Otherwise else block is executed. Switch :Multiway branch statement, easy way to switch different parts code based on value of expression Switch(expre) { case val1 : st1; break; case val2 : st2; break; case val3 : st3; break; default : st4; } Expression can return any simple type and must be compatible with case values.Each value is unique literal not a variable. The case value of the expression is compared with each of the literal in the case. If match is found following case statement is executed. If none of the matches then default statement is executed. Break statement inside switch is used to terminate sequence and control follows after entire switch statement. If omitted continues onto next case A switch statement will run faster than the equivalent logic using if-else (since compiler knows case constants type and only must be compare for equality).

Iteration Statements (loops)


Loop repeatedly executes the same set of instructions until termination condition is set. While:repeats a statement/block until condition is false While(condition) { body of loop } condition must be any boolean expression, loop executes as long as condition is false and control passes to next line of code after loop. The body of the while can be empty i.e null statement ex: while(cond); Do while : this loop always executes body at least once. Because conditional expression is at the bottom of loop do{ Body of the loop }while(condition);

Page No 1

if condition is true the loop will repeat otherwise terminates. It is ueful for menu selection process for : for(intialization; condition; iteration) { body }

initialization is executed only once, while entering into loop and acts as counter variable. Condition to test loop control variable if expression is true, loop is executed otherwise loop terminates. Iteration is used to increment or decrement loop control variable multiple statements are allowed both in initialization and iteration counter by separating using commas. If all 3 parts of the loop are empty then infinite loop creates(as there is no condition).java allows loops to be nested.

Jump Statements
Transfers control to another part of the program Break : terminates a statement sequence in switch or loop Break statement in inner loop causes terminates of that loop, outer loop is unaffected, break is a form of goto. Useful when a existing from a deeply nested loops. break label; label is name of a label that identifies block of code i.e control transfers to named block of code.Labeled block of code must enclose break statement. Continue : to continue running loop but stop processing the remainder of the code in the body. Continue statement transfers control to condition expression in while loop. In for loop goes to iteration counter. Continue may specify label as in block Return : explicitly return from a method. I.e. transfer the control to the caller of the method. Return statement in main() causes control to move to java-run time system. Exit(0) : moves the control out of the java program

Page No 1

Arrays
It is a collection of similar type of elements, which may be int,char,float, can have one or more dimensions accessed by its index. Ex: int a[5]; is allowed in c, but it is not allowed in java. Arrays are objects not variables. Using new actual physical memory is allocated , and array index starts from 0. int a[]; // declaration a[] = new a[5]; // allocation a[4]=5; // assignment a[10]=45; // not a valid statement throws exception since out range of an array, causes run-time error. Intialization of an array : int b[] = {1,2,45,-67}; while initializing an array new operator is not necessary, the compiler counts, and allocates memory. Int n = a.length; length is a variable from jvm which returns number of elements in the array. To display array elements For(int I =0; I<a.length; I++) System.out.println(a[I]); Multidimensional dimensional arrays Int a[][] = new int [4][5] //allocates 20 * 4 Bytes Int a[][]={ {1,2,3}, {4,5,6}, {7,8,9}}; // initialization It is not need to allocate same number of elements each dimension. Int a[][];l a[0] = new int[1]; a[1]= new int [3];

Methods
Page No 1

Method is set of statements to perform a certain task, like function in c. Methods must be invoked only through objects of its class, it can be parameterized and returns any value (or) object

OOPs (Object Oriented Programming)


It is a concept not a language, which provides the following features. C++ Encapsualtion Method Overloading Constructors Destructors Operator Overloading Inheritance Polymorphism Template Exception Handling Multi Threading Container ship Object Persistence Object Concurrency t t t t t t t f t f t f t java t t t t f t(mi) t f t t t f t c# t t t t t t t f t t t f t

There is no language which supports all of the above features, any language which supports basic features Encapsulation, Method overloading, Constructors, Inheritance, polymorphism is called Object-oriented Programming language. Encapsulation: it is mechanism that binds code and data together in a class and keeps safe from external interface. Acquires data security, hiding data from other classes. To achieve encapsulation classes and objects are required. Polymorphism :Two or more methods with single name, but differ in parameter list, it may be type or number of parameters. But not in return type. Poly means many, morphs-forms ex: polytechnic, polyclinic. which allows different sets of routines that all shares with single name. In non-object languages different sets of routines for different names. Behaving differently at differently places.

Page No 1

Inheritance : process by which one object acquires properties from another object (parent). Repetition of code is reduced and no wastage of memory. Reusability, reusing existing classes

Abstraction : to manage complexity. Template: same variable, with different functionality, which is place holder in the program, to replace required data type at runtime. Are used to create generic functions and classes. Exception Handling: To handle run-time errors which results abnormal termination. Normal termination returns to 0 to OS, then clears memory allocated to process. Compile time errors : these are syntax error, which are handled by compiler. Runtime errors : these are unknown instructions, at the time of execution of application, handled by developers while writing the code. Ex: Unknown instruction divide by zero, results 1 to Os, so child is not cleared in the memory { loss of data, on creating again, many child process in the memory } Using exception skip all statements and takes to normal termination then child process clears Operator Overloading: all operators are part of compiler, and without changing original meaning and possible to extends functionality. i.e addition of numeric values but not with objects, Mutlti Threading : Execution of different parts of same application at the same time. Thread is part of an application, to utilize the maximum cpu time. Containership : class containing class, poor feature in java Persistence : Storing object serialization concept in java into a file, using

Object Concurrency : number of clients sharing same object

Page No 1

Class
Are used to define new Data type, which can create new objects of that type called instance of the class. A Class is logical construct and an object is physical construct. (or) it is an blue print of something. In c++ default is private access, java is default access specifier only. A class defines data (structure) and methods (behavior) that are shared by set of objects. Objects are instances of class. Without creating object, data cant be accessed, class members will not acquire memory Object: Instance of the class or physical entity of the class. It is collection of data & methods to manipulate the data. Methods in a class are shared by all objects, method must be invoked only through object only (or) class if method declared as static. Syntax: class classname{ type instance-variable1; type instance-variable2; returntype methodname1(Parameter list){ // body of the method; }} class Emp { int num; float bs; String name[15]; Void setData() { num=100; bs =20589.45; name=prem; } void putData() { System.out.prinln( number = + num); System.out.prinln( basic = + bs); System.out.prinln( nume = + name); }

Page No 1

public class test { public static void main(String args[]) { Emp e = new Emp(); e.setData(); e.putData(); } } The data or variables defined within a class are called instance variables. The code to manipulate this data contained within methods. Each instance (object) of the class contains its own copy variables, thus the data for one object is separate from other object. i.e. changes to instance variable of one object have no effect on the instance variable of another In single .java file can have any number of classes and java compiler automatically generates class files. (or) can put each class in its own .java file. Obtaining objects a class is two-step process. Declare a variable of the class type, which does not define an object. i.e. it is a variable that can refer to an object. Second acquiring and physical copy of the object and assign to that variable using new operator. new operator dynamically allocates memory for an object and returns a reference (address) to a variable. The class name followed by parenthesis specifies the constructor of the class, constructor defines what occurs when object is created. If no explicit constructor is specified then java automatically supplies a default constructor. Object initializes number to zero, objects Boolean to false. But not for local variables. Emp e1 = new Emp (); Emp e2 = e1; to null,

Page No 1

e1,e2 objects refer to same memory. i.e. assignment of e1 to e2 did not allocate memory,only copy of reference. So any changes made through e2 will affect the object e1 . type methodname (parameterlist) { // body of method } type specifies the type of data returned by the method. if does not return then type is void. Method name any valid identifier with in scope. Parameter list sequence of type and identifier separated by commas. Parameters are receiving variables, sending variables are arguments. return value; value can be primitive (or) object. e.setData(); transfers the control to object e, setData() executes the statements in the body then return to calling routine. Methods always invoke with same object of its class. So variables in the method implicitly refers instance variable of the invoked object. String name = e.getName(); Type of value returned by method must be compatiable with receiving variable. setX() getX() isX() toX() readX() writeX() receiveX() sendX() to store data onto object returns data from the object for checking status conversion method, toLower. to read from local resources to write onto local resource socket/network/remote to send to remote target

Constructors
To Initialize an object, instead of initializing all variables in the class by some method. It is member of class which invokes when object is out of scope. Rules: *Invoking constructor has the same name as the class. *Have no return type, not even void. *Java creates default constructor, if explicitly constructor is not defined, initializes with zero. *always called with new operator *access specifier is default *constructor can be overloaded

Page No 1

this
used when a method needs to refer to object that invoked. i.e this always refer to invoked object of the method. Emp(int num, float bs, String name) { this.num = num; this.bs = bs; this.name = name; } this resolve collisions that might occur between instance and local variable. When local has the same name as an instance variable then local variable hides the instance variable, so to overcome the instance variable hiding this is used. Otherwise use different local variable names than instance variable names, but for clarity to have same names this can be used. this can call another constructor of same class Emp(int n) { int (n, emp.getName(); }

Overloading
Defining two or more methods with the same method name with different parameter declaration, overloading on the methods is called polymorphism. Signature: it tells name of the method, number of arguments and type of arguments. Return type is not part of the signature. Overloading methods must differ in the type or number of parameters and return type is not considered. if match is not found then javas automatic type conversion takes place. Ex: integer to double. If method overloading is not supported by java language then each method must given a unique name. In addition to overloading method, constructors also be overloaded.

Page No 1

There are 2 ways that argument can be passed Call by value : this method copies the value of an argument into the formal parameter of a function, if changes made on the parameter, no effect on the argument used. Ex: simple type. Call by reference : reference of an argument (not a value) is passed to the parameter. Changes made to the parameter will affect the argument used to call the function. Ex: objects are passed by call-by-reference. Recursion : a method that calls itself. A recursive call does not make a new copy of method, only arguments are new onto a stack. When returning, parameters are removed from stack. Ex: quick sort algor, Artificial intelligence examples When writing recursive methods, there must be if statement to break the method otherwise method executes infinitely.

Static
Static members can be accessed before any objects of its class are created (or) without reference to any object. Ex: main() is declared static before any object exist. because it must be called

Declaring instance variables as static act as Global Variable. I.e all instances of the class share the same static variables. Restrictions: They can call only static methods and static variables. They can not refer to this or super. Illegal to access any instance variable in static method. Declaring static block to which executes only once. initialize static variable

To call a static method or variable from outside of its class. Ex: classname.method() or variable. Without creation of object, can be accessed using class name. Static fields do not operate on any instance field of a class. I.e without creating an object, no this operator as object is not created.

Page No 1

Inheritance
A class that is inherited is called super class, a class that does inheriting is called subclass. i.e subclass inherits all instance variables and methods defined by super class and add its own, unique elements to inherit a class use extends keyword. A subclass is completely independent of stand alone class and further it can be super class for another subclass. Java does not support inheritance of multiple super class into a single base or child class, but allows multilevel inheritance. Private members of super class can not access into sub class. A reference variable of super class can be assigned to any sub class derived from that super class.

Super
When ever a sub class needs to refer to its immediate super class, can do using super. Super is used to refer super class members that has hidden in sub class. Ex: local variables hides instance variables. Using super, constructor defined in super class can be called and always must be first statement executed inside sub class constructor. Super(parameter list) for constructor Super.member Member can be either method or variable of super class, if super is not used then default constructor of each super class will be executed first than sub class constructor. If subclass constructor does not call a super class explicitly,then super class uses no argument constructor.

Overriding
Page No 1

Method in the sub class is said to be override, the method in super class. I.e super class method is hidden by sub class method. It is possible when subclass method has same name and type signature as in super class. So to access super class method which are hidden can get by using super.

Final
Final variables prevents its contents, modified (lly to constant in c++). Ex: final int a=10; from being

Use Upper case identifiers for final variables which is coding convention. Final variables do not occupy memory per instance. Methods declared as final can not overridden cant modify). To prevent a class from geing (sub class

Dynamic Method (Run-time Polymorphism)


Calling overridden function at runtime rather than compile time is implementation of runtime polymorphism. By using a reference of super class variable can refer to a sub class object. {lly to virtual function in c++ }

Abstract class
If one or more methods have no implementation in super class then abstract modifier must specify for class & method and compulsory must override otherwise subclass becomes abstract. Abstract class cannot be instantiated with new operator since it is not fully defined class It is not possible to declare abstract constructors or static methods. But used to create object references to approach run-time polymorphism by pointing to any subclass object.

Page No 1

A class can inherit only one abstract class Extend abstract class, to create an instance and create reference of abstract but must refer to non-abstract.

Interface

Similar to class and all methods are declared without any body using interface keyword. On implementing an interface using keyword implements by a class then set of all methods must be defined, otherwise class becomes abstract. Used to support run-time polymorphism method from one class to anther. and to call a

Access specifier is either public by default, and so it is not necessary to specify to public. Methods which are declared, have no bodies must ends with Semicolon. Interface name can be any valid identifier. Class that includes interface must implement all methods. Variables are implicitly final and static and cannot change in implementing class. All methods and variables are interface is declared as public. implicitly public, if

Access class classname [extends superclass] [implements Interface[,Interface2]] { class body } an interface reference variable can refer methods declared by its interface but not other methods in implementation class. If class includes an interface, but not fully implemented then class must be declared abstract. Through interface reference variable, java achieves runtime polymorphism.

Page No 1

Object
Object class is super class of all other classes. I.e reference of object type can refer to any other class. Ex: Object a = new myclas(); Methods: boolean equals() compares contents of two objects void finalize() called before an object is destroyed Class getClass() obtains class of an object at runtime void notify() resumes execution thread string toString() returns a string, describes object void wait() execution of thread waits. Object clone() creates a new object.

Packages
Package is a container of classes used to avoid class name collisions. Like class is container for class & method. Creating package: package pkg1[.pkg2][.pkg3]; it must be first statement in java source file, if omitted class name puts into default directory (working). It includes other class from being part of same package. Access is default with in package only, on declaring public can be accessed from anywhere Ex: default package is java.lang package Importing: Import pkg1[.pkg2].classname | *; Public : accessed from any where Default : within same package of sub-class & non-subclass Protected: same as default, and can access from different package of subclass. Private : accessed by members of its class

Page No 1

Garbage Collector
In c++ objects must be released by delete operator using destructor, when object goes out of scope. But in java this technique handles de allocation automatically. When no references to object exist. Memory occupied by the object can be reclaimed by GC automatically during execution of program Garbage collector is a technique for de allocation of memory automatically during execution of program when no references to object exist. Protected void finalize() { body } java runtime system calls finalize method, when ever object of that class is about to destroy by garbage collector. So specify those actions in the finalize that must be performed before an object is destroyed. object holding an non-java resource such as file handle (or) window character font must be freed before object is destroyed.

Exception Handling
To handle abnormal termination at wastage, exception handling is used. runtime and memory

When program terminate normally system resources get cleared automatically. Other wise not cleared, to clear system resources need to handle runtime exception, java provides follwing keywords try, catch, throw, throws and finally. Object -> throwable ->error Object -> throwable -> Exception ->RuntimeException Error class is to handle exceptions which are raised before starting an application. Jvm failures and thread death errors, current version of jdk is not implemented, reserved for future purpose.

Page No 1

Exception class this is to handle exception, which are raised after starting an application, which are recoverable errors. I/O Exception to handle exceptions, to perform I/O transactions, with external resources like keyboard, database server, tcp server and others. Interrupt Exception this is to handle exception which are raised when application is in waiting for shared resources.Runtime Exception to handle exception, when application is currently running. When exception condition arises, object representing that exception is created by jvm and thrown in the method. Exceptions can be generated by java run time system such as violating rules or java language. Java runtime system detects exception such as divide by zero, creates new exception and throws, which must be caught by an exception handler. If exception handler is not supplied then default handler in jrs catches the exception and returns the string describing the exception and terminates the program. Methodname, filename, linenumber are included in stack trace. Java.lang.ArithmeticException / by zero At excep.main(excep .java. 4) Trycatch To handle exception by program itself, which prevents from automatically terminating programme. To handle a run-time error, enclose the code to monitor inside try block and include catch by specifying exception type. Once exception is thrown, a control transfer out of try block into catch block and continues next line following try/catch mechanism. The statements in try and catch must be surrounded by curly braces. Throwable object overrides toString() and returns a string containing a description of the exception. Page No 1

Jvm identifies type of exception and creates instance of type exception, after creating exception then jvm looks for catch block with appropriate exception, if catch is not found, then jvm terminates application abnormally, if catch is found then control enters into the corresponding block and program comes to live and execution starts. Any statements after exception, try block will not be executed Mutliple catch clauses : In some situations, two or more catch clauses can be specified each catching different type of exception. When exception is thrown, each catch is order, if any catch executes others are continues after try/catch block. Ex: ArithmeticException, inspected in bypassed and

ArrayIndexOutOfBoundsException

Exception subclasses must come before any of Exception super class. Exception must not be first catch. Nested try catch Try statement can be nested, i.e try statement can be inside the block of another try. Each time try statement is entered, corresponding exception is pushed onto a stack, if inner try does not have catch handler, next try statement catch handlers are inspected from stack. throw Previously exceptions are catched and are thrown by java run-time system. Using throw keyword, it is possible to throw an exception explicitly. Which must be object of type throwable (or) subclass. throw new throwableinstance; using a parameter into a catch(ArithmeticException (or) throw new ArithmeticException e e)

all javas built in run-time exceptions have 2 constructors, one with no parameter and other takes string parameter. To print string use method getMessage(), printStackTrace(). Page No 1

throws a method causing an exception, but does not handle then it must specify exception using throws clause. So that callers (users) of the method can guard themselves. Type methodname (para list) throws exception-list { // body of the method } finally finally block will execute whether or not an exception is thrown. Which is optional. For each try statement requires a catch or finally clause Useful for closing file handlers, freeing up any resources. Creating own exception Javas build in exception handle most common errors, but to create own exception to application, define a subclass of exception (a subclass of throwable), so override toString().

Page No 1

I/O Streams
Used to perform I/o operations in programs, a stream is a abstraction that either produces or consumes information. Input stream can abstract many kinds of input from disk file, keyboard, network socket. Stream is link between physical device and java I/O system. Javaio system -- stream --physical input / output device Streams are useful differentiating between to deal with I/O, keyboard, network. without

Java provides two types of Streams Byte stream 2) character stream Byte Stream : it handles one byte of data at a time, it works only with ascii keyword set. Character stream : it handles two bytes of data at a time, it works with any keyword set across world wide, this is to handle unique code character. Java implements streams with in java.io, having two abstract classes InputStream and OutputStream in which read() and write() bytes of data are abstract methods. Java.lang.System obtains several aspects of java run time environment. Ex: predifened variables in, out & err. Which are public and static, means that can be used by other part of program and without reference of System class object. Out refers to standard output (console), in refers to input (keyboard) and err refers to error stream. These streams can be redirected to any I/O device. Reading console input Input is accomplished by reading inputstream. Java.lang.InputStream of bytes from

Page No 1

int read() throws IOEXception reads a single byte from IS and returns an integer value. It returns 1 when end of stream is encountered. Public int read(byte [] b) Number of bytes transfers from file to byte array Public long available() This method returns number of bytes still available current position to end of file. Public void close() To close the file. System.in is line buffered, means no input is passed to program until enter is pressed.To redirect input c:>java sample < example.txt OutputStream It is an abstract class it provides abstract methods, which are implemented at child class levels. Public void write(int c) Public void write(byte[] b) To write array of bytes to a file Public void flush() To clear the file data Public void close() To clear the file. Reading a string By using read() to read characters into bytearray(), converting into string object. (or) ReadLine() reads sequence of characters from stream and returns them in string object, but it is in DataInputstream. FileInputStream This class provides constructor to open a file FileInputStream(String path) It provides to open a file in reading mode, if file is already exist then opens the file and sets a pointer to a from

Page No 1

beginning of the file, if the file is not found then throws FileNotFoundException. Reads as single byte from a file and returns integer value. If returns 1 end of file encountered. FileOutputStream This class provides constructor FileInputStream(String filepath, Boolean append) Append=flase write mode; append= true append mode

In write mode, if file already exists then constructor opens the file and truncates the previous data, if file not found then write mode creates the file. In append mode, if file already exists then opens the file and place file pointer at end of the file. So data appends the file. If file is not found, then append mode creates the new file.

Strings
A string is a collection of characters. [ in c++ string is a collection of characters terminated by \0]. Once string object is created, cannot change the characters, i.e each time string is altered a new string object is created. So strings are immutable and efficient than changeable (StringBuffer). String and StringBuffer are defined in java.lang as final. So there are automatically available for all programs and neither of these cannot be sub classed Contents of string instance cannot be changed after if has been created. Variable of string reference can be changed to some other string. Constructors Empty string String s = new string() Initializing with array of characters Char a[] = {a,b,c}; String s = new String(a); Initializing with subrange of characters Page No 1

String(char a[], int stindex, int numbchars) String s = new String(a,3,2) Javas char type uses 16 bit Unicode character set, but strings uses 8 bit from ascii character set. String(string obj) String s = new string (prem); String s1 = new String (s); int length() returns number of characters in the string

String literals Earlier to create string new operator is used, but for string literal java automatically construct object. Ex: String s = prem Concatination + for concatenation of two strings, producing string object as result. String name = prem; int age=29; String s = name+age o/p prem29 String s= name+(29+4) 0/p prem33 Conversion toString() Returns a string, which is overloaded for all simple types and object type. When emp object is used in concatenation emps toString() is automatically invoked. Character Extraction To extract a single character from a string Char ch = s.charAt(1); getBytes() puts the characters into an array of bytes toCharArray() convert all characters in a string object into character array char ch[] = s.toCharArray(); Searching a string

Page No 1

To search a string for specified char or sub string, indexOf() searches for first occurrence. String Comparision To compare two strings equality (same Contents) boolean equals(Object string) To compare and ignores case differences boolean equalsIgnoreCase(String obj) TO find given string begins with specific string boolean startsWith(String str) To find given string ends with specific string Boolean endsWith(String str) equals compares the same characters inside string == compares two object references to same instance compareTo() whether two strings are identical, used for sorting applications and returns < 0, >0, =0. <0 means invoking string is less than object string trim():returns invoking trailing spaces. string with no leading and to

valueOf(): converts data from its internal format human readable form. same as on calling toString() toLowerCase(): converts upper to lower. ToUpperCase(): converts lower to upper. all all characters characters in in string string

from from

substring() : to extract a substring from string. String substring(int start, int end)

StringBuffer
String is fixed length, immutable character where as StringBuffer is growable character sequence. Where inserting, appending is allowed. Allocates more characters memory than actually needed. Constructors

Page No 1

StringBuffer() reserves for 16 characters StringBuffer(int) sets the size of the buffer StrinBuffer(String str) object string size + 16 bytes Reallocation is a costly process in terms of time. I.e fragment memory (changing location). length() : current length of String Buffer. capacity() : total allocated capacity. ensureCapacity() : allocate for certain number of chars. setLength(int) : value less than capacity than characters stored, otherwise data will be lost. value greater than size null characters will be added. charAt() and setCharAt() to obtain a single character from SB. To set (modifyt) the value of character with in SB. getChars(); to copy substring of SB into an array getChars(int source, int end, char a[], targetstarting) append() concatenation any other invoking string buffer. type of data to the end of

insert() inserts one string into another. Sb.insert(2,prem); reverse() reverse the characters with in sb.

Page No 1

Applet
Contained in java.applet, applet are small programs which are automatically installed and are part of document, all applets run in a window, so include java.awt. Applets are not executed by java runtime interpreter rather at java compatible web browser (or) appletviewer. Execution of applet does not begin at main() and output of applet on window, not performed by sop() rather it is handled by drawstring(), output a string to specified at x,y location. Input is handled differently Once applet is compiled and included in HTML file using applet tag and executed by java enabled web browser. applet interacts with user, using awt not I/O console. <applet code </applet> = myapplet width =300 height =300>

Applet -> Panel -> Container -> Component Thus applet provides all necessary window having number of methods

activities

Applet is window based & event driven program rather than console programs.Each interaction on applet as events, to which applet responds. Applet contains various controls Buttons, Checkbox, user interact with these controls and event is generated. Applet controls its execution by 4 methods which have to override. init() first method to be called, for initializing variables, executes only once during run time. start() called after init(), on restarting, it is called for each time an applet HTML document is displayed on the screen (back, forward). paint() called each time when applet output is redrawn, i.e window overwritten by another window, applet window minimized, restored or applet begins execution. stop() when browser leaves html document containing the applet. Ex: when control goes to another page.

Page No 1

destroy() when applet is removed from memory completely. At this time any resources using by applet must free up. update() default fills an applet with default color and then calls paint().Use different color then user will experience a flash of color. drawstring() to output a string in applet use drawString() of Graphics class in paint (or) update. To start line of text on another line must do manually by specifying x and y. for setting colors setBackground(Color newcolor) setForeground(Color newcolor). default foreground black and background is light gray. is

Color.black, blue, cyan, darkgreen, gray, green, lightgray, magenta, orange, pink, red, white, yellow To obtain current setting getBackground() getForeground() Color ab = getBackground(); applet writes to its window when update or paint method are called by AWT. Applet itself updates the window, when information changes call repaint().Cannot create a loop inside paint(), to repeat so call repaint(). repaint() painted is used to repaint window, region can be

statusWindow() to display information in feedback what is happening.

applet

window,

used

for

Applet class inherits mouse events and keyboard event from Component class i.e mouseDown(), mouseDrag(), mouseEnter(), mouseExit(), mouseMove(), mouseUp(), keyDown(), keyUP(). To determine if a key event was generated by user pressing one of these constants event.F1,F2 .. F12, PGDOWN, PGUP, LEFT, RIGHT, UP, DOWN, HOME, event.END. <applet codebase = url code = appletlike alt=altext name = appletinstance width =pixel height=pixel vspace = pixel hspace=pixel > <param name = attributename value = attributevalue> <param name = attributename value = attributevalue> </applet> Page No 1

codebase: base url of the applet, i.e directory. If not specified html documents url directory. Code: name of the file that contain applet .class file relative to codebase. Name: specify name for applet instance, to communicate with other applets on the same page Width & height : gives the size of the applet area. the applet,

Align:alignment of left,right,top,bottom,middle

Vspace : specify space in pixel above & below applet. Hspace : specify space in pixel on each side of applet. Param name and value Allows to specify arguments in html type, applets access this arguments using getParameter(). Passing parameters to applet getParameter() returns the value specified parameter in the form of string object. (for numeric and Boolean values need to convert) java allows applet to load data from the directory that hold html file that started applet (document base).The directory that applet class is loaded (code base) which returns URL objects. Applet Context and showDocument() ShowDocument is used to transfer control to another URL . AppletContext is interface, gets information of applet excution environment. getAppletContext() : currently executing applet context, by obtaining applet context, another document can be view using showDocument(). showDoucment(URL) shows document specified at URL. System.out.println() output is not sent to so use appletviewer or in browser. appletwindow,

Page No 1

Abstract

Window Tool Kit (awt)


create and

Contains numerous classes and methods to manage window for supporting applet window Componet -> Container -> Panel -> Applet Componet -> Container ->Window -> Frame

Component : It is abstract class contains all attributes of visual components. containing 100 s of public methods for managing mouse, keyboard, sizing the window, repainting, fore & back ground colors. Container : It is abstract subclass of Component, which allows other components to be stored inside container and layout features methods Panel : Super class for Applet, it is a window, with no title bar, menu bar (or) border, while running applet. Add() is used to add components onto a panel and other methods are move(), resize() , reshape(). Window : Creates top level window, to create window use subclass of window called Frame. Canvas : Not part of hierarchy, it is a blank window upon which can draw. Frame : It has title bar, menu bar, borders, resizing ( java.awt.Frame ) Constructors : Frame(), Frame(String); Methods : v show() after window has been created, it is not visible until show() is called v hide() to remove it from view. v setTitle(string) to change title in the frame window v resize(int w, int h) to set dimensions of the window b handleEvent(Event e) to handle event, when window is closed, return true (or) pass the event to super class having various id codes for various events. To create a Frame , create subclass of Frame and override methods and Events java.awt.Graphics Origin of window is (0,0) , output takes place through graphics context and Graphics class void drawLine(int sx, int sy, int ex, int ey) void drawRect(int top, int left, int w, int h) void fillRect(int top, int left, int width, int height)

Page No 1

void drawRoundRect(int t, int ydiam)

l, int w, int h, xdiam,

void drawOval(int top, int left, int width, int height) void fillOval(int top, int left, int width, int height) void drawArc(int top, int l, int w, int h, int , int) void fillArc(int top, int l, int w, int h, int , int) void drawPolygon(int x[], int y[], int num) void fillPolygon(int x[], int y[], int num) java.awt.Color to create own color color(int red, int green, int blue) values 0-255 color(int rgbvalue) HSB(hue, saturation, brightness) value 0.9 1.0 Methods: getRed() getGreen(), getBlue(), getRGB() void setColor(Color cr) to set new color Color getColor() to get curren color setting java.awt.Font Font(name,style, size) Name- TimesRoman, Courier, Arial Style- font.PLAIN, font.BOLD, font.ITALIC Font f = new Font(Arial,Font.BOLD | Font.PLAIN, 20); setFont(f); String[] getFontList() returns an array of strings that contains names of fonts String [] fl = getToolkit().getFontList(); Font f = getFont() to find currently selected font. f.getName(), f.getStyle(), f.getSize() FontMetrics determines spacing between lines of text and finds length of a string and centering text Controls These are components allows user to interact with application. Ex: Label, Button, Checkbox, List, Scrollbar, TextField, TextArea create instance and add it to window Page No 1

Component add(Component obj) which returns reference of the component void remove(Component obj) Except label (Passive control) all other controls generates event When user clicks Button override eventHandle called action() Boolean action(Event eo, Object arg) eo describes the event, arg reference to object Label java.awt.Label Contains a string, do not support to interact with user . Label(), Label(String), Label(String, int how) how specifies Label.Left, Label.RIGHT, Label.CENTER void setText(String) String getText() void setAlignment(int how) int getAlignment() Button It is a component that contains a label and generates an event when it is pressed. Action() receives all events generated by all controls and later comparing the string in arg. add() returns a reference to button String getLabel() Checkbox (or) RadioButton

It is an Control used an option on or off, changes state of checkbox on clicking on it. Checkbox(), Checkbox(String str); Checkbxo(String, checkboxgroup, Boolean); boolean getState() String getLabel() CheckboxGroup To create exclusive checkboxes in checkbox can be checked at a time. which one and only Void setState(boolean b) void setLabel(String str)

Checkbox getCurrent() to find currently selected Void setCurrent(Checkbox which) String str = cbg.getCurrent().getLabel(); of selected checkbox to get label

Page No 1

Choice To create a pop list of items, choice is form of menu, if shows only single item void addItem(String) getSelectedItem() int getSelectedIndex() void select(int index) name) String getItem(int index) List Provides multiple choice, scrolling selection list List(), List(int rows, Boolean multiselection) void int int[] String String int countItems() void select(String

Void addItem(String name) addItem(string, int) String getSelectedItem() getSelectedIndex(); String[] getSelectedItems() getSelectedIndexes() int countItems() getItem(int index) Scrollbar

To select values between specified minimum and maximum. Slider box can be dragged to a new position. Scrollbar() default vertical scrollbar Scrollbar(style) Scrollbar.VERTICAL, Scrollbar.HORIZONTAL Scrollbar(style, initvalue, thumbsize, min, max) int getValue() value) int getMinimum void setValues(int

int getMaximum()

by default incr/decr by 1, page incr/decr by 10 void setLineIncrement(int newcr) void setPageIncrement(it newcr) Scrollbar are not passed to action() rather handleEvent()

by

Page No 1

TextField To implement a single line text. TextField() TextField(int) TextField(String) TextField(String,int) String getText() void setText(Sting text) String getSelectedText() Void select(int, int) void setEditable(Boolean) Boolean isEditable() Void setEchoCharacter(char) char getEchoChar() TextArea Multiline editor, instead of single line TextArea() TextArea(lines, chars) TextArea(String)

getText() setText() getSelectedText() select() void appendText(String) void insertText(Str , int index) void replaceText(String, startindex, endindex) MenuBar & Menu Menubar displays a list of top-level menu choices, consisting of one or more menu objects, each men object contains list of menu items, menuitem represent that can be selected Menu(String name) Menu(String name, Boolean) MenuItem(String item) void disable() void enable() setLabel(String name) String getLabel() Boolean getState() MenuItem add(MenuItem mi) Layout managers Layout manager is interface components in a container to set layout, arranging void

Menu add(Menu mn)

Void setLayout(LayoutManager obj) FlowLayout it is default Layout Manager, how words flow in a text editor FlowLayout() how specifies FlowLayout.CENTER FlowLayout(int how) FlowLayout.Left, FlowLayout.RIGHT,

FlowLayout(int how, int horz, int vert) Page No 1

Ex:

setLayout(new FlowLayout(FlowLayout.LEFT))

BorderLayout Common Layout for top-level window with 4 edges BorderLayout() BorderLayout(int how, int horz, int ver) GridLayout Have to define number of rows and columns GridLayout(int rows, int colus) GridLayout(rows, colus, horzspace, vertspa) CardLayout Useful for user interfaces, which are dynamically enabled and disabled, hidden, activated. CardLayout() CardLayout(int horspac, int verspace)

Page No 1

MutiThreading
Two or more parts that can run concurrently, each part as a program called a thread. Multithreaded is specialized form of multitasking. Used for maximum cpu utilization. Process : program that is executing Process based multitasking : * separate memory space for each program * Heavy threads, inter process is expensive. Thread based multitasking : * A single program perform more operations at a time. Ex: Editing test and printing. * Light threads, communication is Inexpensive Definition : Execution of different parts of same application at a same time is called Multithreading. In Multi threading only one child process creates for any number of threads, all of the threads shares common process. Different states of Thread Ready state : it is a thread waiting for cpu time Blocking state : thread goes to blocking while performing I/O transactions with external resources. Sleep state : state of waiting for something for specific amount of time. Shared resources : database connective, tcp server Death state : after completion. Waiting state : it is the state waiting for resources until getting the resources. If thread is in waiting then it should be invoked by some other thread. Suspend State : any child thread is going to perform illegal transactions then main thread suspends the child, if thread is suspend it should be invoked by main thread Current Execution state: it is the state of assigning cpu time to thread.

Page No 1

Scheduling: Thread scheduler schedules different threads for execution, it is part of jvm. Scheduling can be done in 2 ways 1) Time base (or) round robin. 2) prioriy based (or) preemptive. Yielding: it is a process of taking current execution thread into the ready to run state.

Priorities
Java assigns a priority to each thread, that determines how thread should be treated. Ex: main as 5. Priorities are integers, decides when to switch from one thread to next using Context Switch. A Thread relinquishes control by explicitly, yielding, sleeping (or) blocking on I/O. A High priority thread is preempted by a lowpriority thread. Threads of equal priority are time sliced in round robin. A high priority threads get more cpu time than lower. To set a thread priority Final void setPriority(int) with range of 1-10, normal is 5, min-1, max-10. To obtain current priority setting Final int getPriority()

Synchronization
Two threads communicate & share data, without conflicting with each other. By preventing when one thread writing data while another thread reading. When number of threads access same resource at a time, then there is chance of crashing thread to avoid, synchronization is used. Once a thread is inside a synchronized method, no other method can call while it is running. P v wait() thread moves to waiting state. Then it should be invoked by other thread otherwise thread will not invoke. P v notify() invokes first waiting thread P v notifyAll() invokes all waiting threads Page No 1

Runnable interface
Javas multithreading built using Thread class methods or Runnable interface. To create new Thread program implements Runnable interface jJavap java.lang.Thread Methods: Thread t = new Thread(); String str = t.getName(); getName() obtain a thread name getParent() to get parent thread getPriority() obtain a thread priority isAlive() if thread is still running join() wait for a thread to terminate resume() resume execution of thread, i.e. suspended run() entry point for thread sleep() suspend a thread for a period of time start() start a method, by calling a run() suspend() suspend a thread currentThread() returns reference to current thread. All java programs have main() automatically, when program started. thread. Creates must extends Thread or

All child threads are spanned from main thread, when main thread stops,program terminates(or)finish as last thread. Static Thread currentThread() obtains a reference of running thread reference is obtained by calling currentThread(). To change internal name of thread use setName(). Pause for seconds between operation use sleep(). Creating a Thread 1) Extend the Thread 2) Implement Runnable interface

Page No 1

Runnable Easiest way to create a thread, crate a class that implements Runnable interface. And need to define method. Java.lang.Runnable public abstract void run() * when run() returns, current thread will ends. * After implementing Runnable, object of type thread can be instantiated. * Thread(Runnable obj, String name) obj is instance of class that implements Runnable interface, name is thread name. * Thread starts running on calling start() method and in turn calls run(). this in constructor specifies, that to call run() method of this (current) object. After calling t.start() control returns to main(), when main thread resumes, enters into child thread and both threads continue running by sharing the cpu until loop finishes. In multithread, main thread must finish last otherwise java run system may hang. Extending Thread Another way to create thread is create new class that extends thread and then create instance of class. Extending class must override run(). Thread class extending is used when methods in thread class need to be enhanced (or) modified. So simple solution is implement Runnable interface using run(). Creating many Threads Thread t = new Thread() Thread t = new Thread(my thread); Thread(Runnable obj, String name); Obj is instance which implements Runnable.

Page No 1

Java.lang.*
Java.lang automatically imported into all programmes. Classes Boolean Object System Compiler Interfaces Cloneable Double Number StringBuffer ClassLoader SecurityManager Runnable string Class Long Math Character Float Integer Process Runtime Thread ThreadGroup

Simple Types & wrapper Classes Such as int and char are used for performance, passed by value to methods. No two methods refer to same instance of an int. So create object representation for simple types. Enumeration requires only objects, so simple types encapsulated (or) wrapped into a class. Number Abstract class, float, double. that wraps numeric types int, long,

int intValue() double doubleValue()

long longValue() float floatValue()

Double & Float Are wrapper classes for double & float Float(double num) Float(float num) Double(double num) Double(String st) Methods double doubleValue() Double d1 = new Double(3.14); Double d2 = new Double(3.14); Sop(d1.equals(d2)); o/p true Integer & Long Integer(int num) Long(string str) Integer(String st)

Float(String)

Long(long num) String-> int String -> Integer

Static int parseInt(String str) Static Integer valueOf(String str)

Page No 1

int intValue() Static String toString()

IntegerObject -> int int -> string

Boolean To pass boolean variable by reference, constants as true and flase. Boolean(boolean boolval) Boolean(String bool) Process Is abstract class for executing program void destroy() int exitValue() terminates the process returns code from subprocess

Runtime Encapsulates run-time environment, can not create object but can get reference to current Runtime. Controls state & behavior JVM Runtime r = Runtime.getRuntime(); Methods Process exec(String long freeMemory() Void gc() long totalMemory() progname) executes program name bytes available for JRS. initiates Garbage collectior total bytes available for programme.

System Collection of static methods and variables(in,out,err) Static long currentTimeMillis() Returns number of milliseconds from jan 1 1970 Static Properties getProperties() Class Encapsulates run-time state of object or interface, when classes are loaded, objects of type class are created. To obtain class object getClass() in Object. Static class forName(String) return class object String getName() returns complete name of class of Or interface invoking object Boolean isInterface() get properties of JRS

Page No 1

Math Contains all floating point functions for geometry trigonometry E(2.72) pi(3.14) Static double pow(double x, double y) Static double sqrt(double arg) &

Java.util.*
Used for storing collection of objects, generating random numbers, date & time manipulation, token strings. Classes Bitset Observable Random Dictionary StringTokenizer interfaces Enumeration Observer Enumeration Interface, which can enumerate (obtain at a time ) the elements in collection of objects. Methods boolean hasMoreElements() returns true if there are still elements to extract false when all elements enumerated (obtained) Object nextElement() Returns next object in the Enumeration Vector Stack date Properties Hashtable

Vector
Java.lang.Vector Java arrays are fixed lengths, cannot grow (or) shrink ( i.e know advance how elements can hold, at runtime how large array needed ) to handle this situation. Java defines Vector class, variable-length array of object references. Vector can grow (or) decrease in size dynamically. Page No 1

With initial size is created, if size exceeds enlarges, when objects removed vector shrunk. Constructors Vector() vector(int size)

vector

vector(int size, int incr) determined on

Default size is 10, and increment is specified, if not vector size is doubled. Data members in Vector class int capacityIncrement; Object elementData[] int elementCount;

Methods: final void addElement(obj) f Object elementAt(index) f bool contains(obj) final int capacity() final Enumeration elements() f object firstElement() f int indexOf(Object) f v removeAllElements() final int size() f void trimeToSie() f void insertElementAt(obj, int pos)

Stack
Subclass of vector (LIFO, last in first out) includes all methods Push() to put element onto a stack pop() to remove at the top of the stack peek() to use element at positioned empty() true, if nothing on the stack search() if object exists on the stack Stack st = new Stack St.push(new Integer(42)); Integer a = (Integer) st.pop();

Dictionary
Abstract class, represent a key/value storage key, which is a name to retrieve value. Methods Enumeration elements() Object get(key) Enumeration keys() object put(object key, Obj val) Object remove(Object key) int Size()

Page No 1

Hashtable
Dictionary is super class of Hashtable to store objects which are indexed by any other object Hashtable() Hashtable(int) keys(), size()

Methods Put(object key, object val) get(key) contains() clear() remove() Hashtable ht = Ht.put(johb, Enumeration na Enumeation val new Hashtable(); new Double(123.45)); = ht.keys(); = ht.elements();

double v = (double) ht.get(john).doubleValue(); sop(ht.get(john));

Properties
It is subclass of Hashtable, maintain list of values as string key and string values (only strings) Properties type is returned by System.getProperties() for obtaining environment values. Properties prop = new Properties(); Prop.put(Andhra,Hyderabad); Enumertion states = prop.keys(); String str = prop.getProperty(up); Save() and load() are used, when information contained in properties object can be easily saved or loaded from disk or write to stream.

StringTokenizer
Parsing of input string, parsing means dividing an text into a set of discrete parts of tokens Parsing process is called lexer(lexical analyzer) with default delimiters space, tab, newline, return. StringTokenizer() Methods StringTokenizer(str, string delims)

Page No 1

Object nextElemet() String nextElement()

countTokens()

Static String str = hello java in; her; ke: in ; StringTokenizer st = new StringTokenizer(st, =;); While(st.hasMoreElements) { sop(st.nextTokens()); } Bitset: array that holds bit values; vector of bits Set(index) get(index) clear() .or(bitset) .and(set)

Random : This class generates random numbers. Random r = new Random();

Date
Represents date & time (java.util.Date) Date(int y, int m, int d) Date(y,m,d, hr,mm) Number of years elapsed since 1900 0-jan new Date(Thus Feb 15 1996 22:24:34) as string methods: boolean after (date) date equals(Object date) getHours() getMinutes() getYear() setDate(int) Date d = new Date(); String m[]={jan, feb, Sop(m[d.getMonth()]); before(date) getDate() getMonth() setHours(int)

getDay() getSeconds() getHours()

. }

Page No 1