Comments
Description
Transcript
How java program run :- Bytecode: -
How java program run :To understand how java program run, we must understand about two new terms. These are Bytecode and Virtual machine (VM). Bytecode: - This code is actually platform independent. We can consider it as a machine code. When you compile an anyfile.java file successfully, you can get this code. It is in the form of anyname.class file. Virtual Machine:- The name virtual suggests that this is not an actual machine. It is just a program which simulates a machine on which java programs are supposed to run. Actually, you can suppose that is a hardware which runs programs in Bytecode. Source Code Java Compiler Byte Code Output Java Interpreter Fig shows the compilation process and interpreted stage. (Running a Java Program) Difference between Java Applets and Java Application :We can use java for two types of programs, namely applets and applications. Applets are executed in (Java Enabled) web Browsers. Applets are like a small java program. It can be dynamically downloaded from the internet. Applications are programs similar to the ones that we find in any other languages. Since they do not need a browser, they are sometimes referred to as stand-alone application. Advantage of Java technology :1. Get started quickly: - Although the java programming language is a powerful objectoriented language, it’s easy to learn, especially for programmers already familiar with C or C++. 2. Write less code: - Comparisons of program metrics suggest that a program written in the java programming language can be four times than the same program in C++. 3. Write better code:- The java programming language encourages good coding practices, and its garbage collection helps you avoid memory leaks. Its object orientation, its java Beans component architecture, and its wide- ranging, easily extendible API let you reuse other people’s tested code and introduce fewer bugs. 4. Develop program faster:- Your development time may be as much as twice and fast versus writing the same program in C++. 5. Avoid platform independencies with 100% pure java:- You can keep your program portable by following the purity tips mentioned throughout this tutorial and avoiding the use of libraries written in other language. 6. Write once run anywhere:- Because 100% pure java programs are compiled into machine independent Bytecode, they run consistently on any java platform. 1 Amit Kumar 7. Distribute software more easily:- You can upgrade applets easly from a central server. Applets take advantage of the feature of allowing new classes to be loaded “on the fly,” without recompiling the entire program. Java Development Kit Tools :The JDK is a development environment for building applications, applets, and the components using the java programming language. In more technical terms, the current version is called Java TM Platform, Standard edition 6 JDK. The JDK 6 includes tools useful for developing and testing programs written in java. They help us to running them on the java platform. These tools are designed to be used from the command line. They do not provide a GUI. The only exception is the “appletviewer”. Let us describe the contents of JDK 6 in details. 1. Development tools :- Tools and utilities that will help one to develop, execute, debug, and document program written in the java programming language are provided in the “bin” subdirectory. These tools are the foundation of the JDK 6.The basic tools are describe in the given below: a. Javac The compiler of java programming language. b. Java The launcher for java applications. In this release, a single launcher used for both development and deployment. c. Javadoc API documentation generator. d. Appletviewer Run and debug applets without a web browser. e. Jar Manage java Archive (JAR) files. f. Jdb The java debugger. g. Javah C header and sub generator. used to write native methods. h. Javap Class file disassemble. 2. Runtime Environment :- An implementation of the java 2 runtime environment for use by the SDK. The runtime environment includes a JVM, Class libraries, and other files that support the execution of program written in the java programming language. These are present in “jre” sub directory. 3. Addition documentation:- Addition class libraries and support files required by the development tools are present in the “lib” sub directory. Etc…………. 2 Amit Kumar Chapter-3 Java Language Basic Java Program structure :public class <Class Name> { public static void main(String arg[]) { <Datatypes>; ……………………. <Set of codes>; } } Example:- File Name- FirstJava.java public class FirstJava { public static void main(String arg[]) { System.out.println(“This is my first java program”); } } Compile and execute the program:C:\>javac FirstJava.java C:\>java FirstJava This is my first java program C:\> Basic Building Block. Any java program consist of few building blocks like comments, declarations statements and methods. These blocks are formatted by some small atomic quantity is known as tokens. Comments :- Comments are that part of the program, which are supported to give more information to the reader. They increase the readability of the program. The compiler does not convert it in to code.(We may say that compiler ignore it.). In java, the comments are enclosed in pair of /* and */, such comments can be of one or more lines. In addition java uses double slash (//) for single line comments. Any text from // to be end of that line is treated as comment. Variables & Data Types:Variable:- Variable is a name location in memory which holds the constant. According to programming rule variable is an identifier. Hence, rule for formatting variables same as those for formatting identifiers. Rules for variable names can be started as follows: 1. Variable names are formatted with the help of letters and digits. 2. Alphabets can be in upper or lower case. 3. Only letters are allowed as far as string character. Underscore character (_) and Dollar ($) are treated as letter as far as variables re concerned. 3 Amit Kumar 4. The first character cannot be a digit. 5. There is no restriction on number of characters in variables. 6. As white space characters are used to separate tokens, they cannot be a part of variables. Keywords in java abstract assert Boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while Data Types:- The Data that is stored in memory can be of many types for example a person’s age is store as a numeric value and an address is stored as alphanumeric characters. Data type are use to define the operations possible on them and the storage method. The data type in java is classified in two types:1. Primitive or slandered data type. 2. Abstract or derived data type. 1. Primitive or slandered data type. Primitive data type also known as standard data types, are the data types that are built into the java language. The java compiler contains details introduction on each legel option supported by the data type. There are eight data types in java i.s; I. byte 1 Byte (8 Bits). -128 to 127 II. short 2 Byte (16 Bits). -32768 to 32767 III. int 4 Byte (32 Bits). -2147473648 to 2147473647 IV. long 8 Byte (64 Bits). -9223372036854775808 to 9223372036854775807 V. float 4 Byte (32 Bits). -3.4E38 to +3.4E38 VI. double 8 Byte (64 Bits). -1.7E308 to +1.7E308 VII. char 2 Byte (16 Bits). VIII. boolean 2 Byte (16 Bits). NOTE :- Data is internally separated as binary digits (0 and 1).Bits stand for binary digit. A bit can store either 0 or 1. 2. Abstract or Derived data type. Abstract data types are base on primitive data type and have move functionality than primitive data type. For example String is an abstract data type. That can store letters digits and others character like /, (, ), :, ;, $, #,……. The data type cannot perform calculations on a variable of a String data type even if the data stored in it has digits. However String provides methods for one String within another extracting the position of a string. The primitive data type does not have these features. 4 Amit Kumar Conversions / Typecasting :- Java supports two type of conversion I.e. Widening conversion/ Implicit conversion or Narrowing conversion/ Explicit conversion. 1. Widening Conversion :- Widening conversion(Implicit conversion) take place in java when the following condition make true. a. The source and target/destination type must be compatible. b. The target size / capacity must be greater than or equal to source size /capacity. Use:Variable=value/variable/expression; Automatically / Implicitly Target Source -: Widening Conversion or Implicit Conversion:- Example:1. public class Wconversion1 { public static void main(String arg[]) { byte a,b; b=20; a=b; //Widening conversion. System.out.println(“Value of a= “+a); System.out.println(“Value of b= “+b); } } 2. public class Wconversion2 { public static void main(String arg[]) { byte a; int b; a=20; b=a; //Widening conversion. System.out.println(“Value of a= “+a); System.out.println(“Value of b= “+b); } } 2. Narrowing Conversion(Explicit Conversion):- When target size/capacity is less than the source size or capacity or when the source size is greater than the target size, and explicitly conversion required to assign value to smaller size using the syntax given below: Use:5 Amit Kumar Target_type Variable= (Target_type) variable; Or Target_type variable= (Target_type)(Expression); Explicitly Target Source -: Narrowing Conversion or Explicit Conversion:When source is explicitly cast in to smaller type, the conversion involved is referred to as narrowing or explicit conversion. Example:1. public class Nconversion1 { public static void main(String arg[]) { byte a; int b=20; // a=b; //Error (Int valu cannot assign in byte type). a = (byte)b; //Narrowing Conversion. System.out.println(“Value of a= “+a); System.out.println(“Value of b= “+b); } } 2. public class Wconversion2 { public static void main(String arg[]) { byte a,b=10; // a=b*5; //Error (Int valu cannot assign in byte type). a= (byte)(b*5); System.out.println(“Value of a= “+a); System.out.println(“Value of b= “+b); } } Automatically Type Promotion Rule:- Java Automatically promotes: a. b. All byte, short and char type in an expression to integer type. A float variable is initlised at the time of declaring variable to overcome this problem either use double data type or postfix the value with character “f”. Example:6 Amit Kumar 1. public class Aconversion1 { public static void main(String arg[]) { // float a=2.45 ; //Error (Double value cannot assign in float type). float a=2.45f; System.out.println(“Value of a= “+a); } } How to create object in java:- An object in java is a combination of instance variable(Attributes) and methods to work on instance variables, methods must be define and methods is the only way to access the instance variable and instance variable must be encapsulated. A class (Which define object type) in java is a logical frame work and object is physical reality. An object in java is always created dynamically (That is at run time) to create an object in java is a two step process as follows: Step 1:At first create object reference variable in the following format to hold internally the reference of allocated object. Syntax: <Class name/object type> <obj_ref_variable1>,<obj_ref_variable2>,….; Step 2:Secondary create object using new operator in the following format and assign object reference variable to object reference variable. Syntax: <obj_ref_variable1>= new <Class name>( ); Note:- Class name is same as class name of first step. These two steps can be combined in to one. Syntax: <Class name/object type> <obj_ref_variable1>= new <Class name/object type>( ); Note:- An object in java is cannot be of primitive. Console input in Java :Java provides a package named “IO” which contains two important classes named BufferedReader and InputStreamReader which is responsible to accept input from standard input device I,e; keyboard. 7 Amit Kumar In order to create object of these classes to read date from console input iopackage must required to be explicitly import in the user program. import java.io.*; To accept input from standard input device follow the following steps:Step1:- At first create BufferedReader object in the following format. BufferedReader <object>=new BufferedReader(new InputStreamReader(System.in)); Step 2:- Read the data in the local variables using BufferedReader method readLine() in the following format. <Variable>=<BufferedReader Object>.readLine(); Note:- readLine() converts the data in to the String. String in java is an object of class String. Convert String to Numeric type:At the time of accepting value through keyboard we will change the String type value in the numeric type. We will use the following methods: <Numeric var.>=<Numeric wrapperclass>.valueOf(<BufferedReader_obj.>.readLine()).num_typeValue(); Example1:import java.io.*; public class InputTest1 { public static void main(String arg[])throws IOException { BufferedReader obj=new BuggeredReader(new InputStreamReader(System.in)); String str1; System.out.println(“Enter a string”); Str1=obj.readLine(); System.out.println(“Inputed String is “+ str1); } } Example2:import java.io.*; 8 Amit Kumar public class InputTest2 { public static void main(String arg[])throws IOException { BufferedReader obj=new BuggeredReader(new InputStreamReader(System.in)); int num; System.out.println(“Enter a number”); Num=Integer.valueOf(obj.readLine()).intValue(); System.out.println(“Inputed number is “+num); } } Note:- At the time of input with the help of standard input device i.e; keyboard a exception will be raised, which exception is known as IOException that is handle by the system with the help of throws keyboard. -:Operators:Operators perform operations on operands. Operands may be one two or three. Operands are either variables or constants. The operators, which take single operand are called unary operators. Those takes two operands are known as binary operators and one having three operands is known as ternary operator. Most of the operators are binary operators, few are unary while there is only one ternary operator (for example “?:” operator). Arithmetic operators. Assignment operators. Relational operators. Logical operators. Unary operators. Bitwise operators. Others operators. 1. Arithmetic operators:+ * / % (Addition) (Subtraction) (Multiplication) (Division) (Modulo Division)(Remainder) Note :1. When the use of plush (+) operator use with numeric operands, the result is numeric when both the operands are Strings the plush operator concatenates (joins) then when one of the operands is a String objects, the second operand is converted in to String before concatenation. 9 Amit Kumar Example:- Operend1 + Operend2 = Result 5 6 11 5 “ABC” 5ABC “ABC” 5 ABC5 “ABC” “XYZ” ABCXYZ 2. Java use toString() method of java.lang.object class to convert data to the String Data Type. Example1:import java.io.*; public class ArithmeticOperator { public static void main(String arg[])throws IOException { BufferedReader obj=new BuggeredReader(new InputStreamReader(System.in)); int rad; float circlearea,pi=3.14f; System.out.println(“Enter a radius of circle”); rad=Integer.valueOf(obj.readLine()).intValue(); circlearea=pi*rad*rad; System.out.println(“Area of circle is “+circlearea); } } 2. Assignment Operator :We have seen equal to (=) is a basic assignment operator. It assigns value on right hand side to variable on left hand side. Var = <constant/variable/expression>; Example:Marks=90; Note:To handle such situation java provides some shortcut assignment operator, with the combination of arithmetic operator and assignment operator. i.e; += Assign Sum a+=20; a=a+20; -= Assign Difference a-=20; a=a-20; *= Assign Product a*=20; a=a*20; /= Assign Quotient a/=20; a=a/20; %= Assign Remainder a%=20; a=a%20; 3. Relational Operator :When we use relational operator in an expression it returns Boolean Value true or false. Java provides these relational operators. 10 Amit Kumar < <= > >= == != Less than less than or equal to Greater than Greater than or equal to Equal to Not equal to 4. Logical Operator :The logical operator combines the result of Boolean expressions. The following logical operators used in java are: &&(Logical And) :Evaluates to true if both the conditions evaluate to true, false if otherwise. Example X=5; Y=10; x>=5 x>=5 x<5 x>5 && && && && y==10 y>10 y==10 y<10 true false false false ||(Logical or) :Logical or operator evaluates to true if at least one of the condition true, and false if none of the conditions evaluates to true. Example X=5; Y=10; x>=5 || y==10 true x>=5 || y>10 true x<5 || y==10 true x>5 || y<10 false !(Logical Not) :This operator is used to change the true to false and false to true. It is an unary operator. Example Y=10; !(y==10) !(y>10) false true 5. Unary Operator :Java support basically two unary operator. I.e; ++ :Increase the value of the operand by one. 11 Amit Kumar Ex:X=10; X++; ++X X=11; X=11; -- :Decrease the value of the operand by one. Ex:X=10; X--; --X X=9; X=9; Note: - Increment (++) and Decrement (--) operator is used as postfix and prefix order. If it is used as postfix then first drop the value of operand first after that performs the job of operator. And in case of prefix first perform the job of operator and lastly drop the value of operands. 6. Bitwise Operator :Those types of operator which perform own job upon the smallest unit of memory (Bits) is known as bitwise operators. Java supports following bitwise operators: 1. 2. 3. 4. 5. 6. & | ^ ~ >> << Bitwise And Bitwise Or Bitwise XOR Bitwise Complements. Bitwise Right Shift Bitwise Left Shift 7. Others Operator :1. Conditional Operator:Syntax: (Condition)?value1:value2; This operator evaluates the value 1 if the condition result return true and value2 if the condition returns false. Example:X=(y>z)?y:z; X is assigned the value of y if y is greater than z else x is assigned the value of z. 2. New Operator:When user creates an instance of a class, user needs to allocate memory for it. When user declares an object, user merely states its data type. Syntax 12 Amit Kumar Class name object_ref_variable=new Class Name(); Or Class name object_ref_var1,Object_ref_var2,…; Object_ref_var1=new Class name(); Order of precedence of operator Operator Precedence Group Associativity 1. (), [], Postfix ++, Postfix -- Left 2. Unary +, Unary-, Prefix ++, Prefix--, ~, ! Right 3. (type), new Left 4. *, /, % Left 5. +, - Left 6. <<, >>, >>> Left 7. <, <=, >, >= Left 8. ==, != Left 9. & Left 10. | Left 11. && Left 12. || Left 13. ?: Left 14. =, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, |=, ^= Right Final Keyword:The variables are for holding different values at different times. If we want to keep a value constant, we may declare a variable as final. Such a variable has initialized only once. final <data type> var=value; Example:- final int num=30; -: Control Statement:Java supports three type of control statement for controlling the set of statements. These are: 1. Selection Statement 2. Looping Statement 13 Amit Kumar 3. Jump Statement 1. Selection Statement :Java supports two type of selection statement, if and switch. These statements allow controlling the flow of our programs execution based upon conditions known only during run time. if … construct:- (a) The if decision construct is followed by a logical expression in which data is compared and decision is made based on the result of the comparison. Syntax if(<Boolean expression>) { <Set of Statements>; } else { <Set of statements>; } Example: public class IfElse1 { public static void main(String arg[]) { int x=20; int y=30; if(x>y) { System.out.println(“X is greater than Y”); } else { System.out.println(“Y is greater than X”); } } } (b) Nested if … construct:14 Amit Kumar A nested if is an if statement that is the target of another if or else. Nested if is very common in programming. Syntax if(<Boolean expression>) { <Set of Statements>; if(<Boolean expression>) { <Set of Statements>; } else { <Set of statements>; } } else { <Set of statements>; if(<Boolean expression>) { <Set of Statements>; } } Example: public class IfElse2 { public static void main(String arg[]) { int x=20; int y=30; int z=40; if(x>y) { if(x>z) { System.out.println(“X is greater”); } else { if(z>y) 15 Amit Kumar { System.out.println(“Z is greater”); } } } else { if(y>z) { System.out.println(“Y is greater”); } else { System.out.println(“Z is greater ”); } } } } (c) If-else-if … construct:Java supports an else-if word. By using it we will check the condition in option part of our conditional statement. Syntax if(<Boolean expression>) { <Set of Statements>; else if(<Boolean expression>) { <Set of Statements>; } else if(<Boolean expression>) { <Set of statements>; } else { <Set of statements>; } Example: public class IfElseIf1 { public static void main(String arg[]) 16 Amit Kumar { int x=20; int y=30; int z=40; if(x>y&&x>z) { System.out.println(“X is greater”); } else if(y>x&&y>z) { System.out.println(“Y is greater”); } else { System.out.println(“Z is greater ”); } } } (d) Switch case:Switch case structure is used to execute sequence of statements based on selection specified with case statements. Syntax switch (choice) { case 1: <Set Of Statements>; break; case 2: <Set Of Statements>; break; case 3: <Set Of Statements>; break; default: <Set Of Statements>; } Note: Only constraint numeric and character value are allowed with case statements. Variable or expression is allowed within the parenthesis of switch case. Default is optional and can be used if required. Break within switch can be used to break the control of execution and continue on resume it just very next close curly braces encountered. The switch case is internally working on numeric constant. 17 Amit Kumar Maximum of 33 switch structure can be a target of another switch. Example import java.io.*; public class SwitchCase { public static void main(String arg[])throws IOException { BufferedReader obj=new BuggeredReader(new InputStreamReader(System.in)); int dno; System.out.println(“Enter day Number”); dno=Integer.valueOf(obj.readLine()).intValue(); switch(dno) { case 1: System.out.println(“SunDay”); break; case 2: System.out.println(“MonDay”); break; case 3: System.out.println(“TuesDay”); break; case 4: System.out.println(“WedDay”); break; ……….. case 7: System.out.println(“SaturDay”); break; default : System.out.println(“Invalid Day Number”); break; } } } 18 Amit Kumar 2. Looping Statement :A loop causes a section of a program to be repeated a certain number of times. The repetition continues while the condition becomes false. The loop ends and the control are passed to the statement following the loop. Java support three looping constructs While … loop Do … while loop For … loop While loop:The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as: Syntax while (expression) { <Set of statement(s)>; < Increment /Decrement>; } NOTE: The while statement evaluates expression, which must return a Boolean value. If the expression evaluates to true, the while statement executes the set of statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. Increment/ Decrement statement is required to break the loop in certain period. If no Increment/ Decrement statement is found in the body of loop, the loop becomes infinite. Example public class WhileDemo { public static void main(String[] args) { int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } } 19 Amit Kumar Do…While loop:- In some conditions in java, you need to run some statements and processes once at least. For that you have to use the do while loop in after that check the condition then we use the dowhile loop statement. do-while loop is same as the while loop statement but while loop checks the certain condition is first and if condition is true then statements or processes are executed otherwise all the statements written under the while loop is ignored by the interpreter but do - while loop executes all the statements first at once and then check the condition if the condition is true then all the statements are also executed in second times otherwise second times ignored all the statements. Syntax do { <Set of statement(s)>; < Increment /Decrement>; }while(condition); NOTE: In a do…while structure the condition is checked at the end /bottom so, if very first time condition is false, the loop body executed at the last one time. The do…while loop is basically used for menu driven programming. The condition terminated by semicolon. Example public class DoWhile { public static void main(String[] args) { int n = 12345; int t,r = 0; System.out.println("The original number : " + n); do { t = n % 10; r = r * 10 + t; n = n / 10; }while (n > 0); System.out.println("The reverse number : " + r); } } 20 Amit Kumar For loop:- The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. Syntax for (initialization; termination; increment) { <Set of statement(s)>; } NOTE: The initialization expression initializes the loop; it's executed once, as the loop begins. When the termination expression evaluates to false, the loop terminates. The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value. Example public class ForDemo { public static void main(String[] args) { for(int i=1; i<11; i++) { System.out.println("Count is: " + i); } } } 3. Jump Statement :Java support four jump statements; break, continue, return an exit(). These statements transfer control to another part of program. Break: The break statement is used in many programming languages such as c, c++, java etc. Sometimes we need to exit from a loop before the completion of the loop then we use break statement and exit from the loop and loop is terminated. The break statement is used in while loop, do - while loop, for loop and also used in the switch statement. Break statement is used in java for jump the control very next close curly braces. And execute continue the program. 21 Amit Kumar Syntax break; Example:- Checking prime number with in 1 to 50 public class Break { public static void main(String[] args) { int i,j; System.out.println("Prime numbers between 1 to 50 : "); for (i = 1;i < 50;i++ ) { for (j = 2;j < i;j++ ) { if(i % j == 0) { break; } } if(i == j) { System.out.print(" " + i); } } } } Continue: The continue statement is used in many programming languages such as C, C++, java etc. Sometimes we do not need to execute some statements under the loop then we use the continue statement that stops the normal flow of the control and control returns to the loop without executing the statements written after the continue statement. There is the difference between break and continue statement that the break statement exit control from the loop but continue statement keeps continuity in loop without executing the statement written after the continue statement according to the conditions. Syntax continue; 22 Amit Kumar Example 1:public class MainClass { public static void main(String[] args) { for (int i = 0; i < 10; i++) { if (i == 5) { continue; } System.out.println(i); } } } Example 2:public class MainClass { public static void main(String[] args) { int limit = 20; int factorial = 1; OuterLoop: for (int i = 1; i <= limit; i++) { factorial = 1; for (int j = 2; j <= i; j++) { if (i > 10 && i % 2 == 1) { continue OuterLoop; } factorial *= j; } System.out.println(i + "! is " + factorial); } } } 23 Amit Kumar Example 3:public class MainClass { public static void main(String[] args) { int nValues = 50; OuterLoop: for (int i = 2; i <= nValues; i++) { for (int j = 2; j < i; j++) { if (i % j == 0) { continue OuterLoop; } } System.out.println(i); } } } Return : The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method. As such, it is categorized as a jump statement. A brief look at return is presented here. At any time in a method the return statement can be used to cause execution to branch back to the caller of the method. Thus, the return statement immediately terminates the method in which it is executed. Syntax return; or return(var/const/expression); Example:public class ReturnAllValues { public static String name = "Faith Hill"; public static void main(String [] args) { 24 Amit Kumar String myName = getName(); System.out.println(myName); } public String getName() { return name; } } exit() : exit() is a control statement. Which is used to exit from JVM(Java Virtual Machine). It is a method of System class of Java.lang package. Syntax System.exit(int const.); Example :Import java.io.*; public class DemoExit { public static void main(String arg[])throws IOException { BufferedReadder b=new BufferedReader(new InputStreamReader(System.in)); Int num; System.out.println(“Enter a numbe!! if You want to exit then press 5. ”); Num=Integer.valueOf(b.readLine()).intValue(); if(i==5) { System.exit(1); } else { System.out.println(“Value Enter “+num); } } } 25 Amit Kumar -: Array:An array is a representation of data in contiguous space in the memory of our computer. All the variable of the same name each variable is called as element. And each element in the array is distinguished by the index In java array is always instantiated or allocated at run time, using new operator in the following two steps. Step -1 At first array variable/array reference variable is created in the following format. <Datatype> arrayname[]; Step -2 Secondly new operator can be used in the following format to allocate number of boxes/no of elements. Arrayname = new <Datatype>[Size]; Note:The two step process can be combined in to single step as follows. <Datatype> arrayname[]= new <Datatype>[Size]; The size must be provided at compile time as well as run time and must be positive integer value. Example Int arr[]=new int[10]; -: An array of ten elements:Type of array in java:26 Amit Kumar Java support two type of array. 1. One dimensional array. 2. Multi dimensional array. 1. One dimensional array:An array declares with one dimension of type primitive is referred to as one dimensional primitive array. Syntax <Datatype> arrayname[]; arrayname = new <Datatype>[Size]; input/output Statement in Array :We can assign values to array’s element in the following format. Direct initiations. Assignment. Through reading value from System.in. Direct initiations:It is one way by which more than one value can be assign at the time of declaring array in the following format. Syntax <Datatype> arrayname[]={num1,num2,num3,……}; Example int arr[]={2,4,3,65,7}; Assignment:We can assign value to a particular element in java using the syntax given below. Syntax arrayname[index]=Var/value/expression; Example int arr[]=new int[2]; arr[0]=23; arr[1]=22; Reading value from System.in:27 Amit Kumar To assign value to elements at run time required to read value from System.in. Syntax arrayname[index]=obj.readLine(); Example Import java.io.*; public class ArrayInput { public static void main(String arg[])throws IOException { BufferedReader b= new BufferedReader(new InputStreamReader(System.in)); int arr[]=new int[10]; int i; for(i=0;i<10;i++) { System.out.println(“Enter Value For Element*“+(i+1)+”+”); Arr[i]=Integer.valueOf(b.readLine()).intValue(); } for(i=0;i<10;i++) { System.out.println(“Value Of Element*“+(i+1)+”+ = ”+ arr*i+); } } } Command Line Arguments:In any programming languages (Even Java) the main function/method can accept an array of single type arguments dropped at command line at the time of executing a program, which it stores in String array and can be accepted. Note:All type of array allocated in java holds an attributes name ”length” which can be used to get the number of boxes/packets/elements physically allocated. Syntax Arrayname.length; Example 28 Amit Kumar public class CommandLine1 { public static void main(String arg[]) { If(arg.lenth==2) { System.out.println(arg*0++” “+arg*1+); } else { System.out.println(“Must Enter two String as Arguments”); } } } Note:Java provide a routine checkup at run time to ensured that only those elements should be accessed which allocated physically otherwise it leads to runtime error Array index out of bounds. Exception which is not in case of C/C++. 2. Multi dimensional array:Java define multi dimensional array is basically array nested. (Array within array) Syntax 1: Java support two format to declare multi dimensional array these included <Datatype> arrayname[][]; arrayname = new <Datatype>[row Size][col. Size]; Or <Datatype> arrayname[][] = new <Datatype>[row Size][col. Size]; Example int arr[][]; arr=new int[2][3]; Syntax 2: 29 Amit Kumar Java support multi dimensional array as having different length of each row. <Datatype> arrayname[][] = new <Datatype>[row Size][]; Example int arr[][]=new int[3][]; arr[0]=new int[3]; arr[1]=new int[5]; arr[2]new int[2]; 30 Amit Kumar -:Methods:Methods:A Java method is a set of Java statements which can be included inside a Java class. Java methods are similar to functions or procedures in other programming languages. Every Java program must have one main() method. Syntax for declaring methods <access specifiers> <modifiers> <Return Type> <methods name>(type1 arg1,type2 arg2,….) { <Set of Codes>; …………………….; Return(<var/const./Expression>); } 31 Amit Kumar -: Class & Object:Class:A class defines the behaviors of an object. A class is a user-defined data type with a template that serves to define its properties. Once the class type has been defined we can create variables of those types using declarations that are similar to the basic type declarations. In java these variables are termed as instances of classes which are the actual objects. The basic form of a class definition is:A class has data members (Attributes) and member functions (methods). The data members and methods of a class body, in java braces ({ }) are marks the beginning and end of the methods or class. Braces are also used to delimit blocks of object in loops and iterative statements. Syntax for Declaring Class class classname { type instance-variable1; type instance-variable2; // ... type instance-variableN; type methodname1(parameter-list) { // body of method } type methodname2(parameter-list) { // body of method THE JAVA LANG} // ... type methodnameN(parameter-list) { // body of method } } Example:public class Circle { public double x, y; // The coordinates of the center public double r; // The radius // Methods that return the circumference and area of the circle public double circumference() { Return( 2 * 3.14159 * r); } public double area() { return (3.14159 * r*r); } } 32 Amit Kumar Note:1) A class name is mandatory and must be given while declaring a class. The class name is referred to the class and to create instance of the class. 2) The class keyword is used to create class. 3) The access specifier and modifier is optional and are covered later in this section. Object:An object is an instance of a class. Declaring an object is same as declaring of variables. Define object type/user define type using reserve key word class is simply a logical frame work with no reality. To physically allocate object of user define type required two steps to comes in to existence. Step 1. At first allocate object reference variable in the following format. <Object type/Class name> Object_refference_variable1, Object_refference_variable2,…..; At this step no object is physically created and the object reference variable is by default inislized with NULL. Step2. Finally new operator must be used in the following format to physically allocated the object of define type and return the reference to the object reference variable. Object_refference_variable = new <Object type/Class name>; Note:These two steps combined in the single step as follows. <Object type/Class name> Object_refference_variable= new <Object type/Class name>; Example: class square { int sqarea(int side) { int area = side * side; return(area); } int sqpari(int side) { int pari = 4 * side; return(pari); } } 33 Amit Kumar class rectangle { int rectarea(int length,int breadth) { int area = length * breadth; return(area); } int rectpari(int length,int breadth) { int pari = 2*(length + breadth); return(pari); } } public class ObjectClass { public static void main(String args[]) { int sarea1,sarea2,pari1,pari2; int rectarea1,rectarea2,rectpari1,rectpari2; square sq = new square(); rectangle rect = new rectangle(); int a=20; System.out.println("Side of first square = " + a); sarea1 = sq.sqarea(a); pari1 = sq.sqpari(a); System.out.println("Area of first square = " + sarea1); System.out.println("Parimeter of first square = " + pari1); } } Access Specifiers:An access specifier controls the access of class members and variables by other objects. The various types of access specifiers in Java are: public private protected friendly or package The public Access Specifier:Class members with public specifier can be accessed anywhere in the same class, package in which the class is created, or a package other than the one in which the class is declared. You can use a public class, data member, or a method from any object in a Java program. 34 Amit Kumar The public keyword is used to declare a member as public. The following statement shows how to declare a data member of a class as public: public ; The class Account defines the show () method and various data members, such as name and account number. All the classes in the program can access the various details of a customer, such as name and account number. Therefore, these data members and the method are declared public. The show () method is used to display the account number and customer name of a customer. You can use the following code snippet to define a class, Account that contains public data variables and method: Example public class Account { public int account_no; // Data members are accessible outside the class public 'String name; public string name; public void show() //Method declaration { System. out. printIn("Name =" + name); //Statement of the method System.out.printIn("Account number of this customer is= " + account no); } } The private Access Specifier:The private access specifier provides most restricted level access. A data member of class declared as private is accessible at the class level only in which it is defined. You can use the private access specifier to declare members that should be available to the class within which they are declared. The private keyword is used to declare a member as private. In Java, you implement the concept of encapsulation by using the private keyword. The following syntax shows how to declare a data member of a class as private: private ; // Private data member of float type private methodName(); // Private method The Account class defines the show() method and the various data members, such as balance and age. These members are to be accessed only by the objects of the same class. Therefore, these methods art declared private. You can use the following code snippet that shows the Account class with private data variables, such as age and balance: Example class Account 35 Amit Kumar { private int account_no; // Data members converted to private to encapsulate private String name; private int age; private float balance; public void show() //Method can be called from outside class to access data members { System.out.println ("Age of Customer ="+ age); System.out.println("Balance of this customer is=" + balance) ; } } In the preceding code snippet, the objects of Account class can call the show () method, but objects of other classes cannot access or invoke the private members of Account class. The protected Access Specifier:The variables and methods that are declared protected are accessible only to the subclasses of the class in which they are declared. The protected keyword is used to declare a member as protected. The following statement shows how to declare a member as protected: protected ; In an airline reservation application, you can create the Ticket class that consists of various data members, such as flightNumber, date, time, and destination. You can derive the ConfirmedTicket subclass from the Ticket class that consists of an additional data member, seatNumber. You can declare the data members of the Ticket class as protected, which can be accessed by the ConfirmedTicfcet subclass. You can use the following code snippet to define the Ticket class that has protected data variables: Example public class Ticket { protected int flightNumber; //protected data members accessible to derived classes protected String date; protected String time; protected String destination; protected void howData() { //Code Body } } In the preceding code snippet, various data members and methods are declared protected. 36 Amit Kumar The friendly or package Access Specifier:If you do not specify any access specifier, the scope of data members and methods is friendly. Java provides a large number of classes, which are organized into groups in a package. A class, variable, or method that has friendly access is accessible only to the classes of a package. The data members, such as pageNumbers and price, and the showData() method of the Books class are not given access specifiers. The following code snippet shows the Books class that has friendly access specifier: Example Class Books { Int pageNumbers; //The default friendly access is provided to the data memners float price; void showdata() { //code body } } In Java, friendly is not a keyword. It is a term that is used for the access level when no access specifier has been specified. You cannot declare a class, variable, or method with the friendly specifier. This KeyWord:The keyword this is useful when you need to refer to instance of the class from its method. The keyword helps us to avoid name conflicts. As we can see in the program that we have declare the name of instance variable and local variables same. Now to avoid the confliction between them we use this keyword. Here, this section provides you an example with the complete code of the program for the illustration of how to what is this keyword and how to use it. In the example, this.length and this.breadth refers to the instance variable length and breadth while length and breadth refers to the arguments passed in the method. Example class Rectangle { int length,breadth; void show(int length,int breadth) { this.length=length; this.breadth=breadth; } int calculate() { return(length*breadth); } 37 Amit Kumar } public class UseOfThisOperator { public static void main(String[] args) { Rectangle rectangle=new Rectangle(); rectangle.show(5,6); int area = rectangle.calculate(); System.out.println("The area of a Rectangle is : " + area); } } Modifier:Modifier determines how the data member and methods are used in other classes and objects. There are following modifier supported in java. 1) Static 2) Final 1) Static:There may be times in your program where the class objects need to share information – in such cases you can specify one or more class variable and methods that are shared among the objects. When you declare a method in a class static you do not need an instance of the class. You can use static methods to access other static members of the class, however, you cannot use the static method to access any non-static variables or methods. A class containing static members is called as a static class. There is no static identifier for the class. Example public Class MyClass { public static String prop1; public static method1() { prop1 = “Hello”; } public static void main(String args[]) { MyClass.prop1 = “Bye”; MyClass.method1(); } } 2) Final:One of the key benefits of inheritance is to minimise the amount of duplicate code in an application by sharing common code amongst several subclasses. Where equivalent code exists in two related classes, the hierarchy can usually be refactored to move the common code up to a mutual superclass. This also tends to result in a better organisation of code and smaller, simpler compilation units. 38 Amit Kumar Inheritance can also make application code more flexible to change because classes that inherit from a common superclass can be used interchangeably. Example:class Chair { String color; int noofarms; Chair() { System.out.println(“Default constructor called”); } Chair(String c,int noarm) { Color=c; Noofarms=noarm; } } public class WheelChair extends Chair { int noofwheels; public WheelChair(String s, int a, int wheels) { super(s,a);//Invoke super class. noofwheel=wheels; } } -: Constructor:A constructor creates an Object of the class that it is in by initializing all the instance variables and creating a place in memory to hold the Object. It is always used with the keyword new and then the Class name. For instance, new String(); constructs a new String object. Sometimes in a few classes you may have to initialize a few of the variables to values apart from their predefined data type specific values. If java initializes variables it would default them to their variable type specific values. For example you may want to initialize an integer variable to 10 or 20 based on a certain condition, when your class is created. In such a case you cannot hard code the value during variable declaration. Such kind of code can be placed inside the constructor so that the initialization would happen when the class is instantiated. 39 Amit Kumar Example public class Cube1 { int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } Cube1() { length = 10; breadth = 10; height = 10; } Cube1(int l, int b, int h) { length = l; breadth = b; height = h; } public static void main(String[] args) { Cube1 cubeObj1, cubeObj2; cubeObj1 = new Cube1(); cubeObj2 = new Cube1(10, 20, 30); System.out.println(”Volume of Cube1 is : ” + cubeObj1.getVolume()); System.out.println(”Volume of Cube1 is : ” + cubeObj2.getVolume()); } } Rules for a constructor:1. A constructor has the same name as that of the class for which it is declare since called automatically when an object is created. 2. A constructor does not have return type. As we do not call the constructor explicitly. We can not use the return value anyway. 3. Basically java support two type of constructor. I,e: Default constructor Parameterized constructor Differences between methods and constructors. 40 There is no return type given in a constructor signature (header). The value is this object itself so there is no need to indicate a return value. There is no return statement in the body of the constructor. Amit Kumar The first line of a constructor must either be a call on another constructor in the same class (using this), or a call on the superclass constructor (using super). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor. These differences in syntax between a constructor and method are sometimes hard to see when looking at the source. It would have been better to have had a keyword to clearly mark constructors as some languages do. Default constructor If you don't define a constructor for a class, a default parameterless constructor is automatically created by the compiler. The default constructor calls the default parent constructor (super()) and initializes all instance variables to default value (zero for numeric types, null for object references, and false for booleans). Example public class Cube1 { int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } Cube1() { length = 10; breadth = 10; height = 10; } public static void main(String[] args) { Cube1 cubeObj1, cubeObj2; cubeObj1 = new Cube1(); System.out.println(”Volume of Cube1 is : ” + cubeObj1.getVolume()); } } Parameterized constructor At the time of creating object(instance) we will passed the argument/parameter. In that condition the parameterized constructor will be called for passing arguments. 41 Amit Kumar Example public class Cube1 { int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } Cube1() { length = 10; breadth = 10; height = 10; System.out.println(“Default Constructor called”) } Cube1(int l, int b, int h) { length = l; breadth = b; height = h; System.out.println(“Parameterized Constructor called”) } public static void main(String[] args) { Cube1 cubeObj1, cubeObj2; cubeObj1 = new Cube1(); cubeObj2 = new Cube1(10, 20, 30); System.out.println(”Volume of Cube1 is : ” + cubeObj1.getVolume()); System.out.println(”Volume of Cube1 is : ” + cubeObj2.getVolume()); } } Garbage collector:Objects are dynamically created with the help of new operator. These all objects are created in memory and by default not deallocated. In other programming languages like c++. These memory areas will be deallocated with the help of delete operator. But in case of java it takes different approach. It handles deallocation automatically. The technique that accomplishes this is called garbage collection. 42 Amit Kumar -: Overloading:In Java it is possible to define two or more methods/Constructor within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods/Constructors are said to be overloaded, and the process is referred to as overloading. overloading is one of the ways that Java implements polymorphism. Java Support two type of overloading i.e: A) Method Overloading. B) Constructor Overloading. A) 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 their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java implements polymorphism. If you have never used a language that allows the overloading of methods, then the concept may seem strange at first. But as you will see, method overloading is one of Java's most exciting and useful features. When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call. Thus, overloaded methods must differ in the type and/or number of their parameters. While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method. When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call. Here is a simple example that illustrates method overloading: Example class OverloadDemo { void test() { System.out.pri ntln("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; } 43 Amit Kumar } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.2); System.out.println("Result of ob.test(123.2): " + result); } } B) Constructor Overloading:Constructors are used to assign initial values to instance variables of the class. A default constructor with no arguments will be called automatically by the Java Virtual Machine (JVM). Constructor is always called by new operator. Constructors are declared just like as we declare methods, except that the constructors don’t have any return type. Constructor can be overloaded provided they should have different arguments because JVM differentiates constructors on the basis of arguments passed in the constructor. Whenever we assign the name of the method same as class name. Remember this method should not have any return type. This is called as constructor overloading. Example class Rectangle { int l, b; float p, q; Rectangle(int x, int y) { l = x; b = y; } Rectangle(int x) { l = x; b = x; } Rectangle(float x) { p = x; q = x; } Rectangle(float x, float y) 44 Amit Kumar { p = x; q = y; } public int first() { return(l * b); } public int second() { return(l * b); } public float third() { return(p * q); } public float fourth() { return(p * q); } } public class ConstructorOverloading { public static void main(String args[]) { Rectangle rectangle1=new Rectangle(2,4); int areaInFirstConstructor=rectangle1.first(); System.out.println(" The area of a rectangle in first constructor is : " + areaInFirstConstructor); Rectangle rectangle2=new Rectangle(5); int areaInSecondConstructor=rectangle2.second(); System.out.println(" The area of a rectangle in first constructor is : " + areaInSecondConstructor); Rectangle rectangle3=new Rectangle(2.0f); float areaInThirdConstructor=rectangle3.third(); System.out.println(" The area of a rectangle in first constructor is : " + areaInThirdConstructor); Rectangle rectangle4=new Rectangle(3.0f,2.0f); float areaInFourthConstructor=rectangle4.fourth(); System.out.println(" The area of a rectangle in first constructor is : " + areaInFourthConstructor); } } 45 Amit Kumar -: Wrapper Class:Wrapper class is a wrapper around a primitive data type. It represents primitive data types in their corresponding class instances e.g. a boolean data type can be represented as a Boolean class instance. All of the primitive wrapper classes in Java are immutable i.e. once assigned a value to a wrapper class instance cannot be changed further. Wrapper Classes are used broadly with Collection classes in the java.util package and with the classes in the java.lang.reflect reflection package. Following table lists the primitive types and the corresponding wrapper classes: Primitive Wrapper boolean java.lang.Boolean byte java.lang.Byte char java.lang.Character double float int 46 java.lang.Double java.lang.Float java.lang.Integer long java.lang.Long short java.lang.Short void java.lang.Void Amit Kumar -: Inheritance:Inheritance is one of the main concepts of object oriented programming. The base class is named superclass and the child class is named subclass. Using inheritance we can achieve the concepts of reusability. The child class can use the methods and variables of the superclass and add to them its own methods and variables. Inheritance represents problems in the real world. Notes:1) Subclass can only inherit public and protected members but not private members. 2) You can only inherit from single class. (Single inheritance).That is means there is no multiple inheritance in Java. But as a solution to the multiple inheritance java supported class types called “interfaces”. Example class A { int i, j; void showij() { System.out.println("i and j: " + i + " " + j); } } // Create a subclass by extending class A. class B extends A { int k; void showk() { System.out.println("k: " + k); } void sum() { System.out.println("i+j+k: " + (i+j+k)); } } class SimpleInheritance { public static void main(String args[]) { A superOb = new A(); B subOb = new B(); // The superclass may be used by itself. superOb.i = 10; superOb.j = 20; System.out.println("Contents of superOb: "); superOb.showij(); System.out.println(); /* The subclass has access to all public members of its superclass. */ subOb.i = 7; 47 Amit Kumar subOb.j = 8; subOb.k = 9; System.out.println("Contents of subOb: "); subOb.showij(); subOb.showk(); System.out.println(); System.out.println("Sum of i, j and k in subOb:"); subOb.sum(); } } What You Can Do in a Subclass A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members: The inherited fields can be used directly, just like any other fields. You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended). You can declare new fields in the subclass that are not in the superclass. The inherited methods can be used directly as they are. You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it. You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it. You can declare new methods in the subclass that are not in the superclass. You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super. The following sections in this lesson will expand on these topics. Private Members in a Superclass A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass. A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass. Overriding and Hiding Methods Instance Methods An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method. The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, 48 Amit Kumar number and type of parameters, and return type as the method it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type. When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, it will generate an error. For more information on @Override, see Annotations. Class Methods If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass. The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass. Let's look at an example that contains two classes. The first is Animal, which contains one instance method and one class method: public class Animal { public static void testClassMethod() { System.out.println("The class method in Animal."); } public void testInstanceMethod() { System.out.println("The instance method in Animal."); } } //The second class, a subclass of Animal, is called Cat: public class Cat extends Animal { public static void testClassMethod() { System.out.println("The class method in Cat."); } public void testInstanceMethod() { System.out.println("The instance method in Cat."); } public static void main(String[] args) { Cat myCat = new Cat(); Animal myAnimal = myCat; Animal.testClassMethod(); myAnimal.testInstanceMethod(); } } 49 Amit Kumar The Cat class overrides the instance method in Animal and hides the class method in Animal. The main method in this class creates an instance of Cat and calls testClassMethod() on the class and testInstanceMethod() on the instance. The output from this program is as follows: The class method in Animal. The instance method in Cat. As promised, the version of the hidden method that gets invoked is the one in the superclass, and the version of the overridden method that gets invoked is the one in the subclass. Modifiers The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass. You will get a compile-time error if you attempt to change an instance method in the superclass to a class method in the subclass, and vice versa. Basically Java supports only four types of inheritance: 1) Single Inheritance 2) Multi Level Inheritance 1) Single Inheritance:An inheritance in side which a single base class inherits a single derive class is known as single inheritance. When a subclass is derived simply from it's parent class then this mechanism is known as simple inheritance. In case of simple inheritance there is only a sub class and it's parent class. It is also called single inheritance or one level inheritance. Simple Inheritance Example class A { int i, j; 50 Amit Kumar void showij() { System.out.println("i and j: " + i + " " + j); } } // Create a subclass by extending class A. class B extends A { int k; void showk() { System.out.println("k: " + k); } void sum() { System.out.println("i+j+k: " + (i+j+k)); } } class SingleInheritance { public static void main(String args[]) { A superOb = new A(); B subOb = new B(); // The superclass may be used by itself. superOb.i = 10; superOb.j = 20; System.out.println("Contents of superOb: "); superOb.showij(); System.out.println(); /* The subclass has access to all public members of its superclass. */ subOb.i = 7; subOb.j = 8; subOb.k = 9; System.out.println("Contents of subOb: "); subOb.showij(); subOb.showk(); System.out.println(); System.out.println("Sum of i, j and k in subOb:"); subOb.sum(); } } 2) Multilevel Inheritance:It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class then this mechanism is known as the multilevel inheritance. The derived 51 Amit Kumar class is called the subclass or child class for it's parent class and this parent class works as the child class for it's just above (parent) class. Multilevel inheritance can go up to any number of levels. Multilevel Inheritance Example class A { int x; int y; int get(int p, int q) { x=p; y=q; return(0); } void Show() { System.out.println(x); } } class B extends A { void Showb() { System.out.println("B"); } } class C extends B { void display() { System.out.println("C"); } public static void main(String args[]) { A a = new A(); a.get(5,6); 52 Amit Kumar a.Show(); } } Java does not support multiple Inheritance Multiple Inheritances The mechanism of inheriting the features of more than one base class into a single class is known as multiple inheritances. Java does not support multiple inheritances but the multiple inheritance can be achieved by using the interface. In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more than one interfaces in a class. super keyword The super is java keyword. As the name suggest super is used to access the members of the super class.It is used for two purposes in java. The first use of keyword super is to access the hidden data variables of the super class hidden by the sub class. e.g. Suppose class A is the super class that has two instance variables as int a and float b. class B is the subclass that also contains its own data members named a and b. then we can access the super class (class A) variables a and b inside the subclass class B just by calling the following command. super.member; Here member can either be an instance variable or a method. This form of super most useful to handle situations where the local members of a subclass hides the members of a super class having the same name. The following example clarify all the confusions Example class A { int a; float b; void Show() { System.out.println("b in super class: " + b); } } class B extends A { int a; float b; B( int p, float q) 53 Amit Kumar { a = p; super.b = q; } void Show() { super.Show(); System.out.println("b in super class: " + super.b); System.out.println("a in sub class: " + a); } public static void main(String[] args) { B subobj = new B(1, 5); subobj.Show(); } } Use of super to call super class constructor: The second use of the keyword super in java is to call super class constructor in the subclass. This functionality can be achieved just by using the following command. super(param-list); Here parameter list is the list of the parameter requires by the constructor in the super class. super must be the first statement executed inside a super class constructor. If we want to call the default constructor then we pass the empty parameter list. The following program illustrates the use of the super keyword to call a super class constructor. Example class A { int a; int b; int c; A(int p, int q, int r) { a=p; b=q; c=r; } } class B extends A { int d; B(int l, int m, int n, int o) 54 Amit Kumar { super(l,m,n); d=o; } void Show() { System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); } public static void main(String args[]) { B b = new B(4,3,8,7); b.Show(); } } abstract class :An abstract class is a class that is declared by using the abstract keyword. It may or may not have abstract methods. Abstract classes cannot be instantiated, but they can be extended into sub-classes. Java provides a special type of class called an abstract class. Which helps us to organize our classes based on common methods. An abstract class lets you put the common method names in one abstract class without having to write the actual implementation code. An abstract class can be extended into sub-classes, these sub-classes usually provide implementations for all of the abstract methods. The key idea with an abstract class is useful when there is common functionality that's like to implement in a superclass and some behavior is unique to specific classes. So you implement the superclass as an abstract class and define methods that have common subclasses. Then you implement each subclass by extending the abstract class and add the methods unique to the class. Points of abstract class : Abstract class contains abstract methods. Program can't instantiate an abstract class. Abstract classes contain mixture of non-abstract and abstract methods. If any class contains abstract methods then it must implements all the abstract methods of the abstract class. In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier curves, and many other graphic objects. These objects all have certain states (for example: position, orientation, line color, fill color) and behaviors (for example: moveTo, rotate, resize, draw) in common. Some of these states 55 Amit Kumar and behaviors are the same for all graphic objects—for example: position, fill color, and moveTo. Others require different implementations—for example, resize or draw. All GraphicObjects must know how to draw or resize themselves; they just differ in how they do it. This is a perfect situation for an abstract superclass. You can take advantage of the similarities and declare all the graphic objects to inherit from the same abstract parent object—for example, GraphicObject, as shown in the following figure. Classes Rectangle, Line, Bezier, and Circle inherit from GraphicObject -:Interfaces:An interface in the Java programming language is an abstract type that is used to specify an interface (in the generic sense of the term) that classes must implement. Interfaces are declared using the interface keyword, and may only contain method signatures and constant declarations (variable declarations which are declared to be both static and final). An interface may never contain method definitions. As interfaces are implicitly abstract, they cannot be directly instantiated except when instantiated by a class which implements the said interface. The class must implement all of the methods described in the interface, or be an abstract class. Object references in Java may be specified to be of an interface type; in which case they must either be null, or be bound to an object which implements the interface. One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java (other than java.lang.Object, the root class of the Java type system) must have exactly one base class; multiple inheritance of classes is not allowed. However, a Java class/interface may implement/extend any number of interfaces. Syntax <Access Specifier> interface <InterfaceName> [extends other interfaces] { constant declarations member type declarations abstract method declarations } The body of the interface contains abstract methods, but since all methods in an interface are, by definition, abstract, the abstract keyword is not required. Since the interface specifies a set of exposed behaviors, all methods are implicitly public 56 Amit Kumar Example interface Bicycle { void changeCadence(int newValue); void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); } class ACMEBicycle implements Bicycle { // remainder of this class implemented as before } Abstract Classes versus Interfaces There are three main differences between an interface and an abstract class: At the same time multiple interfaces can be implemented, but only extend one class an abstract class may have some method implementation (non-abstract methods, constructors, instance initializers and instance variables) and non-public members abstract classes may or may not be a little bit faster Main reason for the existence of interfaces in Java is: to support multiple inheritance. Languages supporting multiple implementation inheritance, an interface is equivalent to a fully abstract class (a class with only public abstract members). The above differentiation suggests when to use an abstract class and when to use an interface: If you want to provide common implementation to subclasses then an abstract class is used, If you want to declare non-public members, the use abstract method In case of abstract class, you are free to add new public methods in the future, If you're confirm regarding the stablity of the API for the long run then use an interface If you want to provide the implementing classes the opportunity to inherit from other sources at the same time then use an interface. In general, prefer interfaces if you don't need to use an abstract class, because they provide more design flexibility. -: Package:A package is a grouping of related types providing access protection and name space management. Note that types refer to classes, interfaces, enumerations, and annotation types. Enumerations and 57 Amit Kumar annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces. Using Package Members The types that comprise a package are known as the package members. To use a public package member from outside its package, you must do one of the following: Refer to the member by its fully qualified name Import the package member Import the member's entire package Each is appropriate for different situations, as explained in the sections that follow. Importing a Package Member To import a specific member into the current file, put an import statement at the beginning of the file before any type definitions but after the package statement, if there is one. Here's how you would import the Button class from the awt package. import Java.awt.Button; Now you can refer to the Button class by its simple name. Button btn1 = new Button (“Button1); This approach works well if you use just a few members from the awt package. But if you use many types from a package, you should import the entire package. Importing an Entire Package To import all the types contained in a particular package, use the import statement with the asterisk (*) wildcard character. import java.awt.*; Now you can refer to any class or interface in the awt package by its simple name. Button btn1 = new Button (“Button 1”); Label lbl1 = new Label(“Label 1”); The asterisk in the import statement can be used only to specify all the classes within a package, as shown here. It cannot be used to match a subset of the classes in a package. For example, the following does not match all the classes in the awt package that begin with A. import awt.A*; //does not work Instead, it generates a compiler error. With the import statement, you generally import only a single package member or an entire package. 58 Amit Kumar For convenience, the Java compiler automatically imports three entire packages for each source file: (1) the package with no name, (2) the java.lang package (3) the current package (the package for the current file) Apparent Hierarchies of Packages At first, packages appear to be hierarchical, but they are not. For example, the Java API includes a java.awt package, a java.awt.color package, a java.awt.font package, and many others that begin with java.awt. However, the java.awt.color package, the java.awt.font package, and other java.awt.xxxx packages are not included in the java.awt package. The prefix java.awt (the Java Abstract Window Toolkit) is used for a number of related packages to make the relationship evident, but not to show inclusion. Importing java.awt.* imports all of the types in the java.awt package, but it does not import java.awt.color, java.awt.font, or any other java.awt.xxxx packages. If you plan to use the classes and other types in java.awt.color as well as those in java.awt, you must import both packages with all their files: import java.awt.*; import java.awt.color.*; Creating a Package To create a package, you choose a name for the package and put a package statement with that name at the top of every source file that contains the types (classes and interfaces) that you want to include in the package. The package statement (for example, package graphics;) must be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file. Note: If you put multiple types in a single source file, only one can be public, and it must have the same name as the source file. For example, you can define public class Circle in the file Circle.java, define public interface Draggable in the file Draggable.java, define public enum Day in the file Day.java, and so forth. You can include non-public types in the same file as a public type (this is strongly discouraged, unless the non-public types are small and closely related to the public type), but only the public type will be accessible from outside of the package. All the top-level, non-public types will be package private. If you put the graphics interface and classes listed in the preceding section in a package called graphics, you would need six source files, like this: //in the Draggable.java file package graphics; public interface Draggable { 59 Amit Kumar ... } //in the Graphic.java file package graphics; public abstract class Graphic { ... } //in the Circle.java file package graphics; public class Circle extends Graphic implements Draggable { ... } //in the Rectangle.java file package graphics; public class Rectangle extends Graphic implements Draggable { ... } //in the Point.java file package graphics; public class Point extends Graphic implements Draggable { ... } //in the Line.java file package graphics; public class Line extends Graphic implements Draggable { ... } If you do not use a package statement, your type ends up in an unnamed package. Generally speaking, an unnamed package is only for small or temporary applications or when you are just beginning the development process. Otherwise, classes and interfaces belong in named packages. Exception Handling :exception handling 60 Amit Kumar Exceptions let you handle unusual error conditions without cluttering your code with nested ifs after every method call. There are two kinds of Exceptions, checked and unchecked. You don’t need to declare unchecked Exceptions, those that derive from java.lang.Error and java.lang.RuntimeException, in your throws clauses. Checked Exceptions usually derive from java.lang.Exception. For unchecked Exceptions ( i.e. Errors and RuntimeExceptions such as IllegalArgumentException) the throws clause is optional. I find them useful documentation since they show up in the Javadoc. Sample Code The basic syntax to handle an Exception looks like this: String myMethod() { try { return trickyMethod(); } catch ( IOException e ) { return null; } } The basic Syntax to generate an exception looks like this: String trickyMethod() throws IOException { int result = readAnotherChar(); if ( result < 0 ) throw new IOException( "bad data" ); return result; } Types of Exception Exception come is several flavours: RuntimeExceptions, Errors, Checked and Unchecked. Type codes used in describing Exceptions Letter Type 61 Parent Class Checked? (declare throws?) Use R Runtime java.lang.RuntimeException Error that can occur in almost any code e.g. NullPointerException. E Error Serious error you really should not try to catch, e.g. OutOfMemoryError. C Checked java.lang.Exception java.lang.Error Likely exceptional condition that can only occur in specific places in the code e.g. EOFException. Amit Kumar Collectively, RuntimeException, Error and Exception are derived from Throwable. RuntimeException is derived from Exception, which is derived from Throwable. Error is derived directly from Throwable. If you catch RuntimeException you will catch all manner of run time exceptions (type R). If you catch Error you will catch all manner of errors (type E). If you catch Exception you will catch all manner of checked exceptions and run time exceptions (type R+C). If you catch Throwable, you will catch everything, (Type R+E+C ); Table of Specific Exceptions Specific Exceptions Exception Name AbstractMethodError Type E Package Notes java.lang AccessControlException R java.security This is an exception that is thrown whenever a reference is made to a non-existent ACL (Access Control List). notes. AccessException C java.rmi Thrown by certain methods of the java.rmi.Naming class. AclNotFoundException C java.security.acl Thrown whenever a reference is made to a non-existent ACL (Access Control List). ActivateFailedException C java.rmi.activation thrown by the RMI runtime when activation fails during a remote call to an activatable object. ActivationException C java.rmi.activation AlreadyBoundException C javax.naming ApplicationException C org.omg.CORBA.portable Used for reporting application level exceptions between ORBs and stubs ArithmeticException R java.lang Most commonly a divide by zero. notes. ArrayIndexOutOfBoundsException R java.lang Can be handled more generically with IndexOutOfBoundsException. notes. ArrayStoreException R java.lang Thrown to indicate that an attempt has been made to store the wrong 62 Amit Kumar Specific Exceptions Exception Name Type Package Notes type of object into an array of objects. notes. AttributeInUseException C javax.naming.directory AttributeModificationException C javax.naming.directory AuthenticationException C javax.naming AuthenticationNotSupportedException C javax.naming AWTError E java.awt AWTError E java/awt AWTException C java.awt BadLocationException C javax.swing.text BatchUpdateException C java.sql BindException C java.net CannotProceedException C javax.naming CannotRedoException R javax.swing.undo CannotUndoException R javax.swing.undo CertificateEncodingException C java.security.cert CertificateException C java.security.cert CertificateExpiredException C java.security.cert CertificateNotYetValidException C java.security.cert CertificateParsingException C java.security.cert ChangedCharSetException C javax.swing.text 63 This exception is to report bad locations within a document model. Signals that an error occurred while attempting to bind a socket to a local address and port Amit Kumar Specific Exceptions Exception Name Type Package Notes CharConversionException C java.io ClassCastException R java.lang ClassCircularityError E java.lang ClassFormatError E java.lang notes. ClassNotFoundException C java.lang notes. CloneNotSupportedException C java.lang CMMException R java.awt.color CommunicationException C javax.naming ConcurrentModificationException R java.util ConfigurationException C javax.naming ConnectException C java.rmi ConnectIOException C java.rmi ContextNotEmptyException C javax.naming CRLException C java.security.cert DataFormatException C java.util.zip DigestException C java.security EmptyStackException 64 R java.util notes. This exception may be thrown by methods that have detected concurrent modification of a backing object when such modification is not permissible. E.g. two threads modifying a HashMap simultaneously. notes. CRL (Certificate Revocation List) Exception. Thrown by methods in the Stack class to indicate that the stack is empty. Does not refer to the system stack. Amit Kumar Specific Exceptions Exception Name EOFException Error Type C E Package Notes java.io notes. java.lang Catches any serious error such as OutOfMemoryError that you unlikely can recover from. Exception C java.lang generic. Catches any specify Exception plus general Runtime exceptions, but not Errors. ExceptionInInitializerError E java.lang notes. ExceptionInInitializerError E java.lang ExpandVetoException C javax.swing.tree ExportException C java.rmi.server FileNotFoundException C java.io FontFormatException C java.awt GeneralSecurityException C java.security IllegalAccessError E java.lang notes. IllegalAccessException C java.lang Thrown when an application tries to load in a class, but the currently executing method does not have access to the definition of the specified class, because the class is not public and in another package. IllegalArgumentException R java.lang Most common exception to reject a bad parameter to a method. IllegalComponentStateException R java.awt IllegalMonitorStateException R java.lang IllegalPathStateException R java.awt.geom 65 Amit Kumar Specific Exceptions Exception Name Type Package Notes Signals that a method has been invoked at an illegal or inappropriate time. IllegalStateException R java.lang IllegalThreadStateException R java.lang ImagingOpException R java.awt.image IncompatibleClassChangeError E java.lang notes. Similar to ArrayIndexOutOfBoundsException for ArrayList. IndexOutOfBoundsException R java.lang IndirectionException R org.omg.CORBA.portable InstantiationError E java.lang InstantiationException C java.lang InsufficientResourcesException C javax.naming InternalError E java.lang InterruptedException C java.lang InterruptedIOException C java.io InterruptedNamingException C javax.naming IntrospectionException C java.beans InvalidAlgorithmParameterException C java.security InvalidAttributeIdentifierException C javax.naming.directory InvalidAttributesException C javax.naming.directory 66 Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt method in class Thread. This is a GeneralSecurityException. See IllegalArgumentException. Amit Kumar Specific Exceptions Exception Name Type Package InvalidAttributeValueException C javax.naming.directory InvalidClassException C java.io InvalidDnDOperationException R java.awt.dnd InvalidKeyException C java.security InvalidKeySpecException C java.security.spec InvalidMidiDataException C javax.sound.midi InvalidNameException C javax.naming InvalidObjectException C java.io InvalidParameterException R java.security InvalidParameterSpecException C java.security.spec InvalidSearchControlsException C javax.naming.directory InvalidSearchFilterException C javax.naming.directory InvalidTransactionException C javax.transaction InvocationTargetException C java.lang.reflect IOException C java.io JarException C java.util.jar KeyException C java.security KeyManagementException C java.security KeyStoreException C java.security LastOwnerException C java.security.acl LdapReferralException C javax.naming.ldap LimitExceededException C javax.naming 67 Notes notes. Amit Kumar Specific Exceptions Exception Name Type Package LineUnavailableException C javax.sound.sampled LinkageError E java.lang LinkException C javax.naming LinkLoopException C javax.naming MalformedLinkException C javax.naming MalformedURLException C java.net MarshalException C java.rmi MidiUnavailableException C javax.sound.midi MimeTypeParseException C java.awt.datatransfer MissingResourceException R java.util NameAlreadyBoundException C javax.naming NameNotFoundException C javax.naming NamingException C javax.naming NamingSecurityException C javax.naming NegativeArraySizeException R java.lang NoClassDefFoundError E java.lang NoInitialContextException C javax.naming NoninvertibleTransformException C java.awt.geom NoPermissionException C javax.naming NoRouteToHostException C java.net NoSuchAlgorithmException C java.security NoSuchAttributeException C javax.naming.directory 68 Notes notes. Amit Kumar Specific Exceptions Exception Name Type Package Notes NoSuchElementException R java.util NoSuchFieldError E java.lang NoSuchFieldException C java.lang NoSuchMethodError E java.lang NoSuchMethodException C java.lang NoSuchObjectException C java.rmi NoSuchProviderException C java.security notes. NotActiveException C java.io Thrown when serialization or deserialization is not active NotBoundException C java.rmi NotContextException C javax.naming NotOwnerException C java.security.acl NotSerializableException C java.io notes. NullPointerException R java.lang Actually a null reference exception. notes. Commonly thrown when a String is converted to internal binary numeric format. notes. NumberFormatException R java.lang ObjectStreamException C java.io OperationNotSupportedException C javax.naming OptionalDataException 69 C java.io notes. Unexpected data appeared in an ObjectInputStream trying to read an Object. Occurs when the stream contains primitive data instead of the object that is expected by readObject. The EOF flag in the exception is true indicating that no more primitive data Amit Kumar Specific Exceptions Exception Name Type Package Notes is available. The count field contains the number of bytes available to read. OutOfMemoryError E java.lang ParseException C java.text PartialResultException C javax.naming PolicyError E org.omg.CORBA PrinterAbortException C java.awt.print PrinterException C java.awt.print PrinterIOException C java.awt.print PrivilegedActionException C java.security ProfileDataException R java.awt.color PropertyVetoException C java.beans ProtocolException C java.net ProviderException R java.security RasterFormatException R java.awt.image ReferralException C javax.naming RemarshalException C org.omg.CORBA.portable RemoteException C java.rmi 70 By the time this happens it is almost too late. gc has already done what it could. Possibly some process has just started gobbling RAM, or perhaps the problem you are trying to solve is just too big for the size of the allotted virtual ram. You can control that with the java.exe command line switches. Amit Kumar Specific Exceptions Exception Name RMISecurityException Type C Package Notes java.rmi Error that can occur in almost any code e.g. NullPointerException. Use this when to catch general errors when no specific exception is being thrown. RuntimeException R java.lang SchemaViolationException C javax.naming.directory SecurityException R java.lang ServerCloneException C java.rmi.server ServerError E java.rmi ServerException C java.rmi ServerNotActiveException C java.rmi.server ServerRuntimeException C java.rmi ServiceUnavailableException C javax.naming SignatureException C java.security SizeLimitExceededException C javax.naming SkeletonMismatchException C java.rmi.server SkeletonNotFoundException C java.rmi.server SocketException C java.net SocketSecurityException C java.rmi.server SQLException C java.sql StackOverflowError E java.lang notes. StreamCorruptedException C java.io ObjectStream data are scrambled. notes. 71 Amit Kumar Specific Exceptions Exception Name Type Package StringIndexOutOfBoundsException R java.lang StubNotFoundException C java.rmi SyncFailedException C java.io SystemException R org.omg.CORBA TimeLimitExceededException C javax.naming TooManyListenersException C java.util TransactionRequiredException C javax.transaction TransactionRolledbackException C javax.transaction UndeclaredThrowableException R java.lang.reflect UnexpectedException R java.rmi UnknownError E java.lang UnknownException R org.omg.CORBA.portable UnknownGroupException C java.rmi.activation UnknownHostException C java.rmi UnknownHostException C java.net UnknownObjectException C java.rmi.activation UnknownServiceException C java.net UnknownUserException C org.omg.CORBA UnmarshalException C java.rmi UnrecoverableKeyException C java.security UnsatisfiedLinkError E java.lang 72 Notes Can be handled more generically with IndexOutOfBoundsException. notes. notes. notes. Amit Kumar Specific Exceptions Exception Name Type Package Notes UnsupportedAudioFileException C javax.sound.sampled UnsupportedClassVersionError E java.lang notes. UnsupportedDataTypeException C java.io undocumented. notes. UnsupportedEncodingException C java.io UnsupportedFlavorException C java.awt.datatransfer UnsupportedLookAndFeelException C javax.swing UnsupportedOperationException R java.lang UserException C org.omg.CORBA UTFDataFormatException C java.io VerifyError E java.lang VirtualMachineError E java.lang WriteAbortedException C java.io ZipException C java.util.zip Use for code not yet implemented, or that you deliberately did not implement. notes. notes. Missing BadDataFormatException There is no BadDataFormatException to complain about badly formatted data files. You would expect there to be one either derived from IllegalArgumentException like NumberFormatException or from IOException like UTFDataFormatException. You can either reuse IllegalArgumentException or IOException, or roll your own BadDataFormatException. Rolling Your Own Exception Rolling your own Exception is easy: import java.io.IOException; /** * Thrown when stream format from server is out of spec. * * @author Roedy Green 73 Amit Kumar * @version 1.0 2003-07-27 */ public class BadStreamException extends IOException { /** * Create a BadStreamExecption and list a reason why thrown. * * @param reason String describing the reason for the exception. */ public BadStreamException ( String reason ) { super( reason ); } /** * Create a BadStreamException and list no reason why thrown. */ public BadStreamException() { super(); } } Status Code or Exception? Should you report problems with a status code returned from a method or with an Exception? The C-style is to use status codes. There is nothing that says the caller has check a status code. Programmers are lazy and don’t bother to check return codes. No error or warning is generated. If the caller of the caller is the proper place to handle the exception it takes futzing to propagate the information up the chain. Exceptions should be exceptional. They are for errors, things that are not supposed happen. EOFException is a special case. It will happen at most once per file. If there are 50/50 odds of either status, you should use a status code. There is an extra overhead to catching an exception. Don’t use Exceptions to return common place data or status. A rule of thumb might be if a method returns an error more often than 1 in 10, use a status code instead of an Exception to report the problem. Applet:An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a page. When you use a Java technology-enabled browser to view a page that contains an applet, the applet's code is transferred to your system and executed by the browser's Java Virtual Machine (JVM). For information and examples on how to include an applet in an HTML page, refer to this description of the <APPLET> tag. Applet has four stage for complete there job.i.s, Init, start , stop, destroy 74 Amit Kumar Example:import java.applet.Applet; import java.awt.Graphics; public class Simple extends Applet { StringBuffer buffer; public void init() { buffer = new StringBuffer(); addItem("initializing... "); } public void start() { addItem("starting... "); } public void stop() { addItem("stopping... "); } public void destroy() { addItem("preparing for unloading..."); } private void addItem(String newWord) { System.out.println(newWord); buffer.append(newWord); repaint(); } public void paint(Graphics g) { //Draw a Rectangle around the applet's display area. g.drawRect(0, 0,getWidth() - 1,getHeight() - 1); //Draw the current string inside the rectangle. g.drawString(buffer.toString(), 5, 15); } } 75 Amit Kumar Graphics:public abstract class Graphics extends Object The Graphics class is the abstract base class for all graphics contexts that allow an application to draw onto components that are realized on various devices, as well as onto off-screen images. A Graphics object encapsulates state information needed for the basic rendering operations that Java supports. This state information includes the following properties: The Component object on which to draw. A translation origin for rendering and clipping coordinates. The current clip. The current color. The current font. The current logical pixel operation function (XOR or Paint). The current XOR alternation color (see setXORMode(java.awt.Color)). Coordinates are infinitely thin and lie between the pixels of the output device. Operations that draw the outline of a figure operate by traversing an infinitely thin path between pixels with a pixel-sized pen that hangs down and to the right of the anchor point on the path. Operations that fill a figure operate by filling the 76 Amit Kumar interior of that infinitely thin path. Operations that render horizontal text render the ascending portion of character glyphs entirely above the baseline coordinate. The graphics pen hangs down and to the right from the path it traverses. This has the following implications: If you draw a figure that covers a given rectangle, that figure occupies one extra row of pixels on the right and bottom edges as compared to filling a figure that is bounded by that same rectangle. If you draw a horizontal line along the same y coordinate as the baseline of a line of text, that line is drawn entirely below the text, except for any descenders. All coordinates that appear as arguments to the methods of this Graphics object are considered relative to the translation origin of this Graphics object prior to the invocation of the method. All rendering operations modify only pixels which lie within the area bounded by the current clip, which is specified by a Shape in user space and is controlled by the program using the Graphics object. This user clip is transformed into device space and combined with the device clip, which is defined by the visibility of windows and device extents. The combination of the user clip and device clip defines the composite clip, which determines the final clipping region. The user clip cannot be modified by the rendering system to reflect the resulting composite clip. The user clip can only be changed through the setClip or clipRect methods. All drawing or writing is done in the current color, using the current paint mode, and in the current font. Since: JDK1.0 Constructor Summary protected Graphics() Constructs a new Graphics object. Method Summary abstract clearRect(int x, int y, int width, int height) void Clears the specified rectangle by filling it with the background color of the current drawing surface. abstract clipRect(int x, int y, int width, int height) void Intersects the current clip with the specified rectangle. abstract copyArea(int x, int y, int width, int height, int dx, int dy) void Copies an area of the component by a distance specified by dx and dy. abstract create() Graphics Creates a new Graphics object that is a copy of this Graphics object. Graphics create(int x, int y, int width, int height) Creates a new Graphics object based on this Graphics object, but with a new translation and clip area. abstract dispose() void 77 Amit Kumar Disposes of this graphics context and releases any system resources that it is using. void draw3DRect(int x, int y, int width, int height, boolean raised) Draws a 3-D highlighted outline of the specified rectangle. abstract drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) void Draws the outline of a circular or elliptical arc covering the specified rectangle. void drawBytes(byte[] data, int offset, int length, int x, int y) Draws the text given by the specified byte array, using this graphics context's current font and color. void drawChars(char[] data, int offset, int length, int x, int y) Draws the text given by the specified character array, using this graphics context's current font and color. abstract drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) boolean Draws as much of the specified image as is currently available. abstract drawImage(Image img, int x, int y, ImageObserver observer) boolean Draws as much of the specified image as is currently available. abstract drawImage(Image img, int x, int y, int width, int height, Color bgcolor, boolean ImageObserver observer) Draws as much of the specified image as has already been scaled to fit inside the specified rectangle. abstract drawImage(Image img, int x, int y, int width, int height, boolean ImageObserver observer) Draws as much of the specified image as has already been scaled to fit inside the specified rectangle. abstract drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, boolean int sx2, int sy2, Color bgcolor, ImageObserver observer) Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface. abstract drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, boolean int sx2, int sy2, ImageObserver observer) Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface. abstract drawLine(int x1, int y1, int x2, int y2) void Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system. abstract drawOval(int x, int y, int width, int height) void Draws the outline of an oval. abstract drawPolygon(int[] xPoints, int[] yPoints, int nPoints) void Draws a closed polygon defined by arrays of x and y coordinates. void drawPolygon(Polygon p) Draws the outline of a polygon defined by the specified Polygon object. abstract drawPolyline(int[] xPoints, int[] yPoints, int nPoints) void Draws a sequence of connected lines defined by arrays of x and y coordinates. void drawRect(int x, int y, int width, int height) Draws the outline of the specified rectangle. abstract drawRoundRect(int x, int y, int width, int height, int arcWidth, void int arcHeight) 78 Amit Kumar Draws an outlined round-cornered rectangle using this graphics context's current color. abstract drawString(AttributedCharacterIterator iterator, int x, int y) void Draws the text given by the specified iterator, using this graphics context's current color. abstract drawString(String str, int x, int y) void Draws the text given by the specified string, using this graphics context's current font and color. void fill3DRect(int x, int y, int width, int height, boolean raised) Paints a 3-D highlighted rectangle filled with the current color. abstract fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) void Fills a circular or elliptical arc covering the specified rectangle. abstract fillOval(int x, int y, int width, int height) void Fills an oval bounded by the specified rectangle with the current color. abstract fillPolygon(int[] xPoints, int[] yPoints, int nPoints) void Fills a closed polygon defined by arrays of x and y coordinates. void fillPolygon(Polygon p) Fills the polygon defined by the specified Polygon object with the graphics context's current color. abstract fillRect(int x, int y, int width, int height) void Fills the specified rectangle. abstract fillRoundRect(int x, int y, int width, int height, int arcWidth, void int arcHeight) Fills the specified rounded corner rectangle with the current color. void finalize() Disposes of this graphics context once it is no longer referenced. abstract getClip() Shape Gets the current clipping area. abstract getClipBounds() Rectangle Returns the bounding rectangle of the current clipping area. Rectangle getClipBounds(Rectangle r) Returns the bounding rectangle of the current clipping area. abstract getColor() Color Gets this graphics context's current color. abstract getFont() Font Gets the current font. FontMetrics getFontMetrics() Gets the font metrics of the current font. abstract getFontMetrics(Font f) FontMetrics Gets the font metrics for the specified font. boolean hitClip(int x, int y, int width, int height) Returns true if the specified rectangular area intersects the bounding rectangle of the current clipping area. abstract setClip(int x, int y, int width, int height) void Sets the current clip to the rectangle specified by the 79 given coordinates. Amit Kumar abstract setClip(Shape clip) void Sets the current clipping area to an arbitrary clip shape. abstract setColor(Color c) void Sets this graphics context's current color to the specified color. abstract setFont(Font font) void Sets this graphics context's font to the specified font. abstract setPaintMode() void Sets the paint mode of this graphics context to overwrite the destination with this graphics context's current color. abstract setXORMode(Color c1) void Sets the paint mode of this graphics context to alternate between this graphics context's current color and the new specified color. String toString() Returns a String object representing this Graphics object's value. abstract translate(int x, int y) void Translates the origin of the graphics context to the point (x, y) in the current coordinate system. Example import java.awt.*; import java.applet.*; public class Home extends Applet { public void paint(Graphics g) { g.setColor(Color.red); g.drawRect(100,100,300,200); g.setColor(Color.yellow); g.fillRect(100,100,300,200); g.setColor(Color.red); g.drawString("W",210,120); g.setColor(Color.blue); g.drawString("E",225,120); g.setColor(Color.green); g.drawString("L",235,120); g.setColor(Color.blue); g.drawString("C",245,120); g.setColor(Color.red); g.drawString("0",255,120); g.setColor(Color.magenta); g.drawString("M",265,120); g.setColor(Color.red); g.drawString("E",275,120); g.setColor(Color.magenta); 80 Amit Kumar g.fillRect(350,175,50,50); g.drawRect(350,175,50,50); g.setColor(Color.red); g.fillRect(225,225,25,75); g.drawRect(225,225,25,75); g.setColor(Color.green); g.fillRect(250,225,25,75); g.drawRect(250,225,25,75); g.setColor(Color.red); g.drawLine(250,50,50,118); g.drawLine(250,50,450,118); g.drawRect(100,175,25,50); g.drawRect(125,175,25,50); g.drawRect(350,175,25,50); g.drawRect(100,175,50,25); g.drawRect(100,200,50,25); g.drawRect(350,200,50,25); g.drawRect(200,300,100,25); g.drawRect(175,325,150,25); g.drawRect(150,350,200,25); } } //<applet code=Home width=500 height=400></applet> About AWT:The Java programming language class library provides a user interface toolkit called the Abstract Windowing Toolkit, or the AWT. The AWT is both powerful and flexible. Newcomers, however, often find that its power is veiled. The class and method descriptions found in the distributed documentation provide little guidance for the new programmer. Furthermore, the available examples often leave many important questions unanswered. Of course, newcomers should expect some difficulty. Effective graphical user interfaces are inherently challenging to 81 Amit Kumar design and implement, and the sometimes complicated interactions between classes in the AWT only make this task more complex. However, with proper guidance, the creation of a graphical user interface using the AWT is not only possible, but relatively straightforward. This article covers some of the philosophy behind the AWT and addresses the practical concern of how to create a simple user interface for an applet or application. What is a user interface The user interface is that part of a program that interacts with the user of the program. User interfaces take many forms. These forms range in complexity from simple command-line interfaces to the pointand-click graphical user interfaces provided by many modern applications. At the lowest level, the operating system transmits information from the mouse and keyboard to the program as input, and provides pixels for program output. The AWT was designed so that programmers don't have worry about the details of tracking the mouse or reading the keyboard, nor attend to the details of writing to the screen. The AWT provides a well-designed object-oriented interface to these low-level services and resources. Because the Java programming language is platform-independent, the AWT must also be platformindependent. The AWT was designed to provide a common set of tools for graphical user interface design that work on a variety of platforms. The user interface elements provided by the AWT are implemented using each platform's native GUI toolkit, thereby preserving the look and feel of each platform. This is one of the AWT's strongest points. The disadvantage of such an approach is the fact that a graphical user interface designed on one platform may look different when displayed on another platform. Components and containers A graphical user interface is built of graphical elements called components. Typical components include such items as buttons, scrollbars, and text fields. Components allow the user to interact with the program and provide the user with visual feedback about the state of the program. In the AWT, all user interface components are instances of class Component or one of its subtypes. Components do not stand alone, but rather are found within containers. Containers contain and control the layout of components. Containers are themselves components, and can thus be placed inside other containers. In the AWT, all containers are instances of class Container or one of its subtypes. Spatially, components must fit completely within the container that contains them. This nesting of components (including containers) into containers creates a tree of elements, starting with the container at the root of the tree and expanding out to the leaves, which are components such as buttons. The illustration in Figure 1 depicts a simple graphical user interface as it would look when displayed under Windows 95. Figure 2 shows the interface components from Figure 1 arranged as a tree. 82 Amit Kumar Figure 1. A simple graphical user interface Figure 2. User interface component tree Types of components Figure 3 shows the inheritance relationship between the user interface component classes provided by the AWT. Class Component defines the interface to which all components must adhere. 83 Amit Kumar Figure 3. The inheritance relationship The AWT provides nine basic non-container component classes from which a user interface may be constructed. (Of course, new component classes may be derived from any of these or from class Component itself.) These nine classes are class Button, Canvas, Checkbox, Choice, Label, List, Scrollbar, TextArea, and TextField. Figure 4 depicts an instance of each class. Figure 4. Nine user interface components The source for this display is found here. Types of containers The AWT provides four container classes. They are class Window and its two subtypes -- class Frame and class Dialog -- as well as the Panel class. In addition to the containers provided by the AWT, the Applet class is a container -- it is a subtype of the Panel class and can therefore hold components. Brief descriptions of each container class provided by the AWT are provided below. 84 Amit Kumar Window A top-level display surface (a window). An instance of the Window class is not attached to nor embedded within another container. An instance of the Window class has no border and no title. Frame A top-level display surface (a window) with a border and title. An instance of the Frame class may have a menu bar. It is otherwise very much like an instance of the Window class. Dialog A top-level display surface (a window) with a border and title. An instance of the Dialog class cannot exist without an associated instance of the Frame class. Panel A generic container for holding components. An instance of the Panel class provides a container to which to add components. Creating a container Before adding the components that make up a user interface, the programmer must create a container. When building an application, the programmer must first create an instance of class Window or class Frame. When building an applet, a frame (the browser window) already exists. Since the Applet class is a subtype of the Panel class, the programmer can add the components to the instance of the Applet class itself. The code in Listing 1 creates an empty frame. The title of the frame ("Example 1") is set in the call to the constructor. A frame is initially invisible and must be made visible by invoking its show() method. import java.awt.*; public class Example1 { public static void main(String [] args) { Frame f = new Frame("Example 1"); f.show(); } } Listing 1. An empty frame The code in Listing 2 extends the code from Listing 1 so that the new class inherits from class Panel. In the main() method, an instance of this new class is created and added to the Frame object via a call to the add() method. The result is then displayed. The results of both examples should look identical (that is, they should look quite uninteresting). import java.awt.*; 85 Amit Kumar public class Example1a extends Panel { public static void main(String [] args) { Frame f = new Frame("Example 1a"); Example1a ex = new Example1a(); f.add("Center", ex); f.pack(); f.show(); } } Listing 2. A frame with an empty panel By deriving the new class from class Applet instead of class Panel, this example can now run as either a standalone application or as an applet embedded in a Web page. The code for this example is provided in Listing 3. The resulting applet is displayed in Figure 5 (and is still quite uninteresting). import java.awt.*; public class Example1b extends java.applet.Applet { public static void main(String [] args) { Frame f = new Frame("Example 1b"); Example1b ex = new Example1b(); f.add("Center", ex); f.pack(); f.show(); } } Listing 3. A frame with an empty applet 86 Amit Kumar Adding components to a container To be useful, a user interface must consist of more than just a container -- it must contain components. Components are added to containers via a container's add() method. There are three basic forms of the add() method. The method to use depends on the container's layout manager (see the section titled Component layout). The code in Listing 4 adds the creation of two buttons to the code presented in Listing 3. The creation is performed in the init() method because it is automatically called during applet initialization. Therefore, no matter how the program is started, the buttons are created, because init() is called by either the browser or by the main() method. Figure 6 contains the resulting applet. import java.awt.*; public class Example3 extends java.applet.Applet { public void init() { add(new Button("One")); add(new Button("Two")); } public Dimension preferredSize() { return new Dimension(200, 100); } public static void main(String [] args) { Frame f = new Frame("Example 3"); Example3 ex = new Example3(); ex.init(); f.add("Center", ex); f.pack(); f.show(); } } Listing 4. An applet with two buttons 87 Amit Kumar Figure 6. An applet with two buttons Component layout Up to this point, nothing has been said about how the components that have been added to a container are laid out. Layout is controlled not by the container, but by a layout manager associated with the container. The layout manager makes all of the component placement decisions. In the AWT, all layout manager classes implement the LayoutManager interface. The AWT provides five layout managers. They range from very simple to very complex. This article covers only the two layout manager classes used by the examples herein: the FlowLayout class and the BorderLayout class. The FlowLayout class places components in a container from left to right. When the space in one row is exhausted, another row is started. The single-argument version of a container's add() method is used to add components. The BorderLayout class has five zones as depicted in Figure 7. The zones are named "North", "South", "East", "West", and "Center". A single component can be placed in each of these five zones. When the enclosing container is resized, each border zone is resized just enough to hold the component placed within. Any excess space is given to the center zone. The two-argument version of a container's add() method is used to add components. The first argument is a String object that names the zone in which to place the component. Figure 7. The border layout zones Each container class has a default layout manager. The default layout manager for the Frame class and Dialog class is the BorderLayout manager. The default layout manager for the Panel class (and the Applet class) is the FlowLayout manager. The code in Listing 5 uses both layout managers and includes a few more user interface components. The result is displayed in Figure 8. import java.awt.*; 88 Amit Kumar public class Example4 extends java.applet.Applet { public void init() { Panel p; setLayout(new BorderLayout()); p = new Panel(); p.add(new TextArea()); add("Center", p); p = new Panel(); p.add(new Button("One")); p.add(new Button("Two")); Choice c = new Choice(); c.addItem("one"); c.addItem("two"); c.addItem("three"); p.add(c); add("South", p); } public static void main(String [] args) { Frame f = new Frame("Example 4"); Example4 ex = new Example4(); ex.init(); f.add("Center", ex); 89 Amit Kumar f.pack(); f.show(); } } Listing 5. A more complicated example Event handling The examples above do nothing more than display an inert user interface. It is, of course, very important that a user interface take action as a result of user input. It is, however, beyond the scope this article to delve deeply into the mysteries of event handling. That must wait until a future article. However, in the interest of completeness, the example code in Listing 6 shows how to handle one type of event a program may receive. The new class overrides the action() method provided by the Component class. The action() method responds to the action events that are generated, for example, by the selection of an item from a pop-up list. The action() method requires that two parameters be supplied, an Event instance and an Object instance. The Event instance contains information about the event, including the target of the event (the component that first received the event), the x and y coordinates of the event, and the time when the event occurred. The Object instance holds an event-specific piece of data. For Button objects it contains the text in the button label. import java.awt.*; public class Example5 extends java.applet.Applet { TextArea ta = null; public void init() { Panel p; setLayout(new BorderLayout()); p = new Panel(); ta = new TextArea(); p.add(ta); add("Center", p); 90 Amit Kumar p = new Panel(); p.add(new Button("One")); p.add(new Button("Two")); Choice c = new Choice(); c.addItem("one"); c.addItem("two"); c.addItem("three"); p.add(c); add("South", p); } public boolean action(Event e, Object o) { String str = (String)o; ta.appendText(str + "\n"); return false; } public static void main(String [] args) { Frame f = new Frame("Example 5"); Example5 ex = new Example5(); ex.init(); f.add("Center", ex); f.pack(); f.show(); } } Listing 6. An example with event handling 91 Amit Kumar 92 Amit Kumar