ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming?...

224
Naresh Kumar terli Name That Builds You CORE JAVA CO NCEPTS By Naresh

Transcript of ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming?...

Page 1: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh Kumar terliName That Builds You

CORE JAVA

CONCEPTS

By Naresh

Page 2: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Core Java Notes

What is procedural programming?

A procedural program divides the code into smaller blocks called procedures. Procedures can interact with each other. An important point to note in procedural programming is the idea of state. The state of a program is stored in variables. As the program execution goes on, the state changes. The actions (procedures or functions) will change the state (value of the variables). Prolog, Pascal, FORTRAN and PL/SQL are examples. Drawbacks:In procedural language, if the programming code goes beyond around 25,000 lines, it becomes unmanageable and especially when the project comes for modification at a later stage.

What is structured programming?Structured programming is a design approach where complex systems are broken

down into smaller and more manageable pieces. That is, the programmer divides the program’s source code into logically structured chunks (blocks) of code. The advantage is, it makes programs more readable, more reliable and more easily maintainer. Structured programming can be seen as a subset of procedural programming. It is most famous for removing or reducing dependency on the GOTO statement.Delphi and COBOL are examples of structured programming language.Advantages of structured programming language:

Structured programming reduces the complexity. Modularity allows the programmer to tackle problems in logical fashion. Also, using logical structures ensure that the flow of control is clear and readable.

What is java?

Java (with a capital J) is a high-level, programming language, like C, FORTRAN, Smalltalk, Perl, and many others. And also we can say Java is an object-oriented programming language. This means that the language is based on the concept of an object. You can use Java to write computer applications and thousands of other things computer software can do. Using java we can build special programs called applets. Applet is a small java program that can be downloaded from the Internet and played safely within a web browser.

2A winner not one who never fails but one who never QUITS

Naresh kumar

Page 3: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

What is the History of Java?

a. Java was invented by James Gosling in the year of 1991 developed by Sun Micro Systems of U.S.A.

b. In 1991, Patrick Naughton and James Gosling with his co-workers started a secret project called “Green” in Sun Micro System Company their primary aim to design a small computer language that could be used for consumer devices like cable TV switchboxes, Microwave ovens and remote controls. Gosling decided to call his language “oak”.

c. In 1992, they developed and delivered product called “*7” it was an extremely intelligent remote control.

d. In 1995 “oak” was renamed as “java” because of some legal problems. The main reason is oak was the name of an already available computer language so they changed the name to java.

e. Many popular companies including IBM, Microsoft, Netscape and many others support java.

Explain the features of java?

Simple and small, Familiar, Object Oriented, Distributed, two Staged, platform Independent, Robust and Secure, Multithreaded, High performance, Dynamic, Extensible.

Simple and Small: Java is a simple and small language that can be learned easily, even if you have just started programming, and many features of C and CPP that are not added here like pointers, preprocessor header files, GOTO, SIZE OF, and TYPEDEF statement and JAVA does not contain data types STRUCT, and JAVA does not support operator overloading, template classes, multiple inheritance, global variables, pointers, header files and many othersFamiliar: It is familiar language because java uses many constructs of C and CPP and therefore java is looks like a CPP code.Object Oriented : Almost everything in java is a class, or an object. Any code that you write in java is inside a class. Java is purely Object Oriented and provides Abstraction, Encapsulation, Inheritance and Polymorphism. An Object is a software bundle of variables and related methods.Distributed : Java is designed as a distributed language for creating applications on network it has the ability to share both data and programs. Java applications can open and access remote objects on internet very easily. RMI packages are used for creating distributed server and client application. Two Stage Systems: Java is both compiled and interpreted language. Compiler (javac) is used to translate a java program into an intermediate language called java byte code

3A winner not one who never fails but one who never QUITS

Naresh kumar

Page 4: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

(.class files), it is platform independent code and interpreter (java) is used to read each byte code instruction and to run on the computer.

Platform Independence : We know that, java compiler produce the byte code. The byte code can be

executed on a variety of computers running on different operating systems such as windows 95/98, Windows NT, Sun Solaris and Mac OS. Another reason is, size of the primitive data types are machine independent.Robust:

Java is a robust language because it provides many safeguards to ensure reliable code. It has strict compile time checking, runtime checking, it is designed as a garbage-collected language to free the programmers from all memory management problems. Also provides the exception handling technique to handle the exceptions occurred at runtime.Secure:

Security is very important issue when you are going to implement a network based application. Java system doesn’t allow the virus affected applets to run. We are not

4A winner not one who never fails but one who never QUITS

Naresh kumar

Page 5: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

using the pointers here, so programs cannot gain access to memory locations without proper authorization.Multithreaded :

Multithreading is the ability of an application to perform multiple tasks at the same time. For example when you watch a movie on your computer, one task of program is to handle sound effects and another handle screen display so simple programs do many tasks simultaneously.High Performance :

Java byte code was efficiently designed so that it would be easy to translate directly into native machine code for high performance by using a Just-in-Time (JIT) compiler. Java is faster than other interpreted language. Since it is compiled and interpreted. Multithreading provides the overall execution speed of java programs.Dynamic :

Maintaining different versions of an application is very easy in Java.Java is capable of dynamically linking in new class libraries, methods and objects. In java almost everything will be done at run time.Extensible: Java programs support functions written in other languages such as C and CPP. These functions are known as native methods. Native methods are linked dynamically at runtime.

What is Object Oriented Programming Language? And explain the principles of OOP’s concept.

Object Oriented Programming Language: Object Oriented Programming language is an approach which provides the way

of modularizing the programs or it is a programming methodology that helps to organize complex program through the use of inheritance, encapsulation and polymorphism.

Principles of OOP’s concept:

Class: Class is a User-defined abstract data type which contains data members and Member functions or it is a collection of similar objects. Declaring a Class: A Class is described by use of the ‘class’ keyword the attributes and methods (Behavior) of a class are defined inside a class body. In java, the braces {} mark the beginning and the end of a class or method. Here we use the following notation.[ ] - optional< > - are mandatory (must)Syntax:

[Access-specifier][Modifier] class <class-name>{

Data-type instance-variable1;Data-type instance-variable2;

5A winner not one who never fails but one who never QUITS

Naresh kumar

Page 6: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

………………………………Data-type instance-variable-n;Data-type methodname-1 (parameter list){

Body of method}………………………………Data-type method-name-n (parameter list){

Body of method}

}

Here data, or variable defined with in a class are called instance variable. The code is contained with in a method.

Ex:ObjectDemo.java

class Emp{

int eno;String name;String desig;double sal;void getEmpDetails(){

System.out.println (“eno=\t”+eno);System.out.println (“ename=\t”+ename);System.out.println (“desig:\t”+desig);System.out.println (“sal:\t”+sal);

}}Class ObjectDemo{

public static void main(String args[]){

Emp e=new Emp();e.eno=101;e.ename=”Naresh”;e.sal=20000.00;e.desig=”Faculty”;e.getEmpDetails();

}}

D:\java\javac ObjectDemo.java

6A winner not one who never fails but one who never QUITS

Naresh kumar

Page 7: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

D:\java\dir *.classEmp.classObjectDemo.classD:\java\java ObjectDemo

Output: 101NareshFaculty20000.00

Rules for Naming Classes: A class name must not be a keyword in Java. It can begin with a letter, an underscore (or) a $ symbol The name must not contain embedded space or period (.) It can contain characters from various alphabets like Greek, Hebrew and

Japanese. They can be of any length

Conventions for naming classes : A class name must be meaningful. It usually represents a real life class Class names are nouns and must begin with capital letters (Ex: TVs, Bike etc…) If it is too long, the leading upper case letter and each subsequent word with a

leading upper case letter. E.g., HelloWorld, FirstExample etc….

Objects: Object is an instance of a class, or a runtime entity and every object is independent. Every object has a state, identity and behavior. State represented by the variables of that object, identity referred by the reference variable of that object, behavior represents the methods of that class.In easy way object is 4 steps processin.1.It resurve

Syntax:<Class name> <reference variable name>=new <constructor>;Ex:

Emp e = new Emp();

In the above example e is a reference variable. Emp() is a constructor(it is the method, that returns new instance of the class). And new is an operator is used to allocate the memory to an object.

e.eno=101;e.ename=”Naresh”;e.sal=20000.00;Here we are assigning values to instance variables using ‘.’ (Dot) operatore.getEmpDetails ();

7A winner not one who never fails but one who never QUITS

Naresh kumar

Page 8: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Here we are calling the method of an object using ‘.’ (Dot) operatorMethod: A method is a sequence of declaration and executable statements encapsulated together like an independent mini program (sub program).

Declaring methods[Access specifier][Modifier] <Return-type> <method-name> ([parameter-list])

{//body of method

}Conventions for naming a method:

Method must be meaningful Starting letter is lower case. Method name should start with verb followed by noun If the method name contains two or more words join the words and begin each

word with an upper case letter.Ex: readFile.

writeFile.getDetails.

Note: In java every executable statement must be within some method.The methods may be

a. Predefined methods: These are library functions included along with the software.

b. User defined methods: These functions are defined and coded by the programmers for a specific purpose in a project.

Arguments passing:1. Call by value (pass values)2. Call by value (pass objects)

Local Variables:A local variable is a variable that is declared with in a method. They can be used only within that method and they can’t be used outside that method.

Recursion: Recursion is the process of defining something in terms of itself. A method that calls by itself is said to be recursive.The factorial function can be defined recursively asint fact(int n){

int factorial;if(n<=1)return 1;factorial=n*(fact(n-1));return factorial;

}Ex: n=4;//Factorial=[4*[3*[2*1]]];

8A winner not one who never fails but one who never QUITS

Naresh kumar

Page 9: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Encapsulation: Wrapping up of data and methods into a single unit is called Encapsulation. If we take the Emp class we are binding one method and no of variables, which means that we are encapsulating data and methods in to a single unit (Emp class).Abstraction: Abstraction refers essential features without including the background details or explanations. For Ex we apply brake to our two-wheeler, bike stops. But we do not know what the internal mechanism of how brake works. Still, we use brake. Here the brake mechanism to us is abstraction. So, hiding of unnecessary details from the end user.Inheritance: Inheritance is the mechanism that allows the programmer to include one class properties into another class. We can inherit both data members and a method of a thirsty class into newly creation class. The class, which is inherited, is called super class and the newly derived class is called as sub class. Or producing new classes from already existing class is called inheritance; already existed class is called the super class or Base class or parent class. The newly produced class is called derived-class or child-class.

A copy of super-class object is created in the sub-class All the members of super-classes are available to sub-class In inheritance sub-class object contains super-class object If there are constructors in super class they also available to sub-class. Super class default constructors are available automatically to sub-class.

Syntax:class sub-class-name extends super-class-name{}

The inheritance allows subclasses to inherit all the variables and methods of their parent classes. Inheritance may take different forms:

Single inheritance (only one super class) Multiple inheritance (several super classes) Hierarchical inheritance (one super class, many subclasses) Multilevel inheritance (one super class, many subclass)

In single inheritance there is only one base class and only one derived class

In multiple inheritance there is only one derived class that is derived from several base classes i.e. there are

x

y

9A winner not one who never fails but one who never QUITS

Naresh kumar

Page 10: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

In hierarchical inheritance there is only one base class but many derived classes. These derived classes are derived only from one base class. That is, different classes extend the same class.

In multilevel inheritance the class is derived from the derived class and the chain goes.

Polymorphism: It has the ability to take many forms i.e. we can write more than one method in a class with same name but those methods must contain different signature. (Function overloading & overriding)Dynamic Binding: Java is a dynamic language. Java is capable of dynamically linking in new class libraries, methods, and objects.

What Are The Fundamental Characteristics of OOP? Everything in an object oriented paradigm is an object. Each object is an instance of a class. A class is the definition of methods and data.

X Y

Z

x

y z w

x

y

z

10A winner not one who never fails but one who never QUITS

Naresh kumar

Page 11: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

An object of a class encapsulates its own state (data values) but of same behavior. A class may communicate with others via messages, which requests associate

with required arguments. By this way, a class can ask other classes also to perform actions without knowing the details of the work under those actions. This is called Information Hiding.

A class may inherit other class properties. Let class A inherits from class B. then, class A is a subclass of class B and, on the other way around, class B is a super class of class A.

A class can override behaviors inherited from its super class.

What are the benefits of object-oriented programming? OOP provides useful features like encapsulation, inheritance and polymorphism,

not available in traditional programming. Through inheritance, we can eliminate redundant code and extend the use of

existing classes. We can build programs from the standard working modules that communicate

with one another. This leads to saving of development time and higher productivity.

The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in other parts of the program.

Object-oriented systems can be easily upgraded from small to large systems. Program development becomes easy due to increased modularity.

What is Java Environment?

Java environment includes a large number of development tools and hundreds of classes and methods. The development tools are part of the system known as Java Development Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known as the Application Programming Interface (API)

JRE stands for the Java Runtime Environment. This is the package of software that must be installed on a machine in order to run Java applications. That is, JRE gives runtime environment or execution environment to a Java program. It does not include development tools like compiler or debugger etc...

JDK or SDK gives JRE and also a compiler. The JRE includes the Java Virtual Machine, core classes, and supporting files.

Java Development Kit: The Java Development Kit comes with a collection of tools that are used for developing and running Java programs. They include:

Appletviewer (for viewing Java applets) Javac (Java compiler) Java (Java interpreter) Javap (Java desassembler) Javah (for C header files) Javadoc (for creating HTML documents)

11A winner not one who never fails but one who never QUITS

Naresh kumar

Page 12: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Jdb (Java debugger (which helps us to find errors in our programs))

Application Programming Interface: The Java Standard Library (or API) includes hundreds of classes and methods grouped into several functional packages. Most commonly used packages are

a. Language Support Package: A collection of classes and methods required for implementing basic features of Java.

b. Utilities Package: A collection of classes to provide utility functions such as date and time functions.

c. Input/Output Package: A Collection of classes required for input/output manipulation.

d. Networking Package: A Collection of classes for communication with other computers via Internet.

e. AWT Package: The Abstract Window Tool Kit package contains classes that implements platform-independent graphical user interface.

f. Applet Package: This includes a set of classes that allows us to create Java applets. The use of these library classes will become evident when we start developing Java programs.

Briefly explain about the various data types defined by Java.

The java programming language is strongly-typed, which means that all variables must first be declared before they are used. This involves stating the variable’s type and name as follows:Int price=1;By declaring so, it tells Java compiler that a field name “price” exist that holds numerical data and has an initial value of “1”. A primitive type is predefined by the language and is named by a keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are byte, short, int, long, char, float, double and Boolean. These eight types can be classified into four groups as follows:* Integers: the integer types are for numbers without fractional part. Negative values are also allowed. Java defines four integer types. They are byte, short, int and long. Java does not support the concept of unsigned data types and therefore all Java values are by default signed, meaning that they can be positive or negative unsigned is not a keyword. The size and range of these four integer types are shown in the following table:

Type Size RangeByte One byte -128 to 127Short Two bytes -32,768 to 32,767Int Four bytes -2,147,483,648 to 2,147,483,647Long Eight bytes -9,223,372,036,854,775,808 to

9,223,372,036,854,775,807

12A winner not one who never fails but one who never QUITS

Naresh kumar

Page 13: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Example:Byte b=15;Int i=100;Short s=45;Long l=45l;Or Long l=45;

Floating-point Type: Floating-point type is used to hold numbers containing fractional parts such as 45.44 or -23.21. There are two types of floating-point types, float and double. The following table gives the size and range of these two types

Type Size Range DescriptionFloat 4 bytes 3.4e-038 to 3.4e+038 Use full when fractional part is

needed.Double 8 bytes 1.7e-308 to 1.7e+308 Useful for mathematical functions

like sin, cos etc..

Example:Float sal=45.500f; OrFloat sal=45.500F;It must to suffix the float value with f or F. else, it is a compilation error as floating-point number is taken as double by default.Double price=34.45d; or Double price=34.45;

*Characters: “char” is the data type that is used to store characters in Java. Char in Java is not the same as char in C or C++. In C/C++ char is an integer type of 8 bits wide. But is not the case in Java. Java char is of 2 bytes (16 bits) size. Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters (alphabets) found in all general human languages like Thai, Cyrillic, Hebrew, Telugu etc.. Char data type is unsigned by default and is implicitly used by the designer and the range is 0 to 65,535.

File Name: CharDemo.javapublic class CharDemo{

public static void main(String args[]){

char ch1,ch2;ch1=’A’;ch2=66;System.out.print (“ch1 and ch2 are ”);System.out.print (ch1+”, ”+ch2);

}}

13A winner not one who never fails but one who never QUITS

Naresh kumar

Page 14: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Out put: ch1nd ch2 are A, BObserve the statement: ch2=66. 66 is treated as ASCII value and is

implicitly converted to A and assigned to ch2;

* Boolean Type: “Boolean” data type is used when a particular condition is to be tested during the execution of a program, i.e., it is used as flag in java. The Boolean type is used for logical values in control structures. It can have only one of two possible values: true or false. Boolean is used in if and while control structures. Boolean type is denoted by the keyword “boolean” and uses only one byte of storage. All comparison operators return Boolean type values.

Example:boolean b=false;

What is a variable and explain the scope and life time of a variable?

Variable is a storage location with a name. We can assign a value to a variable. That is, it represents a place where a quantity (value) can be stored. The value of variables can be changed. The value can be used by the name of the variable. The object stores its state (properties) in variables (also known as fields).The Java programming language defines three types of variables

Instance variables (Non-static variables): Objects store their individual states in “non-static fields”. That is, fields declared without the static keyword. Non-static variables also called instance variables because they must be called with an object (instance). Every object maintains its own set of instance variables. For examples, the speed of car( car is an object) is independent from another car speed.

Class variables (static fields): A class variable is an instance variable declared with the static modifier, a static variable can be accessed by all the objects of the class. That is, there will be only one copy of the variable that is shared or accessed by all the objects. A class my have any number of objects.

Local variables: Similar to how an object stores its state in instance fields (variables), a method stores its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, in count=0;). The scope of the local variable is within the method or block in which it is declared. That is, other methods cannot use. Local variables are only visible to the methods in which they are declared. That is the other methods cannot use. Local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.

A variable is an identifier and the following rules are to be observed while naming them.

Rules of Identifiers: Case-sensitive

14A winner not one who never fails but one who never QUITS

Naresh kumar

Page 15: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Should not be a keyword Should be a single word Should not start with a digit Should begin with an alphabet, an underscore or $ symbol.

What is casting and what are the rules that are used in automatic casting in Java?

We can assign primitive data types to another. This is called casting. The process of casting is governed by some rules.

Rules of casting:

The datatypes must be compatible. That is a Boolean value is incompatible and cannot be assigned to any other data type.

A datatype of lower size can be assigned to a datatype of higher size (and is done implicitly)

A data type of higher size cannot be assigned to a data type lower size implicitly and is to be done explicitly.

Implicit casting:When we assign variables of datatype of lesser memory size to variables of higher

memory size, the system does casting implicitly. For example

Int I=100;Double d=I;

In the above example, casting is done implicitly by the system as we are assigning I of data type int (occupies 4 bytes) o d of data type double (occupies 8 bytes). This is called as “widening conversion” and is done implicitly.

Explicit casting:

When we assign variables of data type of higher memory size to variables of lesser memory size, system does not perform implicit casting. We have to do ourselves the casting. This is called explicit casting. In explicit casting data will be truncated or precision of the value is lost. For example:

Double d=34.45;//int I=d; //raises compilation errorInt I= (int) d; //explicit casting is done

System.out.println (I); //prints 34 and .34 is truncated

15A winner not one who never fails but one who never QUITS

Naresh kumar

Page 16: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

In the above example, casting is done explicitly by us as we are assigning d of data type double (occupies 8 bytes) to I of data type int (occupies 4 bytes). This is called as “narrowing conversion”

What is an array? Give an example.

An array is a group of similar data type items that share a common name. Arrays occupy contiguous memory locations. Array size is fixed and cannot be altered dynamically. For example we can define an array name salary to represent a set of salaries of a group of employees. A particular value is indicated by writing a number called index number of subscript in square brackets after the array name.

For example: salary[3];In the above example we can store 4 employees’ salaries (array index starts from zero). While the complete set of values is referred to as an array, the individual values are called elements. Arrays can be of any primitive data type. It is also possible to create array of objects.

One-dimensional Arrays:A list of items can be given one variable name using only one subscript and such a variable is called a single-subscripted variable or a one-dimensional array.

To declare one-dimensional array, you will use this general form:Type array-name[] =new type[size];

Here, type declares the base type of the array. The base type determines the data type of each element contained in the array. The number of elements that the array will hold is determined by size. Since arrays are implemented as objects, the creation of an array is a two step process. First, you declare an array reference variable. Second, you allocate memory for the array, assigning a reference to that memory to the array variable. Thus, arrays in java are dynamically allocated using the new operator

Here is an example. The following creates an int array of 10 elements and links it ot an array reference variable named sample.

int sample[]=new int[10];

class ArayDemo{

Public static void main(String args[]){

Int sample[]=new sample[10];for(int i=0;i<10;i++)sample[i]=i;System.out.println (“elements in array sample“);for(int i=0;i<10;i++) System.out.println(“sample[i]);

16A winner not one who never fails but one who never QUITS

Naresh kumar

Page 17: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

}}

Multidimensional Arrays:

Multidimensional array is actually an array of arrays. To declare a multidimensional array variable, each additional index should be specified using another set of square brackets. The following statement declares a two-dimensional array called sales

Int xyz[][]=new int[2][3];File Name: MultiArray.java

public class MultiArray{

public static void main(String args[]){String xyz[][]=new String[2][3]; //creating the array

int j,k=0;for(int i=0;i<2;i++) //initializing the array{

for(j=0;j<3;j++)xyz[i][j]="xyz"+"["+i+"]"+"["+j+"]";

}System.out.println("array elements of xyz[2][3]:\n");for(int i=0;i<2;i++){

for(j=0;j<3;j++)System.out.print (xyz[i][j]+" ");System.out.println();

}}

}

Write a Java class for matrix operations such as Read, Write, Add and Multiply?

In the following program, MyMatrix class, 3 arrays are taken in which each array has 2 rows and 3 columns. We can have this number of rows and columns from keyboard also

The first array array1 is created to take keyboard input for read operation. The second array array2 is taken for matrix operations. The third array array3 is used for storing temporarily the addition and multiplication data.

import java.io.*;class MyMatrix{

int array1[][]=new int[2][3];int array2[][]={{10,20,30},{40,50,60}};

17A winner not one who never fails but one who never QUITS

Naresh kumar

Page 18: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

int array3[][]={{1,2},{3,4},{5,6}};int array4[][]=new int[2][2];DataInputStream dis;public void readMatrix()throws Exception{

dis=new DataInputStream(System.in);System.out.println("Enter 2x3 matrix elements rowwise(6) :");for(int i=0;i<2;i++){for(int j=0;j<3;j++){

System.out.print("Enternumberinposition"+(i+1)+"x"+(j+1)+":\t");String str=dis.readLine();int num=Integer.parseInt(str);array1[i][j]=num;

}}dis.close();

}public void writeMatrix(){

for(int i=0;i<2;i++){for(int j=0;j<3;j++)

System.out.print(array1[i][j]+"\t");System.out.println();}

}public void addMatrix(){

for(int i=0;i<2;i++){for(int j=0;j<3;j++){

array2[i][j]=array1[i][j]+array2[i][j];System.out.print(array2[i][j]+"\t");

}System.out.println();}

}public void multiplyMatrix(){

for(int i=0;i<2;i++){for(int j=0;j<2;j++){

18A winner not one who never fails but one who never QUITS

Naresh kumar

Page 19: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

for(int k=0;k<3;k++)array4[i][j]=array4[i][j]+array1[i][k]*array3[k][j];System.out.print(array4[i][j]+"\t");

}System.out.println();}

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

MyMatrix mm=new MyMatrix();mm.readMatrix();System.out.println("Results of Write Matrix:");mm.writeMatrix();System.out.println("Results of Add Matrix:");mm.addMatrix();System.out.println("Results of Multiply Matrix:");mm.multiplyMatrix();

}}

Write about operators in Java?

An operator is a symbol that operates on one or more arguments to produce a result. Java provides a rich set of operators for manipulating program data. The java programming language supports various arithmetic operators for all floating-point and integer numbers. Most of these were taken directly from C/C++. Following are the most commonly used operators.

Java Operators

Postfix [] () expr++ expr--Unary ++expr –expr +expr –expr ! ~Creation/caste new (type)exprMultiplicative * / %Additive + -Shift <<, >>, >>>Relational <,<=,>,>= instanceofEquality ==,!=Bitwise AND &Bitwise exclusive OR ^Bitwise inclusive OR |Logical AND &&Logical OR ||Ternary ?:Assignment =

19A winner not one who never fails but one who never QUITS

Naresh kumar

Page 20: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Operators are listed in precedence order with the highest precedence at the top of the table.

Assignment:Assignment operators set the value of a variable or expression to some new value.

The simple = operator sets the left hand operand to the value of the right hand operand. The assignment operator is evaluated from right to left, so a=b=c=0; would assign 0 to c, then c to b then b to a.

Arithmetic:/, + and – represent division, addition, and subtraction. * And % represents

multiplication and modulo. % is similar to division but returns the remainder of the division operation. For example, z=5%2; z would be 1. In other words, 5/2 is 2 with a remainder of 1.We should not divide by zero as it raises Arithmetic Exception.

Comparison:The comparison operators return true or false (Boolean) values. These are most

often used in control flow statements such as if, while, and for to determine whether certain lines of code would be executed or not.

Less than: < Less than or equal to: <= Greater than : > Greater than or equal to: >= Equal to: == Not equal to: !=

We should not get the equals and assignment operators confused. Use == to compare operands and use = to assign one operand to another.

Evaluation Order:In Java, the order of operands in an expression is fixed. All operands are

evaluated from left to right. After the operands are evaluated, the assignment operations take place, a[1]=b=10. Assignment is a right to left operation, so b is assigned 10 and then a[1] assigned the value of b, which is 10.

What are Unary Operators?In mathematics, a unary operation is an operation with only one operand.

Operator Use description++ op++ Evaluates to value before incrementing

20A winner not one who never fails but one who never QUITS

Naresh kumar

Page 21: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

++ ++op Evaluates to value after incrementing-- op-- Evaluates to value before decrementing-- --op Evaluates to value after decrementing

What are short cut operators?Observe the following:

int x=20;x=x+10;

in the above code, x is initialized to a value 20. in the second statement, the right-side expression is evaluated and assigned to the left-side one. The value of x is taken and added one to it. After evaluating the expression, the sum is assigned to the same variable (here, x) evaluated on the right-side. Like this, it become necessary in programming to use the current value of the variable, change it and reassign the results back to the same variable.

The above statement rewritten like this:int x=20;x+=10;

+= is called short cut operator. The following table consist common short cut operators available in Java.

Operator Use equivalent+= i+=1 i=i+1-= I-=2 I=I-2*= I*=2 I=I*2/= I/=2 I=I/2%= I%=2 I=I%++ I++ I=I+1-- I-- I=I-1

What are relational Operators?The relational operator compares two values and determines the relationship between them. For example, != returns true if two operands are unequal.

Opetator Use Return true if > op1>op2 op1 is greater than op2>= op1>=op2 op1 is greater than or equal to op2< op1<op2 op1 is less than op2<= op1<=op2 op1 is less than or equal to op2== op1==op2 op1 and op2 are equal!= op1!=op2 op1 and op2 are not equal

What are conditional operators?Relational operators are used with the conditional operators to construct more

complex decision making expressions. One such operator is &&, which performs the Boolean and operation. For example, you can use two different relational operators along with && to determine if both relationships are true.

21A winner not one who never fails but one who never QUITS

Naresh kumar

Page 22: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Operator Use Return true if&& op1 && op2 op1 and op2 are both true|| op1 || op2 Either op1 or op2 is true& op1 & op2 op1 and op2 are both true| op1 | op2 Either op1 or op2 is true

What is Ternary conditional operator?Ternary operators require three operands. The Java language has one ternary

operator, ?:, which is a short-hand for if-else statement.operator Use Return value?: expression ? op1:op2 evaluates expression and returns

op1 if it’s true, else op2

A program to illustrate ternary conditional operator:

public class TernaryOperator{

public static void main(String[] args){

int x=10,y=20;String str=x<y? "x less than y" : "x greater than y";System.out.println("str="+str);

}}Output:

x less than y

Explain the different bitwise logical operators:

Bitwise Operators:

Bitwise operators manipulate data at the bit level. The Java programming language also provides operators that perform bitwise and bit shift operations on integral types. Java’s bitwise operators operate on individual bits of integer (int and long) values. If an operand is shorter than an int, it is promoted to int before doing the operations.

It helps to know how integers are represented in binary. For example the decimal number 3 is represented as 11 in binary and the decimal number 5 is represented as 101 in binary. Negative integers are store in two’s complement form. For example, -4 is 1111 111 1111 1111 1111 1111 1111 1100

The unary bitwise complement operator “~” inverts a bit pattern; it can be applied to any of the integral types, making every “0” a “1” a every “1” a “0”. For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is “00000000” would change its pattern to “11111111”.

22A winner not one who never fails but one who never QUITS

Naresh kumar

Page 23: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

The signed left shift operator “<<” shifts a bit pattern to the left and the signed right shift operator “>>” shifts a bit pattern to the right. The bit pattern is given by the left-hand operand and the number of positions to shift by the right-hand operand. The unsigned right shift operator “>>>” shifts a zero into the leftmost position, while the leftmost position after “>>” depends on sign extension.

Why the main() method in Java is public, static and void

a. “public” is an access specifier. A public member of a class can be accessed by the classes of other packages also. The JVM library classes which execute our program existing in one package and our class to be compiled in another package. To have accessibility for the main () method, we declare the main as public.

b. “static” is a keyword of Java used as an access modifier. Generally to call method we require an object. But sometimes, it may be required to call the method without the help of an object. Then we declare the method as “static”. The same situation comes for main () also. The execution starts from main () method. To allow the JVM to call the main () method without the help of an object, we declare main () as static.

c. “void” is a key word of Java applied to a method to indicate that the method does not return a value. In java, main () is declared as void as it does not return a value.

What are command Line Arguments and how to pass and access them?

We can pass command-line arguments in Java. The arguments that are passed along with the command at the command prompt are called command-line arguments. The following program illustrates it.File Name: CommandLineArgs.java

public class CommandLineArgs{

public static void main(String args[]){System.out.println("Number of elements passed are"+args.length);System.out.println("The elements passed are");for(int i=0;i<args.length;i++)

System.out.println(args[i]+" ");}

}Compile the program as usual. While running give the command like this:C:\windows>java CommandLine1 hai 123 23 madhu bdpsWhen you run like this out put will be like this:Output :

Number of elements passes are 5The elements passes are

23A winner not one who never fails but one who never QUITS

Naresh kumar

Page 24: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Hai 123

23 madhu bdps

Explain new keyword.

new is keyword of Java used with the creation of objects. new allocates memory dynamically (at runtime) for the objects newly created. Observe the following statement:

Demo d1=new Demo ();In the above statement d1 is the reference variable which contains the reference of

the object. New allocates memory 4 bytes top the object d1 which is created newly. Demo () is the constructor of Demo class. The constructor Demo () implicitly returns class object of Demo that must be given some space on the RAM. It is the job of the new keyword to allocate memory. “new” will not create the object, but allocates memory to the object returned by the constructor.

We can define two special kinds of methods in a class i.e.a. Constructorsb. Finalizers (we will discuss later )

What is a constructor?

Constructor is a special method. The name of the constructor and class name must be the same. The advantage of constructor is called automatically when an object is created. We, generally, use the constructors to initialize the variables, setting background and foreground colors etc… A constructor also can have parameters. A constructor without parameters is called default constructor. If you don’t write any constructor in a class the compiler will automatically creates a default constructor

Explain ‘this’ and ‘super’ keywords

These two keyboards are used for two purposes.

1. To refer the hidden data members and method,2. To refer the constructors of the current class and its super class.

1. Members reference:

Local variable is a method can share the same houses as instance variables as class variables.

Sub class can define their own instance variables to hide those defined in this super class.

Sub classes can also define methods to override the method, defined in their super class.

24A winner not one who never fails but one who never QUITS

Naresh kumar

Page 25: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Two special reference variables are available inside any instance method to allow for accessing the hidden variables or overridden methods of that instance i.e.

this- it is used to refer the object, the method is called upon i.e. owner object.Super - it is used to access the methods or data members defined in the super class.

Ex: 1

class A {

int x1;int x2;void f1 (int x1, int x2){this .x1 = x1;this .x2 = x2;}

}

Ex: 2 – class B extends A{

int x1;int x2:void f2(int x1, int x2){this .x1=super.x1 = x1;this .x2 = super .x2 = x2;}

}

2. Constructor referenceIn this concept of inheritance, in the constructor of subclass there is an applied

first statement i.e. the super class constructor with no arguments is called automatically.If we do not like this default behavior, we can over ride it by using this () or super

() method call as the first statement to refer other constructor, of the object of same class or super class respectively.

Ex : class A{

int x1;int x2;A (int x1){this .x1 = x1;}

25A winner not one who never fails but one who never QUITS

Naresh kumar

Page 26: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

A (int x1, int x2){this (x1);this .x2 = x2;}

}

Ex: class B extends A{

int x3;B (int x1, int x2, int x3){Super (x1, x2);this .x3 = x3;}

}

Constructors and Finalize

We can define two special kinds of methods in a class i.e.

I. Constructors, i.e. the method, that return new instance of the class. If we do not define a constructor, we can use the default constructor to create an instance of a class.

II. Finalizers i.e. the functions that are called just before an object in garbage collected.

1. The default constructor is automatically added to the class by the java compiler.2. The constructor allocates storage memory for any member variables that are

declared on Java’s built in data types.3. A contractor is defined in the same way as an ordinary method, but it must have

the same name as the class and have no return type.4. We can define any number of constructors for a class by having different

parameter list and this is called constructor overloading.5. We can define any no. of methods for a class with the same name and different

parameter list and this is called method overloading.6. Java virtual machine automatically retains the memory used by an object when no

variable is referred to that object.7. The process is known as garbage collection.8. Finalizers are used in a situation where a class needs to clean itself before the

garbage collection.9. Finalizers are called just before an object of a class is garbage collector.

26A winner not one who never fails but one who never QUITS

Naresh kumar

Page 27: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

10. Finalizers are used to close opened files or connections to unsure that the related taxes are completed before the object is garbage collected.

11. Example definition of this finalize method is

Example:class A{

int x1=10;int x2=20;int x3=30;

A(int x1){

this.x1=x1;}A(int x1,int x2){

this(x1);this.x2=x2;

}A(int x1,int x2,int x3){

this(x1,x2);this.x3=x3;

}void display(){

System.out.print(x1+"\t");System.out.print(x2+"\t");System.out.println(x3);

}public static void main(String args[]){

A oa1=new A(11);oa1.display();A oa2=new A(11,12);oa2.display();A oa3=new A(11,12,13);oa3.display();

}}

27A winner not one who never fails but one who never QUITS

Naresh kumar

Page 28: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Java’s Data type and Method ModifiersA modifier is a keyword that affects either the lifetime or the accessibility of a

class, a variable, or a member function.

Storage and Lifetime ModifiersThe following sections describe the storage and lifetime modifiers: abstract, static,

synchronized, native, volatile, transient, and final.

The abstract ModifierWhen applied to a class, the abstract modifier indicates that the class has not been

fully implemented and that is should not be instantiated. If applied to member function declaration, the abstract modifier means that the function will be implemented in a subclass. Since the function has no implementation, the class cannot be instantiated and must be declared as abstract. Interfaces are abstract by default.

The static ModifierOrdinarily, each instance of a class has its own copy of any member variables.

However, it is possible to designate a member variable as belonging to the class itself, independent of any objects of that class. Such member variables are called static members and are declared with the static modifier keyword. Static member variables are often used when tracking global information about the instances of a class. The following class tracks the number of instances of itself using a static member variable called instanceCount.

class Myclass {

public static int instanceCount; Myclass( ) {

// each time the constructor is called,// increment the instance counterinstanceCount++;}

static {

instanceCount = 0 :}

}

The synchronized Modifier A synchronized member function allows only one thread to execute the function

at a time. This prevents two threads of execution from undoing each other’s work...

For example, suppose you have two threads, called threads A and B, responsible for updating a bank balance. Suppose also that the account has $100 in it. Now, simultaneously, thread a tries to deposit $50 in the account, while thread B find it at

28A winner not one who never fails but one who never QUITS

Naresh kumar

Page 29: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

$100. Each of them, independently, adds its deposit to the old sum and $150. If thread B finishes last, the account balance is $175. Of course, neither of these new figures is correct! The account should have $225 in it (100 + 50 + 75). The problem is that both threads tried to execute the same code (querying and changing the balance) at the same time. This is exactly the scenario that the synchronized keyword can prevent.

Synchronized methods are not static by default, but they may be declared as static.

The synchronized modifier does not apply to classes or member variables.

The native ModifierNative methods are implemented in other Languages, such as C, so they

have no code block. Many of the classes in the Core API are native because they need to access operating system-specific routines, such as those for drawing graphics on the screen here is an excerpt forms the API’S math class:

/* ** Returns the trigonometric sine of an angle.* @ param a an assigned angle that is measured in radians*/public static native double sin (double a ) ;

This declaration calls a funcition in a native code libarary that calculates the sine of the angle a. On an Intel x 86 platforms, the native code would call the sine function in the x86 processor’s floating-point unit or coprocessor. On other platforms, the native code function may do the computation with software instead. This function also happens to be declared with the public and static modifiers also.

The volatile ModifierA volatile variable is one whose value may change independent of the Java

program itself. Typically, volatile variables represent input from the outside world, such as a variable that denotes the time of day. They are also used to flag variables that could be changed by other threads of execution. The volatile keyword will prevent the compiler from attempting to track changes to the variable. The variable will always be assumed by the compiler to have a (potentially) new value each time it is accessed by Java code. Use of this modifier is rare but necessary, as Just-in-time (JIT) compliers are now common in most Java Virtual Machines.

The transient ModifierOne of the changes introduced with Java 1.1 is adding meaning to the transient

modifier. Java 1.0 supported the modifier, but it had no purpose. It is used in conjunction with serialization to provide for persistent objects. These objects can be avid to disk and restored on another machine or on the same machine. For more information about serialization, see Chapter 19. The transient modifier means not to save the variable.

29A winner not one who never fails but one who never QUITS

Naresh kumar

Page 30: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

The final ModifierMost languages have a way to declare a variable as constant (that is ,

unchangeable), which is true of Java as well. The final keyword indicates that a local variable or member variable cannot be altered. The main use of final variables is as symbolic constants. You can refer to a constant by name and define that name in a single location in your code. If you later need to change the number in your code, you need only make the change at the point your final variable is defined.

Note that if you declare a variable as final, you must also initialize it at the same time:

final int MAX_PAGES =23 :

ACCESS SPECIFIERS

public : any packageprivate: with in the classdefacult: with in the packageprotected: with in the package and subclasses of other package

Object Memory ModelThe dynamically charging part of a program can be divided into two areas i.e.

1. Stack memory area, which is used to store the local variables declared in methods, and blocks.

2. These variables are popped out of this stack upon list from the enclosing method or blocks.

3. A heap memory area, which is used the store the memory for dynamically allocated objects.

References to the objects are placed in the Stack area, but the space for his data members of the objects will reside in this heap area.

Whenever a block of memory calls is no longer referred by any reference variables, then these unused calls can be freed or garbage collected.

Static Members

It is possible to create a member that can be used by it, without reference to specific instance i.e. objects of a class.To create such a member, we precede its declaration with the keyword static.

30A winner not one who never fails but one who never QUITS

Naresh kumar

Page 31: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

When a member is declared static, it can be accessed before any objects of its class are created and without reference to any object.

We can declare both methods and variables as static.

The variables, which are declared inside the class as static, are called class variables, which are the global variables.

All the instances of the class share the same static variables.

The method, declared as static have the following restrictions i.e. They can only call other static methods. They must only access static data. They cannot refer to this or super variables. We can declare a static block inside the class, which gets executed once when the

class is loaded. Outside the class, the static method, and static variable can be used in dependant

of any object These static members can also be referenced through an object reference. But, non-static members must be referenced through only object reference. I.e.

they cannot be referenced with the class name. Inside the non-static methods, we can refer both static and non static members of

the class.

Nested and Inner Classes

1. It is possible to define a class within another class; such classes are called as nested classes or inner classes.

2. The scope of a nested class is bonded by the scope of its enclosing classes. I.e. if B class is defined inside the class A, then B is known to only A, but not outside of A.

3. A nested class has access to the members of its unclosing class including private member.

4. But enclosing class i.e. outer class does not have access to the members of the nested class i.e. inner class.

5. There are two types of nested classes. I.e. static and non static.6. The static nested class is the one, which is defined with static modifier.7. The static nested class cannot refer the members of outer class directing i.e. it

must access through an object.8. The non-static nested class can access all the method and variable of its outer

class directly.

31A winner not one who never fails but one who never QUITS

Naresh kumar

Page 32: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

9. If the inner class is static, then it must be used to create an object outside of the containing class with a hierarchical name as shown below.

Ex:1 on static inner classes

class A{

static class B{}

}class C

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

A.B ob = new A.B ();___}

}

Ex2: on non-static inner classes

class A{

class B{-------}

}class C

{public static void main (String args []){A a=new A();

A.B ob = a.new B();____

}}

Abstract class and abstract methods

32A winner not one who never fails but one who never QUITS

Naresh kumar

Page 33: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Some times we want to create a super class that only defines generated from that will be shared by all of its subclass, learning each sub class to fill the details

Such a class, which is not complete with the implementation of all the methods, is called abstract and it should specify with abstract modifier.

The methods which are incomplete in the abstract class are called abstract methods

The declaration of abstract methods in the abstract class must be specified with abstract as shown below

abstract class A{void f1(){

--------------------------

}abstract void f2();//abstract method}

If there is one single abstract method is a class, then the class must be declared as abstract.

These abstract classes cannot be used to create the objects. But they can be used to inherit into the subclasses.

The subclasses must compulsorily implement the abstract methods of the inherited super class; otherwise the sub class will be come as abstract class.

We cannot declare constructors and abstract static methods of a class. Abstract classes can be used to create object references, so that the super class

reference variable can refer to can objects of its subclasses.

Ex: On Final modifier:

This final modifier is used to prevent overriding i.e. the methods declared as final, cannot be overridden in the subclass. As shown below.

class A{

final void f1(){

------------

}}class B extends A

33A winner not one who never fails but one who never QUITS

Naresh kumar

Page 34: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

{void f1() //error , can’t override{}

}

This final modifier is also used to prevent a class from being inherited.For this we precede the class declaration like final modifier as shown below.

final class A{

------------------}

class B extends A // errors,, can not subclass A.{}

Interfaces

By using the keyword interface, we can specify what a class must do, but not how to do

Interfaces are syntactically similar to classes, but no in variables and methods are declared without any body.

Once an interface is defined, then any no. of classes can implement this interface or one class can implement any no. of interfaces.

To implement an interface, a class must define or implement the complete set of methods declared in the interface as shown below.interface iface1{

void f1(); void f2();

}interface iface2{

void f3();}

class A implement iface1{

public void f1(){-------

34A winner not one who never fails but one who never QUITS

Naresh kumar

Page 35: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

-------}public void f2(){--------------}

}

class B implements iface1, iface2{

public void f1(){

-----------

}public void f2(){

------------

}public void f3(){

------------

} }

The method, that implement a interface must be declared public and also the type signature of the implementing method must math abstractly with the type signature specified in the interface declaration.

If a class implements two interfaces that declare the same methods, then the same method will be used of with either the interface.

We can declare variables of the interface as object references that use an interface. Any instance of any class that implements the interface can be stored in such

interface variables. When we call a method through the interface reference variable, the correct

version will be called based on the actual instance of the interface being referenced to and this is one of the key feature of interface.

This process is similar to using a super class reference to access a sub class object. If a class implements interface, but does not fully implement this method,

deferred by that interface, then that class must be declared as abstract.

35A winner not one who never fails but one who never QUITS

Naresh kumar

Page 36: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

We can use these variables in the interface, to have shared constants into multiple classes by simply declaring an interface that contains variables which are initiated to the desired value.

One interface can inherit another by using the key and extend, such as Interface iface3 extends iface1, iface2. When a class implements such interface, it must provide implementation for all

the methods defined which the interface inheritance chain.Examples :interface iface1{

void display();}interface iface2{

void incrx1();void decrx1();

}interface iface3 extends iface1,iface2{

void set(int p1);}class A implements iface3{

int x1=10;int x2=20;public void display(){

System.out.print(x1+" ");System.out.println(x2);

}public void set(int p1){

x1=x2=p1;}public void incrx1(){

x1++;}public void decrx1(){

x1--;}

}class B implements iface1,iface2{

36A winner not one who never fails but one who never QUITS

Naresh kumar

Page 37: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

int x1=30;public void display(){

System.out.println(x1);}public void incrx1(){

x1++;}public void decrx1(){

x1--;}

}class Interfaceex2{

public static void main(String args[]){

iface3 face3;face3=new A();face3.incrx1();face3.display();face3.set(11);face3.display();face3.decrx1();face3.display();//face3=new B();

iface1 face1;iface2 face2;B ob=new B();

face1=ob;face1.display();//face1.incrx1();

face2=ob;face2.incrx1();ob.display();

}}

Packages

Packages are containers for classes that are used to keep the class name space.

37A winner not one who never fails but one who never QUITS

Naresh kumar

Page 38: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

A unique name has to be used for each class to child name continues in the same name open.

The package is a both name and visibility control mechanism. We can define classes inside a package that are not accessible by code outside that

package. We can also define member that are only exposed to other members of the same

package. This allows the classes to have the knowledge of each other, but not expose that

knowledge to the rest of the world. To create a package, we simply include package statement as the first statement in

a java source file. Any classes declared within that file will belong to the specified package, i.e.

package statement defines a name space in which classes are stored. If we omit the package statement, the class names are placed in the default

package. Example for this package statement is

package my pack; Java uses file system directories to store packages and the directory name must

match with the package name. Here that one file can include the same package statement i.e. the package

statement simply specifies to which package the classes defined in a file belong to package.

We can also create a hierarchy of package. To do so we simply separate each package name from the one above by using a period such as

Package Madhu.mypack; The package hierarchy must reflect the file system i.e. the java file had to be

stored in Madhu my pack directory. CLASS PATH environmental variable is used to specify the specific location that

the java compiler to combine for the class reference. The default current working directory is usually set for the class path

environmental variable defined for the java runtime system. In Java, we use import statement to being certain classes or package into visibility

such as

Import packagename; This package name can be single name or hierarchal name. This import statement should be given used to package statements if any and

before any class definitions. The examples of this import statement are

o Import mypack .A; // for class A of package mypacko Import Madhu.*;// for all the classes of package Madhu

38A winner not one who never fails but one who never QUITS

Naresh kumar

Page 39: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

If a class with the same name consists in two different packages that we import, then the compiler will generate an error when we try to use that class name. In such class we should specify the fully qualified name such as

o Mypack.A oa = new mypack.A(); When a package is imported, only those items which the package are declared as

public. Will be available in the import code. Java’s access controlled mechanism is performed with access specifier of private,

public, protected and default. Private member of a class can be accused only in other member of a class. Packages add another dimension to those accesses specifies and they are shown in

the following table

Sameclass Samepack non subclass

Same pack sub class

Different pack non subclass

Different pack subclass

Private Yes No No No NoDefault Yes Yes Yes No NoProtected Yes Yes Yes No YesPublic Yes Yes Yes Yes yes

package temp2;public class A{

int x1=30;public void display(){System.out.println(x1);}

}//class Usea uses A classimport temp2.A;class Usea{

public static void main(String args[]){A oa=new A();oa.display();}

}

Example 2

39A winner not one who never fails but one who never QUITS

Naresh kumar

Page 40: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

package temp2;public class A{

int x1=10;int x2=20;public A(){}public A(int p1,int p2){

x1=p1;x2=p2;

}public void pubdisplay(){

System.out.println(x1);System.out.println(x2);

}protected void prodisplay(){

System.out.println(x1);System.out.println(x2);

}private void pridisplay(){System.out.println(x1);System.out.println(x2);} void defdisplay(){System.out.println(x1);System.out.println(x2);}

}

// Class Subusea uses class Aimport temp2.A;class B extends A{

void bdisplay(){

prodisplay();pubdisplay();//defdisplay();//pridisplay();

}

40A winner not one who never fails but one who never QUITS

Naresh kumar

Page 41: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

}class Subusea{

public static void main(String args[]){B ob=new B();ob.bdisplay();}

}//class Usea uses A classimport temp2.A;class Usea{

public static void main(String args[]){A oa=new A(11,12);oa.pubdisplay();//oa.pridisplay();//oa.prodisplay();//oa.defdisplay();}

}

We compile the package programs using the below statement (command)

<javac> <-d> <path> <filename> javac compiler-d it is an option that instructs the compiler to create a folder with the package name available in the given file

<path> we have to give the path where u want to create a package

(Here (dot). means present folder.<filename> --> .java file name u want to compile

Ex: javac –d . FirstPack.java

When we execute this command java compiler creates a folder in present directory with the package name available in the FirstPack.java and places the .class files into the newly created folder.

The Type Wrapper Classes

Java deals with two different types of entities: primitive types and true objects. Numbers, Booleans, and characters behave very much like the familiar equivalents of procedural

41A winner not one who never fails but one who never QUITS

Naresh kumar

Page 42: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

languages such as Pascal, C, or even C++. Other object-oriented languages, like Smalltalk, do not handle these primitive types in the same way. Smalltalk, for example, uses objects for everything-numbers are objects, Booleans are objects, and characters are objects, and so on.

Although Java is truly object-oriented, it does not use objects for the most primitive types for the usual reason: performance. Manipulating primitive types without any object-oriented overhead is quite a bit more efficient. However, a uniform and consistent playing field, made up of only objects, is simpler and can be significantly more powerful.Java contains many subsystems that can work only with objects. With many of these subsystems, the need frequently arises to have the system handle numbers, flags (Booleans), or characters. How does Java get around this dilemma? By wrapping the primitive types up in some object sugar coating. You can easily create a class, for example, whose sole purpose is encapsulating a single integer. The net effect would be to obtain an integer object, giving you the universality and power that comes with dealing with only objects (at the cost of some performance degradation).Package java. Lang contains such “type wrapper” classes for every Java primitive type:Class Integer for primitive type intClass Long for primitive type longClass Byte for primitive type byteClass Short for primitive type shortClass Float for primitive type floatClass Double for primitive type doubleClass Character for primitive type charClass Boolean for primitive type BooleanClass Void for primitive type voidAmong the numeric types, class Integer, Long, Byte, Short, Float, and Double are so similar that they all descend from an abstract super class called Number. Essentially, every one of these classes allows you to create an object from the equivalent primitive type, and vice versa.

Exception Handling

An exception is an abnormal condition or we can say it is an object thrown by the Java Run Time Environment during the run time error occurred. There are many cases when abnormal conditions happen during execution of a program. Such as

1. The file we try to opens may not exist.2. The class file we want to execute is missing.3. The n/w communication may be disconnected due to some reasons.4. The operand is not in the legal range for ex. An array and element index

cannot exceed the range of the array

42A winner not one who never fails but one who never QUITS

Naresh kumar

Page 43: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

5. Execution of a statement i.e. division of a number by zero6. When u r trying to parse non integer String into integer etc….

If those abnormal conditions are not pre related or not handled properly then the program will be terminated in middle of execution or it leads to incorrect results.Java provides the sub classes of exception class to handle then abnormal conditions.

A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed.

Exceptions can be generated by the Java run-time system, or they can be manually generated by your code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. Manually generated exceptions are typically used to report some error condition to the caller of a method.

Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.

try: try block is used to place (put) the statements where (in which statements) there is a chance to occur runtime errors.

Every try block must precede either catch block or finally block i.e. after a try block you must write either catch block or finally block.

One try block may contain another try block such type of try block are called nested try blocks

Note: for a try block we can write any number of catch blocks but we can write only one finally block

catch: catch block is used to catch the exception thrown by the Java Runtime Environment, catch block must follow either a try block or a catch block.

finally: finally block is used to write(place) compulsorily executable statements. Like close the streams, close the connections etc….JavaRuntimeEnvironment always executes this block either exception handled or not.

throw: throw key word is used to throw the exceptions manually, use the keyword Any exception that is thrown out of a method must be specified as such by a

Throws: throws clause is used to throw any exception out of a method

43A winner not one who never fails but one who never QUITS

Naresh kumar

Page 44: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

This is the general form of an exception-handling block:

try {// block of code to monitor for errors

}catch (ExceptionType1 exOb) {

// exception handler for ExceptionType1}catch (ExceptionType2 exOb) {

// exception handler for ExceptionType2}// ...finally {

// block of code to be executed before try block ends}

Here, ExceptionType is the type of exception that has occurred.

Java’s Built-in Exceptions

Inside the standard package java.lang, Java defines several exception classes. All exception classes are divided into two types those are

1. Checked exceptions. (Unreported Exceptions)2. Unchecked exceptions.(Reported Exceptions)

Unchecked exceptions.(Reported Exceptions): exceptions derived from RuntimeException (Runtime Exception is a child class of Exception) are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions

Checked exceptions. (Unreported Exceptions): exceptions derived from Exception but not the sub classes of Runtime Exception are called checked exceptions

Exception Types

All exception types are subclasses of the built-in class Throwable which is an immediate subclass of the objects class. Methods are defined in the Throwable class to retrieve the error message associated with the exception and to print the information about the error i.e. where the exception occurs which type exception occurs and what is the cause

44A winner not one who never fails but one who never QUITS

Naresh kumar

Page 45: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Class Throwable has two immediate subclasses: class Error and class Exception. Subclasses of class Exception have the suffix Exception. / Subclasses of class Error have the suffix Error (and then there is ThreadDeath, a subclass of Error). The sub classes of Error are basically used for signaling abnormal system conditions. For example, an out of memory Error signals that the Java Virtual Machine has run out of memory and that the garbage collector is unable to claim any more free memory. A Stack overflow Error signals a stack overflow in the interpreter. These Error exceptions are, in general, unrecoverable and should not be handled

The subclasses of the Exception class are, in general, recoverable. For example, an EOFException signals that a file you have opened has no more date for reading. A file not Found Exception signals that a file you want to open does not exist in the file system. You can handle the exceptions by using a try-catch block

Throwable

Exception Error

Runtime ExceptionDirect sub classes of Exception class

Unchecked ExceptionsChecked Exceptions

Class Not Found ExceptionClone Not Supported ExceptionIllegal Access ExceptionInstantiation ExceptionInterrupted ExceptionNo Such Field ExceptionNo Such Method Exception

ArithmeticException Array Index Out Of Bounds ExceptionArray Store ExceptionClass Cast ExceptionNullPointerExceptionNumber Format ExceptionString Index Out Of Bounds

Subclasses of Runtime Exception

45A winner not one who never fails but one who never QUITS

Naresh kumar

Page 46: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Before you learn how to handle exceptions in your program, it is useful to see what happens when you don’t handle them. This small program includes an expression that intentionally causes a divide-by-zero error.

class ExDemo{

public static void main(String args[]){

System.out.println("Start of main() method");int a=10,b=0,c=0;

c=a/b;System.out.println("c=\t"+c);System.out.println("end of main() method");

}}

When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception. This causes the execution of ExDemo to stop, because once an exception has been thrown, it must be caught by an exception handler. In this example, we haven’t supplied any exception handlers of our own, so the exception is caught by the default handler provided by the Java run-time system. Any exception that is not caught by your program will ultimately be processed by the default handler. The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program. Here is the output generated when this example is executed.

Start of main() methodException in thread "main" java.lang.ArithmeticException: / by zero at ExDemon.main(ExDemon.java:7)

Using try and catch

Although the default exception handler provided by the Java run-time system is useful for debugging, you will usually want to handle an exception yourself. Doing so provides two benefits. First, it allows you to fix the error. Second, it prevents the program from automatically terminating.

To guard against and handle a run-time error, simply enclose the code that you want to monitor inside a try block. Immediately following the try block, includes a catch clause that specifies the exception type that you wish to catch. To illustrate how easily this can be done, the following program includes a try block and a catch clause which processes the ArithmeticException generated by the division-by-zero error:

class ExDemo

46A winner not one who never fails but one who never QUITS

Naresh kumar

Page 47: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

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

System.out.println("Start of main() method");int a=10,b=0,c=0;try{

c=a/b;System.out.println("This will not be printed.");

}catch(ArithmeticException ae){

System.out.println(ae);}System.out.println("c=\t"+c);System.out.println("end of main() method");

}}

Notice that the call to println( ) inside the try block is never executed. Once anexception is thrown, program control transfers out of the try block into the catch block.so execution never “returns” to the try block from a catch. Thus, the line “This will not be printed.” is not displayed. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism.

When u execute above program output will be:

Start of main() methodjava.lang.ArithmeticException: / by zeroc= 0end of main() method

Multiple catch ClausesIn some cases, more than one exception could be raised by a single piece of code.

To handle this type of situation, you can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after the try/catch block. The following example traps two different exception types:

import java.io.*;class ExDemo2{

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

DataInputStream dis=new DataInputStream(System.in);

47A winner not one who never fails but one who never QUITS

Naresh kumar

Page 48: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

System.out.println("Start of main method....");int c=0,a=0,b=0;try{System.out.println("enter a value");a=Integer.parseInt(dis.readLine());System.out.println("enter a value");b=Integer.parseInt(dis.readLine());

c=a/b;}catch(ArithmeticException ae){

System.out.println(ae);System.out.println(ae.getMessage());

}catch(NumberFormatException ae){

System.out.println(ae);ae.printStackTrace();

}System.out.println("c=\t"+c);

System.out.println("End of main method....");}

}

Nested try Statements

The try statement can be nested. That is, a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception. Here is an example that uses nested try statements:

class Emp{

public void display(){

System.out.println("Emp display........");}

}public class ExDemo3{

public static void main(String args[])

48A winner not one who never fails but one who never QUITS

Naresh kumar

Page 49: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

{System.out.println("start of main method");int a[]=new int[args.length];Emp e[]=new Emp[2];e[0]=new Emp();try{

try{for(int i=0;i<a.length;i++)a[i]=Integer.parseInt(args[i]);}catch(ArrayIndexOutOfBoundsException ao){System.out.println("cause:\t"+ao.getMessage());}

for(int i=0;i<e.length;i++)e[i].display();}catch(NullPointerException ne){

System.out.println(ne);}catch(NumberFormatException ne){

System.out.println(ne);}System.out.println("end of main method");

}}

E:\corejava\bindaas>java ExDemo3start of main methodEmp display........java.lang.NullPointerExceptionend of main method

Note: See the third output statement we get a NullPointerException because without initializing an Emp object to e[1] index we are trying to access display method

E:\corejava\bindaas>java ExDemo3 1 2 3 4estart of main methodjava.lang.NumberFormatException: For input string: "4e"end of main method

Note: See the second output statement we get a NumberFormatException because we pass a command line argument “4e” and in execution we are trying to parse that “4e” string into integer i.e. we can parse only numbers which are in the format of strings..

49A winner not one who never fails but one who never QUITS

Naresh kumar

Page 50: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

throw

So far, you have only been catching exceptions that are thrown by the Java run-time system. However, it is possible for your program to throw an exception explicitly, using the throw statement. The general form of throw is shown here:throw ThrowableInstance;Here, ThrowableInstance must be an object of type Throwable or a subclass ofThrowable

throws

If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception.A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result.

This is the general form of a method declaration that includes a throws clause:

type method-name(parameter-list) throws exception-list{// body of method}

Here, exception-list is a comma-separated list of the exceptions that a method can throw

finally

The finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement matches the exception Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns. This can be useful for closing file handles and freeing up any other resources that might have been allocated at the beginning of a method with the intent of disposing of them before returning. The finally clause is optional. However, each try statement requires at least one catch or a finally clause.

Creating Your Own Exception Subclasses

Although Java’s built-in exceptions handle most common errors, you will probably want to create your own exception types to handle situations specific to your applications. This is quite easy to do: just define a subclass of Exception. Here is an example that uses nested UserDefinedException.

50A winner not one who never fails but one who never QUITS

Naresh kumar

Page 51: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

class MyException extends Exception{

MyException(String cause){

super(cause);}

}class Login{

public static void main(String args[]){

java.util.Scanner s=new java.util.Scanner(System.in);System.out.println("enter uname:");String uname=s.next();System.out.println("enter password:");String pwd=s.next();try{

if(uname.equals("bdps") && pwd.equals("vij"))System.out.println("Welcome To BDPS ....\n

VIJAYAWADA");elsethrow new MyException("Invalid User name and password");

}catch(MyException me){

me.printStackTrace();}

}}

MULTITHREADING

Unlike other languages Java provides built-in support for multithreaded programming. Multithreaded program contains two or more parts that can run

51A winner not one who never fails but one who never QUITS

Naresh kumar

Page 52: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking.THREAD: a sub program in a multithreaded program (or) part of a Multithreaded program and each part is used to execute a task.

Now-a-days almost every knows about multitasking because every modern operating system supports multitasking.

There are two distinct types of multitasking:

1. Process-based2. Thread-based

Process-Based:a process is nothing but a program in execution. Thus, process-based multitasking

is the feature that allows your computer to run two or more programs concurrently. For example, process-based multitasking enables you to install oracle software at the same time that you are listening songs on Windows Media Player

Thread-Based:In a thread-based multitasking environment a single program can perform two or

more tasks simultaneously. For instance, a text editor can format text at the same time that it is printing.

Note: Processes are heavyweight tasks that require their own separate address spaces. Context switching from one process to another is also costly. Threads, on the other hand, are lightweight. They share the same address space and cooperatively share the same heavyweight process, Interthread communication is inexpensive, and context switching from one thread to the next is low cost

What is lightweight process and heavy weight process?

Answer:Lightweight process:A thread is considered to be a light weight process because it runs within the context of a program (within the process area) and utilizes the resources allocated to that program.

Heavy weight process: In heavy weight process, the control changes in between threads belonging to different programs (i.e. two different processes). But, in lightweight process, the control changes in between the threads belonging to the same (one) process.

Use: Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum

52A winner not one who never fails but one who never QUITS

Naresh kumar

Page 53: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Creating and Running a Thread:

We can create a thread in two ways1. By extending a thread class2. By Implementing a Runnable interface

To create a thread by extending Thread classIn the following program, 10 numbers (1 to 10) are printed by using a thread with

an interval of 1000 of milliseconds.File Name: ThreadDemo.javaclass MyThread extends Thread{

public void run(){

System.out.println(getName()+" Start");try{

for(int i=1;i<=10;i++){System.out.println(i);Thread.sleep(1000);}

}catch(InterruptedException ie){System.out.println("Thread is interrupted...."+ie);

}System.out.println(getName()+" End");

}}public class ThreadDemo{

public static void main(String args[]){

MyThread mt=new MyThread();mt.start();

}}Output:

53A winner not one who never fails but one who never QUITS

Naresh kumar

Page 54: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

About sleep () methodsleep () is a static method of Thread class with the following signature: public

static void sleep(long milliseconds) throws InterruptedExceptionsleep () method is static and throws a checked exception called Interrupted

Exception That is, when ever we use sleep () method, we should handle the InterruptedException. Sleep method makes a running (active) thread not to run (inactive) for the specified milliseconds of time. When the sleep time expires, the thread becomes automatically active. The active thread executes the run () method. When the thread comes out of the run () method, it dies. That is why we must write the code that is to be executed by the thread in run () method.

About start () methodMyThread mt=new MyThread();mt.start();

Observe the above first statement; we created an object for a class MyThread which extends Thread class i.e. We have created a thread, now we can say the newly created thread is in the new born state. The thread in born state occupies the memory resources but cannot utilize the microprocessor time.

In the second statement, we called the start () method on the thread. Start () method implicitly calls run () method. The thread in Runnable state is active and utilizes microprocessor time. The following is the method signature of the start () method.

MyThread class overrides the run () method of Thread class and contains a for loop that iterates 10 times. Between each iteration, it sleeps for 1 second (1000 milliseconds).

Creation of a thread my implementing Runnable interfaceThe above program is rewritten by implementing the Runnable interface (instead

of extending the Thread class). Every thing is almost same but for the small difference of writing implements instead of extends. Another difference is that the run () method in Thread class is a concrete method and it is left to the subclass to override it. The same run () method in Runnable interface is an abstract method. That is, the subclass that implements the Runnable interface must implement the run () method.File Name: RunnableDemo.java

54A winner not one who never fails but one who never QUITS

Naresh kumar

Page 55: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

class MyThread implements Runnable{

public void run(){

Thread t=Thread.currentThread();System.out.println(t.getName()+" Start");try{

for(int i=1;i<=10;i++){System.out.println(i);Thread.sleep(1000);}

}catch(InterruptedException ie){System.out.println("Thread is interrupted...."+ie);

}System.out.println(t.getName()+" End");

}}public class RunnableDemo{

public static void main(String args[]){

55A winner not one who never fails but one who never QUITS

Naresh kumar

Page 56: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

MyThread mt=new MyThread();Thread t=new Thread(mt);t.start();

}}

Instance of MyThread class is passed as a parameter to the Thread constructor. And instead of starting the class object (mt), an object of Thread class (t) is started. Here, mt is not a thread because it is not extending Thread class. That means, it cannot call the start () method of Thread class directly. To overcome this, the Thread constructor is overloaded that takes an object of a class which implements Runnable interface as parameter and start it. This is the difference between the above two programs.

When to use Runnable interfaceThere is limitation of extending the Thread class. If the class already extends any

other class, it is not possible to extend Thread class (as Java does not support multiple inheritance). In this case we go for Runnable interface.

Thread Scheduler:

Allocation of microprocessor time for al the threads is controlled by ThreadShedular, managed by the operating system. For allocation of microprocessor

56A winner not one who never fails but one who never QUITS

Naresh kumar

Page 57: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

time, thread scheduler takes into consideration many factors like a) the waiting period of thread b) the priority of thread etc. If a thread is in inactive state (as in sleep () method), thread scheduler keeps it away from the pool o active threads. When the inactive state is over, the thread joins back the pool of threads waiting for microprocessor time. It is the job of thread scheduler to manage the pool of threads – when and which thread must be given microprocessor time. Algorithm of thread scheduler is operating system dependent. Different operating systems adopt different algorithms.

Thread scheduler allocates the processor time first to the higher priority threads. To allocate microprocessor time in between the threads of the same priority, thread scheduler follows round-robin fashion.

The Thread class defines several methods that help manage threads. The ones that will be used in this chapter are shown here:

Method MeaninggetName Obtain a thread’s name.setName It sets a name for a thread getPriority Obtain a thread’s priority.isAlive Determine if a thread is still running.join This method waits until the thread on which it is

called terminates.(join method does not allow the parent thread to die until all its child threads die)

run Entry point for the thread.sleep Suspends a thread for a period of time.suspend It suspends a thread (sends it into a blocked state)resume It gets a thread into Runnable state from blocked

statewait and notify or notifyAll wait and notify methods are defined in Object class

and inherited by Thread class . wait method is used to suspend notify method is used to resume a thread and notifyAll method is used to resume more than one thread at a time but these methods only used with synchronization.

start Starts a thread by calling its run method.yield It gets a thread into Runnable state from running

stategetPriority It gets the priority of a threadsetPriority It sets the priority for a threadisDeamon Returns true if the thread is daemon thread else

falsegetThreadGroup Returns the name of the thread group for which the

thread belongs.

57A winner not one who never fails but one who never QUITS

Naresh kumar

Page 58: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Different states in which a thread exist between its birth and garbage collection is called the life cycle of thread.

There are Five States:1. New Born2. Runnable3. Running4. Blocked5. Dead

Born state:When a thread is created, we say it is in the born state. A thread in born state is

inactive and thereby not eligible for microprocessor time; but still occupies memory in the RAM.

58A winner not one who never fails but one who never QUITS

Naresh kumar

Page 59: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

MyThread mt=new MyThread();In the above statement, t1 thread is created but it is not active. To make it active, we have to call start () method.

Runnable state:When a thread is created, it is inactive and to make it active, we call start ()

method on it as follows:mt.start ();

When you call the start () method the thread will goes to the Runnable state. Means not in a running state but it is in a ready to run state (ready to share the microprocessor time).

Running State:When a thread is started (by calling start () method), it calls run () method

implicitly. Then we can say the thread is in the running state and it shares the microprocessor time.

Blocked State:A running thread can be made temporarily inactive for a short period by getting it

into blocked state. The thread in blocked state is inactive and not eligible for processor time.

Dead State:When the thread’s run method execution is over, it dies automatically and the

thread object is garbage collected. A dead thread object cannot be restarted again. By calling stop () method from any state, we can bring the thread to dead state.

Thread Priorities

Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run. In theory, higher-priority threads get more CPU time than lower priority threads. In practice, the amount of CPU time that a thread gets often depends on several factors besides its priority. (For example, how an operating system implements multitasking can affect the relative availability of CPU time.) A higher-priority thread can also preempt a lower-priority one. For instance, when a lower-priority thread is running and a higher-priority thread resumes (from sleeping or waiting on I/O, for example), it will preempt the lower-priority thread.

In theory, threads of equal priority should get equal access to the CPU. But you need to be careful. Remember, Java is designed to work in a wide range of environments. Some of those environments implement multitasking fundamentally differently than others. For safety, threads that share the same priority should yield control once in a while. This ensures that all threads have a chance to run under a non preemptive

59A winner not one who never fails but one who never QUITS

Naresh kumar

Page 60: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

operating system. In practice, even in non preemptive environments, most threads still get a chance to run, because most threads inevitably encounter some blocking situation, such as waiting for I/O. When this happens, the blocked thread is suspended and other threads can run. But, if you want smooth multithreaded execution, you are better off not relying on this. Also, some types of tasks are CPU-intensive. Such threads dominate the CPU. For these types of threads, you want to yield control occasionally, so that other threads can run. To set a thread’s priority, use the setPriority ( ) method, which is a member of Thread. This is its general form: final void setPriority (int level) Here, level specifies the new priority setting for the calling thread. The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively. To return a thread to default priority, specify NORM_PRIORITY, which is currently 5. These priorities are defined as final variables within Thread.

You can obtain the current priority setting by calling the getPriority ( ) method of Thread, shown here:final int getPriority( )

Implementations of Java may have radically different behavior when it comes to scheduling. The Windows XP/98/NT/2000 version works, more or less, as you would expect. However, other versions may work quite differently

What is thread synchronization?

Generally, one thread executes one resource of data at a time. There may be situation when multiple threads access the same data at a time. For example, the joint account holders of an account may access their bank account at a time from different teller counters in bank. This at times lead to data inconsistency, it is necessary to carefully coordinate the actions between threads especially when multiple threads access the same data. To overcome this situation, the threads are to be coordinated or synchronized. Synchronization is the way to see only one thread access one resource at a time.

What is Daemon Threads?

A daemon thread is a thread that runs for the benefit of other threads. Daemon threads are known as service threads. Daemon threads run in the background and come into execution when the microprocessor is idle. The garbage collector is a good example for a daemon thread. We can set a thread to be a daemon one, by calling the method set Daemon (true).

Thread Group

Every thread belongs to some thread group. That is, no thread exists without a thread group (like no file can exist without a directory). When a thread is created without assigning a group name, by default it is put into the main thread group. A thread group can have both threads and other sub thread groups as members (like a directory can have both directories and files). Main is a thread in the thread group called main.

60A winner not one who never fails but one who never QUITS

Naresh kumar

Page 61: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

The following is the signature of the ThreadGroup class:public class ThreadGroup extends ObjectThe importance of a thread group is that all the threads in a thread group can be stopped together by calling tg.stop () or can be suspended by calling tg.suspend () or can be resumed by calling tg.resume () where tg is a thread group name. But we can’t start by calling tg.start (). Each thread in a group must be started individually.

ThreadGroupDemo.java

import java.io.*;class MyThread1 extends Thread{

MyThread1(ThreadGroup tg,String name){

super(tg,name);}public void run(){

for(int i=0;i<10;i++){try{if(i==0)sleep(2000);}catch(Exception e){}}

}}class MyThread2 extends Thread{

ThreadGroup tg1;MyThread2(ThreadGroup tg,String name){

super(tg,name);tg1=tg;

}MyThread2(String name){

super(name);}public void run(){

for(int i=0;i<10;i++){try

61A winner not one who never fails but one who never QUITS

Naresh kumar

Page 62: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

{if(i==0)sleep(2000);}catch(Exception e){}}

}}

class ThreadGroupDemo{

public static void main(String a[])throws Exception{Thread main=Thread.currentThread();ThreadGroup mtg=main.getThreadGroup();ThreadGroup mtgp=mtg.getParent();MyThread2 T4=new MyThread2("Four");T4.start();mtgp.list();ThreadGroup tg1=new ThreadGroup("TG1");System.out.println("tg1 parent:\t"+(tg1.getParent()).getName());MyThread1 T1=new MyThread1(tg1,"First");MyThread2 T2=new MyThread2(tg1,"Second");MyThread2 T3=new MyThread2(tg1,"Third");//System.out.println("T4 thread Group:\t"+(T4.getThreadGroup()).getName());T1.start();T2.start();T3.start();tg1.list();tg1.suspend();System.out.println("D U Want to resume (yes/no)");if(((new DataInputStream(System.in)).readLine()).equals("yes"))tg1.resume();System.out.println("End of main method...");

}}

Dead Lock

In a multithreaded program, if we do not synchronize multiple threads properly, a deadlock situation may arise and if such a situation comes, the program simply hangs. Deadlock comes between synchronized threads only. It occurs when two or more threads wait indefinitely for each other to obtain locks (that is, two threads depends on each other). Say for example, there are two threads; one thread’s output is another’s input.

62A winner not one who never fails but one who never QUITS

Naresh kumar

Page 63: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Now it is a deadlock. Deadlock will not allow both the threads to go further. That is, for execution of one thread depends on the other

DeadLockDemo.java

class ClassA{

public synchronized void first(ClassB b){Thread t=Thread.currentThread();System.out.println(t.getName()+"Entered into the ClassA");try{Thread.sleep(2000);}catch(InterruptedException ie){ie.printStackTrace();}System.out.println(t.getName()+"Is trying to call ClassB last().....");b.last();}public synchronized void last(){

System.out.println("ClassA last........ ");}

}

class ClassB{

public synchronized void first(ClassA a){Thread t=Thread.currentThread();System.out.println(t.getName()+"Entered into the ClassB");System.out.println(t.getName()+"Is trying to call ClassA last().....");a.last();}public synchronized void last(){

System.out.println("ClassB last........ ");}

}class Thread2 implements Runnable{

ClassA a;ClassB b;Thread2(ClassA a,ClassB b){this.a=a;this.b=b;

63A winner not one who never fails but one who never QUITS

Naresh kumar

Page 64: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Thread t=Thread.currentThread();//t.setName("Main Thread");new Thread(this).start();a.first(b);}public void run(){

b.first(a);}

}

public class DeadlockDemo{

public static void main(String args[]){

//ClassA.display();ClassA a=new ClassA();ClassB b=new ClassB();new Thread2(a,b);

}}

ClassPath: Class path is the System variable that contains active directory path.

64A winner not one who never fails but one who never QUITS

Naresh kumar

Page 65: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

UTIL PACKAGES NOTES

Sub classes of Collection interface are called collection classes. Some of these are abstract and some of these are non-abstract. Some of these are…..

1. Abstract Collection2. Abstract List3. Linked List4. Array List5. Hash Set6. Tree Set

Array List: Array List is a dynamic array that stores objects. (size increases when you add and shrinks when you delete).

ArrayListDemo.java

import java.util.*;class Emp{

String get(){return "Ename: Madhu\t eno: "+101+"\tEsal: 30000";}

}class ArrayListDemo{

public static void main(String args[]){Emp e=new Emp();ArrayList list=new ArrayList();list.add(e);list.add(new Emp());list.add(null);list.add(new Integer(10));list.add("Util Packages");list.add("Java");list.add(2,"Six");System.out.println("contains :\t"+list.contains(e));System.out.println("2 nd index "+list.get(2));list.remove(2);System.out.println("2 index "+list.get(2));System.out.println("size of ArrayList :\t"+list.size());Iterator i1=list.iterator();Object o=null;

65A winner not one who never fails but one who never QUITS

Naresh kumar

Page 66: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

while(i1.hasNext()){

o=i1.next();if(o instanceof Emp)System.out.println(((Emp)o).get());elseSystem.out.println(o);

}System.out.println("\nUsing List Iterator");ListIterator li=list.listIterator(3);while(li.hasNext()){o=li.next();if(o instanceof Emp)

System.out.println(((Emp)o).get());elseSystem.out.println(o);

}System.out.println(list);}

}

Iterator:

Iterator means an object with which we can travel all through a range of elements. It works like a pointer in database, sometimes iterator is called as a cursor.

1 Boolean hasNext()2 Object next()3 Void remove() the current element from list.

List Iterator: Used to choose no of elements to print;

listIterator() is a method of LinkedList that returns an object of ListIterator. ListIterator is a sub class of Iterator interface

ListIterator li=list.listIterator();ListIterator li=list.listIterator(3);

This statement prints form 3rd element this facility not available in “Enumeration” interface.Linked List: Linked list includes many convenient methods to manipulate the elements stored. Apart from suing the methods of super class List.. it adds it’s own methods also of which few are illustrated here

1 Void addFirst(Object obj)2 Void addLast(Object obj);3 Object getFirst();

66A winner not one who never fails but one who never QUITS

Naresh kumar

Page 67: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

4 Object getLast();5 Object removeFirst();

6 Object removeLast();

LinkedListDemo.java

import java.util.*;public class LinkedListDemo{

public static void main(String args[]){

LinkedList ll=new LinkedList();byte b=40;ll.add(new Emp());ll.add(null);ll.add(new Character('c'));ll.add(new Byte(b));ll.add(new Long(2345678));ll.add(new Integer(345));Emp e=(Emp)ll.getFirst();System.out.println("First:\n");e.getDetails();System.out.println("\nLast:\t"+ll.getLast());System.out.println("\n Two Items are Entered\n");ll.addFirst(new Float(234.56f));ll.addLast(new Double(123.45));System.out.println("\nFirst:\t"+ll.getFirst());System.out.println("\nLast:\t"+ll.getLast());System.out.println("Is Emp object contains:\t"+ll.contains(e));Iterator itr=ll.listIterator(4);

//4 is a starting index number

Object o=null;while(itr.hasNext()){

o=itr.next();if(o instanceof Emp)((Emp)o).getDetails();elseSystem.out.println(o);

} System.out.println(ll);

}}

67A winner not one who never fails but one who never QUITS

Naresh kumar

Page 68: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

The Vector class implements a grow able array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector, the vector's storage increases in chunks the size of capacityIncrement. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation.

VectorDemo.java

import java.util.*;class Emp{

void getDetails(){

System.out.println("101");System.out.println("Venkateswarulu");System.out.println("Faculty");System.out.println("60000");

}}public class VectorDemo{

public static void main(String args[]){

Vector v=new Vector();Emp e=new Emp();byte b=20;

Byte b1=new Byte(b);v.add(new Integer(10));v.add(new Float(10.50));v.add(new String("Shekar"));v.add(b1);v.add(b1);v.add(e);v.add(new Emp());v.add(0,new String("Zero "));System.out.println("Size of the Vector:\t"+v.size());Object o=v.get(1);System.out.println(o);System.out.println("default capacity of v :\t"+v.capacity());v.add(3,new String(" Manisha"));

68A winner not one who never fails but one who never QUITS

Naresh kumar

Page 69: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Vector v1=(Vector)v.clone();for(int i=0;i<v.size();i++){

o=v.get(i);if(o instanceof Emp)((Emp)o).getDetails();elseSystem.out.println(o);

}System.out.println("Last IndexOf Emp e:\t"+v.lastIndexOf(e));System.out.println("IndexOf Emp e:\t"+v.indexOf(e));System.out.println("Last IndexOf Emp e:\t"+v.lastIndexOf(e,6));System.out.println("Capacity Of Vector :\t"+v.capacity());v.setSize(20);System.out.println("Capacity to Vector :\t"+v.capacity());v.remove(e);System.out.println("deleted object is:\t"+e);System.out.println("\nEnumeration object....\n");Enumeration totele=v1.elements();while(totele.hasMoreElements()){

o=totele.nextElement();if(o instanceof Emp)((Emp)o).getDetails();elseSystem.out.println(o);

}Iterator it=v1.iterator();System.out.println("\nIterator\n");while(it.hasNext()){System.out.println(it.next());}

}}(The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.HashMapDemo.java

import java.util.*;class HashMapDemo{

public static void main(String ar[]){

69A winner not one who never fails but one who never QUITS

Naresh kumar

Page 70: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

HashMap h=new HashMap();h.put("101","Madhu");h.put("102","Balaji");h.put("103","Bhargav");h.put("104","Bhavani");h.put("105","Aparna");Collection c=h.values();Vector =new Vector();v.add(c);Object o=null;Enumeration list=v.elements();while(list.hasMoreElements()){

o=list.nextElement();if(o instanceof Collection){

Iterator it=((Collection)o).iterator();while(it.hasNext()){System.out.println(it.next());}

}

}}

}HashTable class is derived from Dictionary class and provides complete implementation of a key-mapped data structure. HashTable stores the data in the form of key/value pairs. In Hashtable, the key and cvalue may be objects of any type.

HashTableApp.java

import java.lang.System;import java.util.Hashtable;import java.util.*;public class HashTableApp{

public static void main(String args[]){Hashtable h=new Hashtable();Enumeration keys;Enumeration elements;h.put("101","Madhu");h.put("102","Balaji");h.put("103","Bhargav");

70A winner not one who never fails but one who never QUITS

Naresh kumar

Page 71: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

h.put("104","Bhavani");h.put("105","Aparna");System.out.println("get mthod:\t"+h.get("101"));//get method takes key as a parameter and return valuekeys=h.keys();elements=h.elements();while(keys.hasMoreElements()){

System.out.println(keys.nextElement()+":\t"+elements.nextElement());

}}

}

Hash Set:Hash set does not guarantee that the order will remain constant. This class permits

the null element.Methods of this class is not synchronized

HashSetDemo.java

import java.util.*;class HashSetDemo{

public static void main(String ar[]){HashSet hs=new HashSet();hs.add("one");hs.add("Two");hs.add(null);//duplicate are not allowed here it replaces existed onehs.add("one");hs.add("one");hs.add("one");hs.add("one");System.out.println(hs.size());Iterator it=hs.iterator();

while(it.hasNext()){System.out.println(it.next());}

System.out.println(hs);}

}

71A winner not one who never fails but one who never QUITS

Naresh kumar

Page 72: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Tree Set:This class guarantees that the sorted set will be in ascending element order

The tree set implementation is useful when we need to extract elements from a collection in a sorted manner.

TreeSetDemo.java

import java.util.*;class TreeSetDemo{

public static void main(String ar[]){TreeSet ts=new TreeSet();ts.add("Jyothi");ts.add("Gayathri");ts.add("VN Reddy");ts.add("Kumar");ts.add("Raju");Iterator it=ts.iterator();while(it.hasNext()){System.out.println(it.next());}SortedSet ss=ts.subSet("Jyothi","Raju");System.out.println(ss);}

}

StringTokenizerDemo2.javaimport java.util.*;import java.io.*;public class StringTokenizerDemo2{

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

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

//BufferedReader br=new BufferedReader(new FileReader("VectorDemo.java"));

System.out.println("Enter a String");String str,filedata="";while((str=br.readLine())!=null){

72A winner not one who never fails but one who never QUITS

Naresh kumar

Page 73: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

if(str.equals("end"))break;filedata=filedata+str+":";}System.out.println("filedata var :\n"+filedata+"\n\n");Thread.sleep(3000);StringTokenizer token=new StringTokenizer(filedata,":");int numOfTokens=token.countTokens();System.out.println("No of Tokens:\t"+numOfTokens);while(token.hasMoreTokens()){

str=token.nextToken();System.out.println(str);

}

}}

StringTokenizerDemo.java

import java.util.*;class STDemo{

static String s1="This is test for String tokenizer";static String s2="K.madhu: computer science; and Engineering Dept:"+"Java is a

two stage system:"+"Java is a Platform independent Language; simple language"+"it is a robust;and small language";

public static void main(String args[]){

StringTokenizer A=new StringTokenizer(s1);StringTokenizer B=new StringTokenizer(s2,":;");System.out.println("No. of Tokens A|t"+A.countTokens());System.out.println("No. of Tokens B:\t"+B.countTokens());while(A.hasMoreElements())System.out.println(A.nextToken());while(B.hasMoreElements())System.out.println(B.nextToken());

}}

DateDemo.java

import java.util.*;public class DateDemo{

73A winner not one who never fails but one who never QUITS

Naresh kumar

Page 74: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

public static void main(String args[]){String days[]={"","sun","mon","tues","wed","thur","fri","sat"};String am[]={"AM","PM"};Date d=new Date();GregorianCalendar gc=new GregorianCalendar();System.out.println(d);System.out.println("Date:\t"+days[gc.get(Calendar.DAY_OF_WEEK)]+"/"+

((gc.get(Calendar.MONTH))+1)+"/"+gc.get(Calendar.YEAR));System.out.println("Time:\t"+gc.get(Calendar.HOUR)+":"+

(gc.get(Calendar.MINUTE)+1)+":"+(gc.get(Calendar.SECOND)+1)+" "+am[gc.get(Calendar.AM_PM)]);

}}

See the below table which describes the Calendar class and values returned by the get() method of Gregorian Calendar class

Field(of Calendar class) Possible values returned by get()

AM_PM 0 or 1

DAY_OF_WEEK Sunday, Monday etc…to sat 1 to 7

DAY_OF_YEAR 1 to 366

MONTH 0 to 11

DAY_OF_MONTH 1 TO 31

WEEK_OF_MONTH 1 TO 6

WEEK_OF_YEAR 1 to 54

HOUR_OF_DAY 0 to 23

HOUR 1 to 12

MINUTE 0 to 59

SECOND 0 to 59

MILLISECOND 0 to 999

YEAR CURRENT YEAR

74A winner not one who never fails but one who never QUITS

Naresh kumar

Page 75: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

SimpleDateFormatDemo.javaimport java.text.*;import java.util.*;public class SimpleDateFormatDemo{

public static void main(String args[]){Date d=new Date();SimpleDateFormat sdf=null;sdf=new SimpleDateFormat("dd/MMM/yyyy");System.out.println(sdf.format(d));}

}

SEE THE BELOW TABLE WHICH DESCRIBES DEFFERENT FORMATS

Letter Date or Time Component Presentation Examples

G Era designator Text AD y Year Year 1996; 96 M Month in year Month July; Jul; 07 w Week in year Number 27 W Week in month Number 2 D Day in year Number 189 d Day in month Number 10

F Day of week in month Number 2

E Day in week Text Tuesday; Tue a Am/pm marker Text PM H Hour in day (0-23) Number 0 k Hour in day (1-24) Number 24

K Hour in am/pm (0-11) Number 0

h Hour in am/pm (1-12) Number 12

m Minute in hour Number 30 s Second in minute Number 55 S Millisecond Number 978

z Time zone General time zone Pacific Standard Time; PST; GMT-08:00

Z Time zone RFC 822 time zone -0800

75A winner not one who never fails but one who never QUITS

Naresh kumar

Page 76: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Lang Package IMP Programs

PropertiesDemo.java import java.util.*;class PropertiesDemo{

public static void main(String args[]){

Properties prop=System.getProperties();prop.list(System.out);String str=System.getProperty("sun.desktop");System.out.println("......"+str);

}}

ArrayCopy.javaclass ArrayCopy{

public static void main(String args[]){System.err.println("Standard Error Stream");System.out.println("Standard OutputStream ");byte a[]={65,66,67,68,97,98};byte b[]={65,65,67,67,98,98};System.out.println("before copy");System.out.println(new String(a));System.out.println(new String(b));System.arraycopy(a,0,b,0,a.length);System.out.println("after copy");System.out.println(new String(a));System.out.println(new String(b));}

}

ClassDemo.java

interface inf1{}class A implements inf1{}class B extends A{

void printClassName(Object obj) {System.out.println("hash code of Obj:\t"+obj.hashCode());System.out.println("The class of " + obj +" is " +

obj.getClass().getName());Class c=getClass();System.out.println(c.getSuperclass());

}}class ClassDemo{

76A winner not one who never fails but one who never QUITS

Naresh kumar

Page 77: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

public static void main(String args[]){

inf1 i1=new A();A a=new A();B b=new B();b.printClassName(a);b.printClassName(i1);System.out.println(a.getClass());//System.out.println((b.getClass()).getSuperClass());

}}

ExecDemo.java

import java.io.*;class ExecDemo{

static DataInputStream dis;static void execute(InputStream in)throws Exception{

dis=new DataInputStream(in);String str=null;while((str=dis.readLine())!=null)System.out.println(str);

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

InputStream in=null,err=null;DataInputStream dis=null;Runtime r=Runtime.getRuntime();//it returns the current object.Process p1=null,p2=null;System.out.println("Enter the class name u want to execute");String rfile=(new DataInputStream(System.in)).readLine();try{

p1=r.exec("java "+rfile);System.out.println("\\Madhu\\");//p2=r.exec("c:\\windows\\notepad.exe");p2=r.exec("C:\\Program Files\\Windows NT\\Pinball\\

PINBALL.EXE");in=p1.getInputStream();err=p1.getErrorStream();ExecDemo.execute(in);ExecDemo.execute(err);p2.waitFor();

}catch(Exception e){System.out.println("Error"+e);}System.out.println("Note pad Closed.."+p2.exitValue());

}}

77A winner not one who never fails but one who never QUITS

Naresh kumar

Page 78: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

I / O streams

So far we have used variables and arrays for storing data inside the programs. This approach poses the following problems.

1. The data is lost either when a variable goes out of scope or when the program is terminated. That is storage is temporary.

2. It is difficult to handle large volumes of data using variables and arrays

We can overcome these problems by storing data on secondary storage devices such as floppy disks or hard disks. The data is stored in these devices using the concept of files. Data is stored in files is often called persistent data.

A file is a collection of related records placed in a particular area on the disk. A record is composed of several fields and a field is a group of characters. Characters in java are Unicode characters composed of two bytes, each byte containing eight binary digits, 1 or 0.

Concepts of Streams:

In file processing, input refers to the flow of data into a program and output means the flow of data out of a program.

A stream represents a uniform, easy-to-use, object-oriented interface between the program and the input/output devices.

A stream in java is a path along which data flows (like a river or a pipe along which water flows). It has a source (of data) and a destination (for that data). Both the source and the destination may be physical devices or programs or other streams in the same program.

The concept of sending data from one stream to another (like one pipe feeding into another pipe) has made streams in java a powerful tool for file processing. We can build a complex file processing sequence using a series of simple stream operations. This feature can be used to filter data along the pipeline of streams so that we obtain data in a desired format. For example, we can use one stream to get raw data in binary format and then use another stream in series to convert it to integers.

Stream Classes:

The java.io package contains large number of stream classes that provide capabilities for processing all types of data. These classes may be categorized into two groups based on the data type on which they operate.

78A winner not one who never fails but one who never QUITS

Naresh kumar

Page 79: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Byte Stream classes that provide support for handling I/O operations on bytes. Character stream classes that provide support for managing I/O operations on

characters.

BYTE STREAM CLASSES:Byte stream classes have been designed to provide functional features for creating

and manipulating streams and files for reading and writing bytes. Since the streams are unidirectional, they can transmit bytes in only one direction and therefore java provides two kinds of byte stream classes:

Input Stream classes Output Stream classes

Streams

Byte Streams Character Streams

Input Stream Output Stream Reader Writer

Input Stream

String Buffer InputStream

File Input Stream

Byte Array Input Stream

Filter Input Stream

Sequence Input Stream

Object Input Stream

Piped Input Stream

Line Number Input Stream

Data Input Stream

Buffered Input Stream

Pushback Input Stream

Output Stream

ByteArrayOutputStream

File Output Stream

FilterOutputStream

ObjectOutputStream

PipedOutputStream

DataOutputStream

BufferedOutputStream

PrintStream

79A winner not one who never fails but one who never QUITS

Naresh kumar

Page 80: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

CHARACTER STREAM CLASSES:Character stream classes were not a part of the language when it was released in

1995. They were added later when the version 1.1 was announced, character streams can be used to read and write 16-bit Unicode characters. Like byte streams, there are two kinds of character stream classes, namely.

Reader stream classes Writer stream classes.

Buffer: a buffer is a storage place where data can be kept before it is needed by a program that reads or writes that data. By using a buffer, you can get data without always going back to the original source to the data.

1. FileInputStream and FileOutputStream: These streams are used to read the data from file and write the data to the file. But, they are very poor in performance because

Reader

PipedReader

CharArrayReader

StringReader

BufferedReader

InputStreamReader

FilterReader

LinerNumberedReader

FileReader

PushbackReader

Writer

StringWriter

CharArrayWriter

PipedWriter

OutputStreamWriter

FilterWriter

BufferedWriter

PrintWriter

FileWriter

80A winner not one who never fails but one who never QUITS

Naresh kumar

Page 81: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

they read and write the data byte by byte. For this reason, programmers prefer these streams when the file size is of less size. The methods they include are read (), write (), available (), and close () etc…

2. ByteArrayInputStream and StringBufferInputStream: These streams give buffering effect in terms of an array and string buffer. The buffering always increases the performance.

3. SequenceInputStream: This stream is used to merge two files into one file and read the data from more than one file at a time. I.e. it is used to copy a number of source files into one destination file.

4. ObjectInputStream and ObjectOutputStream:These streams are used to read objects and write objects and write objects to a file (for a permanent storage). When we write an object to file, along with the object the encapsulated variables also go and stored in the file. With this, a lot of code comes down. The methods they include are readObject () and writeObject () etc.

5. PipedInputStream and PipedOutputStream: These streams are used to transfer the data between two running threads. PipedInputStream can read the data only from PipedOutputStream

6. LineNumberInputStream: Tt is used to add line numbers that does not exist in the source file. An important method is getLineNumber ().

7. DataInputStream and DataOutputStream: These streams increase the prerformance to a great extent. They include special methods like readInt(). readDouble(). readLine(), writeInt(), writeDouble() and writeBytes() etc., which can read or write an integer, a double or a line at a time (not byte by byte).

8. PrintStream: This is an output stream which writes data. The important methods are println() and print().

9. FilterInputStream and FilterOutputStream: For get more functionality from streams, we can chain (link) streams. The functionality may include the concepts like to add the line numbers in the destination file that do not exists in the source file or to increase the performance. Filter streams are abstract classes. The subclasses of these streams are called as high-level streams and the remaining streams in the hierarchy are called low-level streams.

10.BufferedInputStream andBufferedOutputStream: These are high-level streams being the subclasses of Filter streams

81A winner not one who never fails but one who never QUITS

Naresh kumar

Page 82: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

and they link (attach) a buffer memory to an input/output stream. These are used to increase the performance.

11. PushbackInputStream: Being a high-level stream. It adds functionality to another stream. It can be used to tokenize a stream depending on the delimiter we supply. For example, while tokenizing a string like “Madhu is a god boy” the extra-unwanted delimiter character, white space, can be pushed back to the stream.

CHARACTER STREAMS:

1. BufferedReader and Buffered Writer: They buffer the data while reading and writing, thereby reducing the number of transfers required on the original data source. Buffered streams are typically more efficient than similar non-buffered streams.

2. FilterReader and Filter Writer: These are abstract classes, which add special effects like adding line numbers or increasing the performance etc. They define the interface for filter streams, which filter data as it’s being read or written. Filter streams provide additional functionality to the streams. A filter is a type of stream that modifies the way of handling the existing stream.

3. InputStreamReader and OutputStreamWriter: These streams are used to convert by stream into character stream and vice versa. They form a bridge between byte streams and character streams. An InputStreamReader reads bytes from an InputStream and converts them to characters. Similarly, an OutputStreamWriter converts characters to bytes and writes those bytes to an OutputStream.

4. LineNumberReader: Add line numbers while reading.5. PushbackReader: The PushbackReader class is used for special purpose. Once the program has determined that the current aggregate of data is complete, the extra character is “pushed back” onto the stream. PushbackInputStream is used by programs like compilers that parse their inputs, that is break them into meaningful units (like keywords, identifiers etc).

6. PrintWriter: These class contains convenient printing methods like println () and print (). These are the easiest streams to write to monitor.

1Q. what is serialization (or Object serialization)?

82A winner not one who never fails but one who never QUITS

Naresh kumar

Page 83: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Serialization is the process used for the persistence of an object by writing the object’s state to a stream of data. Object serialization takes an object’s state, and converts it to a byte stream. Object serialization provides a program the ability to read or write a whole object at a time from and to a raw byte stream. A serialized format contains the object’s state information.

Data persistence:we can store object and object’s state in the file this is called data persistence.

Deserialization is the process of converting or reconstructing the state of the serialized object to the original state at a later time.

Object Persistence and Serialization

Ordinarily, a Java object lasts no longer than the program that created it. An object may cease to exist during run time if it is reaped by the garbage collector. ff it avoids that fate, it still dies when the user terminates the browser (for an applet) or the object's runtime envirom-nent (for an application).

In this context, persistence is the ability of an object to record its state so it can be reproduced in the future, perhaps in another environment. For example, a persistent object n-dght store its state in a file. The file can then be used to restore the object in a different runtime enviroziimexit. It is not really the object itself that persists, but rather the information necessary to construct a replica of the object.

An object records itself by writing out the values that describe its state. This process is known as serialization because the object is represented by an ordered series of bytes. Java provides classes that write objects to streams and restore objects from streams.

The main task of serialization is to write the values of an object's instance variables. If a variable is a reference to another object, the referenced object must also be serialized. This process is recursive; serialization may involve serializing a complex tree structure that consists of the original object, the object's object's objects, and so on. An object's ownership hierarchy is known as its graph.

Criteria for Serialization

Not all classes are capable of being serialized. C)nly classes that implement theSerializable or Externalizabl e interfaces successfully be serialized. Both of these interfaces are in the java.io package. An external object, which in practice is a type of output stream, can serialize a serializable object; an externalizable object must be capable of writing its own state, rather than letting the work be done by another object.

You can serialize any class as long as it meets the following criteria:• The class, or one of its superclasses, must implement the java.io.Seria1izable interface.• The class must participate with the writeObject() method to control data that is being saved and append new data to existing saved data.

83A winner not one who never fails but one who never QUITS

Naresh kumar

Page 84: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

• The class must participate with the readObject() method to read the data that was written by the corresponding writeObject() method.

If a serializable class has variables that should not be serialized, those variables must be marked with the transi ent keyword; then the serialization process will ignore them.

NOTE : Implementing write0bject( and readobject( ) methods and throwing the NotSerializableException will prevent serialization of an object. The 0biectoutput Stream (or ObjectInputStream) will catch the exception and abort the process.

The Serializable interface

The Serializable interface does not have any methods. When a class declares that it implements Serializabl e, it is declaring that it participates in the serializable protocol. When an object is serializable and the object's state is written to a stream, the stream must contain enough information to restore the object. This must hold true even if the class being restored has been updated to a more recent (but compatible) version.

The Externalizable InterfaceThe Externalizable interface identifies objects that can be saved to a stream but

that are responsible for their own states. Then an externalizable object is written to a stream, the stream is only responsible for storing the name of the object's class; the object must write its own data. The Externalizable interface is defined as:

public interface Externalizable extends Serializablepublic void writeexternal (ObjectOutput out) throws IOException;public void readexternal (ObjectInput in) throws IOException, ClassNotFoundException;

An extemalizable class must adhere to this interface by providing a writeExternal() method for storing its state during serialization and a readExternal() method for restoring its state during deserialization.

FileDemo.java

import java.io.*;class FileDemo{

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

File f=new

File("E:/corejava/batch45/iostreams/YeFile.java");if(f.createNewFile()){System.out.println(f.getName()+" created");

84A winner not one who never fails but one who never QUITS

Naresh kumar

Page 85: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

}else{

System.out.println(f.getName()+" already existed....");}

File f1=new File("manadir");if(f1.mkdir()){

System.out.println(f1.getName()+" dir created");}elseSystem.out.println(f1.getName()+" dir is already existed");System.out.println("exists:\t"+f.exists());System.out.println("Is File:\t"+f.isFile());System.out.println("IsDirectory:\t"+f.isDirectory());f.setReadOnly();System.out.println("f name:\t"+f.getName());System.out.println("Parent:\t"+f.getParent());System.out.println("Path:\t"+f.getPath());System.out.println("IsReadable:\t"+f.canRead());System.out.println("IsWritable:\t"+f.canWrite());System.out.println("IsHidden:\t"+f.isHidden());System.out.println("LastModified:\t"+new

java.util.Date(f.lastModified()));//f.delete();File dir=new File("E:/corejava/batch45/iostreams");

String files[]=dir.list();for(int i=0;i<files.length;i++){if((new File(files[i])).isDirectory())System.out.println("Dir: "+i+":\t"+files[i]);elseSystem.out.println("File: "+i+":\t"+files[i]);}

}}

FileOutputInputDemo.java

import java.io.*;public class FileOutputInputDemo{

85A winner not one who never fails but one who never QUITS

Naresh kumar

Page 86: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

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

DataInputStream dis=new DataInputStream(System.in);System.out.println("Enter path of the file name you want to copy");String source=dis.readLine();FileInputStream fis=new FileInputStream(source);byte[] b=new byte[fis.available()];fis.read(b);System.out.println("Enter path of the dest file ");String dest=dis.readLine();/*File f=new File(dest);f.createNewFile();*/FileOutputStream fos=new FileOutputStream(dest);fos.write(b);System.out.println("Enter path of the file name you want to see");source=dis.readLine();FileInputStream fis1=new FileInputStream(source);int d;while((d=fis1.read())!=-1){

System.out.print((char)d);}fis1.read(b);System.out.println(new String(b));

fis.close();fis1.close();fos.close();

}}

SequenceInputStreamDemo.java

/* we can read the data form more than one file at a time */

import java.io.*;import java.util.Enumeration;import java.util.*;public class SequenceInputStreamDemo{

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

FileInputStream fis1=new FileInputStream("FileDemo.java");FileInputStream fis2=new FileInputStream("FileOutputDemo.java");FileInputStream fis3=new FileInputStream("FileOutputDemo2.java");Vector coll=new Vector();

86A winner not one who never fails but one who never QUITS

Naresh kumar

Page 87: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

coll.add(fis1);coll.add(fis2);coll.add(fis3);coll.add(new FileInputStream("SequenceInputStreamDemo.java"));Enumeration e=coll.elements();SequenceInputStream sis=new SequenceInputStream(e);//SequenceInputStream sis=new SequenceInputStream(fis2,fis1);/*DataInputStream dis=new DataInputStream(sis);String str;while((str=dis.readLine())!=null)System.out.println(str);*/

BufferedInputStream bis=new BufferedInputStream(sis);BufferedOutputStream bos=new BufferedOutputStream(System.out);int b;while((b=bis.read())!=-1){

bos.write(b);//System.out.print((char)b);

}fsbos.flush();bis.close();bos.close();fis1.close();fis2.close();sis.close();

}}

LineNumberDemo.java

import java.io.*;public class LineNumberDemo{

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

FileInputStream fis=new FileInputStream("PipedInputStreamDemo.java");

LineNumberInputStream ln=new LineNumberInputStream(fis);DataInputStream dis=new DataInputStream(ln);String str=null;while((str=dis.readLine())!=null){

System.out.println(ln.getLineNumber()+" "+str);}

87A winner not one who never fails but one who never QUITS

Naresh kumar

Page 88: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

dis.close();}

}

BufferedInputStreamDemo.java

import java.io.*;public class BufferedInputStreamDemo{

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

ByteArrayInputStream bis=new ByteArrayInputStream("hello hai hello hai".getBytes());

BufferedInputStream bff=new BufferedInputStream(bis);System.out.println(bis.available());int count=bis.available();byte[] b=new byte[count];/*b - destination buffer.0- offset at which to start storing bytes.b.length - maximum number of bytes to read. */bff.read(b,0,b.length);/*we can reset the cursor to first position */bis.reset();for(int i=0;i<count;i++){System.out.print((char)bff.read());}System.out.println();for(int i=0;i<count;i++){System.out.print((char)b[i]);}bis.close();bff.close();

}

}

BufferedOutputStreamDemo.java

import java.io.*;public class BufferedOutputStreamDemo

88A winner not one who never fails but one who never QUITS

Naresh kumar

Page 89: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

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

// FileOutputStream fos=new FileOutputStream("dest.dat",true);//true means added data will appends at the end of dest.dat fileFileOutputStream fos=new FileOutputStream("dest.dat");String str="Java is an Ocean don't dip swim across it";byte[] b=new byte[str.length()];b=str.getBytes();//BufferedOutputStream bos=new BufferedOutputStream(System.out);BufferedOutputStream bos=new BufferedOutputStream(fos);bos.write(b);//bos.flush();for(int i=0;i<b.length;i++){bos.write(b[i]);}bos.close();fos.close();

}}

ByteArrayInputStreamDemo.java

import java.io.*;public class ByteArrayInputStreamDemo{

public static void main(String args[])throws Exception{String str="India is my country \n all the indians are my brothers and sisters";byte[] b=str.getBytes();ByteArrayInputStream bis=new ByteArrayInputStream(b);byte[] b2=new byte[str.length()];bis.read(b2);System.out.println("\n after using read(byte arry) method calling\n");for(int i=0;i<b2.length;i++){

System.out.print((char)b2[i]);Thread.sleep(100);

}System.out.println("\nafter reset method calling usnig second Constructor\n");bis.reset();bis=new ByteArrayInputStream(b,6,10);

byte b3[]=new byte[bis.available()];

89A winner not one who never fails but one who never QUITS

Naresh kumar

Page 90: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

bis.read(b3);int b1;for(int i=0;i<b3.length;i++){

System.out.print((char)b3[i]);Thread.sleep(100);

}bis.reset();System.out.println("\nafter reset method calling\n");while((b1=bis.read())!=-1){

System.out.print((char)b1);Thread.sleep(100);

}bis.close();}

}

ByteArrayOutputStreamDemo.java

import java.io.*;class ByteArrayOutputStreamDemo{

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

String str="Pavan Kalyan is a super star kadu anukunnara avunu";ByteArrayOutputStream bao=new ByteArrayOutputStream();bao.write(str.getBytes(),0,str.length());System.out.println(bao.toString());PrintStream ps=new PrintStream(System.out);bao.writeTo(ps);

}}

DataInputOutput.java

import java.io.*;class DataInputOutput{

public static void main(String args[]){

try{DataInputStream dis=new DataInputStream(System.in);DataOutputStream dos=new DataOutputStream(System.out);System.out.println("Enter data");

90A winner not one who never fails but one who never QUITS

Naresh kumar

Page 91: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

dos.writeBytes(dis.readLine());dos.flush();dis.close();File f=new File("store.txt");f.createNewFile();DataInputStream dis1=new DataInputStream(new

FileInputStream("store.txt"));DataOutputStream dos1=new DataOutputStream(new

FileOutputStream("store.txt"));byte b=20;short s=50;dos1.writeInt(10);dos1.writeBoolean(true);dos1.writeByte(b);dos1.writeShort(s);dos1.writeFloat(10.00f);dos1.writeDouble(44.44);dos1.writeChars("Madhu is a bad faculty in bdps");dos1.writeUTF("Kadu kadu chala manchi faculty nizam....nammu..");dos1.close();System.out.println("int:\t"+dis1.readInt());System.out.println("Boolean:\t"+dis1.readBoolean());System.out.println("byte:\t"+dis1.readByte());System.out.println("short:\t"+dis1.readShort());System.out.println("float:\t"+dis1.readFloat());System.out.println("double:\t"+dis1.readDouble());System.out.println("Chars:\t"+dis1.readLine());System.out.println("String UTF:\t"+dis1.readUTF());dis1.close();}catch(Exception e){}

}}

PipedInputStreamDemo.java

import java.io.*;class Output extends Thread{

PipedOutputStream pos=null;Output(PipedOutputStream pos){

this.pos=pos;}public void run(){

for(int i=0;i<10;i++)

91A winner not one who never fails but one who never QUITS

Naresh kumar

Page 92: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

{try{String str=""+i;System.out.println(getName());pos.write(str.getBytes());//sleep(1000);}catch(Exception e){}

}}

}class Input extends Thread{

PipedInputStream pis=null;Input(PipedInputStream pis){

this.pis=pis;

}public void run(){

for(int i=0;i<10;i++){

try{System.out.println(getName()+":\t"+(char)(pis.read()));//sleep(1000);}catch(Exception e){System.exit(0);}

}}

}public class PipedInputStreamDemo{

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

PipedOutputStream pos=new PipedOutputStream();PipedInputStream pis=new PipedInputStream(pos);Output o=new Output(pos);Input i=new Input(pis);//o.setPriority(10);o.start();//Thread.sleep(1000);i.start();

}}

92A winner not one who never fails but one who never QUITS

Naresh kumar

Page 93: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

PrintStreamDemo.java

import java.io.*;public class PrintStreamDemo{

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

File f=new File("MyFile.txt");f.createNewFile();String str="j2se j2ee j2me";PrintStream ps=new PrintStream(f);PrintStream out=new PrintStream(System.out);PrintStream ps1=new PrintStream("Aaaaa.txt");byte b[]=new byte[str.length()];b=str.getBytes();ps.write(b);str ="\n";b=str.getBytes();ps.write(b);ps.write(50);ps.write(b);ps.write(51);ps.write(b);ps.println("This is my last program...........");ps.println("This is my first program.........");out.println("Hai hai hai hai hai hai hai............");ps1.println("Aaaaaaaaaaaaaaaaaaaa........!");ps.close();ps1.close();out.close();

}}

PushBackDemo.java

import java.io.*;public class PushBackDemo{

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

ByteArrayOutputStream bos=new ByteArrayOutputStream();String str="This is a test";

for(int i=0;i<str.length();i++)

93A winner not one who never fails but one who never QUITS

Naresh kumar

Page 94: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

{bos.write(str.charAt(i));

}System.out.println("Out Stream:\t"+bos);System.out.println("Out Stream:\t"+bos.size());ByteArrayInputStream bis=new

ByteArrayInputStream(bos.toByteArray());PushbackInputStream pbis=new PushbackInputStream(bis);char ch=(char)pbis.read();System.out.println("First character of the String:\t"+ch);pbis.unread((int)'t');System.out.println("inputStream has "+pbis.available()+" available

bytes" );byte b[]=new byte[pbis.available()];for(int i=0;i<b.length;i++){

b[i]=(byte)pbis.read();}pbis.unread((int)'t');System.out.println("inputStream has "+pbis.available()+" available

bytes" );System.out.println("The Data is:\t"+new String(b));bos.close();bis.close();pbis.close();}

}

Student. java

package oos;import java.io.*;class Student implements Serializable{

int sno;String sname;transient String add;

public Student(int sno,String sname,String add){this.sno=sno;this.sname=sname;this.add=add;}public void getDetails(){

System.out.println("Student Details...");

94A winner not one who never fails but one who never QUITS

Naresh kumar

Page 95: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

System.out.println("Sno:\t"+sno);System.out.println("Sname:\t"+sname);System.out.println("Address:\t"+add);

} }Emp.java

package oos;import java.io.*;public class Emp implements Serializable{

int eno;String ename;float esal;transient String add;

public Emp(int eno,String ename,float esal,String add){this.eno=eno;this.ename=ename;this.esal=esal;this.add=add;}public void getDetails(){

System.out.println("Emp Details...");System.out.println("Eno:\t"+eno);System.out.println("Ename:\t"+ename);System.out.println("Esal:\t"+esal);System.out.println("Address:\t"+add);

}}

ObjectOutputStream.java

package oos;import java.io.*;import oos.Emp;import oos.Student;import java.util.*;public class OOS{

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

FileOutputStream fos=new FileOutputStream("MyObj.txt");ObjectOutputStream oos=new ObjectOutputStream(fos);oos.writeObject(new Emp(101,"prasad",2000.00f,"hyd"));

95A winner not one who never fails but one who never QUITS

Naresh kumar

Page 96: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

oos.writeObject(new Emp(102,"varaprasad",20000.00f,"vij"));oos.writeObject(new Student(103,"siva","krishna lanka"));oos.writeObject(new Student(104,"Nalini"," Sri Lanka"));oos.writeObject(new Date());oos.writeObject("Ramjan&Diwali");oos.close();FileInputStream fis=new FileInputStream("MyObj.txt");ObjectInputStream ois=new ObjectInputStream(fis);Object o=null;try{while((o=ois.readObject())!=null){

if(o instanceof Emp)((Emp)o).getDetails();else if(o instanceof Student)

((Student)o).getDetails();else if(o instanceof Date)

System.out.println(o);else

System.out.println(o);

}}catch(EOFException e){}ois.close();

}}

StringBufferInputStreamDemo.java

import java.io.*;public class StringBufferInputStreamDemo{

public static void main(String args[]){ String str="India Zindabaadh";

StringBufferInputStream sb=new StringBufferInputStream(str);

byte[] b=new byte[sb.available()];sb.read(b,0,b.length);for(int i=0;i<b.length;i++){

System.out.print((char)b[i]);}sb.reset();

96A winner not one who never fails but one who never QUITS

Naresh kumar

Page 97: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

System.out.println();for(int i=0;i<b.length;i++){System.out.print((char)sb.read());}

}}

Character Streams

CharIOApp.java

import java.io.*; public class CharIOApp{

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

FileWriter fw=new FileWriter("test.txt");String test="This is a java program";for(int i=0;i<test.length();i++)fw.write(test.charAt(i));fw.close();FileReader fr=new FileReader("test.txt");int ch=0;while((ch=fr.read())!=-1){

System.out.print((char)ch);}fr.close();/*File f=new File("test.txt");f.delete();*/

}}

CharArrayIOApp.java

import java.io.*;public class CharArrayIOApp{

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

CharArrayWriter out=new CharArrayWriter();String s="This is a test for you";for(int i=0;i<s.length();i++)

97A winner not one who never fails but one who never QUITS

Naresh kumar

Page 98: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

out.write(s.charAt(i));System.out.println("outStream:\t"+out);System.out.println("size:\t"+out.size());CharArrayReader read=new

CharArrayReader(out.toCharArray());int ch=0;StringBuffer sb=new StringBuffer();String str=new String();while((ch=read.read())!=-1){

//System.out.print((char)ch);sb.append((char)ch);str=str+(char)ch;

}System.out.println(sb.toString());System.out.println(str);read.close();

}}

StringReaderWriter.java

import java.io.*;public class StringReaderWriter{

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

StringWriter sw=new StringWriter();String str="Discipline \nDynamism and \nDedication are the \npre

requisites of success";FileReader fr=new FileReader("StringReaderWriter.java");int ch=0;while((ch=fr.read())!=-1){

sw.write(ch);}System.out.println(sw);System.out.println(sw.toString());System.out.println(sw.toString().length());StringReader sr=new StringReader(sw.toString());

StringBuffer sb=new StringBuffer();while((ch=sr.read())!=-1){sb.append((char)ch);//sb=sb+(char)ch;

98A winner not one who never fails but one who never QUITS

Naresh kumar

Page 99: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

}System.out.println(sb.length()+"Chars were read");System.out.println("They are"+sb.toString());System.out.println("They are"+sb.reverse());

}}

BufferedReaderWriter.java

import java.io.*;public class BufferedReaderWriter{

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

FileWriter fw=new FileWriter("haa.java");BufferedWriter bw=new BufferedWriter(fw);bw.write("java is an oop language\n",0,23);bw.write("java is an oop language\n",0,23);bw.flush();FileReader fr=new FileReader("haa.java");BufferedReader br=new BufferedReader(fr);String str=null;while((str=br.readLine())!=null){

System.out.println(str);}

}}

RandomAcceeDemo.java

import java.io.*;import java.io.*;public class RandomAccessDemo{

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

RandomAccessFile file=new RandomAccessFile(new File("RandomAccessDemo.java"),"rw");

file.seek(0);System.out.println(file.readLine());System.out.println(file.getFilePointer());file.seek(50);System.out.println(file.readLine());

}

99A winner not one who never fails but one who never QUITS

Naresh kumar

Page 100: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

}

S TRINGS A ND S TRING H ANDLING

In java, Strings can be handled with two classes

1. java.lang.String class2. java.lang.StgingBuffer class

Strings are immutable (not Changeable) where as String Buffers are mutable (Changeable).

When we reassign a value to a variable, system changes the value n the location; but not the location itself. That is, in the same location, the new value of the variable is changed. But incase of strings, it is completely deferent. Incase of strings, if a string is reassigned a new value, a new location is created where the new value is stored and the old location (where old value is stored) is garbage collected. That is , a string value cannot be changed in the same location. This is called immutable and is an overhead to the processor and a negative point for performance. To over come this, Java designers introduced StringBuffer. Generally, incase of a String Buffer, if a value is changed, the location is not changed and in the old location only the value changed

StringDemo.java

public class StringDemo{

public static void main(String args[]){

String data="java is an object oriented programming language";System.out.println(data.length());System.out.println(data.charAt(20));System.out.println(data.indexOf("i"));System.out.println(data.lastIndexOf("i"));data=data.concat("...!");System.out.println(data);System.out.println(data+"...!");byte b[]=data.getBytes();for(int i=0;i<b.length;i++)System.out.print((char)b[i]);char dst[]=new char[47];data.getChars(0, 47,dst,0) ;

100A winner not one who never fails but one who never QUITS

Naresh kumar

Page 101: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

System.out.println();for(int i=0;i<dst.length;i++)System.out.print(dst[i]);System.out.println();System.out.println(data.substring(11));System.out.println(data.substring(11,35));System.out.println(data.toUpperCase());System.out.println(data.toLowerCase());int il=200;String intVal=String.valueOf(il);System.out.println(intVal);System.out.println(data.replace("java","Java"));

}}

StringBufferDemo.java

public class StringBufferDemo{

public static void main(String args[]){

StringBuffer data=new StringBuffer("java is an object oriented programming language");

System.out.println(data.length());System.out.println(data.charAt(20));System.out.println(data.indexOf("i"));System.out.println(data.lastIndexOf("i"));data=data.append("...!");System.out.println(data);System.out.println(data+"...!");char dst[]=new char[47];data.getChars(0, 47,dst,0) ;System.out.println();for(int i=0;i<dst.length;i++)System.out.print(dst[i]);System.out.println();System.out.println(data.substring(11));System.out.println(data.substring(11,35));System.out.println(data.insert(5," 1991 "));System.out.println(data.reverse());System.out.println(data.replace("java","Madhu"));

}}

101A winner not one who never fails but one who never QUITS

Naresh kumar

Page 102: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

AppletsQ1. What is Applet?Ans: To support internet, java includes special programs called applets with a different syntax. A java Applet written and compiled on many platforms can be executed by any browser on the user’s platform. To execute applets, many browsers come with in-built JVM (known as Java-enabled browser).

Java programs can be divided into two categories one is Applications and second one is Applets

Applications are the programs that contain main () method and applets are the programs that do not contain main () method. Applications can be executed with a java interpreter from the command line (with java command). Applets execute in a browser.

Applet: Applet is a java program that runs in a browser.

Viewing Applets: Applets are displayed on the browser by using HTML tag <applet>. Applets can also run on applet viewer is not a full-fledged browser appletviewer is intended just to test applets and understands very minimum HTML tags (and is generally used when a browser is not available). If an applet works with the appletviewer, it definitely works with a browser.

Q2 what are Applet Security restrictions?

Ans: Because java applets are run on a web user’s system, there are serious restrictions on the execution of an Applet. An applet can be downloaded from Internet and can be executed on our system. We do not know who developed the applet and the applet may have some virus or malicious code that may corrupt our system files or may collect our personal information available on our system. For this reason, we require security for our system resources when an applet executes on our system.

Restrictions:1 They cannot read or write files on the user file system.2 They con not communicate with an internet site other than the one that served the

web page that included the applet.3 They cannot run any programs on the user’s system.4 They cannot load programs stored on the user’s system, such as executable

programs and shared libraries.

102A winner not one who never fails but one who never QUITS

Naresh kumar

Page 103: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Q3 what is applet Architecture?

Applets do not contain main() method for executeon, its development is completely different from an application. Applet is window-based and we cannot pass any data from keyboard or display any data at DOS prompt.

Applet programming is closely related with AWT technology. Many similarities exist with AWT frame and applet window, applets are event-driven. We can place AWT controls (like buttons, checkboxes etc.) in an applet. When a button is clicked it raises an event called Action Event. This event is handled by AWT and not by the applet. That is, control is passed to AWT environment to handle the event. It is like an interrupt for the applet execution where its own process is stopped and shifted to event handling mechanism of AWT. The applet should not hold control to execute its own resources when an event occurs. If the control is required to be in applet only, then applet should start a thread of its own and should enter multithreading. One this situation is when the applet wants to show an animation, it can start a separate thread.

To manage the applet window o0perations, we can use mouse. When the window is in focus, we can click a mouse, and then Mouse Event is generated and is handled by MouseListener or MouseMotionListener of AWT event handling mechanism. We can override the methods of MouseListener or MouseMotionListener to have customized actions.

Q4 what are the HTML tags that support applet?

To run applet, we must open it in a browser, Browser provides the execution environment for the applet. We cannot open the applet directly in a browser. We must embed the applet within HTML file. For the HTML includes <APPLET> tag.

About the <APPLET> tag

This is a special extension to HTML for including applets in the web pages. This tag includes many attributes like width, height etc…. this is generally included within the BODY element of the HTML file.

Browser finds and loads the applet by reading the <APPLET> tag’s CODE attribute. In CODE attribute, we write the name of the applet (e.g., CODE=”LifeCycle.class”. writing .class is optional, i.e. we can write it also as CODE=”LifeCycle”). Browser searches for the applet file in the directory from where HTML file is loaded. If the applet file is placed in some other directory, we must write the path in another attribute called CODEBASE.

Q5 what is the lifecycle of an applet?

Applet goes through different stages execution between its birth and death. Many

103A winner not one who never fails but one who never QUITS

Naresh kumar

Page 104: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

of these stages are called implicitly by the browser’s runtime environment.Different stages in which an applet exists between its object creation and

object garbage collection is called the life cycle of the applet.There are 4 methods in the life cycle and all are defined in Applet class. In this

life cycle, applet also uses paint () method, butt it is not defined in Applet class but defined in Component class inherited by the Applet class. Following is the hierarchy of Applet class:ObjectComponentContainerPanelApplet

Following is the brief discussion of the life cycle methods:Init (): when an object of the applet is created, the browser calls init() method. In init (), event though the object is created, the applet is inactive and there by not eligible for microprocessor time. It is equivalent to a constructor. Generally we create threads, loading images, setting background and foreground colors etc. in init () method.

Start (): the init () method implicitly calls start () method. In the start () method, applet becomes active and there by eligible for microprocessor time. When the applet de iconified, the browser also calls start () method.

Stop (): when the applet is iconified, browser calls stop () method. In stop (() method, the applet is inactive and is not eligible for processor time. This is called implicitly by browser when the applet is iconified.

Destroy (): when we close the applet, the browser calls stop () method and sop () in turn calls destroy () method. We use this method to close the sockets, network connections etc.

Init () and destroy () methods are called only once in the life cycle, but start () and stop () methods are called a number of times to make the applet active and inactive.

Paint (): this method does into belong to the lifecycle of an applet but used by the applet very often. This method is not required directly for a program’s execution. We use paint method, to draw graphics, strings etc. on the applet window. This method is called by start () method and also when we resize the applet.

LifeCycle.html

<applet code="LifeCycle" width=400 height=400></applet>

Lifecycle. java

import java.awt.*;import java.applet.*;public class LifeCycle extends Applet{

104A winner not one who never fails but one who never QUITS

Naresh kumar

Page 105: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

String msg="";public void init(){

System.out.println("Init()");msg=msg+"init";setBackground(Color.black);setForeground(Color.red);

}public void start(){

System.out.println("Start()");msg=msg+"start()";

}public void stop(){

System.out.println("Stopped()");msg=msg+"stop";

}public void destroy(){

System.out.println("destroy()");}public void paint(Graphics g){

msg+="paint";g.drawString("My FirstApplet...",10,50);g.drawString(msg,100,100);System.out.println("paint method...");showStatus(msg);

}}

Banner.html

<applet code="Banner.class" width=400 height=400></applet>

Banner.java

import java.awt.*;import java.io.*;import java.applet.*;

105A winner not one who never fails but one who never QUITS

Naresh kumar

Page 106: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

public class Banner extends Applet implements Runnable{ String msg="Java Is an OOPL ";

Thread t=null;boolean flag;

Font f=new Font("impact",Font.BOLD+Font.ITALIC,20);public void init(){

Color c=new Color(200,255,100);setBackground(c);setForeground(Color.red);

}public void start(){

t=new Thread(this);flag=false;t.start();System.out.println("start");

}public void run(){

char ch;for(;;){try{repaint();Thread.sleep(1000);ch=msg.charAt(0);msg=msg.substring(1,msg.length());//System.out.println(msg);msg+=ch;if(flag)break;}catch(InterruptedException e){e.printStackTrace();}}

}public void stop(){

flag=true;t=null;

}public void paint(Graphics g){

g.setFont(f);

106A winner not one who never fails but one who never QUITS

Naresh kumar

Page 107: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

g.drawString(msg,50,30);g.drawLine(20,100,450,100);g.fillRect(25,30,250,300);g.fillArc(15,25,400,200,90,60);

showStatus(msg);}

}

Gcdb.html

<applet code="GetCodeDocumentBase.class" width=400 height=400></applet>

GetCodeDocumentBase.java

import java.awt.*;import java.applet.*;import java.net.URL;public class GetCodeDocumentBase extends Applet{

Image img;Font f=new Font("Georgia",Font.BOLD+Font.ITALIC,20);public void init(){setBackground(new Color(255,255,255));setForeground(new Color(155,55,55));}public void paint(Graphics g){

g.setFont(f);String msg1;URL url1=getCodeBase();msg1="getCodeBase: "+url1.toString();g.drawString(msg1,10,20);URL url2=getDocumentBase();String msg2="get DocumentBase: "+url2.toString();g.drawString(msg2,10,80);img=getImage(url1,"trisha.jpg");g.drawImage(img,20,100,350,200,this);//g.drawImage(img,20,150,this);

}}

AppletContext1.java

107A winner not one who never fails but one who never QUITS

Naresh kumar

Page 108: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

import java.awt.*;import java.applet.*;import java.net.*;/*<applet code=AppletContext1 height=300 width=300></applet>*/public class AppletContext1 extends Applet{

public void init(){

setBackground(Color.green);setForeground(Color.black);

}public void paint(Graphics g){

URL url1=getCodeBase();AppletContext ac=getAppletContext();try{ac.showDocument(new URL(url1,"repaint.html"));}catch(Exception e){g.drawString("Not found",10,20);}showStatus("URL founded.....");String msg2="get DocumentBase: "+url1.toString();g.drawString(msg2,10,80);

}

}

AudioPlayer.java

/*The applet shown below plays several types of audio clips: an AU file, an AIFF file, a WAV file, and a MIDI file. (The AIFF and WAV files used in the examples for this trail were provided by Headspace, Inc.) */import java.applet.*;import java.awt.*;import java.awt.event.*;import java.net.URL;public class AudioPlayer extends Applet{

AudioClip music;Image background;public void init()

108A winner not one who never fails but one who never QUITS

Naresh kumar

Page 109: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

{URL codebase=getCodeBase();music=getAudioClip(codebase,"bird.au");background=getImage(codebase,"trisha.jpg");setLayout(new BorderLayout());Panel buttons=new Panel();Button pbutton=new Button("Play");Button sbutton=new Button("Stop");Button lbutton=new Button("Loop");buttons.add(pbutton);buttons.add(sbutton);buttons.add(lbutton);add("South",buttons);ButtonHandler bh=new ButtonHandler();pbutton.addActionListener(bh);sbutton.addActionListener(bh);lbutton.addActionListener(bh);

}public void stop(){

//music.stop();

}public void paint(Graphics g){

g.drawImage(background,0,0,400,400,this);}public class ButtonHandler implements ActionListener{

public void actionPerformed(ActionEvent ae){

String s=ae.getActionCommand();if(s.equals("Play"))

music.play();if(s.equals("Stop"))

music.stop();if(s.equals("Loop"))

music.loop();}

};};

109A winner not one who never fails but one who never QUITS

Naresh kumar

Page 110: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Add.java

import java.awt.*;import java.awt.event.*;import java.applet.*;import javax.swing.*;/*<applet code=Add height=400 width=400>

</applet>*/public class Add extends Applet{

long x,y,z;TextField t1=new TextField(8);TextField t2=new TextField(8);TextField t3=new TextField(8);Label l1=new Label("Enter a Variable");Label l2=new Label("Enter a Variable");Button b1=new Button("Add");Button b2=new Button("Sub");Button b3=new Button("Mul");Button b4=new Button("Clear");public void init(){

setLayout(null);setBackground(Color.red);setForeground(Color.black);add(l1);add(l2);add(t1);add(t2);add(t3);add(b1);add(b2);add(b3);add(b4);t1.setText("0");t2.setText("0");

b1.addActionListener(new AL());b2.addActionListener(new AL());b3.addActionListener(new AL());b4.addActionListener(new AL());Font f=new Font("Georgia",Font.BOLD,20);l1.setFont(f);l2.setFont(f);t1.setBounds(220,20,80,20);l1.setBounds(65,20,150,20);

110A winner not one who never fails but one who never QUITS

Naresh kumar

Page 111: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

t2.setBounds(220,45,80,20);l2.setBounds(65,50,150,20);t3.setBounds(220,70,80,20);b1.setBounds(40,100,80,20);b2.setBounds(130,100,80,20);b3.setBounds(220,100,80,20);b4.setBounds(130,140,80,20);}

private class AL implements ActionListener{public void actionPerformed(ActionEvent ae){

if(ae.getSource()!=b4){String x1=t1.getText().trim();try{x=Long.parseLong(x1);}catch(NumberFormatException ne){JOptionPane.showMessageDialog(Add.this,"Please give correct

No in textfield one");}String y1=t2.getText().trim();try{y=Long.parseLong(y1);}catch(NumberFormatException ne1)

{JOptionPane.showMessageDialog(Add.this,"Please give correct No in textfield two");}}if(ae.getSource()==b1){z=x+y;t3.setText(String.valueOf(z));}else if(ae.getSource()==b2){z=x-y;t3.setText(String.valueOf(z));}else if(ae.getSource()==b3){z=x*y;t3.setText(String.valueOf(z));}else

111A winner not one who never fails but one who never QUITS

Naresh kumar

Page 112: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

{t1.setText("");t2.setText("");t3.setText("");}

}}

}

Param.html

<applet code=Param.class width=400 height=400><param name="r" value=200><param name="g" value=50><param name="b" value=133><param name="user" value="scott"></applet>

Param.java

import java.applet.*;import java.awt.*;public class Param extends Applet{

int r,g,b;String value;String uname;Font f=new Font("georgia",Font.BOLD+Font.ITALIC,20);public void init(){r=Integer.parseInt(getParameter("r"));g=Integer.parseInt(getParameter("g"));b=Integer.parseInt(getParameter("b"));uname=getParameter("user");setBackground(new Color(r,g,b));setForeground(new Color(b,r,g));value="r="+r+"g="+g+"b="+b;}public void paint(Graphics g){g.setFont(f);g.drawString("Parameter Demo ",150,40);g.drawString(value,150,140);g.drawString("uname="+uname,150,180);}

112A winner not one who never fails but one who never QUITS

Naresh kumar

Page 113: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

}

Repaint2.java

import java.awt.*;import java.io.*;import java.applet.*;import java.net.*;/*

<applet code=Repaint2 width=300 height=300></applet>

*/public class Repaint2 extends Applet implements Runnable{

String iname;Thread t=null;boolean flag;Font f=new Font("impact",Font.BOLD+Font.ITALIC,20);public void init(){

//Color c=new Color(200,255,100);setBackground(Color.yellow);setForeground(Color.red);

}public void start(){

t=new Thread(this);flag=false;t.start();System.out.println("start");

}public void run(){

char ch;for(;;){try{int i=(int)(Math.random()*8);iname=i+".jpg";repaint();Thread.sleep(1000);if(flag)break;}catch(InterruptedException e)

113A winner not one who never fails but one who never QUITS

Naresh kumar

Page 114: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

{e.printStackTrace();}}

}public void stop(){ flag=true;

t=null;}public void paint(Graphics g){

URL path=getCodeBase();Image img=getImage(path,iname);//g.drawImage(img,0,20,300,300,this);g.drawImage(img,0,20,this);showStatus(iname);

}}

Sound.java

import java.applet.*;import java.awt.*;/*<applet code=Sound width=300 height=300></applet>*/public class Sound extends Applet{

AudioClip audio;public void init(){audio=getAudioClip(getCodeBase(),"spacemusic.au");}public void start(){ //audio.play();

audio.loop();}public void stop(){audio.stop();}public void paint(Graphics g){ g.drawString("Audio System Now Plaoying......",10,30);

showStatus("Playing Song....");

}

}

114A winner not one who never fails but one who never QUITS

Naresh kumar

Page 115: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

/*The applet shown below plays several types of audio clips: an AU file, an AIFF file, a WAV file, and a MIDI file. (The AIFF and WAV files used in the examples for this trail were provided by Headspace, Inc.) */

AWT (Abstract Window Toolkit)

The AWT contains numerous classes and methods that allow you to createand manage windows.

Although the main purpose of the AWT is to support applet windows, it can also be used to create stand-alone windows that run in a GUI environment, such as Windows.

The AWT classes are contained in the java.awt package. It is one of Java’s largest packages.

Component Hierarchy of AWT

Class Description------------------------------------------------------------------------------------AWTEvent Encapsulates AWT events.

AWTEventMulticaster Dispatches events to multiple listeners.

Object

Component

Text ComponentButton Container Menu Component Check Box

Text Field

Text Area

Panel Window Menu Menu Bar

Menu Item

Applet Frame Dialog

115A winner not one who never fails but one who never QUITS

Naresh kumar

Page 116: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

BorderLayout The border layout manager Border layout use five components: North, South, East, West and Center.

Button Creates a push button control.

Canvas A blank, semantics-free window

CardLayout The card layout manager. Card layouts emulate index cards. Only the one on top is showing.

Checkbox Creates a check box control.

CheckboxGroup Creates a group of check box controls.

CheckboxMenuItem Creates an on/off menu item.

Choice Creates a pop-up list.

Color Manages colors in a portable, platform-independent fashion.

Component An abstract superclass for various AWT components.

Container A subclass of Component that can hold other components.

Cursor Encapsulates a bitmapped cursor.

Dialog Creates a dialog window.

Dimension Specifies the dimensions of an object. The width is stored in width, and the height is stored in height.

Event Encapsulates events.

EventQueue Queues events.

FileDialog Creates a window from which a file can be selected.

116A winner not one who never fails but one who never QUITS

Naresh kumar

Page 117: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

FlowLayout The flow layout manager. Flow layout positions components left to right, top to bottom.

Font Encapsulates a type font.FontMetrics Encapsulates various information related

to a font. his information helps you display text in a window.

Frame ates a standard window that has a title bar, resize corners, and a menu bar.

Graphics Encapsulates the graphics context. This context is used by the various output methods to display output in a window.

GraphicsDevice Describes a graphics device such as a screen or printer.

GraphicsEnvironment Describes the collection of available Font and GraphicsDevice objects.

GridBagConstraints Defines various constraints relating to the GridBagLayout class.

GridBagLayout The grid bag layout manager. Grid bag layout displays components subject to the constraintsspecified by GridBagConstraints.

GridLayout The grid layout manager. Grid layout displays components in a two-dimensional grid.

Image Encapsulates graphical images.

Insets Encapsulates the borders of a container.

Label Creates a label that displays a string.

List Creates a list from which the user can choose. Similar to the standard Windows list box.

MediaTracker Manages media objects.

Menu Creates a pull-down menu.

117A winner not one who never fails but one who never QUITS

Naresh kumar

Page 118: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

MenuBar Creates a menu bar.

MenuComponent An abstract class implemented by various menu classes.

MenuItem Creates a menu item.

MenuShortcut Encapsulates a keyboard shortcut for a menu item.

Panel The simplest concrete subclass of Container.

Point Encapsulates a Cartesian coordinate pair, stored in x and y.

Polygon Encapsulates a polygon.

PopupMenu Encapsulates a pop-up menu.

PrintJob An abstract class that represents a print job.

Rectangle Encapsulates a rectangle.

Robot Supports automated testing of AWT-based applications. (Added by Java 2, vl.3)

Scrollbar Creates a scroll bar control.

ScrollPane A container that provides horizontal and/or vertical scroll bars for another component.

SystemColor Contains the colors of GUI widgets such as windows, scroll bars, text, and others.

TextArea Creates a multiline edit control.

TextComponent A superclass for TextArea and TextField.

TextField Creates a single-line edit control.

118A winner not one who never fails but one who never QUITS

Naresh kumar

Page 119: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Toolkit Abstract class implemented by the AWT.

Window Creates a window with no frame, no menu bar, and no title.

Layout Managers

The arrangement of several components within a container is called their layout Flow Layout Grid Layout Border Layout Card Layout

These are all subclass of the java.awt.LayoutManager class. You can set the layout by using the setLayout () method.Note:

A panel’s default Layout manager is always Flow Layout. An Applet’s default Layout manager is always Flow Layout and constraint

is FlowLayout.CENTER. A frame’s default Layout manager is always Border Layout.

Delegation event model

Delegation event model, which defines standard and consistent mechanisms to generate and process events. Its concept is quite simple: a source generates an event and sends it to one or more listeners. In this scheme, the listener simply waits until it receives an event. Once received, the listener processes the event and then returns.

In the delegation event model, listeners must register with a source in order to receive an event notification. This provides an important benefit: notifications are sent only to listeners that want to receive them.

To receive events that they did not process and it wasted valuable time. The delegation vent model eliminates this overhead.

EventsIn the delegation model, an event is an object that describes a state change in a

source. It can be generated as a consequence of a person interacting with the elements in a graphical user interface. Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse. Many other user operations could also be cited as examples. Events may also occur that are not directly caused by interactions with a user interface. For example, an event may be generated when a timer expires, a counter exceeds a value,

119A winner not one who never fails but one who never QUITS

Naresh kumar

Page 120: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

software or hardware failure occurs, or an operation is completed. You are free to define events that are appropriate for your application.

Event Sources

A source is an object that generates an event. This occurs when the internal state of that object changes in some way. Sources may generate more than one type of event. A source must register listeners in order for the listeners to receive notifications about a specific type of event. Each type of event has its own registration method.

Here is the general form: public void addTypeListener (Type Listener el)

Here, Type is the name of the event and el is a reference to the event listener. For example, the method that registers a keyboard event listener is called addKeyListener ( ). The method that registers a mouse motion listener is called addMouseMotionListener ( ). When an event occurs, all registered listeners are notified and receive a copy of the event object. This is known as multicasting the event. In all cases, notifications are sent only to listeners that register to receive them.

A source must also provide a method that allows a listener to unregister an interest in a specific type of event. The general form of such a method is this: public void removeTypeListener(TypeListener el) Here, Type is the name of the event and el is a reference to the event listener. For example, to remove a keyboard listener, you would call removeKeyListener( ). The methods that add or remove listeners are provided by the source that generates events. For example, the Component class provides methods to add and remove keyboard and mouse event listeners.

Event Listeners

A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications. The methods that receive and process events are defined in a set of interfaces found in java.awt.event. For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved. Any object may receive and process one or both of these events if it provides an implementation of this interface.

Event Classes

At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the super class for all events.

Its one constructor is shown here: EventObject(Object src)

120A winner not one who never fails but one who never QUITS

Naresh kumar

Page 121: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Here, src is the object that generates this event. EventObject contains two methods: getSource( ) and toString( ).

The getSource( ) method returns the source of the event. Its general form is shown here: Object getSource( )

As expected, toString( ) returns the string equivalent of the event.

The class AWTEvent, defined within the java.awt package, is a subclass of EventObject. It is the superclass (either directly or indirectly) of all AWT-based events used by the delegation event model. Its getID( ) method can be used to determine the type of the event. The signature of this method is shown here:

int getID( )

At this point, it is important to know only that all of the other classes discussed in this section are subclasses of AWTEvent.To summarize:■ EventObject is a superclass of all events.■ AWTEvent is a superclass of all AWT events that are handled by the delegation event model.

The package java.awt.event defines several types of events that are generated by various user interface elements.

Event Class DescriptionActionEvent Generated when a button is pressed, a list item is

double-clicked, or a menu item is selected.AdjustmentEvent Generated when a scroll bar is manipulated.ComponentEvent Generated when a component is hidden, moved, resized, or becomes

visible.

ContainerEvent Generated when a component is added to or removed from a container.

FocusEvent Generated when a component gains or loseskeyboard focus.

InputEvent Abstract super class for all component input event classes. Its Subclasses are KeyEvent, MouseEvent

ItemEvent Generated when a check box or list item is clicked; alsooccurs when a choice selection is made or a checkable menu item is selected or deselected.

KeyEvent Generated when input is received from the keyboard.MouseEvent Generated when the mouse is dragged, moved, clicked,pressed, or

released; also generated when the mouse enters or exits a

121A winner not one who never fails but one who never QUITS

Naresh kumar

Page 122: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

component.

MouseWheelEvent Generated when the mouse wheel is moved. (Added byJava 2, version 1.4)

TextEvent Generated when the value of a text area or text field is changed.

WindowEvent Generated when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit.

Event Class Event Listener Methods Adapter classes

ActionEvent ActionListener actionPerformed(ActionEvent e); NothingAdjustmentEvent

AdjustmentListener

adjustmentValueChanged(AdjustmentEvent e)

Nothing

ComponentEvent

ComponentListener

1.componentHidden(ComponentEvent e)2.componentMoved(ComponentEvent e)3.componentResized(ComponentEvent e)4.componentShown(ComponentEvent e)

Component Adpater

ContainerEvent ContainerListener 1.componentAdded(ContainerEvent e);2.componentRemoved(ContainerEvent e)

Container Adapter

FocusEvent FocusListener 1.public void focusGained(FocusEvent e)2. public void focusGained(FocusEvent e)

Focus Adapter

ItemEvent Item Listener 1. public void itemStateChanged(ItemEvent e)

KeyEvent KeyListener 1.public void keyPressed(KeyEvent e)2. public void keyReleased(KeyEvent e)3. public void keyTyped(KeyEvent e)

KeyAdapater

MouseEvent MouseListener 1. public void mouseClicked(MouseEvent e)2. public void mousePressed(MouseEvent e)3. public void mouseReleased(MouseEvent e)4. public void mouseEntered(MouseEvent e)5. public void mouseExited(MouseEvent e)

MouseAdapter

MouseEvent MouseMotionListener

1.public void mouseMoved(MouseEvent e)2.public void mouseDragged(MouseEvent e)

MouseMotionAdapter

TextEvent TextListener 1.public void textValueChanged(TextEvent e)

Nothing

WindowEvent WindowListener 1.public void Window

122A winner not one who never fails but one who never QUITS

Naresh kumar

Page 123: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

windowActivated(WindowEvent e)2.public void windowDeactivated(WindowEvent e)3.public void windowIconified(WindowEvent e)4.public void windowDeiconified(WindowEvent e)5.public void windowClosed(WindowEvent e)6.public void windowClosing(WindowEvent e)7. public void windowOpend(WindowEvent e)

Adapter

MouseWheelEvent

MouseWheelListener

1. public void mouseWheelMoved(MouseWheelEvent e)

Nothing

ALL AWT &SWING PROGRAMS

Repaint2.java(to print images randomly)

import java.awt.*;import java.io.*;import java.applet.*;import java.net.*;/*

<applet code=Repaint2 width=300 height=300></applet>

*/public class Repaint2 extends Applet implements Runnable{

String iname;Thread t=null;boolean flag;Font f=new Font("impact",Font.BOLD+Font.ITALIC,20);public void init(){

//Color c=new Color(200,255,100);setBackground(Color.yellow);setForeground(Color.red);

}public void start()

123A winner not one who never fails but one who never QUITS

Naresh kumar

Page 124: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

{t=new Thread(this);flag=false;t.start();System.out.println("start");

}public void run(){

char ch;for(;;){try{int i=(int)(Math.random()*8);iname=i+".jpg";repaint();Thread.sleep(1000);if(flag)break;}catch(InterruptedException e){e.printStackTrace();}}

}public void stop(){

flag=true;t=null;

}public void paint(Graphics g){

URL path=getCodeBase();Image img=getImage(path,iname);//g.drawImage(img,0,20,300,300,this);g.drawImage(img,0,20,this);showStatus(iname);

}}

MyFrame.java

import java.awt.*;class MyFrame extends Frame{

public static void main(String args[]){

MyFrame f=new MyFrame();

124A winner not one who never fails but one who never QUITS

Naresh kumar

Page 125: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

f.setVisible(true);f.setSize(200,200);Frame f2=new Frame();f2.setVisible(true);f2.setSize(200,200);

}}

MyFrame2.java

import java.awt.*;class MyFrame2 extends Frame{

MyFrame2(String title){super(title);

//setTitle(title);setVisible(true);setSize(200,200);

}public static void main(String args[]){

new MyFrame2("My First Frame");}

}

MyFrame3.javaimport java.awt.*;class MyFrame3{

public static void main(String args[]){

Frame f=new Frame("MyThird Frame");f.setSize(true);f.setVisible("true");

}}

AddComponents.java

import java.awt.*;class MyFrame extends Frame{

Label name=new Label("Name:");Label pwd=new Label("Password:");TextField tname=new TextField();

125A winner not one who never fails but one who never QUITS

Naresh kumar

Page 126: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

TextField tpwd=new TextField();MyFrame(){

setLayout(null);tpwd.setEchoChar('*');add(name);add(pwd);add(tname);add(tpwd);name.setBounds(100,50,80,10);tname.setBounds(190,50,80,20);pwd.setBounds(100,70,80,10);tpwd.setBounds(190,70,80,20);setSize(300,300);setVisible(true);

}}class AddComponents{

public static void main(String args[]){

new MyFrame();}

}FlowLayoutDemo.java

import java.awt.*;class MyFrame extends Frame{

Button b1=new Button("East");Button b2=new Button("West");Button b3=new Button("North");Button b4=new Button("South");Button b5=new Button("Center");MyFrame(){//FlowLayout fl=new FlowLayout(FlowLayout.LEFT);//FlowLayout fl=new FlowLayout(FlowLayout.CENTER);FlowLayout fl=new FlowLayout(FlowLayout.RIGHT);setLayout(fl);setTitle("MyFrame");setSize(300,300);add(b1);add(b2);add(b3);add(b4);

126A winner not one who never fails but one who never QUITS

Naresh kumar

Page 127: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

add(b5);setVisible(true);}public static void main(String args[]){

new FlowLayoutDemo();

}}

BorderLayoutDemo.java

import java.awt.*; //defaultly frame supports Border Layout.CENTERclass BorderLayoutDemo extends Frame{

Button b1=new Button("Madhu");Button b2=new Button("MadhuSudhan");Button b3=new Button("MadhuSudhanRao");Button b4=new Button("Maddy");Button b5=new Button("Mad");BorderLayoutDemo(){BorderLayout bl=new BorderLayout();setLayout(bl);setTitle("BorderLayout");add("East",b1);add("West",b2);add("North",b3);add("South",b4);add("Center",b5);setSize(300,300);setVisible(true);}public static void main(String args[]){

new BorderLayoutDemo();

}}

CardLayoutDemo.java

import java.awt.*; class CardLayoutDemo extends Frame{ Button b1=new Button("One");

Button b2=new Button("Two");

127A winner not one who never fails but one who never QUITS

Naresh kumar

Page 128: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Button b3=new Button("Three");Button b4=new Button("Four");Button b5=new Button("Five");Button b6=new Button("Sixth");CardLayoutDemo(){CardLayout cl=new CardLayout();setLayout(cl);setTitle("CardLayout");add("1", b1);add("2",b2);add("3",b3);add("4",b4);add("5",b5);add("6",b6);//cl.last(this);//cl.first(this);//cl.next(this);cl.show(this,"4");setSize(300,300);setVisible(true);}public static void main(String args[]){new CardLayoutDemo(); }

}GridLayoutDemo.java

import java.awt.*; class GridLayoutDemo extends Frame{

Button b1=new Button("One");Button b2=new Button("Two");Button b3=new Button("Three");Button b4=new Button("Four");Button b5=new Button("Five");Button b6=new Button("Sixth");GridLayoutDemo(){GridLayout gl=new GridLayout(2,3);setLayout(gl);setTitle("GridLayout");add(b1);add(b2);add(b3);add(b4);add(b5);add(b6);

128A winner not one who never fails but one who never QUITS

Naresh kumar

Page 129: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

setSize(300,300);setVisible(true);}public static void main(String args[]){

new GridLayoutDemo();

}}

MenuDemo.java

import java.awt.*;public class MenuDemo extends Frame{

MenuBar bar=new MenuBar();Menu file=new Menu("File");Menu edit=new Menu("Edit");Menu format=new Menu("Format");Menu view=new Menu("View");Menu help=new Menu("Help");MenuItem nw=new MenuItem("New");MenuItem open=new MenuItem("Open");MenuItem cut=new MenuItem("Cut");MenuItem copy=new MenuItem("Copy");MenuItem font=new MenuItem("Font");MenuItem ww=new MenuItem("WordWrap");MenuItem ht=new MenuItem("HelpTopics");CheckboxMenuItem cb=new CheckboxMenuItem("check");TextArea ta=new TextArea();public MenuDemo(String title){

super(title);

bar.add(file);bar.add(edit);bar.add(format);bar.add(view);bar.add(help);file.add(nw);file.add(cb);file.addSeparator();//to add a line in menufile.add(open);edit.add(cut);edit.add(copy);format.add(font);

129A winner not one who never fails but one who never QUITS

Naresh kumar

Page 130: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

view.add(ww);help.add(ht);add(ta);setMenuBar(bar);setSize(400,400);setVisible(true);

}public static void main(String args[]){

new MenuDemo("Madhu Notepad");}

}

EventHandling

ActionEventDemo.java

import java.awt.*;import java.awt.event.*;class ActionEventDemo extends Frame{

Button b1=new Button("EventHandling");ActionEventDemo(){

add(b1);b1.addActionListener(new AL());setSize(200,300);setVisible(true);

}class AL implements ActionListener{

public void actionPerformed(ActionEvent ae){

System.out.println("Button "+ae.getActionCommand()+" Has been clicked....");

}}public static void main(String args[]){

new ActionEventDemo();}

}

KeyBoardEventDemo.java

130A winner not one who never fails but one who never QUITS

Naresh kumar

Page 131: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

import java.awt.*;import java.awt.event.*;class KeyBoardEventDemo extends Frame{

Font f=new Font("Georgia",Font.BOLD+Font.ITALIC,20);Label str=new Label("Nothing....",Label.CENTER);String value;int unicode;KeyBoardEventDemo(){

setBackground(Color.black);setForeground(Color.red);setFont(f);add(str);this.addKeyListener(new KL());setSize(300,300);setVisible(true);

}class KL implements KeyListener{

public void keyPressed(KeyEvent ke){

unicode=ke.getKeyCode();value=ke.getKeyChar()+": ";str.setText(value+unicode);

}public void keyTyped(KeyEvent ke){

System.out.println("keyTyped");}public void keyReleased(KeyEvent ke){

System.out.println("keyReleased..");}

}public static void main(String args[]){

new KeyBoardEventDemo();}

}

WindowEventDemo.java

131A winner not one who never fails but one who never QUITS

Naresh kumar

Page 132: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

import java.awt.*;import java.awt.event.*;class WindowEventDemo extends Frame{

WindowEventDemo(){this.addWindowListener(new WL());setSize(400,400);setVisible(true);}class WL extends WindowAdapter{

public void windowClosing(java.awt.event.WindowEvent e){System.out.println("window closing");System.exit(0);}

}public static void main(String args[]){new WindowEventDemo();}

}

MouseEventDemo.java

import java.awt.*;import java.awt.event.*;class MouseEventDemo extends Frame{

MouseEventDemo(){this.addMouseListener(new ML());this.addMouseMotionListener(new MML());setSize(400,400);setVisible(true);}class MML extends MouseMotionAdapter{

public void mouseMoved(MouseEvent e){

System.out.println("mouse moved.....");}

}class ML extends MouseAdapter{

132A winner not one who never fails but one who never QUITS

Naresh kumar

Page 133: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

public void mouseClicked(MouseEvent me){System.out.println("mouse clicked:\tx="+me.getX()+" y="+me.getY());}

}public static void main(String args[]){

new MouseEventDemo();}

}

Draw.java

import java.awt.*;import java.awt.event.*;import java.applet.*;/*<applet code= Draw width=400 height=400></applet>*/public class Draw extends Applet{

Button b1=new Button("Rect");Button b2=new Button("Line");Button b3=new Button("Oval");Button b4=new Button("Clear");private Color getColor(){

int r=(int)(Math.random()*255); //return type is doubleint g=(int)(Math.random()*255);int b=(int)(Math.random()*255);System.out.println(r+" "+g+" "+b);return new Color(r,g,b);

}public void init(){

setBackground(getColor());setForeground(getColor());add(b1);Font f=new Font("helvitica",Font.BOLD,15);add(b2);add(b3);add(b4);setFont(f);AL al=new AL();b1.addActionListener(al);b2.addActionListener(al);

133A winner not one who never fails but one who never QUITS

Naresh kumar

Page 134: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

b3.addActionListener(al);b4.addActionListener(al);

}class AL implements ActionListener{

public void actionPerformed(ActionEvent e){

Graphics g=getGraphics();if(e.getSource()==b1){g.setColor(getColor());//g.drawRect(150,150,150,100);g.fillRect(150,150,150,100);}else if(e.getSource()==b2){g.setColor(getColor());g.drawLine(0,0,150,150);}else if(e.getSource()==b3){g.setColor(getColor());//g.drawOval(300,250,150,100);g.fillOval(300,250,100,100);}else if(e.getSource()==b4){g.setColor(getColor());g.clearRect(0,0,800,800);

}

}}

}

FocusEx.java

import java.awt.*;import java.awt.event.*;class FocusEx extends Frame implements FocusListener,ActionListener{ TextField uid,pwd,cpwd;

Font f=new Font("Helvitica",Font.BOLD+Font.ITALIC,15); Label str;

Button res;

134A winner not one who never fails but one who never QUITS

Naresh kumar

Page 135: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

FocusEx() {

setFont(f); uid=new TextField(15); pwd=new TextField(15); cpwd=new TextField(15);

str=new Label("LOGIN IN PROGRESS");Label ud=new Label("User-Id : ");Label pd=new Label("Password : ");Label cpd=new Label("Confirm Password : ");

pwd.setEchoChar('*'); cpwd.setEchoChar('*');

setLayout(null);

add(ud); add(uid); add(pd); add(pwd); add(cpd); add(cpwd);

add(str); res=new Button("Reset");

add(res);

setBackground(Color.red);ud.setBounds(50,70,110,30);uid.setBounds(190,70,130,30);pd.setBounds(50,100,110,30);pwd.setBounds(190,100,130,30);cpd.setBounds(50,130,130,30);cpwd.setBounds(190,130,130,30);res.setBounds(120,170,110,20);str.setBounds(70,190,270,30);setSize(400,400);

setVisible(true); uid.addFocusListener(this); pwd.addFocusListener(this); cpwd.addFocusListener(this); res.addActionListener(this);

this.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent we){

System.exit(0);}});

}

135A winner not one who never fails but one who never QUITS

Naresh kumar

Page 136: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

public void actionPerformed(ActionEvent ae) { uid.setText(""); pwd.setText(""); cpwd.setText(""); uid.requestFocus(); } public void focusLost(FocusEvent fe) { if(fe.getSource().equals(cpwd)) { String user=uid.getText().toUpperCase(); String pass=pwd.getText().toUpperCase(); String cpass=cpwd.getText().toUpperCase(); if(user.equals("SCOTT") && pass.equals(cpass)) str.setText("WELCOME "+user); else str.setText("SORRY! INVALID USER."); repaint(); } } public void focusGained(FocusEvent fe) { if(fe.getSource().equals(uid)) { str.setText("Please enter your User Id"); } else if(fe.getSource().equals(pwd)) { str.setText("Please enter your Password"); } else if(fe.getSource().equals(cpwd)) { str.setText("Please enter your ConfirmPassword"); } } public static void main(String a[]) { FocusEx te=new FocusEx();

}}

136A winner not one who never fails but one who never QUITS

Naresh kumar

Page 137: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

ButtonDemo.java

import java.awt.*;import java.awt.event.*;import javax.swing.AbstractButton;import javax.swing.JButton;import javax.swing.JPanel;import javax.swing.JFrame;import javax.swing.ImageIcon;public class ButtonDemo extends JPanel implements ActionListener { protected JButton b1, b2, b3;

public ButtonDemo() { ImageIcon leftButtonIcon = new ImageIcon("images/right.gif"); ImageIcon middleButtonIcon = new ImageIcon("images/middle.gif"); ImageIcon rightButtonIcon = new ImageIcon("images/left.gif");

b1 = new JButton("Disable middle button", leftButtonIcon); b1.setVerticalTextPosition(AbstractButton.CENTER); b1.setHorizontalTextPosition(AbstractButton.LEFT); b1.setMnemonic(KeyEvent.VK_D); b1.setActionCommand("disable");

b2 = new JButton("Middle button", middleButtonIcon); b2.setVerticalTextPosition(AbstractButton.BOTTOM); b2.setHorizontalTextPosition(AbstractButton.CENTER); b2.setMnemonic(KeyEvent.VK_M);

b3 = new JButton("Enable middle button", rightButtonIcon); //Use the default text position of CENTER, RIGHT. b3.setMnemonic(KeyEvent.VK_E); b3.setActionCommand("enable"); b3.setEnabled(false);

//Listen for actions on buttons 1 and 3. b1.addActionListener(this); b3.addActionListener(this);

b1.setToolTipText("Click this button to disable the middle button.");

137A winner not one who never fails but one who never QUITS

Naresh kumar

Page 138: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

b2.setToolTipText("This middle button does nothing when you click it."); b3.setToolTipText("Click this button to enable the middle button.");

//Add Components to this container, using the default FlowLayout. add(b1); add(b2); add(b3); }

public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("disable")) { b2.setEnabled(false); b1.setEnabled(false); b3.setEnabled(true); } else { b2.setEnabled(true); b1.setEnabled(true); b3.setEnabled(false); } } public static void main(String[] args) { JFrame frame = new JFrame("ButtonDemo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.getContentPane().add(new ButtonDemo(), BorderLayout.CENTER); frame.pack(); frame.setVisible(true); }}

CheckBoxDemo.java

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class CheckBoxDemo extends JPanel { JCheckBox chinButton;

138A winner not one who never fails but one who never QUITS

Naresh kumar

Page 139: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

JCheckBox glassesButton; JCheckBox hairButton; JCheckBox teethButton; StringBuffer choices; JLabel pictureLabel; public CheckBoxDemo() { // Create the check boxes chinButton = new JCheckBox("Chin"); chinButton.setMnemonic(KeyEvent.VK_C); chinButton.setSelected(true);

glassesButton = new JCheckBox("Glasses"); glassesButton.setMnemonic(KeyEvent.VK_G); glassesButton.setSelected(true);

hairButton = new JCheckBox("Hair"); hairButton.setMnemonic(KeyEvent.VK_H); hairButton.setSelected(true);

teethButton = new JCheckBox("Teeth"); teethButton.setMnemonic(KeyEvent.VK_T); teethButton.setSelected(true);

// Register a listener for the check boxes. CheckBoxListener myListener = new CheckBoxListener(); chinButton.addItemListener(myListener); glassesButton.addItemListener(myListener); hairButton.addItemListener(myListener); teethButton.addItemListener(myListener);

// Indicates what's on the geek. choices = new StringBuffer("cght");

// Set up the picture label pictureLabel = new JLabel(new ImageIcon( "images/geek/geek-" + choices.toString() + ".gif")); pictureLabel.setToolTipText(choices.toString());

// Put the check boxes in a column in a panel JPanel checkPanel = new JPanel(); checkPanel.setLayout(new GridLayout(0, 1)); checkPanel.add(chinButton); checkPanel.add(glassesButton);

139A winner not one who never fails but one who never QUITS

Naresh kumar

Page 140: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

checkPanel.add(hairButton); checkPanel.add(teethButton);

setLayout(new BorderLayout()); add(checkPanel, BorderLayout.WEST); add(pictureLabel, BorderLayout.CENTER); setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); } /** Listens to the check boxes. */ class CheckBoxListener implements ItemListener { public void itemStateChanged(ItemEvent e) { int index = 0; char c = '-'; Object source = e.getItemSelectable();

if (source == chinButton) { index = 0; c = 'c'; } else if (source == glassesButton) { index = 1; c = 'g'; } else if (source == hairButton) { index = 2; c = 'h'; } else if (source == teethButton) { index = 3; c = 't'; }

if (e.getStateChange() == ItemEvent.DESELECTED) c = '-';

choices.setCharAt(index, c); pictureLabel.setIcon(new ImageIcon( "images/geek/geek-" + choices.toString() + ".gif")); pictureLabel.setToolTipText(choices.toString()); } }

public static void main(String s[]) { JFrame frame = new JFrame("CheckBoxDemo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0);

140A winner not one who never fails but one who never QUITS

Naresh kumar

Page 141: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

} }); frame.setContentPane(new CheckBoxDemo()); frame.pack(); frame.setVisible(true); }}

RadioButtonDemo.java

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class RadioButtonDemo extends JPanel { static JFrame frame; static String birdString = "Bird"; static String catString = "Cat"; static String dogString = "Dog"; static String rabbitString = "Rabbit"; static String pigString = "Pig"; JLabel picture; public RadioButtonDemo() { // Create the radio buttons. JRadioButton birdButton = new JRadioButton(birdString); birdButton.setMnemonic(KeyEvent.VK_B); birdButton.setActionCommand(birdString); birdButton.setSelected(true);

JRadioButton catButton = new JRadioButton(catString); catButton.setMnemonic(KeyEvent.VK_C); catButton.setActionCommand(catString);

JRadioButton dogButton = new JRadioButton(dogString); dogButton.setMnemonic(KeyEvent.VK_D); dogButton.setActionCommand(dogString);

JRadioButton rabbitButton = new JRadioButton(rabbitString); rabbitButton.setMnemonic(KeyEvent.VK_R); rabbitButton.setActionCommand(rabbitString);

141A winner not one who never fails but one who never QUITS

Naresh kumar

Page 142: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

JRadioButton pigButton = new JRadioButton(pigString); pigButton.setMnemonic(KeyEvent.VK_P); pigButton.setActionCommand(pigString);

// Group the radio buttons. ButtonGroup group = new ButtonGroup(); group.add(birdButton); group.add(catButton); group.add(dogButton); group.add(rabbitButton); group.add(pigButton);

// Register a listener for the radio buttons. RadioListener myListener = new RadioListener(); birdButton.addActionListener(myListener); catButton.addActionListener(myListener); dogButton.addActionListener(myListener); rabbitButton.addActionListener(myListener); pigButton.addActionListener(myListener);

// Set up the picture label picture = new JLabel(new ImageIcon("images/" + birdString + ".gif"));

picture.setPreferredSize(new Dimension(177, 122));

// Put the radio buttons in a column in a panel JPanel radioPanel = new JPanel(); radioPanel.setLayout(new GridLayout(0, 1)); radioPanel.add(birdButton); radioPanel.add(catButton); radioPanel.add(dogButton); radioPanel.add(rabbitButton); radioPanel.add(pigButton);

setLayout(new BorderLayout()); add(radioPanel, BorderLayout.WEST); add(picture, BorderLayout.CENTER); setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); }

/** Listens to the radio buttons. */ class RadioListener implements ActionListener {

142A winner not one who never fails but one who never QUITS

Naresh kumar

Page 143: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

public void actionPerformed(ActionEvent e) { picture.setIcon(new ImageIcon("images/" + e.getActionCommand() + ".gif")); } } public static void main(String s[]) { frame = new JFrame("RadioButtonDemo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); frame.getContentPane().add(new RadioButtonDemo(), BorderLayout.CENTER); frame.pack(); frame.setVisible(true); }}

ComboBoxDemo.java

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class ComboBoxDemo extends JPanel { JLabel picture; public ComboBoxDemo() { String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };

// Create the combo box, select the pig JComboBox petList = new JComboBox(petStrings); petList.setSelectedIndex(4); petList.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox cb = (JComboBox)e.getSource(); String petName = (String)cb.getSelectedItem(); picture.setIcon(new ImageIcon("images/"+petName + ".gif")); } });

143A winner not one who never fails but one who never QUITS

Naresh kumar

Page 144: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

// Set up the picture picture = new JLabel(new ImageIcon("images/"+petStrings[petList.getSelectedIndex()] +".gif")); picture.setBorder(BorderFactory.createEmptyBorder(10,0,0,0)); // The preferred size is hard-coded to be the width of the // widest image and the height of the tallest image + the border. // A real program would compute this. picture.setPreferredSize(new Dimension(177, 122+10));

// Layout the demo setLayout(new BorderLayout()); add(petList, BorderLayout.NORTH); add(picture, BorderLayout.SOUTH); setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); }

public static void main(String s[]) { JFrame frame = new JFrame("ComboBoxDemo");

frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); frame.setContentPane(new ComboBoxDemo()); frame.pack(); frame.setVisible(true); }}

ColorChooser.java

import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;import javax.swing.colorchooser.*;

public class ColorChooserDemo extends JFrame {

144A winner not one who never fails but one who never QUITS

Naresh kumar

Page 145: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

public ColorChooserDemo() { super("ColorChooserDemo");

//Set up the banner at the top of the window final JLabel banner = new JLabel("Welcome to the Tutorial Zone!", JLabel.CENTER); banner.setForeground(Color.yellow); banner.setBackground(Color.blue); banner.setOpaque(true); banner.setFont(new Font("SansSerif", Font.BOLD, 24)); banner.setPreferredSize(new Dimension(100, 65));

JPanel bannerPanel = new JPanel(new BorderLayout()); bannerPanel.add(banner, BorderLayout.CENTER); bannerPanel.setBorder(BorderFactory.createTitledBorder("Banner"));

//Set up color chooser for setting text color final JColorChooser tcc = new JColorChooser(banner.getForeground()); tcc.getSelectionModel().addChangeListener( new ChangeListener() { public void stateChanged(ChangeEvent e) { Color newColor = tcc.getColor(); banner.setForeground(newColor); } } ); tcc.setBorder(BorderFactory.createTitledBorder( "Choose Text Color"));

//Add the components to the demo frame Container contentPane = getContentPane(); contentPane.add(bannerPanel, BorderLayout.CENTER); contentPane.add(tcc, BorderLayout.SOUTH); }

public static void main(String[] args) { JFrame frame = new ColorChooserDemo(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} });

145A winner not one who never fails but one who never QUITS

Naresh kumar

Page 146: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

frame.pack(); frame.setVisible(true); }}

TabbedPaneDemo.java

import javax.swing.JTabbedPane;import javax.swing.ImageIcon;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JFrame;

import java.awt.*;import java.awt.event.*;

public class TabbedPaneDemo extends JPanel { public TabbedPaneDemo() { ImageIcon icon = new ImageIcon("images/middle.gif"); JTabbedPane tabbedPane = new JTabbedPane();

Component panel1 = makeTextPanel("Blah"); tabbedPane.addTab("One", icon, panel1, "Does nothing"); tabbedPane.setSelectedIndex(0);

Component panel2 = makeTextPanel("Blah blah"); tabbedPane.addTab("Two", icon, panel2, "Does twice as much nothing");

Component panel3 = makeTextPanel("Blah blah blah"); tabbedPane.addTab("Three", icon, panel3, "Still does nothing");

Component panel4 = makeTextPanel("Blah blah blah blah"); tabbedPane.addTab("Four", icon, panel4, "Does nothing at all");

//Add the tabbed pane to this panel. setLayout(new GridLayout(1, 1)); add(tabbedPane); }

protected Component makeTextPanel(String text) {

146A winner not one who never fails but one who never QUITS

Naresh kumar

Page 147: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

JPanel panel = new JPanel(false); JLabel filler = new JLabel(text); filler.setHorizontalAlignment(JLabel.CENTER); panel.setLayout(new GridLayout(1, 1)); panel.add(filler); return panel; }

public static void main(String[] args) { JFrame frame = new JFrame("TabbedPaneDemo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} });

frame.getContentPane().add(new TabbedPaneDemo(), BorderLayout.CENTER); frame.setSize(400, 125); frame.setVisible(true); }}

InternalFrameDemo.java

import javax.swing.*;import java.awt.*;import java.awt.event.*;class InternalFrameDemo extends JFrame{

JMenuBar bar=new JMenuBar();JMenu m=new JMenu("frames");JMenuItem i1=new JMenuItem("one");JMenuItem i2=new JMenuItem("two");JMenuItem i3=new JMenuItem("three");JMenuItem i4=new JMenuItem("four");JDesktopPane jdp=new JDesktopPane();JInternalFrame jf1=new

JInternalFrame("First",true,false,true,true);JInternalFrame jf2=new

JInternalFrame("Second",true,false,true,true);JInternalFrame jf3=new

JInternalFrame("Three",true,false,true,true);JInternalFrame jf4=new

JInternalFrame("Fouth",true,false,true,true);InternalFrameDemo(){

147A winner not one who never fails but one who never QUITS

Naresh kumar

Page 148: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

bar.add(m);m.add(i1);m.add(i2);m.add(i3);m.add(i4);jf1.getContentPane().add(new JButton("First Frame"));jf2.getContentPane().add(new JButton("Second

Frame"));jf3.getContentPane().add(new JButton("Third Frame"));jf4.getContentPane().add(new JButton("Fourth

Frame"));try{jf1.setMaximum(true);jf2.setMaximum(true);jf3.setMaximum(true);jf4.setMaximum(true);}catch(Exception e){}jf1.setVisible(true);jf2.setVisible(true);jf3.setVisible(true);jf4.setVisible(true);jdp.add(jf1);jdp.add(jf2);jdp.add(jf3);jdp.add(jf4);i1.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){jf1.setSize(400,400);jf1.toFront();}

});i2.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){jf2.setSize(400,400);jf2.toFront();}

});i3.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){jf3.setSize(400,400);

148A winner not one who never fails but one who never QUITS

Naresh kumar

Page 149: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

jf3.toFront();}

});i4.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){jf4.setSize(400,400);jf4.toFront();}

});Container c=getContentPane();c.add(bar,BorderLayout.NORTH);c.add(jdp,BorderLayout.CENTER);}public static void main(String arg[]){

InternalFrameDemo ifd=new InternalFrameDemo();ifd.setSize(500,500);ifd.setVisible(true);

}}

Scroll.java

import javax.swing.*;import java.awt.*;import java.awt.event.*;class Scroll extends JFrame implements AdjustmentListener{

int r,gr,b;Container c;JPanel jp=new JPanel();JPanel jp1=new JPanel();JTextField jt1=new JTextField(10);JTextField jt2=new JTextField(10);JTextField jt3=new JTextField(10);JScrollBar js1=new

JScrollBar(SwingConstants.HORIZONTAL,10,5,0,260);JScrollBar js2=new

JScrollBar(SwingConstants.VERTICAL,0,5,0,260);JScrollBar js3=new

JScrollBar(SwingConstants.HORIZONTAL,0,5,0,260);JScrollBar js4=new

JScrollBar(SwingConstants.VERTICAL,0,5,0,260);public Scroll()

149A winner not one who never fails but one who never QUITS

Naresh kumar

Page 150: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

{c=getContentPane();jp.setLayout(new BorderLayout());jp.add(js1,BorderLayout.NORTH);jp.add(js2,BorderLayout.EAST);jp.add(js3,BorderLayout.SOUTH);jp.add(js4,BorderLayout.WEST);jp1.add(jt1);jp1.add(jt2);jp1.add(jt3);c.add(jp,BorderLayout.NORTH);c.add(jp1,BorderLayout.SOUTH);jp.setBackground(Color.red);js1.addAdjustmentListener(this);js2.addAdjustmentListener(this);js3.addAdjustmentListener(this);js4.addAdjustmentListener(this);jt1.setForeground(Color.red);

jt1.setBackground(Color.black);jt2.setForeground(Color.red);jt2.setBackground(Color.black);jt3.setForeground(Color.red);jt3.setBackground(Color.black);

//show();}public void adjustmentValueChanged(AdjustmentEvent e){

if(e.getSource()==js1){r=js1.getValue();js1.setBackground(new Color(r,gr,b));jt1.setText(String.valueOf(js1.getValue()));jp.setBackground(new Color(r,gr,b));jp1.setBackground(new Color(r,gr,b));}else if(e.getSource()==js2){

gr=js2.getValue();jt2.setText(String.valueOf(js2.getValue()));

js2.setBackground(new Color(r,gr,b));jp.setBackground(new Color(r,gr,b));

jp1.setBackground(new Color(r,gr,b)); }else if(e.getSource()==js3){

150A winner not one who never fails but one who never QUITS

Naresh kumar

Page 151: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

b=js3.getValue();js3.setBackground(new Color(r,gr,b));jt3.setText(String.valueOf(js3.getValue()));jp.setBackground(new Color(r,gr,b));

jp1.setBackground(new Color(r,gr,b));}else if(e.getSource()==js4){

c.setBackground(new Color(r,gr,b));

}}public static void main(String args[]){

Scroll s=new Scroll();s.setSize(400,400);s.setVisible(true);

}}

TreeDemo.java

import javax.swing.*;import javax.swing.event.*;import javax.swing.tree.*;import java.awt.*;class TreeDemo extends JFrame{

Container c;TreeDemo(){

setTitle("TreeDemo");c=getContentPane();

DefaultMutableTreeNode root =new DefaultMutableTreeNode("country");

DefaultMutableTreeNode country =new DefaultMutableTreeNode("India");

root.add(country);DefaultMutableTreeNode state=new

DefaultMutableTreeNode("AndhraPradesh");country.add(state);DefaultMutableTreeNode city=new

DefaultMutableTreeNode("Hyderabad");

151A winner not one who never fails but one who never QUITS

Naresh kumar

Page 152: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

state.add(city);city=new DefaultMutableTreeNode("Tirupathi");state.add(city);city=new DefaultMutableTreeNode("Vizag");state.add(city);

state=new DefaultMutableTreeNode("Karnataka");country.add(state);city=new DefaultMutableTreeNode("Bangalore");

state.add(city);

state=new DefaultMutableTreeNode("TamilNadu");country.add(state);city=new DefaultMutableTreeNode("Chennai");state.add(city);city=new DefaultMutableTreeNode("Tiruchanur");

state.add(city);city=new DefaultMutableTreeNode("Tanjavour");

state.add(city);

JTree tree=new JTree(root);c.add(new JScrollPane(tree));setSize(300,300);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) {

TreePath tp=e.getPath(); DefaultMutableTreeNode node=(DefaultMutableTreeNode)tp.getLastPathComponent(); if (node == null) return;

Object nodeInfo = node.getUserObject();System.out.println("nodeInfo:\t"+nodeInfo.toString());

if (node.isLeaf()) { } } });

}public static void main(String args[]){

new TreeDemo();}

}

152A winner not one who never fails but one who never QUITS

Naresh kumar

Page 153: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Calculator.java

import java.awt.*;import java.awt.event.*;import javax.swing.ImageIcon;class Calculator extends Frame{

Double x,y,z;char sym;String sval="";String str="1234567890+*/-.=";Button b[]=new Button[str.length()];TextField tf=new TextField(100);Panel p1=new Panel();Panel p2=new Panel();AL al;Image img;String res="";Calculator(){

Toolkit tk=Toolkit.getDefaultToolkit();img=tk.createImage("images/Bird.gif");setIconImage(img);p1.setLayout(new FlowLayout(FlowLayout.LEFT));p1.add(tf);add(p1);p2.setLayout(new GridLayout(4,4));add("North",p1);add(p2);addButtons();setSize(00,190);setBackground(Color.blue);setVisible(true);//setResizable(false);addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent we){dispose();}

});}private Color getColor(){

int r=(int)(Math.random()*255); //return type is doubleint g=(int)(Math.random()*255);int b=(int)(Math.random()*255);

153A winner not one who never fails but one who never QUITS

Naresh kumar

Page 154: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

return new Color(r,g,b);}public void addButtons(){

al=new AL();for(int i=0;i<b.length;i++){

b[i]=new Button(str.charAt(i)+"");p2.add(b[i]);b[i].setBackground(getColor());b[i].setForeground(Color.white);b[i].setFont(new Font("Georgia",Font.BOLD,30));b[i].addActionListener(al);

}}

class AL implements ActionListener{

public void actionPerformed(ActionEvent ae){

for(int i=0;i<10;i++){if(ae.getSource()==b[i]){sval=sval+ae.getActionCommand();System.out.println(sval);}}if(ae.getSource()==b[10]){

try{x=Double.parseDouble(sval);sym='+';sval="";}catch(Exception e){}

}

else if(ae.getSource()==b[13]){

try{x=Double.parseDouble(sval);sym='-';sval="";}catch(Exception e){}

154A winner not one who never fails but one who never QUITS

Naresh kumar

Page 155: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

}else if(ae.getSource()==b[11]){

try{x=Double.parseDouble(sval);sym='*';sval="";}catch(Exception e){}

}else if(ae.getSource()==b[12]){

try{x=Double.parseDouble(sval);sym='/';sval="";}catch(Exception e){}

}

else if(ae.getSource()==b[14]){

try{sval=sval+ae.getActionCommand();}catch(Exception e){}

}else if(ae.getSource()==b[15]){

try{y=Double.parseDouble(sval);sval="";switch(sym){case '+' :

res=String.valueOf(x+y);break;

case '-' :res=String.valueOf(x-y);break;

case '*' :res=String.valueOf(x*y);break;

case '/' :res=String.valueOf(x/y);

155A winner not one who never fails but one who never QUITS

Naresh kumar

Page 156: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

break;default :

break;}}catch(NumberFormatException e){}

}if(res.equals(""))tf.setText(sval);else{tf.setText(res);res="";}

System.out.println("Button "+ae.getActionCommand()+" Has been clicked....");

}}public static void main(String args[]){

new Calculator();

}}

Table. java(Table creation using JTable class)

import java.awt.*;import javax.swing.*;public class TableDemo extends JFrame{

Toolkit tk=Toolkit.getDefaultToolkit();Dimension d;JTable tab;Object rowData[][]={{"101","Madhu","L.K.G","B"},

{"102","BHUVAN","U.K.G","A"},{"103","PRATHYUSHA","L.K.G","C"},{"104","SONI","1st","D"},{"105","MONI","1st","D"},{"106","MANI","2nd","B"}};

Object col[]={"No","Name","CLASS","SECTION"};TableDemo(String title){

super(title);d=tk.getScreenSize();

156A winner not one who never fails but one who never QUITS

Naresh kumar

Page 157: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

tab=new JTable(rowData,col);tab.setBackground(new Color(255,255,43));tab.setSelectionBackground(Color.black);tab.setSelectionForeground(Color.red);tab.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);tab.setGridColor(java.awt.Color.green);add(new JScrollPane(tab));setSize(d);setVisible(true);

}public static void main(String args[]){

new TableDemo("Table ");}

}

Networking

Java is a programming language for the Internet. It provides the package java.net used for networking programs.

Network: A network is simply is an organization of several computers that can all communicate with each other.

Internet

The collection of all computers that can communicate using the Internet Protocol suit (IPS), with the computers and networks registered with Internet Network Information Center (INIC).

(Or)

The internet is a network of networks that makes information easily accessible, even between different types of computers.

Modem: A modem is a device that allows two computers to communicate over a standard phone line.

Protocol: protocol is a set of rules and conventions followed by systems that communicate over a network.

Computers on the Internet Communicate by Exchanging packets of data, known as IP (Internet Protocol) packets.

IP: IP is the network protocol used to send information from one computer to another computer over the Internet. They are routed via special routing algorithms from a source computer to destination

157A winner not one who never fails but one who never QUITS

Naresh kumar

Page 158: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

computer.

In order for IP to send packets from a source computer to a destination computer, it must have some way of identifying these computers. all computers on the internet are identified using one or more IP address. A computer may have more than one IP address if it has more than on interface to computers that are connected to the Internet.

IP addresses are 32 bit numbers, they may be written in decimal, hexadecimal, or other formats, but the most common format is dotted decimal notation.

ex: 204.212.0.1

Domain Name System:

The Internet has adopted a mechanism, the DomainNameSystem (DNS), whereby computer names can be associated with IP addresses. These computer names are referred to as domain names.

Connection Oriented vs Connectionless Communication

Transport protocols are used to deliver information from one port to another and thereby enable communication between application programs. They use either a connection oriented or connectionless method of communication. TCP is a connection oriented protocol, and UDP (User Datagram Protocol) is a connectionless transport protocol.

The TCP connection oriented protocol establishes a communication link between a source port/IP address and a destination port/IP address. Ex: Telephone conversation.

TCP implements the connection as a stream of bytes from source to destination. This feature allows the use of I/O streams of java.io package.

UDP is a connection less protocol in that it does not establish connection.ex: postal mail

When using UDP an application program writes the destination

158A winner not one who never fails but one who never QUITS

Naresh kumar

Page 159: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

port and IP address on a datagram and thenSends the datagram to its destination. UDP is less reliable than TCP because there is no delivery-assurance or error-detection-and correction mechanisms built into the protocol.

Sockets and Client/Server Communication:

Clients and servers establish connections and communicate via sockets.

Connections are communication links that are created over the Internet using TCP.

Some client/server applications are also built around the connectionless UDP. These applications also use sockets to communicate.

Clients create client sockets and connect them to server sockets.

Port: Data transmitted over the Internet, is accompanied by addressing information that identifies the computer and the port for which it is destined. The computer is identified by 32 bit IP address, which IP uses to deliver data to the right computer in the network. Ports are identified by a 16 bit number, which TCP and UDP use the port to deliver the data to the right application.

The TCP/UDP protocols use ports to map incoming data to a particular process running on a computer.

Port numbers ranges from 0 to 65535 because ports are represented by 16 bit numbers. The port numbers ranges from 0 to 1023 are reserved for use by well-known services. These ports are called well-known ports.

URL: URL is an acronym for uniform Resource Locator and is a reference (an Address) to a resource on the Internet. It is an address of a resource on the web.

Syntax: Protocol identifies//resource name

Let’s look at the URL http://www.yahoo.com In the above example is a URL which address the yahoo web site.URL has two components

1. Protocol identifier(E.g.: HTTP)2. Resource name

159A winner not one who never fails but one who never QUITS

Naresh kumar

Page 160: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

Protocol identifier and Resource names are separated by a colon and the two forward slashes. The first one is used to give the name of the protocol. The next one is fetch the resource.

There are two kinds of TCP sockets in java. One is for servers, and the other is for clients.

Server Socket:The ServerSocket class is designed to be a listener which

waits for clients to connect. Socket:

The Socket class is designed to connect to server sockets and initiate protocal

The creation of Socket object implicitly establishes a connection between the client and server. There are no methodsor constructors that explicitly expose the details of establishing that connection.

There are two constructors used to create client sockets:

1. Socket(String hostname,int port)Creates a socket connecting the localhost to the named host and

port;can throw anUnknownHostException or an IOException

2. Creates a socket using a preexisting InetAddress object and a port; can throw an IOException;

Scocket(InetAddress inet,int port)

java.net:

Socket, Server Socket, Datagram Socket classes implement clientServer sockets for connection-oriented and connection less Communication.Datagram Packet:This class is used to construct UDP Datagram packets

The InetAddress Class:

The InetAddress class encapsulates Internet addressIt supports both numeric IP address and host names.getLocalHost: it is a static method and that returns an InetAddressobject that represents the Internet address of the local host computer.

160A winner not one who never fails but one who never QUITS

Naresh kumar

Page 161: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

getByName : It is a static method and returns an InetAddress object for a specified host.getAllByName: It returns an array of all Internet addresses associated with a particular hostgetAddress : It gets the numeric IP address of the host identified by the InetAddress Object,

GetHostName: getHostName method gets its domain name.

getHostAddress: returns the numeric IP address of an InetAddress object as a dotted decimal string.

isMulticastAddress (): method returns a Boolean value that indicates whether an InetAddress objet trptrdrnyd s mulyivsdy sfftrdd.

access ():

The access method of the Socket class is used to access the I/O streams and connection parameters associated with a connected socket.

The getInetAddress () and getPort () methods get the IP address of the destination host

And the distination host port number to which the socket is connected.

GetLocalPort () method returns source host local port number associated with the socket.

GetLocalAddress () returns the local IP address associated with the socket

GetInputStream () and getOutputStream () are used to access the input and output streams associated with a socket. The close() method is used to close a socket.

InetAddressDemo.java

import java.net.*;import java.io.*;public class InetAddressDemo{

161A winner not one who never fails but one who never QUITS

Naresh kumar

Page 162: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

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

InetAddress ia=InetAddress.getLocalHost();System.out.println("Host and Address Is:\t"+ia);System.out.println("Host Name:\t"+ia.getHostName());//unreported

exception java.net.UnknownHostExceptionString s=ia.toString();System.out.println("IP Address:\t"+s.substring(s.indexOf("/")+1));

}}

FindIPAddress.java

import java.net.*;import java.io.*;public class FindIPAddress{

public static void main(String ar[])throws Exception{

DataInputStream dis=new DataInputStream(System.in);System.out.println("Ente the host name");String s=dis.readLine();try{InetAddress add=InetAddress.getByName(s);System.out.println("IP address"+add);}catch(UnknownHostException ah){System.out.println("no host with given name");}

}}

DNS.java

import java.net.*;public class DNS{

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

InetAddress [] address=InetAddress.getAllByName("java.sun.com");for(int j=0;j<address.length;j++)System.out.println(address[j]);

}}

162A winner not one who never fails but one who never QUITS

Naresh kumar

Page 163: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

URLComponents.java

import java.net.*;class URLComponents{

public static void main(String args[]) throws Exception{//URL url=new URL("http://localhost:8080/servlets-examples/servlet/Welcome?

uname=chandu&uname1=Doctor");URL url=new URL("http://www.rediffmail.com:80/chandu/net/Example?

uname=xxx&uname1=yyy");

System.out.println("Protocal:"+url.getProtocol());System.out.println("port:"+url.getPort());System.out.println("Host:"+url.getHost());System.out.println("File:"+url.getFile());System.out.println("Ext:"+url.toExternalForm());System.out.println("query :"+url.getQuery());System.out.println("reference :"+url.getRef());System.out.println("default port :"+url.getDefaultPort());

}}

URLCon.java

import java.net.*;import java.io.*;public class URLCon{

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

URL url=new URL("http://localhost:8888/RequestDispatcherPro/welcome.html");

URLConnection uc=url.openConnection();System.out.println("Host Name:\t"+url.getHost());String fname=url.getFile();System.out.println("File Name:\t"+url.getFile());System.out.println("Port No:\t"+url.getPort());System.out.println("Protocol No:\t"+url.getProtocol());System.out.println(new java.util.Date(uc.getDate()));InputStream in=uc.getInputStream();FileOutputStream fos=new

FileOutputStream(fname.substring(fname.lastIndexOf("/")+1));

163A winner not one who never fails but one who never QUITS

Naresh kumar

Page 164: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

int c=0;while((c=in.read())!=-1){//System.out.print((char)c);fos.write(c);

}in.close();fos.close();

}

}

Client.java

import java.net.*;import java.io.*;public class Client{

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

Socket s=null;BufferedReader b=null;try{s=new Socket(InetAddress.getLocalHost(),98);//s=new Socket(IP address of another system,98);b=new BufferedReader(new InputStreamReader(s.getInputStream()));

}catch(UnknownHostException ue){System.out.println("I dont Know the Host:");System.exit(0);}String inp;while((inp=b.readLine())!=null){

System.out.println(inp);}b.close();s.close();

}}

Server.java

164A winner not one who never fails but one who never QUITS

Naresh kumar

Page 165: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

import java.net.*;import java.io.*;public class Server{

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

ServerSocket s1=null;try{

s1=new ServerSocket(98);}catch(IOException u1){

System.err.println("could not found port 98");System.exit(1);

}Socket c=null;try{

c=s1.accept();;System.out.println("Connection from"+c);

}catch(IOException e){System.err.println("accept failedd");

System.exit(1);}PrintWriter out=new PrintWriter(c.getOutputStream(),true);BufferedReader in=new BufferedReader(new

InputStreamReader(c.getInputStream()));String l;BufferedReader sin=new BufferedReader(new

InputStreamReader(System.in));System.out.println("Ok... I am Ready Type Now");while((l=sin.readLine())!=null){

out.println(l);}out.close();sin.close();c.close();s1.close();

}}

DatagramPacketClient.java

165A winner not one who never fails but one who never QUITS

Naresh kumar

Page 166: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

import java.net.*;import java.io.*;public class DatagramPacketClient{

public static void main(String args[]){

byte b[]=new byte[512];

DatagramPacket dp=new DatagramPacket(b,b.length);DatagramSocket ds=null;try{ds=new DatagramSocket(666);}catch(SocketException se){se.printStackTrace();}System.out.println("Waiting.......");try{ds.receive(dp);}catch(IOException e){e.printStackTrace();}String str=new String(dp.getData());System.out.println(str.trim());System.out.println("Client add:\t"+dp.getAddress());System.out.println("Client port:\t"+dp.getPort());

}

}

DatagramPacketServer.java

import java.net.*;import java.io.*;public class DatagramPacketServer{

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

DatagramSocket ds=new DatagramSocket(999);byte b[]="Hello Server Datagram Socket....".getBytes();InetAddress ia=InetAddress.getLocalHost();DatagramPacket dp=new DatagramPacket(b,b.length,ia,666);ds.send(dp);System.out.println(dp);System.out.println("dataSend.....");System.out.println("address:\t"+dp.getAddress());System.out.println("port:\t"+dp.getPort());

}}

166A winner not one who never fails but one who never QUITS

Naresh kumar

Page 167: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

ClientChat.java

import java.net.*;import java.io.*;public class ClientChat{

public static void main(String args[]) throws Exception{DataInputStream rc=new DataInputStream(System.in);String str=null;InetAddress inet=InetAddress.getLocalHost();Socket s=new Socket(inet,6500);DataInputStream din=new DataInputStream(s.getInputStream());DataOutputStream dout=new DataOutputStream(s.getOutputStream());try{if(!(s.isClosed())){while(true){System.out.println("Enter Data");str=rc.readLine();dout.writeUTF(str);str=din.readUTF();System.out.println(str);}}else{

s.close();}}catch(Exception e){System.out.println("server closed");}}

}

ChatServer.java

import java.net.*;

167A winner not one who never fails but one who never QUITS

Naresh kumar

Page 168: ramudonikana.files.wordpress.com€¦  · Web viewCore Java Notes. What is procedural programming? A procedural program divides the code into smaller blocks called procedures. Procedures

Naresh kumar terli CORE JAVA Name That builds You

import java.io.*;public class ChatServer{

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

DataInputStream rc;//=new DataInputStream(System.in);String str=null;ServerSocket ss;//=new ServerSocket(6500);//System.out.println("Waiting");Socket s;//=ss.accept();

DataInputStream din=null;//=new DataInputStream(s.getInputStream());DataOutputStream dout=null;//=new DataOutputStream(s.getOutputStream());

try{rc=new DataInputStream(System.in);ss=new ServerSocket(6500);System.out.println("Waiting");s=ss.accept();if(!(s.isClosed())){while(true){din=new DataInputStream(s.getInputStream());dout=new DataOutputStream(s.getOutputStream());str=din.readUTF();System.out.println(str);System.out.println("Enter Data");str=rc.readLine();dout.writeUTF(str);

}}}catch(Exception e){

dout.writeUTF("Server Closed.byeeeeeee ");}

}}

168A winner not one who never fails but one who never QUITS

Naresh kumar