Java

152
www.aspgmca.blogspot.com UNIT - I Introduction: Programming Languages are classified into the following categories a) Monolytic Programming Languages b) Procedural Programming Languages c) Structured Programming Languages d) Object Oriented Programming Languages a) Monolytic Programming Languages: Monolytic Programming Languages contain number of lines of data. Drawback: 1. It is not subroutine concept. 2. The program code is duplicated each time it is to be used. Examples: Assembly Language, Basic b) Procedural Programming Languages: The important features of Procedural Programming Languages are i) Emphasis on algorithm rather than data ii) Programs are organized in form of subroutine iii) Program controls are through jumps (goto) and calls to subroutine iv) Data move overly around the system from function to function v) It follows top down approach in program design vi) It is suitable for medium size software applications 1 1 ---- 2 --- -- -- 100 --- Global data

Transcript of Java

Page 1: Java

www.aspgmca.blogspot.com

UNIT - I

Introduction:

Programming Languages are classified into the following categoriesa) Monolytic Programming Languagesb) Procedural Programming Languagesc) Structured Programming Languagesd) Object Oriented Programming Languages

a) Monolytic Programming Languages: Monolytic Programming Languages contain number of lines of data.

Drawback: 1. It is not subroutine concept.2. The program code is duplicated each time it is to be used.

Examples: Assembly Language, Basic

b) Procedural Programming Languages: The important features of Procedural Programming Languages are

i) Emphasis on algorithm rather than dataii) Programs are organized in form of subroutineiii) Program controls are through jumps (goto) and calls to subroutineiv) Data move overly around the system from function to functionv) It follows top down approach in program designvi) It is suitable for medium size software applications

Drawback: 1. Data Security problem2. Difficult to maintain program code3. It doesn’t model to real world problem very well

Examples: Fortran, Cobol

c) Structured Programming Languages: In Structured Programming Languages programs consist of multiple modules and each module has a set of functions of related types. The important features of Structured Programming Languages are

i) Programs are divided into individual procedures that performs discrete tasks

ii) Procedures are independent of each otheriii) Procedures have their own local data and processing logic

1

1 ----2 -------100 ---

Global data

Page 2: Java

www.aspgmca.blogspot.com

iv) Introduction of the concepts of user defined datatypesv) Maintenance of a large software system costly

Sub programming

Module 1 Module 2

Drawback: 1. Data Security problem2. It doesn’t model real world problem very well

Examples: Pascal, C

d) Object Oriented Programming Languages: The important features of Object Oriented Programming Languages are

i) Emphasis on data rather than functionsii) Programs are divided into objectsiii) Functions that operate on the data of an object are together in the data

structureiv) Data is hidden and cannot be accessed by external functions (Data

security)v) Objects may communicate with each other through functionsvi) New data can be easily added to the functions whenever necessaryvii) It follows bottom-up approach in program designing

Object A Object B

Object CThe important features of Object Oriented Programming are

a) Encapsulation

2

Global data

Data

functions

Data

Functions

Data

functions

Page 3: Java

www.aspgmca.blogspot.com

b) Abstractionc) Inheritanced) Polymorphism

a) Encapsulation: The mechanism by which the data and functions are bounded together with an object definition. By means of Encapsulation, it can possible to protect the data.b) Abstraction: It is the process of defining data type often called an abstract data type together with the principle of data hiding.

Abstract Data type refers to the program defined data type together with a set of operations than can be performed on the data. Data hiding is a property where by the internal data structure of an object is hidden from the rest of the program. The data can be accessed only by the function declared with in the class.c) Inheritance: Inheritance is the mechanism that allows the programmer to derive new classes from existing classes. The derived classes inherit the methods and data of the parent class.d) Polymorphism: Polymorphism is a feature that allows giving a single name to different methods with different parameters. Depending on the parameters only one particular method is executed.

Object Based Programming = Data Encapsulation + Data Hiding + Overloading (Polymorphism)Example: Ada

Dynamic Binding: When a method is called within a program, it associated with the program at run time rather than at compile time is called dynamic binding.

Object Oriented Programming = Object Based Programming Concepts + Inheritance + Dynamic Binding (Polymorphism)Example: C++, JAVA

Advantages of OOP1. OOP uses objects in programming languages.2. The independence of each object easily to development and maintenance of the

program3. Data Hiding and Data Abstraction increase reliability and helps the programmer

to built secure programs.4. Dynamic Binding increases flexibility by permitting the addition of new class

objects without having to modify the existing code.5. Inheritance with Dynamic Binding enhances the reusability of code.

Applications of OOP

1. Simulation and Modeling2. User Interface Design3. Artificial Intelligence and Expert Systems4. Neural Networks5. Web Designing6. CAD/CAM System

3

Page 4: Java

www.aspgmca.blogspot.com

JAVA: Java Programming Language was designed by “James Gosling” at Sun Microsystems in 1991. This language was initially called “Oak” but was renamed “Java” in 1995. It follows both the features of C and C++.

Java Programming Language was very useful on Internet Programming. Since, by this language we can easily transfer the information from server to the nodes through the network. It provides active programs when we are viewing the passive data and self-executing programs. Generally, in the case of network programs Security and Portability is the main active areas concern. The Java Applet Programming provides such things.

Java programs are classified into 2 types.1. Application Programs2. Applet Programs

An Application is a program run on the computer under the operating system of the computer. This is similar to the other programming languages.

An Applet is an application designed to be transmitted over the Internet and executed by a Java-compatible Web browser.

Java Features/Buzz Words

a) Platform Independent: Java is a platform independent language. Once we create the program in one operating system, the program is worked in any operating system that is transmitted to the operating system.

b) Portable: The most significant contribution of Java over other languages is its portability. Java programs can be easily moved from one computer system to another anywhere and any time. Changes and upgrades in operating systems, processors, system resources will not forces any changes in Java programming.

c) Object oriented: Java is a true object oriented language. Why because without class we can’t run the program. Without main we can run the program. Almost everything in Java is an object. All program code & data reside with objects and classes. The object model in Java is simple and easy.

d) Robust & Secure: Java is a Robust Language. It provides many safe guards to ensure reliable code. It is designed as garbage collected language relieving the programmers, virtually all memory management problems. Java also incorporates the concept of exception handling, which captures serious errors and eliminates any risk on crashing the system.

Security becomes an important issue for a language that is used for programming on Internet. Java systems not only verify all memory access but also ensure that no viruses are communicated with the Applet.

e) Distributed: Java is designed as a distributed language for creating applications on network. It has the ability to share both data and program. Java applications can open and remote object on Internet as easily as they can do in local system.

f) Simple & Small: Java is a simple & small language. Many features of C and C++ that are sources are unreliable code are not part of Java. For example, Java doesn’t use Pointers, Preprocessors, Header files, goto statements and many others.

g) Multi Threaded: Java was designed to meet the real-world requirement of creating interactive, networked programs. Java supports multithreaded programming, which

4

Page 5: Java

www.aspgmca.blogspot.com

allows to handling multi tasks simultaneously. This means we need not wait for the application to finish one task before beginning another one.

h) Dynamic: Java is a dynamic language. Java is capable on dynamically linking in new class, libraries, methods and objects. Java support functions written in other languages such as C and C++. These functions are known as native methods. Native methods are linked dynamically at run time.

i) Compile & Interpreted: Usually a Computer language is either compiled or interpreted. Java combined both these approaches thus making. Java is a two-stage system. First Java Compiler translates source code into byte code instruction and therefore in the second stage Java Interpreter generates machine code that can be directly executed by the machine that is running the Java program.

Interpreter is called JVM (Java Virtual Machine). Java applications are platform independent. JVM, JDK are platform dependent. Interpreter is different for all operating systems like DOS, UNIX etc.,

The main drawback of C is the program cannot run in any other operating system. It is advantage of Java.

j) High performance: Java performance is impressing for an interpreted language due to the use of intermediate code. Java architecture is also design to reduce overheads during runtime. The incorporation of multithreading enhances, the overall executions, speed of Java programs.

BASICS OF JAVA ENVIRONMENT:

Phase 1

Phase 2

Phase 3 Primary Memory

5

Editor disk

Compiler disk

disk

Class loader

Page 6: Java

www.aspgmca.blogspot.com

Phase 4 Primary Memory

Phase 5 Primary Memory

Phase 1: Java program is typed in a text editor (Notepad, Edit plus) and makes corrections if necessary. The programmer specifies that the file in the editor should be save. The program is stored on a second storage device such as a disk. Java program files are stored with .java extension filenames.

Save: c:\jdk1.2.1\bin\filename.java

Phase 2: The programmer gives the command javac filename.java to compile the program. At this stage, the Java compiler translates the Java program into byte code that is the language understood by the Java Interpreter. If the program compiles correctly, a file called filename.class is produced. This is the file containing byte codes that will interpret during the execution phase.

Phase 3: This phase is called loading. The program must place in memory before it can be executed. This is done by the class loader, which takes the .class file containing in byte code and translates it into the memory. The .class file can be loaded from a disk on your system or over a network.

Phase 4: Byte code verifier confirms that all byte codes are valid and don’t valid Java Security Instructions.

Phase 5: Java Interpreter reads byte code and translates them into a language that the computer can understand and it executes the code.

Java Development Kit: Java Development Kit is a collection of classes, Java compiler and Java virtual machine Interpreter. It also consist useful utilities for debugging, documentation, compiling and run java programs.The following are the some components of a Java Development Kit.

javac: The java compiler, converts java source code into byte codeSyntax: javac filename.java

java: The java interpreter, executes java application byte does directly from class file

Syntax: java filename jdb: The java debugger that allows to step through the program one line at a time,

set break points, and examine variablesSyntax: jdb filename

servletrunner: A simple web server to test servlets

6

Byte code verifier

Interpreter

Page 7: Java

www.aspgmca.blogspot.com

appletviewer: A java interpreter that executes java applet classes hosted by HTML

Syntax: appletviewer filename.html

Java Virtual Machine (JVM): Java provides both compiler and a software machine called JVM for each computer machine. The Java Compiler translates the Java Source Code (Java program) into an intermediate code known as byte code, which executes on special type of machine. This machine is called Java Virtual Machine and exists only inside the computer memory. The byte code is machine independent code and can run in any system.

The byte code is not a machine specific code. Java Interpreter takes the byte code and translates it into its own system machine language and runs the results.

Just In Time (JIT): The Java Virtual Machine is an interpreter that translates and runs each byte code instruction separately whenever it is needed by the computer program. In some cases it is very slow.

As an alternative, Java also provides local compiler for each system that will compile byte code file into executable code for faster running. Java calls these compilers Just In Time compilers.

Java Standard Library(JSL): The Java API (Application Programming Interface) is a collection of classes and methods grouped in the form of packages. JDK 1.2 has 58 packages, it is also known as Java Standard Library.

The important Packages in Java area) java.lang: It contains the main language support class. It contains wrappers, strings and basic features of Javab) java.util: It provides classes that support date, time, basic event processing etc.,c) java.io: It provides reading and writing data in the form of streams.d) java.awt: It provides classes for creating GUI programs.e) java.applet: It includes set of classes to support for applet programming.f) javax.swing: It provides classes for swing operation programming.

Differences between C++ and Java1. Java does not include structure and union.2. It is not possible to declare unsigned integer in Java.3. Pointers don’t exist in Java.4. Java does not have a preprocessor.5. There are no header files and delete operators.6. Java does not allow goto, sizeof and typedef.7. Java does not support the multiple inheritance.

***

7

Source code Java Compiler Byte code

Byte code Java Interpreter Machine code

Page 8: Java

www.aspgmca.blogspot.com

Java Tokens: Tokens are smallest individual units in a program. The compiler reads the source program one character at a time grouping the source program into a sequence of atomic units called Tokens. Reserved words, identifiers, constants, operators etc., are the examples of Java Tokens.

Keywords: The Keywords or Reserved words are one, which have a special and predefined meaning to the Java compiler. There are 48 reserved words currently used in Java. These words cannot be used as names for a variable, constant, class or method. Reserved words are

abstract boolean break byte case catchchar class const continue default dodouble else extends final finally floatfor goto if implements import instanceofint interface long native new packageprivate protected public return short staticstrictfp super switch synchronized this throwthrows transient try void volatile whiletrue false null

Note: const and goto are reserved for future use. Java reserved words true, false and null reserved words are used to represent the values.

Datatype : Datatypes are used to specify the type of data that a variable can attain. There are 2 types of datatypes. 1. Primitive Datatypes 2. Non-Primitive Datatypes1. Primitive Datatype: It is also called as standard, intrinsic or built-in datatypes. There are eight primitive datatypes available in Java. Those are byte, short, int, long, char, float, double and boolean. These can be classified into four groups.

Integers : byte, short, int, longFloating point numbers : float, doubleCharacters : charBoolean : boolean

Type Size Range Bits Bytes

int 32 4 -2,147,483,648 to 2,147,483,647long 64 8 -9,223,372,036,854,775,808 to

9,223,372,036,854,775,807short 16 2 -32,768 to 32,767byte 8 1 -128 to 127float 32 4 3.4 e –0.38 to 3.4 e +0.38double 64 8 1.7 e –308 to 1.7 e +308char 16 2 0 to 65535boolean 8 1 true / false

Note: 1. Java does not support have any unsigned types2. Variables of types char, byte, short, int, long, float and double are all given the value ‘0’ by default3. Variable of type boolean are given ‘false’ by default4. All primitive datatypes in Java are portable (Platform independent)

8

Page 9: Java

www.aspgmca.blogspot.com

2. Non-Primitive Datatype: These are also known as Derived Datatype or Abstract Datatype or Reference type. These are built on primitive data types.Examples: string, class, array, interface etc.,

Variable: The name given to the various elements to store the information is called an identifier or variable. The rules for variables are as follows:

Variable must be begin with a letter, a dollar ($) symbol or an underscore ( _ ) followed by a sequence of letters

Variable names must be unique There should be no space in between any two characters of an identifiers Keywords cannot be used for variable name Java is a case-sensitive, so upper and lower case letters are distinct

Declaring a Variable: All variables must be declared before they can be used. The basic form of a variable declaration is

Syntax: type identifier;Where type is represents datatype of the variable, identifier is the name of the variable.

Example: int a;More than one variable of the same type can be declared by using a comma-separated list.

Syntax: type identifier1, identifier2, ……, identifiern;Example: float x, y, z;

Initializing a Variable: Variable can also be initialized with equal sign and a value.Syntax: type identifier = value;Example: int a = 3;

Dynamic Initialization: Java allows variables to be initialized dynamically, using any expression valid at a time the variable is declared.

Example: class dyna{

public static void main(String args[]){

double a=3.0, b=4.0;double c=Math.sqrt(a*a+b*b);System.out.println(“Hypotenuse is” + c);

}}

Scope & Lift-time of a Variable:

An identifier duration also called lifetime is the period during which that identifier exist in memory. Identifier that represent local variables in a method i.e., parameters and variables declared in the method body have automatic duration. Automatic declaration are created when program control reaches their declaration they exist while the block in which they are declare is active and they are destroyed when the block in which they are declared is exceeded. We will refer to variables of automatic duration has automatic variables or local variables.

Java also has identifiers of static duration. Variables and references of static duration exist from the point at which the class that defines them is loaded into memory for execution until the program termination.

9

Page 10: Java

www.aspgmca.blogspot.com

Identifier scope is where the identifier can be a reference in a program. The scope of an identifier is class scope and block scope.

Methods and instance variable of a class have class scope. Class scope begins at the beginning left brace of the class definition and ends at the closing right brace of the class definition.

Identifiers declared inside a block have block scope. Block scope begins at the identifiers declaration and ends at the terminating right brace of the block. Local variables of the method have block scope.

Class: A class is a non-primitive datatype that contains member variables (data) and member functions (methods) that operates on the variables. A class is declared by the use of the class keyword. The general form of class definition is as follows.

Syntax: class class-name{

datatype instance-variable1;datatype instance-variable2;--datatype instance-variablen;datatype methodname1(parameter-list){// method body}--datatype methodnamem(parameter-list){// method body}

}

The data, or variables defined with in a class are called instance variables. The code is present with in methods. Collection of methods and variables defined with in a class are called members of the class.

Example: class box{double width, height, depth;double volume( ){return width*height*depth;}}

Object: Object is an instance of the class. By means of the object only, we can access the functions (methods).

main( ){box a = new box( );a.volume();

10

Page 11: Java

www.aspgmca.blogspot.com

}Comments in a Program: Three types of comment statements are available in Java. They are

i) Single line comment (//)ii) Multi line comment (/* and */)iii) Documentation comment (/** and */)

1. Single line comment: For a single line comment we use double slash (//) to begin a comment. It ends at the end of line.

Example: // Program for stack operations2. Multi line comment: For more than one line of information, we use multi line comments. Multi line comments are starts with /* and ends with */.

Example: /* Program for stack operations Designed by shabbir PBRVITS, Kavali */

3. Documentation comment: For the documentation purpose, we use documentation comments. Documentation comments are starts with /** and ends with */.

Example: /** A test for JDK@ Author S.Prabhu@ version 1.0 */

Input and Output Statements: java.lang package consists a class called ‘System’ which contains console I/O methods. If we want to take the information from the keyboard and display the information on the screen, Java uses Stream objects. The system provides three basic streams. Those are

a) System.inb) System.outc) System.err

System.in refers to the standard input stream, System.out refers to the standard output stream and System.err refers to the standard error stream.System.out class consists of two methods to print the strings and values on the screen. They are 1. print( ) 2. println( ).1. print( ): Syntax: System.out.print(list);

This statement prints the values of the variable name specified in the list of output unit.

Example: System.out.print(“hai”);System.out.print(“java”);

O/P: haijava2. println( ): Syntax: System.out.println(list);

This statement prints the values of the variable name in the list, the cursor is advanced by one line and the next statement is print in the next line.

Example: System.out.print(“hai”);System.out.print(“java”);

O/P: haijava

Note: Java has a version of the ‘+’ operator for string concatenation that enables a string and a value of another datatype.

Example: sum = 50“sum is” + sum

11

Page 12: Java

www.aspgmca.blogspot.com

Here, sum is automatically converted to a string and concatenated with the “sum is” which results in the string sum is 50

Example: “y#2=”+7O/P: y#2=7

Command Line Arguments: Java has the facility of command line arguments. Java main method consists array of string objects. When we run the program, the array will fill with the values of any arguments it was given in the command line.

Building the Java Program:Java is a text file that contains one or more class definitions. Java compiler

requires that a source file use the .java file name extension.Example: class Example

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

System.out.println("Hello");}}

The keyword ‘class’ is used to declare the new class is being defined Example is an identifier that is the name of the class Entire class definition will be between the opening curly brace ({) and the closing

curly brace (}) ‘public’ keyword is an access specifier, which allows the programmer to control

the visibility of class members The keyword ‘static’ allows main() to be called without having to instantiate a

particular instance of the class. Since, main() method is called by the Java interpreter before any objects are made

The keyword ‘void’ used to tell the compiler that main() does not return a value main() is a method called when a Java application begins String args[] declares a parameter named args, which is an array of instances of

the class string. args receives any command line arguments present when the program is executed

Now the file is saved with .java extension . Let the file name is taken as Example.java

Compiling & Running the Java Program:To compile Example.java program by the compiler javac, specify the name of the

source file on the command line asC:\> javac Example.javaHere, the Java compiler creates a file called Example.class that contain byte code

version of the program. The class file is run by the Java interpreter, called java by passing the name to command line argument as

C:\> java Example

12

Page 13: Java

www.aspgmca.blogspot.com

O/P: Hello

Example: Write a program to read two values and print the values

class ex2 {

public static void main(String[] args) {

System.out.println(args[0]);System.out.println(args[1]);

}}

Primitive datatypes are to be converted into object type by using the wrapper classes. Integer class is used as wrapper class for primitive datatype int. parseInt( ) method converts string to an int.

Example: Write a program to read two integer values and print the sum

class ex3 {

public static void main(String[] args) {int a,b,sum;a=Integer.parseInt(args[0]);b=Integer.parseInt(args[1]);sum=a+b;System.out.println("sum of a and b is"+sum);}

}

OPERATORS

Operator is a symbol that performs a specified operation between the data items. Java provides the following different types of operators.

a) Arithmetic operators: Operator Meaning

+ Addition- Subtraction* Multiplication/ Division% Modulus

Example:

class arope {

public static void main(String[] args)

13

Page 14: Java

www.aspgmca.blogspot.com

{int a,b,sum,sub,mul,div,mod;a=Integer.parseInt(args[0]);b=Integer.parseInt(args[1]);sum=a+b;sub=a-b;mul=a*b;div=a/b;mod=a%b;System.out.println("Addition="+sum);System.out.println("Subtraction="+sub);System.out.println("Multiplication="+mul);System.out.println("Division="+div);System.out.println("Remainder="+mod);

}}

b) Arithmetic Assignment Operators:Syntax: variable operator = expression

Which is equivalent tovariable = variable operator expression

Operator Example Equivalent Expression

+ = a + = 4 a = a + 4- = a - = 5 a = a – 5* = a * = 3 a = a * 3/ = a / = 8 a = a / 8% = a % = 5 a = a % 5

c) Assignment Operator: ‘=’ is an assignment operator used to assign the value to a variable.

Syntax: variable = value;Example: a = 7;

d) Increment and Decrement Operators: ‘++’ and ‘--' are Java’s increment and decrement operators. The increment operator increased its operand by one. The decrement operator decreased its operand by one.Example:

class a {

public static void main(String[] args) {int x=4;System.out.println("x++:"+ ++x); //O/P: 5int y=10;System.out.println("x++:"+ y++); //O/P: 5int p=5;

14

Page 15: Java

www.aspgmca.blogspot.com

int t=--p+3;System.out.println("t :"+t); //O/P: 7}

}e) Relational Operators: Relational Operators determines the relationship between the two operands. Operator Meaning Example

= = equal to A= =B!= Not equal to A!=B> Greater than A>B< Less than A<B>= Greater than or equal to A>=B<= Less than or equal to A<=B

f) Logical Operators: Logical operators are used to check for compound conditions, which are formed, by the combination of two or more relational expressions. Java provides the following logical operators and these are follows truth tables and produce Boolean values.

Operators: Logical AND &&Logical OR ||Logical NOT !

Truth table for Logical AND(&&):Op1 Op2 Op1 && Op2T T TT F FF T FF F F

Truth table for Logical OR(||):Op1 Op2 Op1 && Op2T T TT F TF T TF F F

Truth table for Logical NOT(!):Op1 !Op1T FF T

g) Conditional Operator: Java has a decision operator called conditional operator. “? :” are conditional operators. These operators are also called ternary operators.

Syntax: testconditon ? expression1 : expression2Here, if the testcondition is true, then expression1 is evaluated otherwise, expression2 is evaluated.

Example: max = (a>b) ? a : b;

h) Bit-wise Operators: The following bit-wise operators are provided by Java. These operators act upon the individual bits on their operands.

Operator Meaning

15

Page 16: Java

www.aspgmca.blogspot.com

~ Bit-wise unary NOT& Bit-wise AND| Bit-wise OR^ Bit-wise exclusive OR>> Shift right<< Shift left|= Bit-wise OR Assignment^= Bit-wise exclusive OR Assignment>>= Shift right Assignment<<= Shift left Assignment

These operators act upon the individual bits on their operands. Bit-wise Logical Operators (&, |, ^ and ~) follows the following truth tables

Op1 Op2 Op1|Op2 Op1&Op2 Op1^Op2 ~Op10 0 0 0 0 11 0 1 0 1 00 1 1 0 1 11 1 1 1 0 0

javax.swing: It is package contains an important class called JOptionPane class. This class is used to display dialog boxes. It provides two important predefined methods showInputDialog and showMessageDialog called static methods. Such methods are always used their class name followed by a dot operator.

ShowInputDialog: showInputDialog is a method of class JOptionPane. It is a static method and the general format is as

Syntax: JOptionPane.showInputDialog(argument);The argument indicates to the user what to do in the text field.

Example: JOptionPane.showInputDialog(“Enter a value”); When we perform this operation the input dialog box is available as

The users types characters in the text field then clicks the ok button, it returns string to the program.

showMessageDialog: showMessageDialog is method of class JOptionPane. It is a static method. The general format of showMessageDialog is in two ways.

Syntax1: JOptionPane.showMessageDialog(null,argument1);

16

Input

Enter a value?

OK cancel

Page 17: Java

www.aspgmca.blogspot.com

The first argument must be null keyword. The second argument is the string that is required to display. The title bar of message dialog contains the string “Message” to indicate that the dialog is presenting a message to the user. The default icon is INFORMATION_MESSAGE.

Example: JOptionPane.showMessageDialog(null,”value=”+x);

Syntax2: JOptionPane.showMessageDialog(null,argument2,argument3,argument4)

The first argument must be null keyword. The second argument is the message to display. The third argument is the string to display in the title bar of the dialog. The fourth argument is a value indicating the type of message dialog to display.

For argument4 some of the message dialogs areJOptionPane.PLAN_MESSAGEJOptionPane.ERROR_MESSAGEJOptionPane.INFORMATION_MESSAGEJOptionPane.WARNING_MESSAGEJOptionPane.QUESTION_MESSAGE

Example:JOptionPane.showMessageDialog(null,”value=”+x,”output”, JOptionPane.ERROR_MESSAGE)

import statement: import statement is similar to the #include statement in C. Using the import statements, we can access to classes that are part of other packages.

Example: import javax.swing.JOptionPane;This statement instructs that the interpreter to load the JOptionPane class contained in the javax.swing package.

Example:import javax.swing.JOptionPane;class ch {

public static void main(String[] args) {String sn1;int x;

17

Message

Value=10

iOK

output

Value=10

OK

Page 18: Java

www.aspgmca.blogspot.com

sn1=JOptionPane.showInputDialog("Enter x value");x=Integer.parseInt(sn1);

JOptionPane.showMessageDialog(null,"value="+x,"output",JOptionPane.ERROR_MESSAGE); }}Control Statements

Depending on the results of computations the flow of control may require to jump from one part of the program to another part, such jumps are called Control statements. The control statements are of two categories.

1. Decision (Conditional) control statements2. Loop control statements3. Jump control statements

1. Decision (Condition) Control statements: In decision control statements, depending on the result of evaluation of an expression a statement or block of statements are executed. The condition involves boolean values either true or false. Java provides the following decision control statements.

a) if statementb) if-else statementc) nested if-else statementd) switch

a) if statement: The if statement conditionally process the statements when the specified test condition is true.

Syntax: if(condition){

// Block of statements}

Flowchart:

Here, if the condition is true then block of statements are executed. Otherwise, block of statements are not executed and the control is passed to the next statements available after the block statements.

The statements are either simple or compound statements. If the statements are single statement then they ended with a semicolon. If the statements are compound statements then they are placed in between the left and right curly braces.

18

Condition

Block of statements

Next statements

Page 19: Java

www.aspgmca.blogspot.com

Example:

class if1 {

public static void main(String[] args) {

int a=6,b=4;if(a>b)System.out.println("a is big");

}}

b) if-else statement: In if-else statement general form is asSyntax: if (condition)

{//true block statements

}else{

//false block statements}

Flowchart:

Here, first the test condition is evaluated. If the condition is true, then true block statements are executed otherwise false block statements are executed.

The statements are either simple or compound statements. If the statements are single statement then they ended with a semicolon. If the statements are compound statements then they are placed in between the left and right curly braces.

Example:

class if2{

public static void main(String[] args)

19

Condition

true block statements

Next statements

false block statements

Page 20: Java

www.aspgmca.blogspot.com

{int a=2,b=4;if(a>b)System.out.println("a is big");elseSystem.out.println("b is big");

}}

c) Nested if-else statement: The if-else statement is placed within another if-else statement such methods are called nested if-else statement.

Syntax: if (condition1){else if(condition2){

//block1 statements}else{

//block2 statements}}else{

//block3 statements}

Lab Program1: Write a program to print the roots of a quadratic equation ax2+bx+c=0

import javax.swing.JOptionPane;import java.text.DecimalFormat;class lab1 {

public static void main(String[] args) {double a,b,c,dis,root1,root2,p;DecimalFormat d=new DecimalFormat("0.00");a=Double.parseDouble(JOptionPane.showInputDialog("Enter a value"));b=Double.parseDouble(JOptionPane.showInputDialog("Enter b value"));c=Double.parseDouble(JOptionPane.showInputDialog("Enter c value"));dis=(b*b-4*a*c);if(dis==0){System.out.println("Roots are real and equal");root1=-b/(2*a);System.out.println("Root1="+(d.format(root1)));System.out.println("Root2="+(d.format(root1)));}else if(dis>0){

20

Page 21: Java

www.aspgmca.blogspot.com

System.out.println("Roots are real and different");p=Math.sqrt(dis);root1=(-b+p)/(2*a);root2=(-b-p)/(2*a);System.out.println("Root1="+(d.format(root1)));System.out.println("Root2="+(d.format(root2)));}elseSystem.out.println("Roots are imaginary");}

}

d) switch statement: The switch statement allows section among the multiple section of a code depending on the value of an expression. The objective is to check several possible constant values for an expression.

Syntax: switch (expression){case value1: block1 statements

break;case value2: block2 statements

break;..default: default block statements}

Flowchart:

First, the switch statement evaluates the expression and check whether the evaluated value is coinciding with any case value or not. If any value is coinciding, it

21

expression

block1 statements

Block2 statements

default block1statements

Next statements

Page 22: Java

www.aspgmca.blogspot.com

executes that particular block of statements until the break statement is reached. After executing the statements the control is transferred out of the statements that are available after the switch statement.

If any value is not coinciding with the case value then it executes default block statements. Default block is an optional.Note: case values are either integer constant or character constant.

Example:

class if4 {

public static void main(String[] args) {

int rno;rno=Integer.parseInt(args[0]);switch(rno){case 1:System.out.println("RED");

break;case 2:System.out.println("GREEN");

break;case 3:System.out.println("BLUE");

break;default:System.out.println("Select 1,2 or 3 only");}

}}

Example:

class if5{

public static void main(String[] args) {

char rno='t';switch(rno){case 'a':System.out.println("RED");

break;case 'b':System.out.println("GREEN");

break;case 'c':System.out.println("BLUE");

break;default:System.out.println("Select 1,2 or 3 only");}

}}

2. Loop Control Statements: A Loop statement allows to run a statement or block of statements repeatedly for a certain number of times. The repetition is continues while the

22

Page 23: Java

www.aspgmca.blogspot.com

condition is true. When the condition becomes false, then loop ends and control passed to the next statements following the loop. Repetitive execution of statements is called looping. Java provides three types of loop control statements.

a) while statementb) do-while statementc) for statement

a) while statement: while loop executes the statements repeatedly as long as a given condition becomes true. When the condition becomes false the control immediately pass to the next statements available after the loop statements.

Syntax: while (condition){

//statements}

Flowchart:

The statements are either simple or compound statements. If the statements are single statement then they ended with a semicolon. If the statements are compound statements then they are placed in between the left and right curly braces.

Lab Program2: Write a program to print the first n fibonacci sequence numbers

class lab2 {

public static void main(String[] args) {

int f0=1,f1=1,i=3,f2,n;n=Integer.parseInt(args[0]);System.out.println(f0);System.out.println(f1);while(i<=n){f2=f0+f1;System.out.println(f2);f0=f1;f1=f2;i++;}

}}

23

condition

statements Next statements

Page 24: Java

www.aspgmca.blogspot.com

b) do-while statement: In do-while loop statements, first the control executes the statements then it checks for the condition. The statements are executed repeatedly as long as a given condition becomes true. If the condition becomes false then the control comes out from the loop and executes the statements available after the loop statements.

Syntax: do{

//statements} while (condition);

Flowchart:

The statements are either simple or compound statements. If the statements are single statement then they ended with a semicolon. If the statements are compound statements then they are placed in between the left and right curly braces. The main difference between while and do-while statement is do-while statement executes the statements at least once even the condition becomes false.

Example: Write a program to check whether a given number is Armstrong number (153) or not

class labd {

public static void main(String[] args) {

int x,n,temp,sum=0;n=Integer.parseInt(args[0]);temp=n;do{x=n%10;sum=sum+x*x*x;n=n/10;}while(n>0);if(sum==temp)System.out.println("Number is armstrong");elseSystem.out.println("Number is not armstrong");

24

statements

condition

Next statements

Page 25: Java

www.aspgmca.blogspot.com

}}

c) for statement: The for statement also repeat a statement or compound statements for a specified number of times. The general form of for statement is as

Syntax: for (initialization;condition;increment/decrement){

//statements}

Flowchart:

Initialization is the start with the assigning value to the variable and it executes only once at the start of the loop. Then the control checks for the test condition.

In condition section, if the condition becomes true then the control pass to the block of statements and executed. After executing the statements the control pass to the increment/decrement section. After incrementing/decrementing the variable again the control is passed to the condition section. This procedure is repeated as long as the condition becomes true.

If the condition becomes false, the control passes out of the loop statements.

Note: 1. Multiple initializations are possible by comma operator.Ex: for( i = 0,j = 5; i<n; i++, j--)

2. At the place of condition section, it is also possible to use relational expressions

Example:

Lab Program3: To print all prime numbers between a given range

import javax.swing.JOptionPane;class lab3 {

public static void main(String[] args) {

int n,j,x,count;//n=Integer.parseInt(args[0]);

n=Integer.parseInt(JOptionPane.showInputDialog("Enter range"));for(int i=1;i<=n;i++)

25

initialization

condition

statements Next statements

Page 26: Java

www.aspgmca.blogspot.com

{x=i;count=0;j=2;while(j<x){if(x%j==0){count=1;break;}j++;}if(count==0)System.out.println(x+"is prime");}}

}

3. Jump Control Statements: Java provides the following Jump Control statements.a) break statementb) continue statementc) return statementd) exit statement

a) break statement: break statement executed in a while, do-while, for or switch statements causes immediate exist from that structure. It can be used in two ways as unlabeled break and labeled break statement.

Unlabeled break statement:Syntax: break;Example: for(int k=1;k<=10;k++)

{if(k= =5)break;System.out.println(k);}

O/P: 1 2 3 4

Labeled break statement: To break out of nested structures, we can use the labeled break statements. This statement, when executed in a while, do-while and for statements causes immediate exit from that structure and any number of enclosing repetition structures. Program execution resumes with the first statement after the enclosing labeled compound statement.

Example:

class ex {

public static void main(String[] args) {

stop:

26

Page 27: Java

www.aspgmca.blogspot.com

{for(int row=1;row<=10;row++){for(int col=1;col<=5;col++){if(row==3)break stop;System.out.print("* ");}.out.println("\n");}}

}}

O/P: * * * * ** * * * *

b) continue statement: continue statement executed in a while, do-while or for statements skip the remaining statements in the body of that structure and proceeds with the next iteration of the loop. It can be used in two ways as unlabeled continue and labeled continue statement.

Unlabeled continue statement:Syntax: continue;Example: for(int k=1;k<=10;k++)

{if(k= =5)continue;System.out.println(k);}

O/P: 1 2 3 4 6 7 8 9 10

Labeled continue statement: The labeled continue statement when executed in a repetition structure skips the remaining statements in that structure body and any number of enclosing repetition on structure and proceeds with the next iteration of an enclosed labeled repetition.

Example:

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

stop:for(int row=1;row<=4;row++){for(int col=1;col<=3;col++){if(col==2)continue stop;System.out.print(col);

27

Page 28: Java

www.aspgmca.blogspot.com

}System.out.println("\n");}

}}

O/P: 1111

c) return statement: The return statement is used to explicitly return from a method. This causes program control to transfer back to the caller of the method. The return statement immediately terminates the method in which it executes.

Syntax: return;

d) exit statement: The method exit( ) is defined in System package. The purpose of exit is to terminate the program with a specific exit code.

Syntax: System.exit(exit_code);The program finish normally by placing exit_code as ‘0’ other value means error.

Example: System.exit(0);

ArraysAn Array is a group of contiguous or related data items that share a common name. A particular value is indicated by writing a number called ‘index number’ or ‘subscript’ in square bracket after the array name. Arrays are classified into different types. They are

1. One-Dimensional Array2. Two-Dimensional Array3. Multi-Dimensional Array

One-Dimensional Array: One-Dimensional Array is a list of homogenious items can be given one variable name using only one subscript. Individual value of an array is called an element. Like an ordinary variable, arrays must be declared and created in the computer memory before they are used. Creation of an array contains two sections. They are 1. Declaration of the array 2. Creating memory locations.

Syntax: type arrayname[ ]; // declarationarrayname = new type[size]; // allocation of memory

(or)type arrayname[ ]=new type[size];

Where,type defines the datatype of the variables stored in the arrayarrayname defines the name of the arraynew operator is used to allocate dynamic memory in the computer for the arraysize defines the number of memory location of the array

Example: int number[];number = new int[5];

It can also be initialize arrays automatically when they are declared. The syntax is as

Syntax: type arrayname[]={list of values};

28

Page 29: Java

www.aspgmca.blogspot.com

Where, list of values contains number of values separated by commas and surrounded by curly braces

Example: type number[]={35,40,56,23};

In Java, all arrays store the allocated size in a variable named length. We can access the length of the array using the syntax

Syntax: arrayname.length;Example 1: Write a program to read 5 numbers and print the sum of it.

class arr1{

public static void main(String[] args) {

int sum=0;int no[]=new int[10];for(int i=0;i<5;i++){no[i]=Integer.parseInt(args[i]);sum=sum+no[i];}System.out.println("Total="+sum);

}}

Example 2: Write a program to sort the list of values in ascending order

class arr1{

public static void main(String[] args) {

int temp;int no[]={34,78,23,11,99};for(int i=0;i<no.length-1;i++){for(int j=i+1;j<no.length;j++){if(no[i]>no[j]){temp=no[i];no[i]=no[j];no[j]=temp;}}}for(int i=0;i<no.length;i++)System.out.println(no[i]);

}}

29

Page 30: Java

www.aspgmca.blogspot.com

Two-Dimensional Array: A Two-Dimensional Array is a collection of homogeneous data items that share a common name using two subscripts. It stores table of data. This representation is very useful for matrix representations as first subscript represents the number of rows and second subscript represents the number of columns.

Syntax: type arrayname[][]; // declarationarrayname = new type[size1][size2]; // allocation of memory

(or)type arrayname[ ][]=new type[size1][size2];

Where,type defines the datatype of the variables stored in the arrayarrayname defines the name of the arraynew operator is used to allocate dynamic memory in the computer for the arraysize1 defines the number of rows of memory location of the arraysize2 defines the number of columns of memory location of the array

Example: int number[][];number = new int[5][6];

It can also be initialize arrays automatically when they are declared. The syntax is as

Syntax: type arrayname[][]={list of values};Or

type arrayname[][]={{row1 values}, {row2 values}, .. }

Lab Program 6: Java program to multiply two matrices

import javax.swing.JOptionPane;class arr2 {

public static void main(String[] args) {int m,n,p,q,i,j,k;int a[][]=new int [10][10];int b[][]=new int [10][10];int c[][]=new int [10][10];m=Integer.parseInt(JOptionPane.showInputDialog("Enter rows of Matrix

A"));n=Integer.parseInt(JOptionPane.showInputDialog("Enter columns of

Matrix A"));p=Integer.parseInt(JOptionPane.showInputDialog("Enter rows of Matrix

B"));q=Integer.parseInt(JOptionPane.showInputDialog("Enter columns of

Matrix B"));if(n==p){for(i=0;i<m;i++){

30

Page 31: Java

www.aspgmca.blogspot.com

for(j=0;j<n;j++)a[i][j]=Integer.parseInt(JOptionPane.showInputDialog("Enter a["+i+"]

["+j+"]:"));}for(i=0;i<p;i++){for(j=0;j<q;j++)b[i][j]=Integer.parseInt(JOptionPane.showInputDialog("Enter b["+i+"]

["+j+"]:"));}for(i=0;i<m;i++){for(j=0;j<q;j++){c[i][j]=0;for(k=0;k<n;k++)c[i][j]=c[i][j]+a[i][k]*b[k][j];}}for(i=0;i<m;i++){System.out.println();for(j=0;j<q;j++)System.out.print(" "+c[i][j]);}}else{JOptionPane.showMessageDialog(null,"Multiplication not possible");}}

}

Multi-Dimensional Array: Multi-Dimensional Array is a list of values shared by a common name using multi subscripts. If the array contains three subscripts then the array is called as Three-Dimensional array and so on.

Syntax: type arrayname[][]…[]=new int[size1][size2]…[sizen];Example: type number[][][]=new int[4][5][6];

Type conversion and Casting:

Java permits mixing of constants and variables of different types, but during execution it follows type conversions. In Java, type casting can be done in two ways. They are

1. Implicit Type Casting 2. Explicit Type Casting1. Implicit Type Casting: In an expression, if the operands are of different types the lower type is automatically converted to the higher type before the operation preceeds by the Java Interpreter. The result is of the higher type. Such type of casting is called

31

Page 32: Java

www.aspgmca.blogspot.com

Implicit Type Casting. In Implicit Type Casting there is no loss of data. The following are some of implicit type castings with no loss of data

from to

byte short, char, int, long, float, doubleshort char, int, long, float, doublechar int, long, float, doubleint long, float, doublelong float, doublefloat double

2. Explicit Type Casting: If we want to force to convert the operands of an expression from one type to another type depending on user choice, such type of casting is called Explicit Type Casting. In Explicit Type Casting there is a chance of data loss when we convert the operands from higher type to lower type. The process of converting the value is known as Casting a value. The general form of casting is as

Syntax: (datatype) expression;Example: x = (int) 7.5;

Note: The final result of an expression is converted to the type of the variable before assigning to the left hand side variable. In such case following chances are introduced.

float to int causes truncation of the fractional part double to float causes rounding of digits long to int causes dropping of the excess of higher order bits

32

Page 33: Java

www.aspgmca.blogspot.com

***

Unit – II

Class: A class is a non-primitive datatype that contains member variables (data) and member functions (methods) that operates on the variables. A class is declared by the use of the class keyword. The general form of class definition is as follows.

Syntax: class class-name{

datatype instance-variable1;datatype instance-variable2;--datatype instance-variablen;datatype methodname1(parameter-list){// method body}--datatype methodnamem(parameter-list){// method body}

}

The data, or variables defined with in a class are called instance variables. The code is present with in methods. Collection of methods and variables defined with in a class are called members of the class.

Example: class box{double width, height, depth;double volume( ){return width*height*depth;}}

33

Page 34: Java

www.aspgmca.blogspot.com

Creating Objects: An Object in Java is a block of memory that contains space to store all the instance variables. Creating an object of a class is a two-step process.

1. Declare a variable of the class type. At this stage, the variable refers to an object only.

2. Assigning an actual, physical copy of the object and assign it to that variable by means of ‘new’ operator. The new operator dynamically allocates memory for an object and returns a reference to that object.

Example: Rectangle rect1; // referencerect1 = new Rectangle(); // instantiate

(or)Rectangle rect1 = new Rectangle();

The first statement declares a variable to hold the object reference.

rect1

The second statement assigns the object reference and allocates memory

rect1

Note: Each object contains its own instance variables of its class. This means that any changes to the variables of one object have no effect on the variables of another. But the function name is name for both objects.

It is also possible to create two or more references to the same object.

Example: Rectangle r1 = new Rectangle( );Rectangle r2 = r1;

r1

r2

Methods: Methods allows the programmer to modularize a program. All variables declared in method definition are local variables and method parameters are also local variables. All methods must define inside a class definition. The general form of a method is as

Syntax: type method-name (parameter-list){

// body of the method}

where,

34

null

Rectangle object

Rectangle object

Page 35: Java

www.aspgmca.blogspot.com

type specifies the type of data returned by the method. If the method does not return any value, its return type must be void

The method-name is a valid identifier parameter-list is a sequence of type and identifier pairs separated by commas.

The variable receives the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameter list will be empty

body of the method describes the operations to be performed on the data

Example: int sum(int a, int b){

int c;c=a+b;return c;

}Accessing class members: All variables must be assigned values before they are used in our program. All class members are accessed by means of “dot” operator.The general format of accessing instance variable of the class by dot operator is as

Syntax: objectname.variablename;Where, objectname is name of the object, variablename is the name of the instance variable.

Example: rect1.length=15;rect1.width=10;

rect1.lengthrect1

rect1.width

The general format of accessing instance methods of the class by dot operator is asSyntax: objectname.methodname(parameter-list);

Where, objectname is name of the object, methodname is the name of the instance method that calls with the object and paramerter-list is a list of actual values separated by commas.

Example: void getdata(int x, int y){

length=x;width=y;

}

rect1.getdata(10,20);

// Write a program to calculate the area of a rectangle.

class Rectangle {

int length1,width1;void getdata(int x,int y){

length1=x;width1=y;

35

15

10

Page 36: Java

www.aspgmca.blogspot.com

}int calarea(){

int area=length1*width1;return area;

}}

class prg{

public static void main(String[] args) {

int a,b;Rectangle rect1=new Rectangle();Rectangle rect2=new Rectangle();rect1.length1=15;rect1.width1=4;a=rect1.length1*rect1.width1;System.out.println("Area of Rectangle1="+a);rect2.getdata(2,3);b=rect2.calarea();System.out.println("Area of Rectangle2="+b);

}}

Method Overloading: In Java it is possible to define two or more methods within the same class that share the same name as long as these methods have different sets of parameters (Based on the number of parameters, the types of the parameters and the order of the parameters). Then the methods are said to be overloaded, and the process is referred as Method Overloading.

When the overload method is called the Java compiler selects the proper method by examine the number, type and order of the arguments in the call. Method Overloading is commonly used to create several methods with same name that perform fast accessing.Note: Two methods differ in only by return type will result in a syntax error.

Example1:

class overload {

int square(int x){return x*x;}double square(double x){return x*x;}

}class check{

public static void main(String[] args)

36

Page 37: Java

www.aspgmca.blogspot.com

{overload r1=new overload();int k=r1.square(3);double p=r1.square(4.0);System.out.println("k value="+k);System.out.println("p value="+p);

}}

Example2:

class overload1 {

int sum(int x){return x+x;}int sum(int x,int y,int z){return x+y+z;}

}class check1{

public static void main(String[] args) {

overload1 r1=new overload1();int k=r1.sum(3,5,7);System.out.println("k value="+k);

}}

Constructors: A constructor is a special method of class, which is invoked automatically, whenever an object of a class is created. It has the same name as its class and resides similar to a method. A constructor has the following characteristics.

It doesn’t have any return type not even void The constructor can be declared as public It can be overloaded It is normally used to initialize the member of the object

Different types of Constructors:1) Default Constructor: A constructor that accepts no parameters is called the default constructor. If no constructors are defined for a class, the Java system automatically generates the default constructor.

Example:

class Time1{

int hour,min,sec;

37

Page 38: Java

www.aspgmca.blogspot.com

public Time1(){hour=10;min=45;sec=23;}void printdata(){System.out.println(hour+"hours:"+min+"minutes:"+sec+"seconds");}

}class const1{

public static void main(String[] args) {

Time1 t=new Time1();t.printdata();

}}

O/P: 10hours:45minutes:23seconds

2) Parameterized Constructor: A constructor that takes arguments as parameters is called parameterized constructor. If any constructors are defined by a class with the parameters, Java will not create a default constructor for the class.

Example:

class Time1{

int hour,min,sec;public Time1(int h,int m,int s){hour=h;min=m;sec=s;}void printdata(){System.out.println(hour+"hours:"+min+"minutes:"+sec+"seconds");}

}class const2{

public static void main(String[] args) {

Time1 t=new Time1(10,9,4);t.printdata();

}}

38

Page 39: Java

www.aspgmca.blogspot.com

O/P: 10hours:9minutes:4seconds

Constructor Overloading: An interesting feature of the constructor is that a class can have multiple constructors. This is called Constructor Overloading. All the constructors have the same name as corresponding to the class name that they are differ only interms of their signature as number of arguments or datatypes or order.

Example:

class Time1{

int hour,min,sec;public Time1(){hour=0;min=0;sec=0;}public Time1(int h){hour=h;min=0;sec=0;}public Time1(int h, int m){hour=h;min=m;sec=0;}public Time1(int h,int m,int s){hour=h;min=m;sec=s;}void printdata(){System.out.println(hour+"hours:"+min+"minute:"+sec+"sec");}

}class const3{

public static void main(String[] args) {

Time1 t=new Time1();t.printdata();Time1 t1=new Time1(9);t1.printdata();Time1 t2=new Time1(7,8);t2.printdata();

39

Page 40: Java

www.aspgmca.blogspot.com

Time1 t3=new Time1(10,9,4);t3.printdata();

}}

Static Class Members: Generally each class contains instance variables and instance methods. Every time the class is instantiated, a new copy of each of them is created. They are accessed using the objects with the dot operator.

If we define a member that is common to all the objects and accessed without using a particular object i.e., the member belong to the class as a whole rather than the objects created from the class. Such facility can be possible by using “static” keyword.The members declared with the static keyword are called static members.

Example: static int x;static int show(int x,int y);

The important points about static class members are Static members can be accessible without the help of objects. It can be accessible

by using the syntax: classname.members; A static method can access only static members (data + method) A static block will be executed first (before main). Static variables are initialized

first A static member data store the same memory for all objects Static method cannot be referred to ‘this’ or ‘super’ in anyway.

Example1:

class static1 {

static int c=0;void increment(){c++;}void display(){System.out.println("Value="+c);}

}class Mstatic{

public static void main(String[] args) {static1 s=new static1();static1 s1=new static1();static1 s2=new static1();s.increment();s1.increment();

40

Page 41: Java

www.aspgmca.blogspot.com

s2.increment();s.display();s1.display();s2.display();}

}

O/P: value=3value=3value=3

without static keyword

s1 s2 s3

with static keyword

s1 s2 s3

Example2:

class static1 {

static int a=10;static int b=34;static void call(){System.out.println("Value1="+a);}

}class Mstatic1{

public static void main(String[] args) {static1.call();System.out.println("Value2="+static1.b);}

}

O/P: Value1=10Value2=34

Example3:

41

0 0 0

0

Page 42: Java

www.aspgmca.blogspot.com

class static2 {

static int a=10,b;static void method(int x){System.out.println("x="+x);System.out.println("a="+a);System.out.println("b="+b);}static{System.out.println("static block");b=a*4;}

}class Mstatic2{

public static void main(String[] args) {static2.method(35);}

}

O/P: static blockx=35a=10b=40

Access Modifiers/Control:

Java provides four types of Access Modifiers. They are public, protected, default and private.

Access Location public protected friendly or default privateSame class Y Y Y YSub class in same package Y Y Y NOther classes in same package Y Y Y YSub classes in other packages Y Y N NNon-sub classes in other packages

Y N N N

For good programming technique place member data as private and member functions as public.

Example:

class modi {

42

Page 43: Java

www.aspgmca.blogspot.com

private int k=6;void display(){System.out.println("k in display="+k);}

}class ex{

public static void main(String[] args) {modi obj=new modi();obj.display();//System.out.println("k in main="+obj.k);//this statement provides error since private variable//can not be possible to access by other class}

}

this keyword: Java define “this” keyword, that can be used inside any method to refer the current object. “this” is always a reference to the object on which method was invoked. “this” reference is implicitly used to refer to both the instance variables and methods of current object.

Example 1:

class Box{

int len,dep,hei;Box(int len,int dep, int hei){this.len=len;this.dep=dep;this.hei=hei;}int volume(){return len*dep*hei;}

}class this1{

public static void main(String[] args) {

Box obj=new Box(1,2,3);int x=obj.volume();System.out.println("volume="+x);

}}

O/P: volume=6

43

Page 44: Java

www.aspgmca.blogspot.com

“this” reference is also used explicitly refer to the instance variables.

Example 2:

class Box{

int len=10;void method(){int len=40;System.out.println("local value="+len);System.out.println("Instance value="+this.len);}

}class this2{

public static void main(String[] args) {

Box obj=new Box();obj.method();

}}

O/P: local value=40Instance value=10

Argument Passing: Arguments passed to a sub-routine (method) is falls into two categories. 1. Call by value

2. Call by reference

1. Call by Value: Call by value copies the value of an argument into the formal parameter of the sub-routine. Therefore, if changes made to the parameter of the sub-routine have no effect on the argument used to call it.

Example:

class Test {

void meth(int i, int j){i*=2;j/=2;}

}class cbv{

public static void main(String[] args)

44

Page 45: Java

www.aspgmca.blogspot.com

{Test obj=new Test();int a=4,b=7;System.out.println("Before calling a="+a+" b="+b);obj.meth(a,b);System.out.println("After calling a="+a+" b="+b);}

}

O/P: Before calling a=4 b=7After calling a=4 b=7

2. Call by Reference: In this method, a reference to an argument is passed to the parameter. Inside the parameter, this reference is used to access the actual argument specified in the call. Therefore, any changes made to the parameter will effect the argument used to call it. This one is also referred as passing an object as parameter to a method.

Example:

class Test {

int a,b;Test(int i,int j){a=i;b=j;}void meth(Test ox){ox.a*=2;ox.b/=2;}

}class cbr{

public static void main(String[] args) {Test obj=new Test(4,5);System.out.println("Before calling a="+obj.a+" b="+obj.b);obj.meth(obj);System.out.println("After calling a="+obj.a+" b="+obj.b);}

}

O/P: Before calling a=4 b=5After calling a=8 b=2

45

Page 46: Java

www.aspgmca.blogspot.com

Recursion: A recursive method is a method that calls itself either directly or indirectly through another method. A method call itself is termed as Recursion.Example: fact(n) = 1 ; if n=0

n*fact(n-1) ; n 1

// Write a program to print the factorial of a given number using recursion

class a {

double fact(double x){if(x==0)return 1;elsereturn x*fact(x-1);}

}class recur{

public static void main(String[] args) {a obj=new a();int p=Integer.parseInt(args[0]);double t=obj.fact(p);System.out.println("facatorial="+t);}

}

// Write a program to print the first n Fibonacci sequence numbers using recursion (Lab Program: 2)

class a {

int f(int x){if(x==0||x==1)return x;elsereturn (f(x-1)+f(x-2));}

}class fibo{

public static void main(String[] args) {a obj=new a();int p=Integer.parseInt(args[0]);for(int i=1;i<=p;i++){int t=obj.f(i);System.out.println(" "+t);

46

Page 47: Java

www.aspgmca.blogspot.com

}}

}

// Write a program to print the sum of ‘n’ numbers using the recursive formulasum (n) = 0 ; if n = 0

n + sum(n-1) ; if n 1

Random Number Generation: The elements of change can be introduced through the random method.Consider the following statement

double value = Math.random( );The random( ) method generates a double value from 0.0 to 1.0(not included). The range of values produced directly by random is often different than what is needed in a specific application.

Example: A program that stimulates rolling six-sided die would required random integers in the range (1,6)

The general formula for this type of problems using random method is a+(int)(Math.random( )*b). Where ‘a’ is a shifting value that is equal to the fist number in the range of integers and ‘b’ is the scaling factor that is equal to the width of range of the integer.

class random {

public static void main(String[] args) {

for(int i=1;i<=20;i++){int s=1+(int)(Math.random()*6);System.out.print(s);if(i%5==0)System.out.print("\n");}

}}

Recursion Vs Iteration:

Recursion Iteration

1. Recursion uses a selection structure like 1. Iteration uses a repetitive structure if, if-else etc., like while, do-while etc.,2. Recursion terminates when base case is 2. Iteration terminates when the loop recognized Continuation condition fails3. It can occur infinitely 3. It can occur infinitely4. Extra memory is required 4. Extra memory is not required

47

Page 48: Java

www.aspgmca.blogspot.com

Nested Class and Inner Classes It is possible to define a class within another class such classes are known as nested classes. A nested class has access to all of the variables and methods of its outer class. But the outer class doesn’t access the variables and methods of nested class. Since the scope of a nested class is bounded by the scope of its enclosing class.

There are two types of nested classes: static and non-static A static nested class is a class started with ‘static’ modifier. Due to the static it must access the members of its enclosing class through an object. Direct access cannot be possible.A non-static class is a class as ordinary representation of class. The most important type of the non-static class is “Inner class”. The inner class has access to all of the variables and methods of its outer class. Thus, inner class scope is fully within the scope of its outer class.

Example:

class outer{

int out_x=34;void test(){inner in=new inner();in.display();}class inner{void display(){System.out.println("value="+out_x);}}

}class test{

public static void main(String[] args) {outer y=new outer();y.test();}

}

Strings

A string is a collection of characters. Java implements strings as object type of String. Java provides three types of string handling classes.

1. String Class2. StringBuffer Class3. StringTokenizer Class

48

Page 49: Java

www.aspgmca.blogspot.com

String and StringBuffer classes are defined in java.lang pacakage. StringTokenizer are defined in java.util package.

1. String Class:A string is an object of class String. String literals or constants written as a sequence of characters in double quotes. A string may be assigned in declaration to string reference as

String color = ”blue”It initializes string reference color to refer the anonymous string object blue.Note: 1. Once we create a string object, we cannot change the contents of string instance.

2. A variable declared as a string reference can be changed at any time.

String Constructors: String class provides several types of constructors. They area) String( ): It creates an empty string with no characters in it.b) String(String): It takes one String as a parameter.c) String(StringBuffer): Allocates a new string that contains the sequence of

characters currently contained in the string buffer argument.d) String(byte[] bytes): Construct a new String by converting the specified array of

bytes using the platform's default character encoding.e) String(bytes byte[], int startindex, int numberofcharacters): Allocates new string

positioned with the startindex by counting the number of charactes.f) String(char chars[]): Creates a string initialized by an array of characters.g) String(char chars[], int startindex, int numberofcharacters): Creates a string

initialized by an array of characters with the startindex by counting the number of charactes.

Methods:

1. int length( ): It returns the number of characters in a given string.Example: String s1=new String(“hello”);

System.out.println(s1.length());

class len {

public static void main(String[] args) {String s1=new String("hello");System.out.println(s1.length());}

}

2. char charAt(int where): It returns the character at the specified location. “where” must be a nonnegative specified location within the string. The first element of a string is considered to be at position “zero”.Example:

class pos {

public static void main(String[] args) {

49

Page 50: Java

www.aspgmca.blogspot.com

String s1=new String("hello java");char c=s1.charAt(7);System.out.println("character="+c);}

}

3. void getChars(int sourcestart, int sourceend, char target[], int targetstart): It extracts more than one character at a time and copy the characters of the string into a character array.

The first argument is the starting index from which characters are copied in the string. The second argument is the index that is one part of the last character to be copied from the string. The third argument is the array into which the characters are copied. The last argument is the starting index where the copied characters are placed in the character array.

Example:

class get{

public static void main(String[] args) {String s1="java programming language";char c[]=new char[10];s1.getChars(3,8,c,0);for(int i=0;i<(8-3);i++)System.out.print(c[i]);}

} O/P: a prog

4. boolean equals( ): It compares the two strings and returns true if the strings contain the same characters in the same order, and false otherwise. The comparison is case-sensitive.

Syntax: boolean equals(Object string);

Example:

class equal {

public static void main(String[] args) {

String s1=new String("india");String s2=s1;if(s1.equals(s2))System.out.println("Strings are Equal");elseSystem.out.println("Strings are not Equal");

}}

50

Page 51: Java

www.aspgmca.blogspot.com

5. boolean equalsIgnoreCase( ): It compares the two strings and returns true if the strings contain the same characters in the same order, and false otherwise by ignoring the case characters.

Syntax: boolean equalsIgnoreCase(String str);

Example:

class equall{

public static void main(String[] args) {

String s1=new String("india");String s2=new String(“InDia”);if(s1.equalsIgnoreCase(s2))System.out.println("Strings are Equal");elseSystem.out.println("Strings are not Equal");

}}

6. int compareTo(String str ): It returns ‘0’ if the two strings are equal. ‘Negative number’ if the invoking string is less than str and ‘postivite number’ if the invoking string is greater than str that is passed as an argument. The comparision is case-sensitive.

Example:

class comp{

public static void main(String[] args) {

String s1=new String("hello");String s2=new String("india");if((s1.compareTo(s2))>0)System.out.println("S1 is greater than s2");else if((s1.compareTo(s2))<0)System.out.println("S2 is greater than s1");elseSystem.out.println("Two stings are equal");

}}

O/P: S2 is greater than s1

If we want to ignore case differences when comparing two strings, we use the syntax of the form: int compareToIgnoreCase(String str)This method was added by Java 2.

7. regionMatches( ): It compares a specific region inside a string with another specific region in another string. It follows two methods.

1. boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numchars)

51

Page 52: Java

www.aspgmca.blogspot.com

2. boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numchars)

The first argument is the starting index of the string that invokes the method. The second argument is a comparison string. The third argument is starting index in the comparison string. The last argument is the number of characters to compare between the two strings. IgnoreCase is true the method ignores the case of the objects being compared.

Example 1:

class rmatch1{

public static void main(String[] args) {

String s1=new String("happy birthday");String s2=new String("Happy birthday");if(s1.regionMatches(0,s2,0,5))System.out.println("Match");elseSystem.out.println("Not Match");

}}

Example 2:

class rmatch1{

public static void main(String[] args) {

String s1=new String("happy birthday");String s2=new String("Happy birthday");if(s1.regionMatches(true,0,s2,0,5))System.out.println("Match");elseSystem.out.println("Not Match");

}}

8. int indexOf(int ch): int indexOf(String str): int indexOf(char ch): It search for the first occurrence of a character. If the character is found the index of that characters in the string is returned. Otherwise, it returns ‘-1’.

Example:

class index {

52

Page 53: Java

www.aspgmca.blogspot.com

public static void main(String[] args) {String letter=new String("Java programming language");System.out.println(letter.indexOf('v')); //O/P: 2System.out.println(letter.indexOf("programming")); //O/P: 5System.out.println(letter.indexOf('A')); //O/P: -1}

}

9. int indexOf(int ch, int startIndex): int indexOf(String ch, int startIndex): int indexOf(char ch, int startIndex): It searches the occurrence of character from the startIndex argument.

Example:

class indexof{

public static void main(String[] args) {String letter=new String("Java programming language");System.out.println(letter.indexOf('m',2)); //O/P: 11}

}

10. int lastIndexOf(int ch): int lastIndexOf(char ch): int lastIndexOf(String ch): It searches the last occurrence of the character. The search is performed from the end of the string towards the beginning of the string. If the character is found the index of that character in the string is return. Otherwise, it returns ‘-1’.

Example:

class lindexof{

public static void main(String[] args) {String letter=new String("Java programming language");System.out.println(letter.lastIndexOf('n')); //O/P: 19System.out.println(letter.lastIndexOf("language")); //O/P: 17}

}

11. int lastIndexOf(int ch, int startIndex): int lastIndexOf(String ch, int startIndex): int lastIndexOf(char ch, int startIndex): It searches the last occurrence of the character starting with the startIndex to search the string from ending to the beginning.

Example:

53

Page 54: Java

www.aspgmca.blogspot.com

class lindexof{

public static void main(String[] args) {String letter=new String("Java programming language");System.out.println(letter.lastIndexOf('n',11)); //O/P: -1}

}

12. String substring(int startIndex): It returns a copy of the sub string that begins that startIndex and return to the end of the invoking string.

Example:

class sub{

public static void main(String[] args) {

String s=new String("Java programming language");System.out.println(s.substring(8));

}}O/P: gramming language

13. String substring(int startIndex, int endIndex): It returns all the characters from the beginning index upto but not including the ending index.

Example:

class s13{

public static void main(String[] args) {String s=new String("program");System.out.println(s.substring(2,5)); //O/P: ogr}

}

14. boolean startsWith(String str): boolean endsWith(String str): The startsWith( ) method determines whether a given string begins with a specified string or not. Conversely, endsWith( ) method determines whether string ends with a specified string or not.

Example:

class s14{

public static void main(String[] args) {

54

Page 55: Java

www.aspgmca.blogspot.com

String s=new String("Java is a program");if(s.startsWith("is"))System.out.println("Match");elseSystem.out.println("Not Match");}

}

//O/P: Not Match

15. String concat(String str): It concatenates two string objects.

Example:

class s15{

public static void main(String[] args) {String s=new String("Java ");String s1=s.concat("program");System.out.println(s1);}

}

O/P: Java program

16. String replace(char original, char replacement): It replace all characters of one character in the invoking string with another character.

Example:

class s16{

public static void main(String[] args) {String s="Hello";System.out.println(s.replace('l','w')); //O/P: Hewwo}

}

17. String toLowerCase(): It converts all uppercase characters into lowercase characters of a string.

Example:

class s17{

public static void main(String[] args) {String s="HELLO";

55

Page 56: Java

www.aspgmca.blogspot.com

System.out.println(s.toLowerCase()); //O/P: hello}

}

18. String toUpperCase():It converts all lowercase characters into uppercase characters of a string.

Example:

class s17{

public static void main(String[] args) {String s="hello";System.out.println(s.toUpperCase()); //O/P: HELLO}

}

19. String trim(): It returns a copy of the invoking string from which any leading and lining white space has been removed.

Example:

class s18{

public static void main(String[] args) {String s=" hello";System.out.println(s.trim());}

}

20. char[] toCharArray(): It returns a character array containing a copy of the characters in a string.

Example:

class s20{

public static void main(String[] args) {String s="hello";char ch[]=s.toCharArray();for(int i=0;i<ch.length;i++)System.out.println(ch[i]);}

}

21. String toString(): It converts all objects into strings objects.

Example:

56

Page 57: Java

www.aspgmca.blogspot.com

class s21 {

public static void main(String[] args) {Integer i=new Integer(10);System.out.println(i.toString()); //O/P: 10}

}

LabProgram 5: Write a program to sort the list of names in ascending order.

class lab5 {

public static void main(String[] args) {String ch[]={"india","hai","andhra"};String temp;for(int i=0;i<ch.length-1;i++){for (int j=i+1;j<ch.length;j++){if((ch[i].compareTo(ch[j]))>0){temp=ch[i];ch[i]=ch[j];ch[j]=temp;}}}for(int i=0;i<ch.length;i++)System.out.println(ch[i]);}

}

2. StringBuffer Class:

Once a string object is created its contents cannot be changed. But the StringBuffer class provides the feature of creating and manipulating dynamic string information i.e., mutable strings. Every StringBuffer class is capable for storing a number of characters specified by its capacity. If the capacity of StringBuffer exceeded the capacity is automatically expanded to accommodate the additional characters.

StringBuffer Constructors:

a) StringBuffer(): It is a default StringBuffer Constructor to create StringBuffer with no characters init and an initial capacity of 16 characters.b) StringBuffer(String str): It takes a string argument to create a StringBuffer containing the characters of the string argument. The initial capacity is the number of arguments in the string argument + 16.

57

Page 58: Java

www.aspgmca.blogspot.com

c) StringBuffer(int size): It takes an integer argument and creates a StringBuffer with no characters init. The initial capacity is specified by the integer.

Example:

class sb {

public static void main(String[] args) {StringBuffer s1,s2,s3;s1=new StringBuffer();s2=new StringBuffer("hello");s3=new StringBuffer(45);System.out.println(s1.capacity()+s2.capacity()+s3.capacity()); //O/P: 82}

}

Methods:

1. int length(): It returns the number of characters in a StringBuffer.

Example:

class sb1{

public static void main(String[] args) {StringBuffer s=new StringBuffer("hello");System.out.println(s.length()); //O/P: 5}

}

2. int capacity(): It returns the number of characters that can be stored in a StringBuffer without allocating more memory.

Example:

class sb2{

public static void main(String[] args) {StringBuffer s=new StringBuffer("hello");System.out.println(s.capacity()); //O/P: 21}

}

3. void ensureCapacity(): It is provided to allow the programmer to guarantee that a StirngBuffer has a minimum capacity where capacity specifies the size of the buffer.

Example:

58

Page 59: Java

www.aspgmca.blogspot.com

class sb3{

public static void main(String[] args) {StringBuffer s=new StringBuffer("hello");s.ensureCapacity(75);System.out.println(s.capacity()); //O/P: 75}

}

4. void setLength(int len): It increase or decrease the length of StringBuffer.

Example:

class sb4{

public static void main(String[] args) {StringBuffer s=new StringBuffer("abcdefghijkl");s.setLength(5);System.out.println(s); //O/P: abcde}

}

5. char charAt(int where): It returns a character at the specified where position.

Example:

class sb5{

public static void main(String[] args) {StringBuffer s=new StringBuffer("abcdefghijkl");System.out.println(s.charAt(7)); //O/P: h}

}

6. void setCharAt(int where, char ch): It takes an integer and a character argument and sets the character at the specified position of the character argument.

Example:

class sb6{

public static void main(String[] args) {StringBuffer s=new StringBuffer("abcdef"); //O/P: Hbcdefs.setCharAt(0,'H');System.out.println(s);}

}

59

Page 60: Java

www.aspgmca.blogspot.com

7. void getChars(int Sourcestart, int Sourceend, char Target[], int Targetstart): It copies the sub string of a StringBuffer into character array. Sourcestart specifies the starting index from which characters should be copied in StringBuffer. Sourceend specifies the index one past the last character to be copied from the StringBuffer. Target specifies the character array into which the characters are to be copied. Targetstart specifies the starting location of the character array from where the first character should be placed.

Example:

class sb7{

public static void main(String[] args) {StringBuffer s=new StringBuffer("abc def");char ch[]=new char[s.length()];s.getChars(3,s.length(),ch,0);for(int i=0;i<ch.length;i++)System.out.println(ch[i]); //O/P: def}

}

8. StringBuffer reverse(): It returns the reverse contents of the StringBuffer.

Example:

class sb8{

public static void main(String[] args) {StringBuffer s=new StringBuffer("abcdef");System.out.println(s.reverse());}

}

3. StringTokenizer class:

In programming languages, statements are divided into individual pieces like identifiers, keywords, and operators etc., called Tokens. Java provides StringTokenizer class that breaks a string into its component tokens. This class is available in java.util package. Tokens are separator from one another by delimiters (special operators), white space characters such as blank, tab, new line and carriage return.

StringTokenizer Constructors:

a) StirngTokenizer(Stirng str)b) StirngTokenizer(Stirng str, String delimiters)c) StirngTokenizer(Stirng str, String delimiters, boolean delimiterAsToken)

In all versions str is a string that is tokenized.In the first version, the default delimiters are used.

60

Page 61: Java

www.aspgmca.blogspot.com

In the second version and third versions delimiters in string that specifies the delimiters.In the third version if “delimiterAsToken” is true then the delimiters also returned as tokens when the string is tokenized otherwise, the delimiters are not returned. Delimiters are not returned as tokens by the first two forms.

Methods:

1. int countTokens(): Using the current set of delimiters the method determines the number of tokens left to be tokenized and return the result.2. boolean hasMoreTokens(): It returns true if one or more tokens remain in the string and returns false if there are none.3. String nextToken(): It returns the next token as string.

Example:

import java.util.*;class st {

public static void main(String[] args) {String s=new String("abc def gh");StringTokenizer t=new StringTokenizer(s);System.out.println(t.countTokens());while(t.hasMoreTokens())System.out.println(t.nextToken());}

}

O/P: 3abcdefgh

LabProgram 7: Write a program that reads a line of integers, then displays each integers and the sum of all the integers

import javax.swing.JOptionPane;import java.util.*;class lab7 {

public static void main(String[] args) {//String s=new String("4$8$9$67");//StringTokenizer t=new StringTokenizer(s,"$");String s;s=JOptionPane.showInputDialog("Enter the string");StringTokenizer t=new StringTokenizer(s,"$");int a,sum=0;System.out.println(t.countTokens());while(t.hasMoreTokens()){

61

Page 62: Java

www.aspgmca.blogspot.com

a=Integer.parseInt(t.nextToken());System.out.println(a);sum=sum+a;}System.out.println("Total="+sum);}

}

LabProgram 4: Write a program to check whether a given string is palindrome or not.

import javax.swing.JOptionPane;class lab4 {

public static void main(String[] args) {

String s;s=JOptionPane.showInputDialog("Enter a String");char ch[]=s.toCharArray();int i,j,count=0;for(i=0,j=ch.length-1;i<j;i++,j--){if(ch[i]!=ch[j]){System.out.println("Not polindrome");count=1;break;}}if(count==0)System.out.println("Polindrome");

}}

Garbage CollectionObjects are dynamically allocated by using the new operator such objects are

destroyed automatically and their memory released for later reallocation in Java. The technique that accomplishes this is called “Garbage Collection”. Garbage collection works when no references to an object exist, the object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed. Java run-time implementations will take various approaches to garbage collection.

finalize( ) method:The garbage collector of an object called this method when the garbage collection

determines that those are no more references to the object. It is also placed some actions inside the finalized method. The following points are related to finalize( ) method.

1. Every class has Object class as a super class2. Every class in Java can have a finalize( ) method that returns resources to the

system3. A class should have only one finalize( ) method that takes no argument.

Method finalize( ) is originally defined in class Object

62

Page 63: Java

www.aspgmca.blogspot.com

The finalize( ) method has the following syntaxSyntax: protected void finalize( )

{// finalization code

}

Example:

class Garbage extends Object {

int x,y;void setdata(int a,int b){x=a;y=b;}void printdata(){System.out.println("x="+x+" y="+y);}protected void finalize(){System.out.println("finalizer");}

}class Mg{

public static void main(String[] args) {

Garbage obj=new Garbage();Garbage obj1=new Garbage();obj.setdata(10,20);obj.printdata();obj1=null;System.gc(); // method to call garbage collector//obj1.setdata(2,3); //errorobj.printdata();

}}

O/P: x=10 y=20finalizerx=10 y=20

63

Page 64: Java

www.aspgmca.blogspot.com

--- *** ---

Unit – III

Inheritance: The mechanism of deriving a new class from an old one is called inheritance. A class that is inherited (old class) is called a super class or base class or parent class. The class that does the inheriting (new class) is called a subclass or derived class or child class. Inheritance allows subclasses to inherit all the variables and methods of their parent classes.

Inheritance is classified into different forms.a) Single Inheritance: Derivation a subclass from only one super class is called Single Inheritance.

Super class (or) Base class (or) Parent class

Subclass (or) Derived class (or) Child class

64

A

B

Page 65: Java

www.aspgmca.blogspot.com

b) Hierarchical Inheritance: Derivation of several classes from a single super class is called Hierarchical Inheritance.

c) Multilevel Inheritance: Derivation of a class from another derived class s called Multilevel Inheritance.

d) Multiple Inheritance: Derivation of one class from two or more super classes is called Multiple Inheritance. But Java does not support Multiple Inheritance directly. It can be implemented by using Interface concept.

e) Hybrid Inheritance: Derivation of a class involving more than one form of Inheritance is called Hybrid Inheritance.

65

A

DCB

A

C

B

A

C

B

A

Page 66: Java

www.aspgmca.blogspot.com

Defining a Subclass: A subclass is defined as Syntax: class subclass-name extends superclass-name

{variable declaration;method declaration;

}The keyword extends signifies that the properties of the super class name are

extended to the subclass name. The subclass will now contain its own variables and methods as well as those of the super class. But it is not vice-versa.

Example 1: Program for Single Inheritance

class A {

int len,bre;void getdata(int x,int y){len=x;bre=y;}void printdata(){System.out.println("length="+len);System.out.println("Breadth="+bre);}

}class B extends A{

int wid;void putdata(int x,int y,int z){len=x;bre=y;wid=z;

66

D

CB

Page 67: Java

www.aspgmca.blogspot.com

}void printdata1(){printdata();System.out.println("Width="+wid);}void calarea(){int area=len*bre*wid;System.out.println("Area="+area);}

}class si{

public static void main(String[] args) {B obj=new B();obj.putdata(10,20,30);obj.printdata1();obj.calarea();}

}

Example 2: Program for Hierarchical Inheritance

class A {

int len,bre;void getdata(int x,int y){len=x;bre=y;}void printdata(){System.out.println("length="+len);System.out.println("Breadth="+bre);}

}class B extends A{

int wid;void getdata1(int x,int y){getdata(x,y);}void calarea(){printdata();

67

Page 68: Java

www.aspgmca.blogspot.com

int area=len*bre;System.out.println("Area="+area);}

}class C extends A{

int wid;void putdata(int x,int y,int z){len=x;bre=y;wid=z;}void printdata1(){printdata();System.out.println("Width="+wid);}void calarea1(){int area=len*bre*wid;System.out.println("Area="+area);}

}class hi{

public static void main(String[] args) {B obj=new B();obj.getdata1(10,20);obj.calarea();

C obj1=new C();obj1.putdata(1,2,3);obj1.printdata1();obj1.calarea1();}

}

//Example Program for Hierarchical Inheritance

import java.text.*;class Employee{int Empno;double Basic,DA,HRA;String Empname;void readdata(int x,String y){

68

Page 69: Java

www.aspgmca.blogspot.com

Empno=x;Empname=y;}void readsalary(double x,double y,double z){Basic=x;DA=y;HRA=z;}void printdata(){System.out.println("Employee Number:"+Empno);System.out.println("Employee Name :"+Empname);}void printsalary(){DecimalFormat df=new DecimalFormat("0.00");System.out.println("Employee Basic :"+df.format(Basic));System.out.println("Employee DA :"+df.format(DA));System.out.println("Employee HRA :"+df.format(HRA));}}

class TSalary extends Employee{void showdata(){readdata(111,"Vishnu");printdata();readsalary(2589.00,567,1090);printsalary();}void calsalary(){DecimalFormat df=new DecimalFormat("0.00");double netsal;netsal=Basic+DA+HRA;System.out.println("Employee Netsalary="+df.format(netsal));}}

class PSalary extends Employee{double Itax;void readtax(double x){Itax=x;}void showdata(){readdata(1000,"Kamal");

69

Page 70: Java

www.aspgmca.blogspot.com

printdata();readsalary(12589.00,1567,2090);printsalary();}void calsalary(){DecimalFormat df=new DecimalFormat("0.00");double Gsal,netsal;Gsal=Basic+DA+HRA;netsal=Gsal-Itax;System.out.println("Income Tax Amount="+df.format(Itax));System.out.println("Employee Netsalary="+df.format(netsal));}}class Harch {

public static void main(String[] args) {TSalary obj=new TSalary();obj.showdata();obj.calsalary();PSalary obj1=new PSalary();obj1.readtax(800);obj1.showdata();obj1.calsalary();}

}

Example 3: Program for Multilevel Inheritance

import javax.swing.JOptionPane;class student{

int rno;void readdata1(){rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number"));}void printdata1(){System.out.println("Roll Number="+rno);}

}class exam extends student{

int m1,m2,m3;void readdata2(){readdata1();m1=Integer.parseInt(JOptionPane.showInputDialog("Enter sub1 marks"));

70

Page 71: Java

www.aspgmca.blogspot.com

m2=Integer.parseInt(JOptionPane.showInputDialog("Enter sub2 marks"));m3=Integer.parseInt(JOptionPane.showInputDialog("Enter sub3 marks"));}void printdata2(){printdata1();System.out.println("Sub 1 marks="+m1);System.out.println("Sub 2 marks="+m2);System.out.println("Sub 3 marks="+m3);}

}class results extends exam{

int avg;void printdata3(){printdata2();avg=(m1+m2+m3)/3;if(avg<35)System.out.println("FAIL");else if(avg>=35 && avg<50)System.out.println("THIRD CLASS");else if(avg>=50 && avg<60)System.out.println("SECOND CLASS");else if(avg>=60 && avg<75)System.out.println("FIRST CLASS");else if(avg>=75)System.out.println("DISTINCTION");}

}class mi {

public static void main(String[] args) {

results obj=new results();obj.readdata2();obj.printdata3();

}}

Member Access Rules:

1. By means of sub class object it is possible to access all the instance variables and instance methods of the super class.2. By means of sub class object it cannot be possible to access the instance variable of super class, if it is declared as private. Since, the data is protected in that class.

import javax.swing.JOptionPane;class student

71

Page 72: Java

www.aspgmca.blogspot.com

{private int rno;void readdata1(){rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number"));}

}class exam extends student{

void printdata1(){readdata1(); System.out.println("Roll Number="+rno); // produces compilation error}

}class mi2{

public static void main(String[] args) {

exam obj=new exam();obj.printdata1();

}}

3. Referring to super class object with a subclass reference produces syntax error. In such case we need type casting.Example:

import javax.swing.JOptionPane;class student{

int rno;void readdata1(){rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number"));}

}class exam extends student{

void printdata1(){readdata1();System.out.println("Roll Number="+rno);}

}class mi2{

public static void main(String[] args) {

72

Page 73: Java

www.aspgmca.blogspot.com

student s1=new exam();exam e1=(exam)s1;e1.printdata1();

}}

super keyword: A subclass constructor is used to construct the instance variable of both the subclass and the super class. The subclass constructor uses the keyword super to invoke the constructor method of the super class. The keyword super is used subject to the following conditions.

super may be used only within the subclass constructor method The call to super class constructor must appear as the first statement with in the

subclass constructor If a parameterized constructor is used, then the signature is matched with the

parameters passed to the super method as super(parameter-list);

Example 1:

class student {

public student(){System.out.println("super");}

}class exam extends student{

public exam(){System.out.println("sub");}

}class s{

public static void main(String[] args) {

exam obj=new exam();}

}

O/P: supersub

Example 2:

class student {

public student(){System.out.println("super");

73

Page 74: Java

www.aspgmca.blogspot.com

}}class exam extends student{

public exam(){super( ); // explicit call of super( )System.out.println("sub");}

}class s{

public static void main(String[] args) {

exam obj=new exam();}

}

O/P: supersub

Example 3:

class student {

int len,bre;public student(int a,int b){len=a;bre=b;}int area(){return len*bre;}

}class exam extends student{

int ht;public exam(int x,int y,int z){super(x,y);ht=z;}int volume(){return len*bre*ht;}

}class s{

74

Page 75: Java

www.aspgmca.blogspot.com

public static void main(String[] args) {

exam obj=new exam(2,3,4);System.out.println("area="+obj.area());System.out.println("volume="+obj.volume());

}}

Another important use of super is applicable to situations in which member names of a subclass hide members by the same name in the super class. It is similar to the ‘this’ keyword except that it always refers to the super class of the subclass in which it is used. The general form is as

super.memberwhere member can be either a method or an instance variable

Example:

class A {

int i=7;}class B extends A{

int i=6;void show(){System.out.println("super i="+super.i);System.out.println("sub i="+i);}

}

class s1{

public static void main(String[] args) {

B obj=new B();obj.show();

}}

Method OverridingA method in a subclass has the same name, type of the variables and order of the

variables as a method in its super class, then the method in the subclass is said to be override the method in the super class. The process is called Method Overriding. In such process the method defined by the super class will be hidden.

When the method is called, the method defined in the super class has invoked and executed instead of the method in the super class. The super reference followed by the dot (.) operator may be used to access the original super class version of that method from the subclass.

75

Page 76: Java

www.aspgmca.blogspot.com

Note: 1. Method Overriding occurs only when the name and type signature of the two methods are identical.

2. If method name is identical and the type signature is different, then the process is said to be Method Overloading.

Example 1:

class A {

int i,j;public A(int a,int b){i=a;j=b;}void show(){System.out.println("i="+i+"\n"+"j="+j);}

}class B extends A{

int k;B(int a,int b,int c){super(a,b);k=c;}void show(){System.out.println("k="+k);}

}class override{

public static void main(String[] args) {

B obj=new B(1,2,3);obj.show();

}}

O/P: k=3

Example 2:

class A {

int i,j;public A(int a,int b){

76

Page 77: Java

www.aspgmca.blogspot.com

i=a;j=b;}void show(){System.out.println("i="+i+"\n"+"j="+j);}

}class B extends A{

int k;B(int a,int b,int c){super(a,b);k=c;}void show(){super.show();System.out.println("k="+k);}

}class override{

public static void main(String[] args) {

B obj=new B(1,2,3);obj.show();

}}

O/P: i=1j=2k=3

Resolve the method call at compile time is known as “compile time” or “early binding” or “static binding”. Resolve the method at run time is known as “run time” or “late binding” or “dynamic binding”.

Method Overriding forms on the basis of Java concept Dynamic Method Dispatch. It is the mechanism by which a call to an overridden function is resolved at run time, rather than compile time. And this method is very useful to show for Java implements run-time polymorphism.

“Super class reference variable can refer to a subclass object” is the principle to resolve calls to overridden methods at run time. If a super class contains a method that is overridden by a subclass, then when different types of objects are referred to through a super class reference variable, different version of the methods are executed and the determination is made at run time.

Lab Program 21: Example program for Java supports Run time Polymorphism.

class figure

77

Page 78: Java

www.aspgmca.blogspot.com

{double dim1,dim2;figure(double x,double y){dim1=x;dim2=y;}double area(){System.out.println("Area undefined");return 0;}

}class rectangle extends figure{

rectangle(double a,double b){super(a,b);}double area(){System.out.println("Rectangle Area");return dim1*dim2;}

}class triangle extends figure{

triangle(double x,double y){super(x,y);}double area(){System.out.println("Triangle Area");return dim1*dim2/2;}

}class run{

public static void main(String[] args) {figure obj=new figure(10,10);rectangle obj1=new rectangle(9,5);triangle obj2=new triangle(10,8);

figure a; //a is a reference of type figure(super class)a=obj1; //a refers to object of rectangle(sub class)System.out.println("Area="+a.area());

a=obj; //a refers to object of figureSystem.out.println("Area="+a.area());

78

Page 79: Java

www.aspgmca.blogspot.com

a=obj2; //a refers to object of triangleSystem.out.println("Area="+a.area());}

}

O/P: Rectangle AreaArea=45.0Area undefinedArea=0.0Triangle AreaArea=40.0

Abstract Class:Classes from which objects cannot be instantiated with new operator are called

Abstract Classes. Each abstract class contains one or more abstract methods. In a class if there exist any method with no method body is known as abstract method. An abstract method is declared as

Syntax: abstract type method-name (parameter-list);“abstract” is a keyword used for declaring abstract methods. To declare a class as abstract, use the abstract keyword in front of the class keyword at the beginning of the class declaration. No objects are created to an abstract class. For the abstract methods, the implementation code will be defined in its subclass.

Example:

abstract class figure {

double dim1,dim2;figure(double x,double y){dim1=x;dim2=y;}abstract double area();

}class rectangle extends figure{

rectangle(double a,double b){super(a,b);}double area(){System.out.println("Rectangle Area");return dim1*dim2;}

}class triangle extends figure

79

Page 80: Java

www.aspgmca.blogspot.com

{triangle(double x,double y){super(x,y);}double area(){System.out.println("Triangle Area");return dim1*dim2/2;}

}class abs{

public static void main(String[] args) {//figure obj=new figure(10,10); //error

rectangle obj1=new rectangle(9,5);System.out.println("Area="+obj1.area());

triangle obj2=new triangle(10,8);figure a;a=obj2;System.out.println("Area="+a.area());}

}

Note: 1. We cannot declare any abstract constructors.2. Concrete (general) methods are also being inside any abstract class.3. Abstract classes are used for general purposes.4. An abstract class must be subclass and override it methods.5. Super class has only method name and signature end with semicolon.6. Abstract classes cannot be used to instantiate objects, but they can used to

create object reference due to Java supports Run-time Polymorphism.

final keywordA final is a keyword used for three purposes. They area) final as constant: A variable can be declared as constant with the keyword final. It must be initialized while declaring. One we initialized the variable with final keyword it cannot be modified in the program. This is similar to the const in C/C++.

Example: final int x = 10;x = 45 //error

b) final to prevent overriding: A method that is declared as final cannot be overridden in a subclass method. It the methods that are declared as private are implicitly final.

Example: class A{

final void show( ){

80

Page 81: Java

www.aspgmca.blogspot.com

System.out.println(“Hello”);}

}class B extends A{

void show( ){ //errorSystem.out.println(“Hai”);}

}

c) final to prevent inheritance: The class that is declared as final implicitly declares all of its methods as final. The class cannot be extended to its subclass.

Example: final class A{

void show( ){System.out.println(“Hello”);}

}class B extends A //error{

void show( ){System.out.println(“Hai”);}

}

Object ClassJava provides a special class called “Object” class that is available in java.lang package. It is the super class of all other classes. So, a reference variable of type Object is created, it refers to object of any other class. Object class defines the following methods that are available in every object.

Method PurposeObject clone( ) Creates a new object that is the same as the

object being clonedboolean equals(Object object) Determines whether one object is equal to

anothervoid finalize( ) Called before an unused object is recycledClass getClass( ) Obtains the class of an object at run timeint hashCode( ) Returns the hash code associated with the

invoking objectvoid notify( ) Resumes execution of a thread waiting on

the invoking objectvoid notifyAll( ) Resumes execution of all threads waiting

on the invoking objectString toString( ) Returns a string that describes the object

81

Page 82: Java

www.aspgmca.blogspot.com

void wait( ) Waits on another thread of executionvoid wait(long milliseconds)void wait(long milliseconds, int nanoseconds)

Array of Objects: To instantiate more than one object for a single class, we use Array of Objects.

Example:

import javax.swing.JOptionPane;class a {

int x,y;void readdata(){x=Integer.parseInt(JOptionPane.showInputDialog("Enter x value"));y=Integer.parseInt(JOptionPane.showInputDialog("Enter y value"));}void printdata(){System.out.println("x="+x+"\n"+"y="+y);}

}class aob{

public static void main(String[] args) {a ob[]=new a[5];for(int i=0;i<5;i++){ob[i]=new a();ob[i].readdata();ob[i].printdata();}}

}

UNIT – IV

INTERFACES

82

Page 83: Java

www.aspgmca.blogspot.com

Interface is a collection of method declaration and constants that one or more classes of objects will use. Interface definition is same as class except that it consists of the methods that are declared have no method body. They end with a semicolon after the parameter list. Syntax for an interface is as follows.

Syntax: <access specifier> interface <it-name>{

type varname1=value;type varname2=value;..returntype method-name1(parameter-list);returntype method-name2(parameter-list);..

}

Here, access specifier is public or not used. public access specifier indicates that the

interface can be used by any class. Otherwise, the interface will accessible to class that are defined in the same package as in the interface.

interface keyword is used to declare the class as an interface. it-name is the name of the interface and it is a valid identifier. Variables declared inside the interface are implicitly final and static. They cannot

be changed in the implementing class. All the methods in an interface are implicitly abstract methods. Method

implementation is given in later stages. The main difference between a class and interface is class contains methods with

method body and the interface contains only abstract methods.

Example: public interface shape{

int radius=2;public void area(int a);

}

Implementing Interfaces: Once an interface has been defined, one or more classes can implement that interface. “implements” keyword used for implementing the classes. The syntax of implements is as follows.

Syntax: class class-name implements interface1, interface2, .. interfacen{

……..…….. // class body……..

}If a class implements more than one interface, the interfaces are separated with a

comma operator. The methods that implement an interface must be declared public. Also type signature of the implementing method must match exactly the type signature specified in the interface definition.

Example:

83

Page 84: Java

www.aspgmca.blogspot.com

interface it1{

int x=10,y=20;public void add(int a,int b);public void sub(int a,int b);

}class it2 implements it1 {

public void add(int s,int w){System.out.println("Addition="+(s+w));}public void sub(int s,int w){System.out.println("Subtraction="+(s-w));}public static void main(String[] args) {it2 obj=new it2();obj.add(3,4);obj.sub(5,2);System.out.println(obj.x+obj.y);obj.x=70; // error since x is final variable in interface}

}

Note:1. Interface methods are similar to the abstract classes so, that it cannot be instantiated.2. Interface methods can also be accessed by the interface reference variable refer to the object of subclass. The method will be resolved at run time. This process is similar to the “super class reference to access a subclass object”.

Example:

interface it1{

int x=10,y=20;public void add(int a,int b);public void sub(int a,int b);

}class it2 implements it1 {

public void add(int s,int w){System.out.println("Addition="+(s+w));}public void sub(int s,int w){System.out.println("Subtraction="+(s-w));

84

Page 85: Java

www.aspgmca.blogspot.com

}public static void main(String[] args) {it2 obj=new it2();it1 ref;ref=obj;System.out.println(ref.x+ref.y);}

}

3. If a class includes an interface but does not fully implement the methods defined by that interface, then the class becomes abstract class and must be declared as abstract in the first line of its class definition.

Example:

interface it1{

int x=10,y=20;public void add(int a,int b);public void sub(int a,int b);

}abstract class it2 implements it1 {

public void add(int s,int w){System.out.println("Addition="+(s+w));}

}class it3 extends it2{

public void sub(int s,int w){System.out.println("Subtraction="+(s-w));}public static void main(String[] args) {it3 obj=new it3();obj.add(5,6);}

}

Various forms of Interface Implementations:

85

Page 86: Java

www.aspgmca.blogspot.com

1. interface

implements

classextends

class

2. interface

implements implements

interface interface

3.class interface

extends extendsimplements

class interface

extends

class

4. interface interface

implements implements

interface

implements

class

Multiple Inheritance: Multiple Inheritances does not support by Java directly. Multiple Inheritances enables to derive a class from multiple parent classes.Let A and B are parent classes and C is the derived class

86

A B

A

B

C

A

B C

A

C

B E

D

A B

D

C

Page 87: Java

www.aspgmca.blogspot.com

Java provides Interface approach to support the concept of Multiple Inheritance. A class can also implements multiple interfaces.

Example:

class Test {

int sub1,sub2,sub3;void readdata1(int x,int y,int z){sub1=x;sub2=y;sub3=z;}void printdata1(){System.out.println("sub1 marks="+sub1);System.out.println("sub2 marks="+sub2);System.out.println("sub3 marks="+sub3);

}}interface Sports{

int smarks=55;public void printdata2();

}class Result extends Test implements Sports{

int sum;public void printdata2(){printdata1();sum=sub1+sub2+sub3+smarks;System.out.println("Total Marks="+sum);}

}

class mul{

public static void main(String[] args) {Result obj=new Result();obj.readdata1(35,67,89);obj.printdata2();}

87

C

Page 88: Java

www.aspgmca.blogspot.com

}

Hybrid Inheritance: Derivation of a class involving more than one form of Inheritance is called Hybrid Inheritance.

Example:

import javax.swing.JOptionPane;class Student {

int rno;String name;void readdata1(){rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number"));name=JOptionPane.showInputDialog("Enter name");}void printdata1(){System.out.println("Roll number="+rno);System.out.println("Name ="+name);}

}class Test extends Student{

int m1,m2,m3;void readdata2(){m1=Integer.parseInt(JOptionPane.showInputDialog("Enter sub1 marks"));m2=Integer.parseInt(JOptionPane.showInputDialog("Enter sub2 marks"));m3=Integer.parseInt(JOptionPane.showInputDialog("Enter sub3 marks"));}void printdata2(){System.out.println("Sub1="+m1+" Sub2="+m2+" Sub3="+m3);}

}

88

A

D

CB

Page 89: Java

www.aspgmca.blogspot.com

interface Sports{

int smarks=55;public void printdata3();

}class Result extends Test implements Sports{

int sum;public void printdata3(){System.out.println("Sports marks="+smarks);}public void readdata3(){readdata1();readdata2();}public void printdata4(){sum=m1+m2+m3+smarks;printdata1();printdata2();printdata3();System.out.println("Total Marks="+sum);}

}class hy{

public static void main(String[] args) {Result obj=new Result();obj.readdata3();obj.printdata4();}

}

PACKAGES

89

Page 90: Java

www.aspgmca.blogspot.com

Package is a collection of related classes. Each class defines number of methods. Java packages are classified into 2 types.

1. Java API (Application Programming Interface) packages (or) Predefined packages (or) Built-in packages: These packages are defined by the system. Some of the example for system defined packages are java.lang, java.util, java.io, java.awt, java.applet etc.,

2. User defined packages: These packages are defined by the user.

Defining a Package:To define a package, place “package” command as the first statement in the Java

source file. So, that any class declared within that file will belong to the specified package. The syntax of package creation is as follows.

Syntax: package pack-name;where pack-name is the name of the package.

Example: package mypack;public class number{

public void add (int a,int b){System.out.println(“Sum=”+(a+b));}

}

The class that is defined in the package must be start with the public access modifier. So, that it can be accessible by any another of them. If it is not public, it is possible to access only in that package.

Java uses file system directories to store packages. We save the program with number.java and compile the package is as

javac –d . number.javaDue to this compilation mypack directory is automatically created and .class file is stored in that directory.

Package creation has completed. The package information is now including in our actual program by means of “import” statement. “import” is a keyword that links the package with our program. It is placed before the class definitions.

import mypack.*;or

import mypack.number;

Example 1:

import mypack.number;class pack{

public static void main(String[] args) {

number obj=new number();obj.add(3,4);

}}

Example 2:

90

Page 91: Java

www.aspgmca.blogspot.com

package math1;public class Mcal{

public void square(int x){System.out.println("Square of "+x+" is"+(x*x));}public void cube(int x){System.out.println("cube "+x+" is"+(x*x*x));}

}

import math1.Mcal;class calc {

public static void main(String[] args) {

Mcal obj=new Mcal();obj.square(3);obj.cube(4);

}}

Example 3:

package p6;public class Balance {String name;double bal;public Balance(String n, double b){name=n;bal=b;}public void show(){if(bal<0){System.out.println(name+"---"+bal);}}}

import p6.Balance;class Account {

91

Page 92: Java

www.aspgmca.blogspot.com

public static void main(String[] args) {Balance c[]=new Balance[3];c[0]=new Balance("John",123.33);c[1]=new Balance("Arun",157.02);c[2]=new Balance("Siri",-12.33);for(int i=0;i<3;i++)c[i].show();}

}

Note: 1. Java source file contains only one public class and any number of non-pubic classes. The filename should be same as the name of the public class with .java extension.

2. Package contain any number of public and default classes.Example: package p1;

public class x{

// body of x this class is accessible}class y{

// body of y not accessible due to non-use} of public access modifier

Let we want to access all the classes of information then the classes are stored in different files with the same package name.

Example: package mypack;public class number{

public void add (int a,int b){System.out.println(“Sum=”+(a+b));}

}

package mypack;public class number1{

public void sub(int a,int b){System.out.println("sub="+(a-b));}

}

import mypack.number;import mypack.number1;class pack{

public static void main(String[] args)

92

Page 93: Java

www.aspgmca.blogspot.com

{number obj=new number();obj.add(3,4);number1 obj1=new number1();obj1.sub(6,2);

}}

Sub Packages: It is also possible to create sub packages for the main package.Syntax: package pack1.pack2;

where pack1 is the main package and pack2 is the sub package.

Example:

package pack1;public class x{

public void show(){System.out.println("Super");}

}

package pack1.pack2;public class y{

public void display(){System.out.println("Sub");}

}

import pack1.x;import pack1.pack2.y;class che{

public static void main(String[] args) {

x obj=new x();obj.show();y obj1=new y();obj1.display();

}}

Access ProtectionJava provides four types Access modifiers as public, private, default and

protected. Any variable declared as public, it could be accessed from anywhere. Any variable declared as private cannot be seen outside of its class. Any variable declared as default, it is visible to subclasses as well as to other classes in the same package. Any

93

Page 94: Java

www.aspgmca.blogspot.com

variable declared as protected, it allows an element to be seen outside of current package, but only to classes that subclass directly.

public private default protectedSame class Yes Yes Yes YesSame package sub class Yes No Yes YesSame package non-subclass Yes No Yes YesDifferent package sub class Yes No No YesDifferent package non-subclass Yes No No No

Example:

package p1;public class protect{

int n=1;private int n_pri=2;protected int n_pro=3;public int n_pub=4;public protect(){System.out.println("Super constructor");System.out.println("default="+n);System.out.println("private="+n_pri);System.out.println("protected="+n_pro);System.out.println("pubic="+n_pub);}

}

package p1;class derive extends protect{

derive(){System.out.println("Sub constructor");System.out.println("default="+n);//System.out.println("private="+n_pri);//since it is a private variable in package p1System.out.println("protected="+n_pro);System.out.println("pubic="+n_pub);}

}

import p1.protect; class same{

public static void main(String[] args) {

protect obj=new protect();}

94

Page 95: Java

www.aspgmca.blogspot.com

}

CLASSPATH

A class path is an environmental variable, which tells the java virtual machine and other java tools (java, javac), where to find the class libraries, including user-defined class libraries.

By default, java uses the classpath as

C:\jdk1.2.1\lib\classes.zip

A user defined class path is set for the environment as

C:\>SET CLASSPATH=%CLASSPATH%;C:\P

***

UNIT – V

EXCEPTION HANDLING

Exception: An exception is an abnormal event that rises during the execution of a program and disturbs the normal flow of instructions i.e., exception is a run-time error.Consider the following example:

class hello {

public static void main(String[] args) {

int a=10,b;

95

Page 96: Java

www.aspgmca.blogspot.com

b=a/0;System.out.println("value="+b);

}}

When we try to compile this program, it does not produce any errors. But when it runs the program it produces a message as “java.lang.ArithmeticException: / by zero”. This exception error message is displayed and the program terminates without executing the remaining statements.

Exception Handling: Exception Handling is designed for error processing. It enables a program to catch all types of exceptions of certain type or related type. Exception handling is designed for dealing with Synchronous errors such as an attempt to divide by zero, out of bounds exception etc., It is not designed to deal with Asynchronous errors such as mouse checks, key strokes etc.,

Exception Handling is used in situation arises the system can recover from causing the exception. The procedure is called Exception Handling and done by the Exception Handler.

All exception types are subclasses of built-in class Throwable. It is a super class. The class is available in java.lang package. It contains errors and exceptions.

Throwable (super class)

Errors Exceptions (Asynchronous) (Synchronous)

Run-time Exceptions IO Exceptions

Java defines several exception classes inside the java.lang package. These are all subclass of Run-time Exceptions. The following are the some of the examples of exceptions and these are unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions.

Exception Meaning

ArithmeticException Arithmetic error, such as divide-by-zeroArrayIndexOutOfBoundsException Array index is out-of-boundsIllegalArgumentException Illegal argument used to invoke a methodIllegalThreadStateException Requested operation not compatible with

current thread stateIndexOutOfBoundsException Some type of index is out-of-boundsNegativeArraySizeException Array created with a negative sizeNullPointerException Invalid use of a null referenceNumberFormatException Invalid conversion of a string to a numeric

formatStringIndexOutOfBounds Attempt to index outside the bounds of a

96

Page 97: Java

www.aspgmca.blogspot.com

string

java.lang package contains some another type of exceptions that does not handle itself. Here, the compiler checks that what is to be done when this arise, because of this checking that they are called checked exceptions. Examples for checked exceptions are

Exception Meaning

ClassNotFoundException Class not foundIllegalAccessException Access to a class is deniedInterruptedException One thread has been interrupted by another

threadNoSuchMethodException A requested method does not exist

Exception-Handling FundamentalsJava exception handling is managed through five keywords. They are 1) try

2)catch 3) throw 4) throws 5) finally. The general format of an exception-handling block is as

Syntax: try{

// block of code to monitor for errors}catch (ExceptionType1 exob){

// exception handler for exception type1}catch (ExceptionType2 exob){

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

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

Here, ExceptionType is the type of exception that has occurred and exob is the exception object.try block: The statements that are produces exception are identified in the program and the statements are placed with in a try block

Syntax: try{

// block of code to monitor for errors}

If an exception occurs within the try block, the appropriate exception handler (catch block) associated with the try block handles the exception immediately.

catch block: The catch block is used to process the exception raised. The catch block is placed immediately after the try block.

Syntax: catch (ExceptionType exob)

97

Page 98: Java

www.aspgmca.blogspot.com

{// exception handler for exception type

}

finally block: This block is placed after the last catch block. This block is executed regardless of whether or not an exception is raised.

Syntax: finally{

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

1. The control enters into the try block and executes the statements. If an exception is raised, the exception throws and it caught by exception handler catch block. And the particular catch block statements are executed. The control never backs again to the try block. If no exceptions raised, catch blocks are not executed the control directly passed to the finally block.

2. No statements are placed between try block and catch block.

Example 1:

class ex11{

public static void main(String[] args) {

try{int a=10,b;b=a/0;System.out.println("b="+b);}catch(ArithmeticException e){System.out.println("Exception raised");}System.out.println("Quit");

}}

O/P: Exception raisedQuit

Example 2:

class ex12{

public static void main(String[] args) {

int x[]=new int[10];try{

98

Page 99: Java

www.aspgmca.blogspot.com

x[20]=100;}catch(ArrayIndexOutOfBoundsException e){System.out.println("Exception caught");}finally{System.out.println("Not possible to print");System.out.println("Quit");}

}}

Methods of Exception Object

a) String getMessage( ): It returns the descriptive string stored in an exception.Example: / by zero

b) String toString( ): It returns an error message with the class name of the exception the descriptive string to be stored in the exception.

Example: java.lang.ArithmeticException: / by zero

package

class

string

c) void printStackTrace( ): This is the standard output error stream. It displays the error message with the class name of the exception the descriptive string to be stored in the exception along with the line number and name of the program.

Example: java.lang.ArrayIndexOutOfBoundsExceptionat ex12.main (ex12.java:8)

class name file name

method name line number

Example 1:

class ex12{

public static void main(String[] args) {

int x[]=new int[10];try{x[20]=100;}

99

Page 100: Java

www.aspgmca.blogspot.com

catch(ArrayIndexOutOfBoundsException e){System.out.println(e.getMessage());System.out.println(e.toString());e.printStackTrace();}

}}

Example 2:

class ex12{

public static void main(String[] args) {

String s=new String("Java programming language");try{System.out.println(s.substring(45));}catch(StringIndexOutOfBoundsException e){System.out.println(e.getMessage());System.out.println(e.toString());e.printStackTrace();}

}}

Example 3:

import java.text.DecimalFormat;class n {

public static void main(String[] args) {

try{double x=25.6776;DecimalFormat d=null;System.out.println(d.format(x));}catch(NullPointerException e){System.out.println(e.getMessage());System.out.println(e.toString());e.printStackTrace();}

}}

100

Page 101: Java

www.aspgmca.blogspot.com

Multiple Catch StatementsMultiple catch clauses handle the situation where more than one exception could

be raised by a single piece of code. In such situations specify two or more catch blocks, each specify different type of exception. Multiple catch statements are arranged in respective order of exceptions that araised by the try block (optional).

Example:

class cat {

public static void main(String[] args) {try{int a=args.length;System.out.println("a="+a);int b=42/a;int c[]={1};c[42]=99;}catch(ArithmeticException e){System.out.println(e.getMessage());}catch(ArrayIndexOutOfBoundsException e){System.out.println(e.getMessage());}}

}

Note: A subclass must come before their super classes in a series of catch statements. Exception class is the super class of all exceptions.

Example:

class cat1{

public static void main(String[] args) {try{int a=0;int b=42/a;}catch(ArithmeticException e){System.out.println(e.getMessage());}catch(Exception e)

101

Page 102: Java

www.aspgmca.blogspot.com

{System.out.println(e.getMessage());}}

}

Nested try StatementsA try block is placed inside the block of another try block is termed as Nested try block statements. If any error statement is in outer try block it goes to the corresponding outer catch block. If any error statement is in inner try block first go to the inner catch block. If it is not the corresponding exception next goes to the outer catch, which is also not corresponding exception then terminated.

Example:

class ntry {

public static void main(String[] args) {

try{int a=args.length;int b=42/a;System.out.println("a="+a);try{if(a==1)a=a/(a-a);if(a==2){int c[]={1};c[42]=99;}}catch(ArrayIndexOutOfBoundsException e){System.out.println("Array Exception:"+e);}}catch(ArithmeticException e){System.out.println("Arithemetic exception:"+e);}

}}

Example:

class ntry1{

102

Page 103: Java

www.aspgmca.blogspot.com

public static void main(String[] args) {

try{int a=args.length;int b=42/a;System.out.println("b="+b);}catch(ArithmeticException e){System.out.println("Arithemetic exception:"+e);}finally{System.out.println("final block");}System.out.println("after try block");

}}

throw statementAll previous exceptions are catching that are thrown by the java run time system. It is also possible to create for a program that throws an exception explicitly, using the “throw” statement. The general format of throw statement is

Syntax: throw throwable-instance;Here, throwable-instance must be an object type of Throwable class or subclass of Throwable. There are two ways to obtain a Throwable object.

1. Using a parameter into a catch clause2. Creating one with the new operator

Example:

class ntry2{

public static void main(String[] args) {

try{throw new ArithmeticException("hello");}catch(ArithmeticException e){System.out.println(e.getMessage());}

}}

O/P: hello

Example:

103

Page 104: Java

www.aspgmca.blogspot.com

class t{

public t(){try{throw new NullPointerException("demo");}catch(NullPointerException e){System.out.println("caught");throw e; //rethrow the exception}}

}class ntry2{

public static void main(String[] args) {

try{t obj=new t();}catch(NullPointerException e){System.out.println("Recaught");}

}}

O/P: caughtRecaught

throws statementIf a method is capable of causing an exception that it doesn’t handle, it must specify the behavior to the callers of the method can guard themselves against that exception. This can be done by throws statement in the method declaration.

A throws statement lists the types of exceptions that a method might throw. This is necessary for all exceptions except that 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 statement. Otherwise, it reports compile time error. The general format of throws statement is as

Syntax: type method-name(parameter-list) throws exception-list{

// method body}

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

Example:

104

Page 105: Java

www.aspgmca.blogspot.com

class t{

public t()throws NullPointerException{System.out.println("caught");throw new NullPointerException("demo");}

}class ntry3{

public static void main(String[] args) {

try{t obj=new t();}catch(NullPointerException e){System.out.println("Recaught");}

}}

O/P: caughtRecaught

User-defined ExceptionsIt is also possible to create our own exceptions types to handle situations specific to our application. Such exceptions are called User-defined Exceptions. User-defined exceptions are created by extending Exception class. The throw and throws keywords are used while implementing user-defined exceptions.

Example:

class own extends Exception {

own(String msg){super(msg);}

}class Test1{

public static void main(String[] args) {

try{int mark=Integer.parseInt(args[0]);if(mark>100)

105

Page 106: Java

www.aspgmca.blogspot.com

{throw new own("Greater than 100");}System.out.println("Marks="+mark);}catch(own e){System.out.println("Exception caught");System.out.println(e.getMessage());}finally{System.out.println("completed");}

}}

O/P: Exception caughtGreater than 100completed

MULTITHREADED PROGRAMMING

106

Page 107: Java

www.aspgmca.blogspot.com

A Multithreaded program contains two or more parts that can run concurrently. Each part of such program is called a thread, and each thread defines a specific path of execution. Multithreading is a specialized form of Multitasking.

Multitasking: All modern operating systems support the concept of multitasking. Multitasking is the feature that allows the computer to run two or more programs concurrently. CPU scheduling deals with the problem of deciding for which of the process, the ready queue is to be allocated. It follows CPU (Processor) scheduling algorithms.

a) Priority Scheduling:

Process Burst time Priority

P1 10 2 P2 01 4 P3 02 2 P4 01 1 P5 05 3

0 1 6 16 18 19

The priority scheduling follows on Sun Solaris systems. But it doesn’t work on the present operating systems like windows NT etc., The thread with a piece of system code is called the thread scheduler. It determines which thread is running actually in the CPU.

The Solaris java platform runs a thread of given priority to completion or until a higher priority thread becomes ready at that point preemption occurs.

b) Round-Robin Scheduling:

Process Burst time

P1 24 P2 10 P3 03

Time Quantum (or) Time Sliced : 04

0 4 8 11 15 19 23 25 29 33 37

Round Robin scheduling is available on Windows 95 and Windows NT is time sliced.

107

P2 P5 P1 P3 P4

P1 P2 P3 P1 P2 P1 P2 P1 P1 P1

Page 108: Java

www.aspgmca.blogspot.com

Java supports thread implementation depending on round robin scheduling. Here, each thread is given a limited amount of time called time quantum. While executing the process when that time quantum expires the thread is made to wait state and all threads that are equal priority get their chances to use their quantum in round robin fashion.

Difference between Multiprocessing and Multithreading

Multiprocessing Multithreading

1. More than one process running simultaneously 1. More than one thread running simultaneously

2. Its part of a program 2. Its part of a program3. It’s a heavy wait process 3. It’s a light wait process4. Process is divided into threads 4. Threads are divided into

sub threads5. There is no communications between 5. Within the process threads are

processors directly communicated

Note: 1. Java provides built-in support for multithreaded programming2. Java multithreading is a platform independent3. Elimination of main loop/polling is the main benefit of multithreaded

programming.

Thread States (or) Lift-Cycle of a ThreadThe life cycle of a thread contains several states. At any time the thread is falls

into any one of the states.

The thread that was just created is in the born state. The thread remains in this state until the threads start method is called. This

causes the thread to enter the ready state. The highest priority ready thread enter the running state when the system assigns

a processor to the thread i.e., the thread begins executing. When a running thread calls wait the thread enters into a waiting state for the

particular object on which wait was called. Every thread in the waiting state for a given object becomes ready on a call to notify all by another thread associated with that object.

When a sleep method is called in a running thread, that thread enters into the suspended (sleep) state. A sleeping thread becomes ready after the designated sleep time expires. A sleeping thread cannot use a processor even if one is available.

A thread enters the dead state when its run( ) method complete (or) terminates for any reason. A dead thread is eventually be disposed of by the system.

108

Page 109: Java

www.aspgmca.blogspot.com

One common way for a running thread to enter the blocked state is when the thread issues an input or output request. In this case a blocked thread becomes ready when the input or output waits for completes. A blocked thread can’t use a processor even if one is available.

Thread class constructors

1. Thread( )2. Thread(String Threadname)3. Thread(Runnable obj)4. Thread(Runnable obj, String name)5. Thread(ThreadGroup tg, String Threadname)

Methods

1. String getName( ): It obtains the name of the thread.2. void setName(String str): It sets the name of the thread.3. int getPriority( ): It obtains the priority of the thread.4. void setPriority(int): It sets the priority of the thread.5. boolean isAlive( ): Determines if a thread is still running or not. It returns true if the thread upon which it is called is still running. Otherwise, it returns false.6. void sleep(long milliseconds): Suspend a thread for a period of time.7. void start( ): Start a thread by calling its run method.8. void run( ): It defines the code that constitutes the new thread. When ever the start( ) method executes it automatically call of run( ) method.9. void join( ): This method waits until the thread on which it is called terminates.10. Thread currentThread( ): It returns a reference to the currently executing thread.11. void yield( ): A thread can call the yield method to give other threads a chance to execute.12. ThreadGroup getThreadGroup( ): It returns the name of the thread group which contain currently running thread. ThreadGroup represents set of Threads. It has one constructor method as ThreadGroup(String name).

Main Thread: When a java program starts up, one thread begins running immediately. This one is main thread, which is created by virtual machine. It is executed in the program for the first time. It must be the last thread to finish execution. When the main thread stops the program terminates.

Even though the main thread is automatically created when the program starts, it can be controlled through Thread object. For this we obtain a reference to by calling the method “currentThread( )”.

Example:

class demo {

public static void main(String[] args) {Thread obj=Thread.currentThread();System.out.println("current="+obj);obj.setName("india");

109

Page 110: Java

www.aspgmca.blogspot.com

System.out.println("after="+obj);}

}

O/P: current=Thread[main,5,main]after=Thread[india,5,main]

Example:

class demo {

public static void main(String[] args) {Thread obj=Thread.currentThread();try{for(int n=5;n>0;n--){System.out.println(n);obj.sleep(1000);}}catch(InterruptedException e){System.out.println("exception");}}

}

Creating a new ThreadA new thread can be created in two ways 1. implements the Runnable interface2. extends the Thread class itself

1. implements the Runnable interface: Runnable is a system defined interface. Once we create a class, it implements the Runnable interface forms a thread class. To implement Runnable, a class need only implement a single method called run( ).

Example:

class new1 implements Runnable{

Thread t;public new1(){t=new Thread(this,"child thread");System.out.println("sub thread="+t);t.start();}public void run(){

110

Page 111: Java

www.aspgmca.blogspot.com

try{for(int n=5;n>0;n--){System.out.println("child="+n);Thread.sleep(500);}}catch(InterruptedException e){System.out.println("child exception");}System.out.println("child exit");}

}class demo1{

public static void main(String[] args) {new new1();try{for(int n=5;n>0;n--){System.out.println("main="+n);Thread.sleep(1000);}}catch(InterruptedException e){System.out.println("main exception");}System.out.println("main exit");}

}

2. extending the Thread class: The second way to create a thread is to create a new class that extends Thread, and then create an instance of that class. The extending class must override the run( ) method. It must also call start( ) to begin execution of the new thread.

Example:

class newthread extends Thread{

public newthread(){super("child thread");System.out.println("sub thread="+this);start();}

111

Page 112: Java

www.aspgmca.blogspot.com

public void run(){try{for(int n=5;n>0;n--){System.out.println("child="+n);Thread.sleep(500);}}catch(InterruptedException e){System.out.println("child exception");}System.out.println("child exit");}

}class demo2{

public static void main(String[] args) {new newthread();try{for(int n=5;n>0;n--){System.out.println("main="+n);Thread.sleep(1000);}}catch(InterruptedException e){System.out.println("main exception");}System.out.println("main exit");}

}

Example:

class a extends Thread{

public void run(){for(int n=0;n<5;n++){if(n==3)yield();System.out.println("child 1="+n);}}

112

Page 113: Java

www.aspgmca.blogspot.com

}class b extends Thread{

public void run(){for(int n=0;n<5;n++){try{sleep(1000);}catch(Exception e){}System.out.println("child 2="+n);}}

}

class c extends Thread{

public void run(){for(int n=0;n<5;n++){if(n==2)stop();System.out.println("child 3="+n);}}

}

class demo3{

public static void main(String[] args) {a obj=new a();b obj1=new b();c obj2=new c();obj.start();obj1.start();obj2.start();}

}

Example:

class b implements Runnable{

Thread t;b(String tname)

113

Page 114: Java

www.aspgmca.blogspot.com

{t=new Thread(this,tname);t.start();}public void run(){try{for(int n=0;n<5;n++){System.out.println("child 1="+n);//sleep(1000); can't work in the case implementing interfaceThread.sleep(1000);}}catch(InterruptedException e){System.out.println("child exception");}}

}

class demo4{

public static void main(String[] args) {b obj1=new b("one");b obj2=new b("two");System.out.println("b is alive:"+obj1.t.isAlive());System.out.println("c is alive:"+obj2.t.isAlive());try{obj1.t.join();obj2.t.join();}catch(InterruptedException e){System.out.println("child exception");}System.out.println("b is alive:"+obj1.t.isAlive());System.out.println("c is alive:"+obj2.t.isAlive());}

}

Thread Priorities

Every thread in Java is assigned a priority value, when more than one thread is computing for CPU time. Generally highest priority thread is running before the lowest priority thread. It is also possible to set priority to each thread by the user using setPriority( ) method. System defined thread priorities are

114

Page 115: Java

www.aspgmca.blogspot.com

Thread.MIN_PRIORITY 1Thread.MAX_PRIORITY 10Thread.NORM_PRIORITY 5

The default priority is Thread.NORM_PRIORITY

Example:

class Demo extends Thread{

public void run(){

for(int i=1;i<=3;i++)System.out.println(getName()+" "+i);

}}class ThprDemo {

public static void main(String[] args) {

Demo obj=new Demo();Demo obj1=new Demo();Demo obj2=new Demo();obj.setPriority(Thread.MAX_PRIORITY);obj1.setPriority(Thread.MIN_PRIORITY);obj2.setPriority(Thread.NORM_PRIORITY);obj.start();obj1.start();obj2.start();

}}

O/P: Thread-1 1Thread-1 2Thread-1 3Thread-3 1Thread-3 2Thread-3 3Thread-2 1Thread-2 2Thread-2 3

SynchronizationWhen two or more threads need access to a shared resource, they need someway

to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called Synchronization. Java uses the concept of monitor (also called Semaphore) for Synchronization.

A monitor is an object that is used as a mutually exclusive lock, or mutex. The monitor allows one thread at a time to execute a Synchronized method on the object.

115

Page 116: Java

www.aspgmca.blogspot.com

116